‹‹ ‹{"files":{"node_modules":{"files":{"ajv":{"files":{".runkit_example.js":{"size":496,"offset":"0","integrity":{"algorithm":"SHA256","hash":"e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf","blockSize":4194304,"blocks":["e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf"]}},"LICENSE":{"size":1090,"offset":"496","integrity":{"algorithm":"SHA256","hash":"a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3","blockSize":4194304,"blocks":["a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3"]}},"dist":{"files":{"2019.js":{"size":3188,"offset":"1586","integrity":{"algorithm":"SHA256","hash":"4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4","blockSize":4194304,"blocks":["4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4"]}},"2019.js.map":{"size":1639,"offset":"4774","integrity":{"algorithm":"SHA256","hash":"a91b0607c55ef90f269dbefb567c975cfae953341c13761c43b7f8b78e44b91f","blockSize":4194304,"blocks":["a91b0607c55ef90f269dbefb567c975cfae953341c13761c43b7f8b78e44b91f"]}},"2020.js":{"size":2894,"offset":"6413","integrity":{"algorithm":"SHA256","hash":"908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a","blockSize":4194304,"blocks":["908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a"]}},"2020.js.map":{"size":1473,"offset":"9307","integrity":{"algorithm":"SHA256","hash":"845f8c979380377abe0db2a8a8ba9c5484d88cc69dc6704db84c6fc176b330d5","blockSize":4194304,"blocks":["845f8c979380377abe0db2a8a8ba9c5484d88cc69dc6704db84c6fc176b330d5"]}},"ajv.js":{"size":2841,"offset":"10780","integrity":{"algorithm":"SHA256","hash":"edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297","blockSize":4194304,"blocks":["edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297"]}},"ajv.js.map":{"size":1476,"offset":"13621","integrity":{"algorithm":"SHA256","hash":"f6a0d17a5cdb4891ab056a48c852cc6dbb5e5ef262e3fccfc9021782d3714d44","blockSize":4194304,"blocks":["f6a0d17a5cdb4891ab056a48c852cc6dbb5e5ef262e3fccfc9021782d3714d44"]}},"compile":{"files":{"codegen":{"files":{"code.js":{"size":4676,"offset":"15097","integrity":{"algorithm":"SHA256","hash":"1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d","blockSize":4194304,"blocks":["1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d"]}},"code.js.map":{"size":5309,"offset":"19773","integrity":{"algorithm":"SHA256","hash":"6662bc0c87dfefa43cabfe916340b03c128e6b4ffe8d08d162231a337299fe60","blockSize":4194304,"blocks":["6662bc0c87dfefa43cabfe916340b03c128e6b4ffe8d08d162231a337299fe60"]}},"index.js":{"size":23127,"offset":"25082","integrity":{"algorithm":"SHA256","hash":"f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c","blockSize":4194304,"blocks":["f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c"]}},"index.js.map":{"size":23829,"offset":"48209","integrity":{"algorithm":"SHA256","hash":"081d235ee23ad618f56c6bbda22b646522cba1b20534711fddfdbcb2b075affc","blockSize":4194304,"blocks":["081d235ee23ad618f56c6bbda22b646522cba1b20534711fddfdbcb2b075affc"]}},"scope.js":{"size":5198,"offset":"72038","integrity":{"algorithm":"SHA256","hash":"d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286","blockSize":4194304,"blocks":["d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286"]}},"scope.js.map":{"size":5174,"offset":"77236","integrity":{"algorithm":"SHA256","hash":"a5a146bfb90c9f6cb861d91503437e230f340c410a63400530e1bf493d84b0ec","blockSize":4194304,"blocks":["a5a146bfb90c9f6cb861d91503437e230f340c410a63400530e1bf493d84b0ec"]}}}},"errors.js":{"size":5771,"offset":"82410","integrity":{"algorithm":"SHA256","hash":"53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2","blockSize":4194304,"blocks":["53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2"]}},"errors.js.map":{"size":6085,"offset":"88181","integrity":{"algorithm":"SHA256","hash":"5dfef5ea1d9707666aadcda54e93bff03e3a7f9730aec490ac31e5203eccd294","blockSize":4194304,"blocks":["5dfef5ea1d9707666aadcda54e93bff03e3a7f9730aec490ac31e5203eccd294"]}},"index.js":{"size":10046,"offset":"94266","integrity":{"algorithm":"SHA256","hash":"05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac","blockSize":4194304,"blocks":["05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac"]}},"index.js.map":{"size":9269,"offset":"104312","integrity":{"algorithm":"SHA256","hash":"ad95a3a7cce920acd10b89d06581e3e2542bd0b6a4b44320b55bd18531efe99a","blockSize":4194304,"blocks":["ad95a3a7cce920acd10b89d06581e3e2542bd0b6a4b44320b55bd18531efe99a"]}},"jtd":{"files":{"parse.js":{"size":13727,"offset":"113581","integrity":{"algorithm":"SHA256","hash":"548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f","blockSize":4194304,"blocks":["548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f"]}},"parse.js.map":{"size":15725,"offset":"127308","integrity":{"algorithm":"SHA256","hash":"90e560b9f7e4b32959b514576dbb0d3a9dc3466e0ea65e0f3ac53e7bb34ab1c0","blockSize":4194304,"blocks":["90e560b9f7e4b32959b514576dbb0d3a9dc3466e0ea65e0f3ac53e7bb34ab1c0"]}},"serialize.js":{"size":9391,"offset":"143033","integrity":{"algorithm":"SHA256","hash":"1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0","blockSize":4194304,"blocks":["1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0"]}},"serialize.js.map":{"size":10737,"offset":"152424","integrity":{"algorithm":"SHA256","hash":"faaa5b0f5f27386d08abac9a54613bb4823fb5991b666715ab475ea85b391acd","blockSize":4194304,"blocks":["faaa5b0f5f27386d08abac9a54613bb4823fb5991b666715ab475ea85b391acd"]}},"types.js":{"size":291,"offset":"163161","integrity":{"algorithm":"SHA256","hash":"e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78","blockSize":4194304,"blocks":["e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78"]}},"types.js.map":{"size":236,"offset":"163452","integrity":{"algorithm":"SHA256","hash":"b1c351a2a5810e00c4bbf3814fdc6b83fde3b016a79b8c5fc66cb32a0988abb5","blockSize":4194304,"blocks":["b1c351a2a5810e00c4bbf3814fdc6b83fde3b016a79b8c5fc66cb32a0988abb5"]}}}},"names.js":{"size":1440,"offset":"163688","integrity":{"algorithm":"SHA256","hash":"3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493","blockSize":4194304,"blocks":["3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493"]}},"names.js.map":{"size":974,"offset":"165128","integrity":{"algorithm":"SHA256","hash":"2b28eacf577a5b5b2a6bade9e61097af1e84a4fb848fca153432e5c5a239e7d7","blockSize":4194304,"blocks":["2b28eacf577a5b5b2a6bade9e61097af1e84a4fb848fca153432e5c5a239e7d7"]}},"ref_error.js":{"size":543,"offset":"166102","integrity":{"algorithm":"SHA256","hash":"81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7","blockSize":4194304,"blocks":["81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7"]}},"ref_error.js.map":{"size":474,"offset":"166645","integrity":{"algorithm":"SHA256","hash":"3101f665a6485ffee1c377d4cc015d9bb23af186ec941907afe03386406adc4b","blockSize":4194304,"blocks":["3101f665a6485ffee1c377d4cc015d9bb23af186ec941907afe03386406adc4b"]}},"resolve.js":{"size":5006,"offset":"167119","integrity":{"algorithm":"SHA256","hash":"df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9","blockSize":4194304,"blocks":["df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9"]}},"resolve.js.map":{"size":4850,"offset":"172125","integrity":{"algorithm":"SHA256","hash":"837e46750307e91c812466a0549472678800b29c1d3c9373f41fd795cb88c5ce","blockSize":4194304,"blocks":["837e46750307e91c812466a0549472678800b29c1d3c9373f41fd795cb88c5ce"]}},"rules.js":{"size":918,"offset":"176975","integrity":{"algorithm":"SHA256","hash":"ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9","blockSize":4194304,"blocks":["ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9"]}},"rules.js.map":{"size":1030,"offset":"177893","integrity":{"algorithm":"SHA256","hash":"d5c077c6e1149c7e92fcaae92def87cd549f9407acbbcaf5a27dd5a76fab67c6","blockSize":4194304,"blocks":["d5c077c6e1149c7e92fcaae92def87cd549f9407acbbcaf5a27dd5a76fab67c6"]}},"util.js":{"size":7103,"offset":"178923","integrity":{"algorithm":"SHA256","hash":"fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5","blockSize":4194304,"blocks":["fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5"]}},"util.js.map":{"size":7083,"offset":"186026","integrity":{"algorithm":"SHA256","hash":"9deb815ce282c61c7e68adbd649aa7efe1e58f49e0b5c18d022d2f3b3717f442","blockSize":4194304,"blocks":["9deb815ce282c61c7e68adbd649aa7efe1e58f49e0b5c18d022d2f3b3717f442"]}},"validate":{"files":{"applicability.js":{"size":853,"offset":"193109","integrity":{"algorithm":"SHA256","hash":"50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0","blockSize":4194304,"blocks":["50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0"]}},"applicability.js.map":{"size":775,"offset":"193962","integrity":{"algorithm":"SHA256","hash":"399e5834d6364657feb5c799d87ca3141e8e653ef021b38489937319d7c4f2ad","blockSize":4194304,"blocks":["399e5834d6364657feb5c799d87ca3141e8e653ef021b38489937319d7c4f2ad"]}},"boolSchema.js":{"size":1531,"offset":"194737","integrity":{"algorithm":"SHA256","hash":"c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f","blockSize":4194304,"blocks":["c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f"]}},"boolSchema.js.map":{"size":1380,"offset":"196268","integrity":{"algorithm":"SHA256","hash":"d2ba3c7b7cc92d4f4488e5dd785ded04ad4a42cdc69c68c45f929566edcf7ab9","blockSize":4194304,"blocks":["d2ba3c7b7cc92d4f4488e5dd785ded04ad4a42cdc69c68c45f929566edcf7ab9"]}},"dataType.js":{"size":8409,"offset":"197648","integrity":{"algorithm":"SHA256","hash":"697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52","blockSize":4194304,"blocks":["697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52"]}},"dataType.js.map":{"size":7776,"offset":"206057","integrity":{"algorithm":"SHA256","hash":"5ddbd0361b1a521ba2e822ed40a7156d9d6211c68ef2c4677f6496c151ce9e08","blockSize":4194304,"blocks":["5ddbd0361b1a521ba2e822ed40a7156d9d6211c68ef2c4677f6496c151ce9e08"]}},"defaults.js":{"size":1448,"offset":"213833","integrity":{"algorithm":"SHA256","hash":"05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428","blockSize":4194304,"blocks":["05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428"]}},"defaults.js.map":{"size":1342,"offset":"215281","integrity":{"algorithm":"SHA256","hash":"dd09145eaed811c656aeb2e9bf74d7aaafb4dc986a158cb20c017bdbde53d5b5","blockSize":4194304,"blocks":["dd09145eaed811c656aeb2e9bf74d7aaafb4dc986a158cb20c017bdbde53d5b5"]}},"index.js":{"size":20552,"offset":"216623","integrity":{"algorithm":"SHA256","hash":"cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd","blockSize":4194304,"blocks":["cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd"]}},"index.js.map":{"size":21391,"offset":"237175","integrity":{"algorithm":"SHA256","hash":"fc7822f544bb4db6d457c858c53ba2e6be77a55d35a192e67011e1c8dd4d9c5c","blockSize":4194304,"blocks":["fc7822f544bb4db6d457c858c53ba2e6be77a55d35a192e67011e1c8dd4d9c5c"]}},"keyword.js":{"size":5695,"offset":"258566","integrity":{"algorithm":"SHA256","hash":"ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76","blockSize":4194304,"blocks":["ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76"]}},"keyword.js.map":{"size":6011,"offset":"264261","integrity":{"algorithm":"SHA256","hash":"3051e66f0a88cfb62ce8de46e2ca85780e2f0b64f62fc1fa091e77af47a51b4e","blockSize":4194304,"blocks":["3051e66f0a88cfb62ce8de46e2ca85780e2f0b64f62fc1fa091e77af47a51b4e"]}},"subschema.js":{"size":3858,"offset":"270272","integrity":{"algorithm":"SHA256","hash":"ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc","blockSize":4194304,"blocks":["ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc"]}},"subschema.js.map":{"size":3148,"offset":"274130","integrity":{"algorithm":"SHA256","hash":"9a6beb742ae31a368004b444fb9ecaa49899eefe05e747e36c11b82e6a2c288a","blockSize":4194304,"blocks":["9a6beb742ae31a368004b444fb9ecaa49899eefe05e747e36c11b82e6a2c288a"]}}}}}},"core.js":{"size":25202,"offset":"277278","integrity":{"algorithm":"SHA256","hash":"51be29c7ed7288622f755c0f1bebd3da4a9907d77aa2c33b0f2a0a5b6b339603","blockSize":4194304,"blocks":["51be29c7ed7288622f755c0f1bebd3da4a9907d77aa2c33b0f2a0a5b6b339603"]}},"core.js.map":{"size":21608,"offset":"302480","integrity":{"algorithm":"SHA256","hash":"0357910e20ce75d511ca46f838803be796d605fcddecbc325131a82fcfc04472","blockSize":4194304,"blocks":["0357910e20ce75d511ca46f838803be796d605fcddecbc325131a82fcfc04472"]}},"jtd.js":{"size":3360,"offset":"324088","integrity":{"algorithm":"SHA256","hash":"9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44","blockSize":4194304,"blocks":["9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44"]}},"jtd.js.map":{"size":2036,"offset":"327448","integrity":{"algorithm":"SHA256","hash":"b8d25a9ac802a23e0e008abcbe4a9684a1bad31fd36b5e977e677527d6087f51","blockSize":4194304,"blocks":["b8d25a9ac802a23e0e008abcbe4a9684a1bad31fd36b5e977e677527d6087f51"]}},"refs":{"files":{"data.json":{"size":409,"offset":"329484","integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]}},"json-schema-2019-09":{"files":{"index.js":{"size":938,"offset":"329893","integrity":{"algorithm":"SHA256","hash":"ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d","blockSize":4194304,"blocks":["ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d"]}},"index.js.map":{"size":726,"offset":"330831","integrity":{"algorithm":"SHA256","hash":"3ba84273c35f49642ee68ddf2ea561e8ecbaf00329e323e210c8b6f6cc580e01","blockSize":4194304,"blocks":["3ba84273c35f49642ee68ddf2ea561e8ecbaf00329e323e210c8b6f6cc580e01"]}},"meta":{"files":{"applicator.json":{"size":1566,"offset":"331557","integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]}},"content.json":{"size":477,"offset":"333123","integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]}},"core.json":{"size":1273,"offset":"333600","integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]}},"format.json":{"size":375,"offset":"334873","integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]}},"meta-data.json":{"size":758,"offset":"335248","integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]}},"validation.json":{"size":2264,"offset":"336006","integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]}}}},"schema.json":{"size":1579,"offset":"338270","integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]}}}},"json-schema-2020-12":{"files":{"index.js":{"size":1026,"offset":"339849","integrity":{"algorithm":"SHA256","hash":"2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1","blockSize":4194304,"blocks":["2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1"]}},"index.js.map":{"size":751,"offset":"340875","integrity":{"algorithm":"SHA256","hash":"79fed7d771c96ee134e413a39cac77f0e670228a684e1cbb58cfb0603a8f9877","blockSize":4194304,"blocks":["79fed7d771c96ee134e413a39cac77f0e670228a684e1cbb58cfb0603a8f9877"]}},"meta":{"files":{"applicator.json":{"size":1441,"offset":"341626","integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]}},"content.json":{"size":479,"offset":"343067","integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]}},"core.json":{"size":1344,"offset":"343546","integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]}},"format-annotation.json":{"size":420,"offset":"344890","integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]}},"meta-data.json":{"size":758,"offset":"345310","integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]}},"unevaluated.json":{"size":472,"offset":"346068","integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]}},"validation.json":{"size":2264,"offset":"346540","integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]}}}},"schema.json":{"size":2166,"offset":"348804","integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]}}}},"json-schema-draft-06.json":{"size":3449,"offset":"350970","integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]}},"json-schema-draft-07.json":{"size":3811,"offset":"354419","integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]}},"json-schema-secure.json":{"size":2521,"offset":"358230","integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]}},"jtd-schema.js":{"size":2882,"offset":"360751","integrity":{"algorithm":"SHA256","hash":"ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92","blockSize":4194304,"blocks":["ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92"]}},"jtd-schema.js.map":{"size":2824,"offset":"363633","integrity":{"algorithm":"SHA256","hash":"732b58ce3fbd6aaac7a2423daa1f8dc134ff07a2336dbb2c5d13efd91a94a11b","blockSize":4194304,"blocks":["732b58ce3fbd6aaac7a2423daa1f8dc134ff07a2336dbb2c5d13efd91a94a11b"]}}}},"runtime":{"files":{"equal.js":{"size":286,"offset":"366457","integrity":{"algorithm":"SHA256","hash":"c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274","blockSize":4194304,"blocks":["c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274"]}},"equal.js.map":{"size":199,"offset":"366743","integrity":{"algorithm":"SHA256","hash":"addc8498c8bf12ce8d2dc33c34805d0940eca3692c66105d99e270793c85fcae","blockSize":4194304,"blocks":["addc8498c8bf12ce8d2dc33c34805d0940eca3692c66105d99e270793c85fcae"]}},"parseJson.js":{"size":5401,"offset":"366942","integrity":{"algorithm":"SHA256","hash":"1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e","blockSize":4194304,"blocks":["1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e"]}},"parseJson.js.map":{"size":5339,"offset":"372343","integrity":{"algorithm":"SHA256","hash":"cd9de6145208c3b595ccab1a800d1b492c89ddf41f8b682909e8c96d6d6b5bc7","blockSize":4194304,"blocks":["cd9de6145208c3b595ccab1a800d1b492c89ddf41f8b682909e8c96d6d6b5bc7"]}},"quote.js":{"size":943,"offset":"377682","integrity":{"algorithm":"SHA256","hash":"1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2","blockSize":4194304,"blocks":["1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2"]}},"quote.js.map":{"size":877,"offset":"378625","integrity":{"algorithm":"SHA256","hash":"299ec640699b8c7601d58d6446fa0f3c639b307166971226950c845a819a7dc9","blockSize":4194304,"blocks":["299ec640699b8c7601d58d6446fa0f3c639b307166971226950c845a819a7dc9"]}},"re2.js":{"size":213,"offset":"379502","integrity":{"algorithm":"SHA256","hash":"e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361","blockSize":4194304,"blocks":["e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361"]}},"re2.js.map":{"size":182,"offset":"379715","integrity":{"algorithm":"SHA256","hash":"891ce3a6e69c7c08f3e13ab0a950c2def22137c1bcd1f3dff54391f796e122cc","blockSize":4194304,"blocks":["891ce3a6e69c7c08f3e13ab0a950c2def22137c1bcd1f3dff54391f796e122cc"]}},"timestamp.js":{"size":1536,"offset":"379897","integrity":{"algorithm":"SHA256","hash":"05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef","blockSize":4194304,"blocks":["05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef"]}},"timestamp.js.map":{"size":1994,"offset":"381433","integrity":{"algorithm":"SHA256","hash":"4e4eb1e7923ca19f3935fdfb76dfa7ee88d2914be490b1d702ffab13bfce07fe","blockSize":4194304,"blocks":["4e4eb1e7923ca19f3935fdfb76dfa7ee88d2914be490b1d702ffab13bfce07fe"]}},"ucs2length.js":{"size":808,"offset":"383427","integrity":{"algorithm":"SHA256","hash":"1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890","blockSize":4194304,"blocks":["1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890"]}},"ucs2length.js.map":{"size":728,"offset":"384235","integrity":{"algorithm":"SHA256","hash":"5ad0a6c09c26dd193c807813a9a22304d7c4534af6f13361032ecedaf58e8a7d","blockSize":4194304,"blocks":["5ad0a6c09c26dd193c807813a9a22304d7c4534af6f13361032ecedaf58e8a7d"]}},"uri.js":{"size":218,"offset":"384963","integrity":{"algorithm":"SHA256","hash":"d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578","blockSize":4194304,"blocks":["d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578"]}},"uri.js.map":{"size":182,"offset":"385181","integrity":{"algorithm":"SHA256","hash":"7751d10beb734802801b650c3e934553f2b26ba26bc68b20796734b7f9fd9955","blockSize":4194304,"blocks":["7751d10beb734802801b650c3e934553f2b26ba26bc68b20796734b7f9fd9955"]}},"validation_error.js":{"size":337,"offset":"385363","integrity":{"algorithm":"SHA256","hash":"11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815","blockSize":4194304,"blocks":["11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815"]}},"validation_error.js.map":{"size":332,"offset":"385700","integrity":{"algorithm":"SHA256","hash":"833d51e4ffee8e2e21c53b6aca02bdf70349233e8620b36d093bfb6b0157bff2","blockSize":4194304,"blocks":["833d51e4ffee8e2e21c53b6aca02bdf70349233e8620b36d093bfb6b0157bff2"]}}}},"standalone":{"files":{"index.js":{"size":4480,"offset":"386032","integrity":{"algorithm":"SHA256","hash":"361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f","blockSize":4194304,"blocks":["361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f"]}},"index.js.map":{"size":4078,"offset":"390512","integrity":{"algorithm":"SHA256","hash":"a1afc5f1e9166c87da0c8e96b39560ba7c2df532adb495ad2b39c2ebfce68860","blockSize":4194304,"blocks":["a1afc5f1e9166c87da0c8e96b39560ba7c2df532adb495ad2b39c2ebfce68860"]}},"instance.js":{"size":1015,"offset":"394590","integrity":{"algorithm":"SHA256","hash":"4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3","blockSize":4194304,"blocks":["4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3"]}},"instance.js.map":{"size":1091,"offset":"395605","integrity":{"algorithm":"SHA256","hash":"7f59241ec6792fa719f3151610ef417552e986f45eb7c2f368a5c19a9b6261f7","blockSize":4194304,"blocks":["7f59241ec6792fa719f3151610ef417552e986f45eb7c2f368a5c19a9b6261f7"]}}}},"types":{"files":{"index.js":{"size":110,"offset":"396696","integrity":{"algorithm":"SHA256","hash":"fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71","blockSize":4194304,"blocks":["fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71"]}},"index.js.map":{"size":111,"offset":"396806","integrity":{"algorithm":"SHA256","hash":"dc7dd6ae1631a9726121bba97c02b42640360d3667f8650f78242d078693c4e6","blockSize":4194304,"blocks":["dc7dd6ae1631a9726121bba97c02b42640360d3667f8650f78242d078693c4e6"]}},"json-schema.js":{"size":116,"offset":"396917","integrity":{"algorithm":"SHA256","hash":"2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28","blockSize":4194304,"blocks":["2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28"]}},"json-schema.js.map":{"size":123,"offset":"397033","integrity":{"algorithm":"SHA256","hash":"c33ce191e73eead1689338837205402bb586032b089eafc83210e4e1f1a5b221","blockSize":4194304,"blocks":["c33ce191e73eead1689338837205402bb586032b089eafc83210e4e1f1a5b221"]}},"jtd-schema.js":{"size":115,"offset":"397156","integrity":{"algorithm":"SHA256","hash":"6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d","blockSize":4194304,"blocks":["6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d"]}},"jtd-schema.js.map":{"size":121,"offset":"397271","integrity":{"algorithm":"SHA256","hash":"c2840f14191be8435778a2a64a8e0600500dde376910b05c52865e2deafb09c9","blockSize":4194304,"blocks":["c2840f14191be8435778a2a64a8e0600500dde376910b05c52865e2deafb09c9"]}}}},"vocabularies":{"files":{"applicator":{"files":{"additionalItems.js":{"size":1931,"offset":"397392","integrity":{"algorithm":"SHA256","hash":"7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099","blockSize":4194304,"blocks":["7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099"]}},"additionalItems.js.map":{"size":2093,"offset":"399323","integrity":{"algorithm":"SHA256","hash":"f8d4898f0f5a507cf88a43dbcffb4ae82e7bb600d56602513085151032aac571","blockSize":4194304,"blocks":["f8d4898f0f5a507cf88a43dbcffb4ae82e7bb600d56602513085151032aac571"]}},"additionalProperties.js":{"size":4309,"offset":"401416","integrity":{"algorithm":"SHA256","hash":"e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a","blockSize":4194304,"blocks":["e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a"]}},"additionalProperties.js.map":{"size":3762,"offset":"405725","integrity":{"algorithm":"SHA256","hash":"90cae7b84831914a0513d8db46fbe45e39cceba6c8ab3b39d853bd6439edc95a","blockSize":4194304,"blocks":["90cae7b84831914a0513d8db46fbe45e39cceba6c8ab3b39d853bd6439edc95a"]}},"allOf.js":{"size":756,"offset":"409487","integrity":{"algorithm":"SHA256","hash":"98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7","blockSize":4194304,"blocks":["98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7"]}},"allOf.js.map":{"size":812,"offset":"410243","integrity":{"algorithm":"SHA256","hash":"bc57edbf872aa33f295435a714b3612f887c29abf411aa114d2b92a89461ee5b","blockSize":4194304,"blocks":["bc57edbf872aa33f295435a714b3612f887c29abf411aa114d2b92a89461ee5b"]}},"anyOf.js":{"size":343,"offset":"411055","integrity":{"algorithm":"SHA256","hash":"8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5","blockSize":4194304,"blocks":["8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5"]}},"anyOf.js.map":{"size":327,"offset":"411398","integrity":{"algorithm":"SHA256","hash":"c05bb310be6b4e46482835cfe8978d34a8591a57722661d039f685d6e1ebd2d3","blockSize":4194304,"blocks":["c05bb310be6b4e46482835cfe8978d34a8591a57722661d039f685d6e1ebd2d3"]}},"contains.js":{"size":3680,"offset":"411725","integrity":{"algorithm":"SHA256","hash":"56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c","blockSize":4194304,"blocks":["56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c"]}},"contains.js.map":{"size":3843,"offset":"415405","integrity":{"algorithm":"SHA256","hash":"b6136d502d30985c5f9367214191e1a15f7ffffa7e66d38b5d90ce97c5fb3069","blockSize":4194304,"blocks":["b6136d502d30985c5f9367214191e1a15f7ffffa7e66d38b5d90ce97c5fb3069"]}},"dependencies.js":{"size":3198,"offset":"419248","integrity":{"algorithm":"SHA256","hash":"c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b","blockSize":4194304,"blocks":["c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b"]}},"dependencies.js.map":{"size":3172,"offset":"422446","integrity":{"algorithm":"SHA256","hash":"58bd7453681e4e1f067f12ee46b0963fbb7b3dd91d5635146e892021541ea0af","blockSize":4194304,"blocks":["58bd7453681e4e1f067f12ee46b0963fbb7b3dd91d5635146e892021541ea0af"]}},"dependentSchemas.js":{"size":354,"offset":"425618","integrity":{"algorithm":"SHA256","hash":"d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e","blockSize":4194304,"blocks":["d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e"]}},"dependentSchemas.js.map":{"size":353,"offset":"425972","integrity":{"algorithm":"SHA256","hash":"acf03cc2df2951050a845f391f71d74a82cf2448b628a791cfc37a1ef12cdc69","blockSize":4194304,"blocks":["acf03cc2df2951050a845f391f71d74a82cf2448b628a791cfc37a1ef12cdc69"]}},"if.js":{"size":2438,"offset":"426325","integrity":{"algorithm":"SHA256","hash":"42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4","blockSize":4194304,"blocks":["42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4"]}},"if.js.map":{"size":2455,"offset":"428763","integrity":{"algorithm":"SHA256","hash":"ecf2c80d9856d1678e643d6f4c77a36cd7bec448594ec6034fb72b558fce8939","blockSize":4194304,"blocks":["ecf2c80d9856d1678e643d6f4c77a36cd7bec448594ec6034fb72b558fce8939"]}},"index.js":{"size":1529,"offset":"431218","integrity":{"algorithm":"SHA256","hash":"5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3","blockSize":4194304,"blocks":["5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3"]}},"index.js.map":{"size":766,"offset":"432747","integrity":{"algorithm":"SHA256","hash":"0b98845a246a8859fa44824daf69b40fe465f65075e2db2121aace15214dcf50","blockSize":4194304,"blocks":["0b98845a246a8859fa44824daf69b40fe465f65075e2db2121aace15214dcf50"]}},"items.js":{"size":1993,"offset":"433513","integrity":{"algorithm":"SHA256","hash":"fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e","blockSize":4194304,"blocks":["fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e"]}},"items.js.map":{"size":2052,"offset":"435506","integrity":{"algorithm":"SHA256","hash":"a20b4a4a1802ca7708a0e8bcbb69b3b604522eeab131008bae7e8490b87c434f","blockSize":4194304,"blocks":["a20b4a4a1802ca7708a0e8bcbb69b3b604522eeab131008bae7e8490b87c434f"]}},"items2020.js":{"size":1037,"offset":"437558","integrity":{"algorithm":"SHA256","hash":"c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f","blockSize":4194304,"blocks":["c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f"]}},"items2020.js.map":{"size":947,"offset":"438595","integrity":{"algorithm":"SHA256","hash":"8f28ef13b54491f634fbd00c89b87dab96f0e490e0065d5aeac3853345e906dc","blockSize":4194304,"blocks":["8f28ef13b54491f634fbd00c89b87dab96f0e490e0065d5aeac3853345e906dc"]}},"not.js":{"size":773,"offset":"439542","integrity":{"algorithm":"SHA256","hash":"ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718","blockSize":4194304,"blocks":["ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718"]}},"not.js.map":{"size":831,"offset":"440315","integrity":{"algorithm":"SHA256","hash":"c5b821f2b5cee147a5dbc645470a3528d1e87f3f9faa9f5a41cd353a075d60db","blockSize":4194304,"blocks":["c5b821f2b5cee147a5dbc645470a3528d1e87f3f9faa9f5a41cd353a075d60db"]}},"oneOf.js":{"size":2257,"offset":"441146","integrity":{"algorithm":"SHA256","hash":"e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2","blockSize":4194304,"blocks":["e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2"]}},"oneOf.js.map":{"size":2046,"offset":"443403","integrity":{"algorithm":"SHA256","hash":"ebab3ad34f13bc50265cb5ef9943beeef9f4e65c97a64533081da51d765dd526","blockSize":4194304,"blocks":["ebab3ad34f13bc50265cb5ef9943beeef9f4e65c97a64533081da51d765dd526"]}},"patternProperties.js":{"size":3236,"offset":"445449","integrity":{"algorithm":"SHA256","hash":"0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655","blockSize":4194304,"blocks":["0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655"]}},"patternProperties.js.map":{"size":2734,"offset":"448685","integrity":{"algorithm":"SHA256","hash":"a8103db59a1c72cd5fea553943b386d21f5544f40202cb1b1af7ef465142c8d1","blockSize":4194304,"blocks":["a8103db59a1c72cd5fea553943b386d21f5544f40202cb1b1af7ef465142c8d1"]}},"prefixItems.js":{"size":354,"offset":"451419","integrity":{"algorithm":"SHA256","hash":"16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23","blockSize":4194304,"blocks":["16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23"]}},"prefixItems.js.map":{"size":381,"offset":"451773","integrity":{"algorithm":"SHA256","hash":"1f3562cac09a9442410a3b01bdf1930bf4cbb3fc4840704c6c6327be37aec33c","blockSize":4194304,"blocks":["1f3562cac09a9442410a3b01bdf1930bf4cbb3fc4840704c6c6327be37aec33c"]}},"properties.js":{"size":2153,"offset":"452154","integrity":{"algorithm":"SHA256","hash":"c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f","blockSize":4194304,"blocks":["c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f"]}},"properties.js.map":{"size":2054,"offset":"454307","integrity":{"algorithm":"SHA256","hash":"33599345842c02b84401f6abc5b8df58023ffa180c148430a0e62d8eb2198ba3","blockSize":4194304,"blocks":["33599345842c02b84401f6abc5b8df58023ffa180c148430a0e62d8eb2198ba3"]}},"propertyNames.js":{"size":1221,"offset":"456361","integrity":{"algorithm":"SHA256","hash":"b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7","blockSize":4194304,"blocks":["b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7"]}},"propertyNames.js.map":{"size":1230,"offset":"457582","integrity":{"algorithm":"SHA256","hash":"a606f571bd198bcc4d9414887a57650669989bd0795181d07310e08a46aaec64","blockSize":4194304,"blocks":["a606f571bd198bcc4d9414887a57650669989bd0795181d07310e08a46aaec64"]}},"thenElse.js":{"size":446,"offset":"458812","integrity":{"algorithm":"SHA256","hash":"9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d","blockSize":4194304,"blocks":["9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d"]}},"thenElse.js.map":{"size":442,"offset":"459258","integrity":{"algorithm":"SHA256","hash":"474cff337e6d5c8ac35258cfc1b98d82367934b6d6a31bc261da7058e1008e4e","blockSize":4194304,"blocks":["474cff337e6d5c8ac35258cfc1b98d82367934b6d6a31bc261da7058e1008e4e"]}}}},"code.js":{"size":6216,"offset":"459700","integrity":{"algorithm":"SHA256","hash":"9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63","blockSize":4194304,"blocks":["9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63"]}},"code.js.map":{"size":6030,"offset":"465916","integrity":{"algorithm":"SHA256","hash":"1db25a8b2b7a34ad9d348246d6f849f61d4e29538a16ad6498d77b1c3497d534","blockSize":4194304,"blocks":["1db25a8b2b7a34ad9d348246d6f849f61d4e29538a16ad6498d77b1c3497d534"]}},"core":{"files":{"id.js":{"size":267,"offset":"471946","integrity":{"algorithm":"SHA256","hash":"49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11","blockSize":4194304,"blocks":["49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11"]}},"id.js.map":{"size":257,"offset":"472213","integrity":{"algorithm":"SHA256","hash":"fdeedb6446a7ddac6fc0dc0094bd70af32d00dc908ae2564f5519c45f6cd0897","blockSize":4194304,"blocks":["fdeedb6446a7ddac6fc0dc0094bd70af32d00dc908ae2564f5519c45f6cd0897"]}},"index.js":{"size":357,"offset":"472470","integrity":{"algorithm":"SHA256","hash":"f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e","blockSize":4194304,"blocks":["f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e"]}},"index.js.map":{"size":306,"offset":"472827","integrity":{"algorithm":"SHA256","hash":"47810777e556d4dfd64ed64eea5a9553e2c2ad632bac15944c8aafb75da4236d","blockSize":4194304,"blocks":["47810777e556d4dfd64ed64eea5a9553e2c2ad632bac15944c8aafb75da4236d"]}},"ref.js":{"size":5234,"offset":"473133","integrity":{"algorithm":"SHA256","hash":"1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1","blockSize":4194304,"blocks":["1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1"]}},"ref.js.map":{"size":5094,"offset":"478367","integrity":{"algorithm":"SHA256","hash":"102a133a0c29f09af757ac3715b3fe8d98b60d3651a8c288fc8aec35c51e4745","blockSize":4194304,"blocks":["102a133a0c29f09af757ac3715b3fe8d98b60d3651a8c288fc8aec35c51e4745"]}}}},"discriminator":{"files":{"index.js":{"size":4845,"offset":"483461","integrity":{"algorithm":"SHA256","hash":"b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e","blockSize":4194304,"blocks":["b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e"]}},"index.js.map":{"size":4243,"offset":"488306","integrity":{"algorithm":"SHA256","hash":"5dd1b53a8e69c78a9e4eaf155e5e6f9e3856814a529632403d6deecda6efc1b2","blockSize":4194304,"blocks":["5dd1b53a8e69c78a9e4eaf155e5e6f9e3856814a529632403d6deecda6efc1b2"]}},"types.js":{"size":308,"offset":"492549","integrity":{"algorithm":"SHA256","hash":"2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa","blockSize":4194304,"blocks":["2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa"]}},"types.js.map":{"size":239,"offset":"492857","integrity":{"algorithm":"SHA256","hash":"4ab17ff95b7fec251f810c0d2c7bf2d9814b9ec733134195b91df6cf11821eaa","blockSize":4194304,"blocks":["4ab17ff95b7fec251f810c0d2c7bf2d9814b9ec733134195b91df6cf11821eaa"]}}}},"draft2020.js":{"size":762,"offset":"493096","integrity":{"algorithm":"SHA256","hash":"2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445","blockSize":4194304,"blocks":["2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445"]}},"draft2020.js.map":{"size":419,"offset":"493858","integrity":{"algorithm":"SHA256","hash":"a45cb9b26d482a3a9018d4815ba277e409b83571c09c3a1065b9ba3390a7f891","blockSize":4194304,"blocks":["a45cb9b26d482a3a9018d4815ba277e409b83571c09c3a1065b9ba3390a7f891"]}},"draft7.js":{"size":557,"offset":"494277","integrity":{"algorithm":"SHA256","hash":"8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170","blockSize":4194304,"blocks":["8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170"]}},"draft7.js.map":{"size":328,"offset":"494834","integrity":{"algorithm":"SHA256","hash":"e556fccd950796d8b708fe1fa2aa8bcdc37ef037be9e3234be5297085d90cb62","blockSize":4194304,"blocks":["e556fccd950796d8b708fe1fa2aa8bcdc37ef037be9e3234be5297085d90cb62"]}},"dynamic":{"files":{"dynamicAnchor.js":{"size":1261,"offset":"495162","integrity":{"algorithm":"SHA256","hash":"78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7","blockSize":4194304,"blocks":["78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7"]}},"dynamicAnchor.js.map":{"size":1351,"offset":"496423","integrity":{"algorithm":"SHA256","hash":"a1a2f8ca7533601839749c902345c3001c95af3566eb30636eb6994d6bcfc0e7","blockSize":4194304,"blocks":["a1a2f8ca7533601839749c902345c3001c95af3566eb30636eb6994d6bcfc0e7"]}},"dynamicRef.js":{"size":1985,"offset":"497774","integrity":{"algorithm":"SHA256","hash":"acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917","blockSize":4194304,"blocks":["acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917"]}},"dynamicRef.js.map":{"size":1679,"offset":"499759","integrity":{"algorithm":"SHA256","hash":"4050eb882360e99c6a92d89a3c4f83e84f7f9df4d8e5c235ff9da9805d721a8f","blockSize":4194304,"blocks":["4050eb882360e99c6a92d89a3c4f83e84f7f9df4d8e5c235ff9da9805d721a8f"]}},"index.js":{"size":457,"offset":"501438","integrity":{"algorithm":"SHA256","hash":"8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b","blockSize":4194304,"blocks":["8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b"]}},"index.js.map":{"size":278,"offset":"501895","integrity":{"algorithm":"SHA256","hash":"cae8a099e83300e7e71269dcbd1918b399d9fe4e11d82ca1ddb59547ab962c14","blockSize":4194304,"blocks":["cae8a099e83300e7e71269dcbd1918b399d9fe4e11d82ca1ddb59547ab962c14"]}},"recursiveAnchor.js":{"size":522,"offset":"502173","integrity":{"algorithm":"SHA256","hash":"9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76","blockSize":4194304,"blocks":["9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76"]}},"recursiveAnchor.js.map":{"size":435,"offset":"502695","integrity":{"algorithm":"SHA256","hash":"14cfed1db7bb14734fd2d0d9dd4be341f16ef368d7890a90424e6646c1d0115f","blockSize":4194304,"blocks":["14cfed1db7bb14734fd2d0d9dd4be341f16ef368d7890a90424e6646c1d0115f"]}},"recursiveRef.js":{"size":325,"offset":"503130","integrity":{"algorithm":"SHA256","hash":"7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d","blockSize":4194304,"blocks":["7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d"]}},"recursiveRef.js.map":{"size":339,"offset":"503455","integrity":{"algorithm":"SHA256","hash":"aa22a9e7bdfce86b5eb802e6d806dc7d835d58a0dbc9165d72777206380ed7f6","blockSize":4194304,"blocks":["aa22a9e7bdfce86b5eb802e6d806dc7d835d58a0dbc9165d72777206380ed7f6"]}}}},"errors.js":{"size":111,"offset":"503794","integrity":{"algorithm":"SHA256","hash":"7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc","blockSize":4194304,"blocks":["7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc"]}},"errors.js.map":{"size":120,"offset":"503905","integrity":{"algorithm":"SHA256","hash":"d551cb2d686656a44924038afa1c337933a1e5f953a8e5f09837dc3895332675","blockSize":4194304,"blocks":["d551cb2d686656a44924038afa1c337933a1e5f953a8e5f09837dc3895332675"]}},"format":{"files":{"format.js":{"size":4317,"offset":"504025","integrity":{"algorithm":"SHA256","hash":"6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f","blockSize":4194304,"blocks":["6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f"]}},"format.js.map":{"size":3832,"offset":"508342","integrity":{"algorithm":"SHA256","hash":"35575d56b5d5b5140b5575388d6e8ab5cdc097123eabe8c1e1e2f6d742fffcc5","blockSize":4194304,"blocks":["35575d56b5d5b5140b5575388d6e8ab5cdc097123eabe8c1e1e2f6d742fffcc5"]}},"index.js":{"size":209,"offset":"512174","integrity":{"algorithm":"SHA256","hash":"d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67","blockSize":4194304,"blocks":["d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67"]}},"index.js.map":{"size":205,"offset":"512383","integrity":{"algorithm":"SHA256","hash":"ad27029bd96489edc361684b818651562c0ba5eb6a0484bc52bcbb178e16e68d","blockSize":4194304,"blocks":["ad27029bd96489edc361684b818651562c0ba5eb6a0484bc52bcbb178e16e68d"]}}}},"jtd":{"files":{"discriminator.js":{"size":2785,"offset":"512588","integrity":{"algorithm":"SHA256","hash":"14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2","blockSize":4194304,"blocks":["14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2"]}},"discriminator.js.map":{"size":2701,"offset":"515373","integrity":{"algorithm":"SHA256","hash":"c3b235680e571d21f99900ac5be4ce3457399b6881926dea7b1f36978e3ec848","blockSize":4194304,"blocks":["c3b235680e571d21f99900ac5be4ce3457399b6881926dea7b1f36978e3ec848"]}},"elements.js":{"size":949,"offset":"518074","integrity":{"algorithm":"SHA256","hash":"b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b","blockSize":4194304,"blocks":["b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b"]}},"elements.js.map":{"size":908,"offset":"519023","integrity":{"algorithm":"SHA256","hash":"2cfe04080ae8f1ff3a86805676dd57cb6e55134325d473fa36f57837d72eca05","blockSize":4194304,"blocks":["2cfe04080ae8f1ff3a86805676dd57cb6e55134325d473fa36f57837d72eca05"]}},"enum.js":{"size":1745,"offset":"519931","integrity":{"algorithm":"SHA256","hash":"4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154","blockSize":4194304,"blocks":["4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154"]}},"enum.js.map":{"size":1708,"offset":"521676","integrity":{"algorithm":"SHA256","hash":"87baba23c330e61539325d324acb2697c83a94e86e2902d2da3a08bc606230ff","blockSize":4194304,"blocks":["87baba23c330e61539325d324acb2697c83a94e86e2902d2da3a08bc606230ff"]}},"error.js":{"size":893,"offset":"523384","integrity":{"algorithm":"SHA256","hash":"d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9","blockSize":4194304,"blocks":["d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9"]}},"error.js.map":{"size":716,"offset":"524277","integrity":{"algorithm":"SHA256","hash":"4737604dbfbcf18ad231ff4188391cf349fc0238baa89062956fc56fa1703a6f","blockSize":4194304,"blocks":["4737604dbfbcf18ad231ff4188391cf349fc0238baa89062956fc56fa1703a6f"]}},"index.js":{"size":962,"offset":"524993","integrity":{"algorithm":"SHA256","hash":"c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d","blockSize":4194304,"blocks":["c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d"]}},"index.js.map":{"size":530,"offset":"525955","integrity":{"algorithm":"SHA256","hash":"31b17824ebfbdb2d2e7f5ae6835627153d57e8ebe801ba93988e4df2fea6f028","blockSize":4194304,"blocks":["31b17824ebfbdb2d2e7f5ae6835627153d57e8ebe801ba93988e4df2fea6f028"]}},"metadata.js":{"size":810,"offset":"526485","integrity":{"algorithm":"SHA256","hash":"237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68","blockSize":4194304,"blocks":["237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68"]}},"metadata.js.map":{"size":797,"offset":"527295","integrity":{"algorithm":"SHA256","hash":"b4815c6a53d59294b48ae16adb6bfa3f36a1052b2a23b3763124a8b27747c538","blockSize":4194304,"blocks":["b4815c6a53d59294b48ae16adb6bfa3f36a1052b2a23b3763124a8b27747c538"]}},"nullable.js":{"size":859,"offset":"528092","integrity":{"algorithm":"SHA256","hash":"ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a","blockSize":4194304,"blocks":["ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a"]}},"nullable.js.map":{"size":821,"offset":"528951","integrity":{"algorithm":"SHA256","hash":"4d28df1f7dbde477e3501ab0d049b5643b5e7911d59603ebb24161ba8ef00f08","blockSize":4194304,"blocks":["4d28df1f7dbde477e3501ab0d049b5643b5e7911d59603ebb24161ba8ef00f08"]}},"optionalProperties.js":{"size":436,"offset":"529772","integrity":{"algorithm":"SHA256","hash":"82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62","blockSize":4194304,"blocks":["82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62"]}},"optionalProperties.js.map":{"size":398,"offset":"530208","integrity":{"algorithm":"SHA256","hash":"58c1f7d7f168abe67793982f655adaef8b76937875373a26552c840c3812b898","blockSize":4194304,"blocks":["58c1f7d7f168abe67793982f655adaef8b76937875373a26552c840c3812b898"]}},"properties.js":{"size":6320,"offset":"530606","integrity":{"algorithm":"SHA256","hash":"4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35","blockSize":4194304,"blocks":["4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35"]}},"properties.js.map":{"size":5884,"offset":"536926","integrity":{"algorithm":"SHA256","hash":"7323488a259181201748b81e3c70628ef17842fdcc9ff917859240369d7f5380","blockSize":4194304,"blocks":["7323488a259181201748b81e3c70628ef17842fdcc9ff917859240369d7f5380"]}},"ref.js":{"size":2648,"offset":"542810","integrity":{"algorithm":"SHA256","hash":"4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460","blockSize":4194304,"blocks":["4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460"]}},"ref.js.map":{"size":2476,"offset":"545458","integrity":{"algorithm":"SHA256","hash":"1f76ab8797ae96dadfb9f03bb0c170d822417224ec2e395431cd0d0a51922001","blockSize":4194304,"blocks":["1f76ab8797ae96dadfb9f03bb0c170d822417224ec2e395431cd0d0a51922001"]}},"type.js":{"size":2706,"offset":"547934","integrity":{"algorithm":"SHA256","hash":"f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c","blockSize":4194304,"blocks":["f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c"]}},"type.js.map":{"size":2614,"offset":"550640","integrity":{"algorithm":"SHA256","hash":"8956607890334c9fd8eb242e2ae900c64e0c7ccc6879ce5f283fedadaa5e1fc2","blockSize":4194304,"blocks":["8956607890334c9fd8eb242e2ae900c64e0c7ccc6879ce5f283fedadaa5e1fc2"]}},"union.js":{"size":343,"offset":"553254","integrity":{"algorithm":"SHA256","hash":"f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280","blockSize":4194304,"blocks":["f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280"]}},"union.js.map":{"size":320,"offset":"553597","integrity":{"algorithm":"SHA256","hash":"53c59966c45cc6fb1276f8f933ea2f9fa79be5a91c2595a79d940c147abf5519","blockSize":4194304,"blocks":["53c59966c45cc6fb1276f8f933ea2f9fa79be5a91c2595a79d940c147abf5519"]}},"values.js":{"size":1838,"offset":"553917","integrity":{"algorithm":"SHA256","hash":"6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2","blockSize":4194304,"blocks":["6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2"]}},"values.js.map":{"size":1783,"offset":"555755","integrity":{"algorithm":"SHA256","hash":"0dc547866a1329dbe62fb89f961c74611069ad797639acce2def6a185e657c6a","blockSize":4194304,"blocks":["0dc547866a1329dbe62fb89f961c74611069ad797639acce2def6a185e657c6a"]}}}},"metadata.js":{"size":427,"offset":"557538","integrity":{"algorithm":"SHA256","hash":"45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609","blockSize":4194304,"blocks":["45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609"]}},"metadata.js.map":{"size":299,"offset":"557965","integrity":{"algorithm":"SHA256","hash":"7d888e73dee29bee063f1e98884e6a40386f5ee653a8ed6208e43b973a3542cd","blockSize":4194304,"blocks":["7d888e73dee29bee063f1e98884e6a40386f5ee653a8ed6208e43b973a3542cd"]}},"next.js":{"size":433,"offset":"558264","integrity":{"algorithm":"SHA256","hash":"491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7","blockSize":4194304,"blocks":["491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7"]}},"next.js.map":{"size":243,"offset":"558697","integrity":{"algorithm":"SHA256","hash":"79890db3838840ab79e117248e523f9d3c97742b042b02382326fb2bf14f0918","blockSize":4194304,"blocks":["79890db3838840ab79e117248e523f9d3c97742b042b02382326fb2bf14f0918"]}},"unevaluated":{"files":{"index.js":{"size":350,"offset":"558940","integrity":{"algorithm":"SHA256","hash":"4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4","blockSize":4194304,"blocks":["4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4"]}},"index.js.map":{"size":236,"offset":"559290","integrity":{"algorithm":"SHA256","hash":"8a4aff71617048ad134ff9d6773270168595b0268c5330d8450b90e71496f8be","blockSize":4194304,"blocks":["8a4aff71617048ad134ff9d6773270168595b0268c5330d8450b90e71496f8be"]}},"unevaluatedItems.js":{"size":1588,"offset":"559526","integrity":{"algorithm":"SHA256","hash":"4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda","blockSize":4194304,"blocks":["4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda"]}},"unevaluatedItems.js.map":{"size":1813,"offset":"561114","integrity":{"algorithm":"SHA256","hash":"03ade2a02a69c0b0bad0dbe74d70964daab47a65f5d4796cdb927edd00c06ec8","blockSize":4194304,"blocks":["03ade2a02a69c0b0bad0dbe74d70964daab47a65f5d4796cdb927edd00c06ec8"]}},"unevaluatedProperties.js":{"size":2608,"offset":"562927","integrity":{"algorithm":"SHA256","hash":"665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe","blockSize":4194304,"blocks":["665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe"]}},"unevaluatedProperties.js.map":{"size":2518,"offset":"565535","integrity":{"algorithm":"SHA256","hash":"7eea70788f708b843fa81cecb7c90aef4ae473b2cb5f5cf9f3229d1025fcffc0","blockSize":4194304,"blocks":["7eea70788f708b843fa81cecb7c90aef4ae473b2cb5f5cf9f3229d1025fcffc0"]}}}},"validation":{"files":{"const.js":{"size":852,"offset":"568053","integrity":{"algorithm":"SHA256","hash":"ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a","blockSize":4194304,"blocks":["ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a"]}},"const.js.map":{"size":819,"offset":"568905","integrity":{"algorithm":"SHA256","hash":"5f9e6e0702178bf1ce990751be7fb9369403af96e7f724bc361da8c27b16d8ea","blockSize":4194304,"blocks":["5f9e6e0702178bf1ce990751be7fb9369403af96e7f724bc361da8c27b16d8ea"]}},"dependentRequired.js":{"size":403,"offset":"569724","integrity":{"algorithm":"SHA256","hash":"cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa","blockSize":4194304,"blocks":["cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa"]}},"dependentRequired.js.map":{"size":376,"offset":"570127","integrity":{"algorithm":"SHA256","hash":"62fd57bce66b2b2cffa208b30e7dab00011936f05ae2a5b075c04461663e06a4","blockSize":4194304,"blocks":["62fd57bce66b2b2cffa208b30e7dab00011936f05ae2a5b075c04461663e06a4"]}},"enum.js":{"size":1901,"offset":"570503","integrity":{"algorithm":"SHA256","hash":"61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22","blockSize":4194304,"blocks":["61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22"]}},"enum.js.map":{"size":1999,"offset":"572404","integrity":{"algorithm":"SHA256","hash":"3d74c4a70ce905cb4c07c75fededfb51d7124e683cf4ce394e89835fad8b1a2b","blockSize":4194304,"blocks":["3d74c4a70ce905cb4c07c75fededfb51d7124e683cf4ce394e89835fad8b1a2b"]}},"index.js":{"size":1036,"offset":"574403","integrity":{"algorithm":"SHA256","hash":"4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4","blockSize":4194304,"blocks":["4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4"]}},"index.js.map":{"size":595,"offset":"575439","integrity":{"algorithm":"SHA256","hash":"42fce077fc1751290cef9a3b2e48546262724d61f91d44751e6e4075ce159ed4","blockSize":4194304,"blocks":["42fce077fc1751290cef9a3b2e48546262724d61f91d44751e6e4075ce159ed4"]}},"limitContains.js":{"size":495,"offset":"576034","integrity":{"algorithm":"SHA256","hash":"0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d","blockSize":4194304,"blocks":["0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d"]}},"limitContains.js.map":{"size":473,"offset":"576529","integrity":{"algorithm":"SHA256","hash":"56076461ebadbfbbd25cf53a8eaf5e61368f325443f6fe8e6ed9bea5d7b24445","blockSize":4194304,"blocks":["56076461ebadbfbbd25cf53a8eaf5e61368f325443f6fe8e6ed9bea5d7b24445"]}},"limitItems.js":{"size":852,"offset":"577002","integrity":{"algorithm":"SHA256","hash":"49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec","blockSize":4194304,"blocks":["49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec"]}},"limitItems.js.map":{"size":905,"offset":"577854","integrity":{"algorithm":"SHA256","hash":"4d8e8e8f64bd85fab47be9c03276d23d52421b18cdabe2962c8cac38d5109459","blockSize":4194304,"blocks":["4d8e8e8f64bd85fab47be9c03276d23d52421b18cdabe2962c8cac38d5109459"]}},"limitLength.js":{"size":1130,"offset":"578759","integrity":{"algorithm":"SHA256","hash":"379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2","blockSize":4194304,"blocks":["379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2"]}},"limitLength.js.map":{"size":1145,"offset":"579889","integrity":{"algorithm":"SHA256","hash":"bc33ca19aa1613710c361b334d5387a178441fb79f368898dcdce1d8075f54f5","blockSize":4194304,"blocks":["bc33ca19aa1613710c361b334d5387a178441fb79f368898dcdce1d8075f54f5"]}},"limitNumber.js":{"size":1036,"offset":"581034","integrity":{"algorithm":"SHA256","hash":"3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65","blockSize":4194304,"blocks":["3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65"]}},"limitNumber.js.map":{"size":1300,"offset":"582070","integrity":{"algorithm":"SHA256","hash":"8fb0880eb5eba874c7424e9b5f4c6f14a436330a471e0c791b39248e1abf2d9f","blockSize":4194304,"blocks":["8fb0880eb5eba874c7424e9b5f4c6f14a436330a471e0c791b39248e1abf2d9f"]}},"limitProperties.js":{"size":896,"offset":"583370","integrity":{"algorithm":"SHA256","hash":"8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac","blockSize":4194304,"blocks":["8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac"]}},"limitProperties.js.map":{"size":915,"offset":"584266","integrity":{"algorithm":"SHA256","hash":"0d819ad8104004b82be28bb3e86c96eefbff850e0fc1bd21bf43678a17a2ebfa","blockSize":4194304,"blocks":["0d819ad8104004b82be28bb3e86c96eefbff850e0fc1bd21bf43678a17a2ebfa"]}},"multipleOf.js":{"size":1023,"offset":"585181","integrity":{"algorithm":"SHA256","hash":"df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd","blockSize":4194304,"blocks":["df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd"]}},"multipleOf.js.map":{"size":986,"offset":"586204","integrity":{"algorithm":"SHA256","hash":"ff3ca557d3ed080cc3397829b9641b11764118afa8ce3c97ec2f6f47ae0c8c69","blockSize":4194304,"blocks":["ff3ca557d3ed080cc3397829b9641b11764118afa8ce3c97ec2f6f47ae0c8c69"]}},"pattern.js":{"size":1323,"offset":"587190","integrity":{"algorithm":"SHA256","hash":"86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195","blockSize":4194304,"blocks":["86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195"]}},"pattern.js.map":{"size":1449,"offset":"588513","integrity":{"algorithm":"SHA256","hash":"87277c96cf32b25da6e01a4ef46f202f741872a43f360af2838d209e114f5d77","blockSize":4194304,"blocks":["87277c96cf32b25da6e01a4ef46f202f741872a43f360af2838d209e114f5d77"]}},"required.js":{"size":3188,"offset":"589962","integrity":{"algorithm":"SHA256","hash":"b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054","blockSize":4194304,"blocks":["b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054"]}},"required.js.map":{"size":2994,"offset":"593150","integrity":{"algorithm":"SHA256","hash":"93e4965462fa0e78f52e96498550ce19eca50f70872ffae95baeb4b59e66b1bd","blockSize":4194304,"blocks":["93e4965462fa0e78f52e96498550ce19eca50f70872ffae95baeb4b59e66b1bd"]}},"uniqueItems.js":{"size":3037,"offset":"596144","integrity":{"algorithm":"SHA256","hash":"666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52","blockSize":4194304,"blocks":["666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52"]}},"uniqueItems.js.map":{"size":3354,"offset":"599181","integrity":{"algorithm":"SHA256","hash":"ca96cb4269f0665b48201bbd3bf767583b2d337cc6bfd1f8e3135c54c09780b5","blockSize":4194304,"blocks":["ca96cb4269f0665b48201bbd3bf767583b2d337cc6bfd1f8e3135c54c09780b5"]}}}}}}}},"lib":{"files":{"2019.ts":{"size":2502,"offset":"602535","integrity":{"algorithm":"SHA256","hash":"d56766ac02c001a4f808c99281e466c4ed004118169e1d93b1b383dbe8ebfdbc","blockSize":4194304,"blocks":["d56766ac02c001a4f808c99281e466c4ed004118169e1d93b1b383dbe8ebfdbc"]}},"2020.ts":{"size":2217,"offset":"605037","integrity":{"algorithm":"SHA256","hash":"0172fbdd0f09d7cec4243374ef3148da91ac504b436c1b058bbb482fdb1ad603","blockSize":4194304,"blocks":["0172fbdd0f09d7cec4243374ef3148da91ac504b436c1b058bbb482fdb1ad603"]}},"ajv.ts":{"size":2229,"offset":"607254","integrity":{"algorithm":"SHA256","hash":"db86e7216e623df616513e1191e428b8d73c9f2cb1a36720fff0f12003d22a85","blockSize":4194304,"blocks":["db86e7216e623df616513e1191e428b8d73c9f2cb1a36720fff0f12003d22a85"]}},"compile":{"files":{"codegen":{"files":{"code.ts":{"size":4474,"offset":"609483","integrity":{"algorithm":"SHA256","hash":"3e088cc949e98ccef11611d64f11b3035182c257dd055587f3cc3081b59b8f85","blockSize":4194304,"blocks":["3e088cc949e98ccef11611d64f11b3035182c257dd055587f3cc3081b59b8f85"]}},"index.ts":{"size":23051,"offset":"613957","integrity":{"algorithm":"SHA256","hash":"5d36911057430b7beedd1acf8026afb6529a09bf8b974c47d68d9a72be252ea6","blockSize":4194304,"blocks":["5d36911057430b7beedd1acf8026afb6529a09bf8b974c47d68d9a72be252ea6"]}},"scope.ts":{"size":5981,"offset":"637008","integrity":{"algorithm":"SHA256","hash":"a4cc6bc51633c0a67e09d61926a769a4d805f13931fd3541957a8e80d2b86a16","blockSize":4194304,"blocks":["a4cc6bc51633c0a67e09d61926a769a4d805f13931fd3541957a8e80d2b86a16"]}}}},"errors.ts":{"size":5269,"offset":"642989","integrity":{"algorithm":"SHA256","hash":"088cd10b6fb1e7ee6fde64d791f17d06f9b79cb126c35f98ae02cffafec44480","blockSize":4194304,"blocks":["088cd10b6fb1e7ee6fde64d791f17d06f9b79cb126c35f98ae02cffafec44480"]}},"index.ts":{"size":12299,"offset":"648258","integrity":{"algorithm":"SHA256","hash":"fd39c4872a98fd27d899345d92da8b5e9c92a3b311a9f91e156080349f85c869","blockSize":4194304,"blocks":["fd39c4872a98fd27d899345d92da8b5e9c92a3b311a9f91e156080349f85c869"]}},"jtd":{"files":{"parse.ts":{"size":12345,"offset":"660557","integrity":{"algorithm":"SHA256","hash":"3f987db29f450b9463fc64a2d594325d21155d3e7934a143ab1a744ce0d7ecd6","blockSize":4194304,"blocks":["3f987db29f450b9463fc64a2d594325d21155d3e7934a143ab1a744ce0d7ecd6"]}},"serialize.ts":{"size":8573,"offset":"672902","integrity":{"algorithm":"SHA256","hash":"f523467687cad8197f51828d97dba711087fd7fb7447626a672823fcc227f6b7","blockSize":4194304,"blocks":["f523467687cad8197f51828d97dba711087fd7fb7447626a672823fcc227f6b7"]}},"types.ts":{"size":311,"offset":"681475","integrity":{"algorithm":"SHA256","hash":"4f9a151d6cb7028d5eb483a2f0aab17a2f8a411b0af6b48108712cf6448b0822","blockSize":4194304,"blocks":["4f9a151d6cb7028d5eb483a2f0aab17a2f8a411b0af6b48108712cf6448b0822"]}}}},"names.ts":{"size":1116,"offset":"681786","integrity":{"algorithm":"SHA256","hash":"7e985cf51593c03cfac0317c9cceecddc70ab630673a3f5af739885255b2be64","blockSize":4194304,"blocks":["7e985cf51593c03cfac0317c9cceecddc70ab630673a3f5af739885255b2be64"]}},"ref_error.ts":{"size":513,"offset":"682902","integrity":{"algorithm":"SHA256","hash":"1a3246eb3a9a09e185099600b550185a5fe84b22e27d854ddc7273d5e35315ac","blockSize":4194304,"blocks":["1a3246eb3a9a09e185099600b550185a5fe84b22e27d854ddc7273d5e35315ac"]}},"resolve.ts":{"size":4674,"offset":"683415","integrity":{"algorithm":"SHA256","hash":"83fa181288f15f4be781fe8baa6735fcfee169efbf3f7710a86a50c6cac5acb5","blockSize":4194304,"blocks":["83fa181288f15f4be781fe8baa6735fcfee169efbf3f7710a86a50c6cac5acb5"]}},"rules.ts":{"size":1456,"offset":"688089","integrity":{"algorithm":"SHA256","hash":"d736019109db360c5bb5d5fb12132a0d518ff3c01238c93b8f317a2879cbdf85","blockSize":4194304,"blocks":["d736019109db360c5bb5d5fb12132a0d518ff3c01238c93b8f317a2879cbdf85"]}},"util.ts":{"size":6639,"offset":"689545","integrity":{"algorithm":"SHA256","hash":"2f9441df72d2d7996f90403f5f31d6d156036a9e8e39a773a3e52812462dbcad","blockSize":4194304,"blocks":["2f9441df72d2d7996f90403f5f31d6d156036a9e8e39a773a3e52812462dbcad"]}},"validate":{"files":{"applicability.ts":{"size":739,"offset":"696184","integrity":{"algorithm":"SHA256","hash":"22a43ed9cc6d17524013990d049d96494db39c95f1122e103c01dfc87a820497","blockSize":4194304,"blocks":["22a43ed9cc6d17524013990d049d96494db39c95f1122e103c01dfc87a820497"]}},"boolSchema.ts":{"size":1298,"offset":"696923","integrity":{"algorithm":"SHA256","hash":"e5c41cd20170d246d1d40ac54bf7df4cbef084238d27f2a8d69faa2d597600cf","blockSize":4194304,"blocks":["e5c41cd20170d246d1d40ac54bf7df4cbef084238d27f2a8d69faa2d597600cf"]}},"dataType.ts":{"size":7094,"offset":"698221","integrity":{"algorithm":"SHA256","hash":"37adffaf46b9648699ea8b08a3caf6d5d031de027b955dd5f69ad2a72e7f03e3","blockSize":4194304,"blocks":["37adffaf46b9648699ea8b08a3caf6d5d031de027b955dd5f69ad2a72e7f03e3"]}},"defaults.ts":{"size":1215,"offset":"705315","integrity":{"algorithm":"SHA256","hash":"8ae3dec515bbf81721af940ed1ca3ff1edbbb5e2c24187f441822c89e3925c27","blockSize":4194304,"blocks":["8ae3dec515bbf81721af940ed1ca3ff1edbbb5e2c24187f441822c89e3925c27"]}},"index.ts":{"size":19445,"offset":"706530","integrity":{"algorithm":"SHA256","hash":"841338dea0ff90d44bde71f0651879edad186fd50d7bb6d03243b0085e557c48","blockSize":4194304,"blocks":["841338dea0ff90d44bde71f0651879edad186fd50d7bb6d03243b0085e557c48"]}},"keyword.ts":{"size":5337,"offset":"725975","integrity":{"algorithm":"SHA256","hash":"83e14ccb96fb8e24bb81af1c0d12a724472f713faf5ff2af2a8fd1be43da273f","blockSize":4194304,"blocks":["83e14ccb96fb8e24bb81af1c0d12a724472f713faf5ff2af2a8fd1be43da273f"]}},"subschema.ts":{"size":4366,"offset":"731312","integrity":{"algorithm":"SHA256","hash":"79eb0fbb091074cdbc7149f3fe6bf0c174f76f53f82cf90f346285505eb4113e","blockSize":4194304,"blocks":["79eb0fbb091074cdbc7149f3fe6bf0c174f76f53f82cf90f346285505eb4113e"]}}}}}},"core.ts":{"size":30790,"offset":"735678","integrity":{"algorithm":"SHA256","hash":"c9a2785949f4ba6dbe26c536a95437f38cf688cf74301666c8a33a816ae5030d","blockSize":4194304,"blocks":["c9a2785949f4ba6dbe26c536a95437f38cf688cf74301666c8a33a816ae5030d"]}},"jtd.ts":{"size":4172,"offset":"766468","integrity":{"algorithm":"SHA256","hash":"e7157f96fc310c1488fdc78d12c6c33f3064d23859049e5d1fffa0a21d57f262","blockSize":4194304,"blocks":["e7157f96fc310c1488fdc78d12c6c33f3064d23859049e5d1fffa0a21d57f262"]}},"refs":{"files":{"data.json":{"size":409,"offset":"770640","integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]}},"json-schema-2019-09":{"files":{"index.ts":{"size":899,"offset":"771049","integrity":{"algorithm":"SHA256","hash":"b0650c20759d7c19f624f1a7c8f3688eb7833a9ff964598dc0d4513e685d6b8d","blockSize":4194304,"blocks":["b0650c20759d7c19f624f1a7c8f3688eb7833a9ff964598dc0d4513e685d6b8d"]}},"meta":{"files":{"applicator.json":{"size":1566,"offset":"771948","integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]}},"content.json":{"size":477,"offset":"773514","integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]}},"core.json":{"size":1273,"offset":"773991","integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]}},"format.json":{"size":375,"offset":"775264","integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]}},"meta-data.json":{"size":758,"offset":"775639","integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]}},"validation.json":{"size":2264,"offset":"776397","integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]}}}},"schema.json":{"size":1579,"offset":"778661","integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]}}}},"json-schema-2020-12":{"files":{"index.ts":{"size":982,"offset":"780240","integrity":{"algorithm":"SHA256","hash":"9c4f608142c423538ffee89094935d3dede32664a1fc47c3cb4b248550946000","blockSize":4194304,"blocks":["9c4f608142c423538ffee89094935d3dede32664a1fc47c3cb4b248550946000"]}},"meta":{"files":{"applicator.json":{"size":1441,"offset":"781222","integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]}},"content.json":{"size":479,"offset":"782663","integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]}},"core.json":{"size":1344,"offset":"783142","integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]}},"format-annotation.json":{"size":420,"offset":"784486","integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]}},"meta-data.json":{"size":758,"offset":"784906","integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]}},"unevaluated.json":{"size":472,"offset":"785664","integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]}},"validation.json":{"size":2264,"offset":"786136","integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]}}}},"schema.json":{"size":2166,"offset":"788400","integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]}}}},"json-schema-draft-06.json":{"size":3449,"offset":"790566","integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]}},"json-schema-draft-07.json":{"size":3811,"offset":"794015","integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]}},"json-schema-secure.json":{"size":2521,"offset":"797826","integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]}},"jtd-schema.ts":{"size":2586,"offset":"800347","integrity":{"algorithm":"SHA256","hash":"76b788839e3f26ccbb073309b452595482714f2105295d009145d7b79e336003","blockSize":4194304,"blocks":["76b788839e3f26ccbb073309b452595482714f2105295d009145d7b79e336003"]}}}},"runtime":{"files":{"equal.ts":{"size":236,"offset":"802933","integrity":{"algorithm":"SHA256","hash":"013de4ec7e4006015ef49ec787737636dc048a913aad0922295fc8b0eb15aa10","blockSize":4194304,"blocks":["013de4ec7e4006015ef49ec787737636dc048a913aad0922295fc8b0eb15aa10"]}},"parseJson.ts":{"size":4553,"offset":"803169","integrity":{"algorithm":"SHA256","hash":"79d1f9a5ae035324c73d85f146c00c19714f73a61d822470a12d28edd6be0fd5","blockSize":4194304,"blocks":["79d1f9a5ae035324c73d85f146c00c19714f73a61d822470a12d28edd6be0fd5"]}},"quote.ts":{"size":802,"offset":"807722","integrity":{"algorithm":"SHA256","hash":"b87b625e0ca6a17d96c7af7999b7eaacc956c4265a49b54877d8fa9de295c1e3","blockSize":4194304,"blocks":["b87b625e0ca6a17d96c7af7999b7eaacc956c4265a49b54877d8fa9de295c1e3"]}},"re2.ts":{"size":157,"offset":"808524","integrity":{"algorithm":"SHA256","hash":"10841997f170df64628a12998362f97dec5052d06495a20ad72f725bd1bac2e7","blockSize":4194304,"blocks":["10841997f170df64628a12998362f97dec5052d06495a20ad72f725bd1bac2e7"]}},"timestamp.ts":{"size":1492,"offset":"808681","integrity":{"algorithm":"SHA256","hash":"08509863a735667f2b8c5fb68d92f318947bd975cdf2a230ede606af96a8fbd4","blockSize":4194304,"blocks":["08509863a735667f2b8c5fb68d92f318947bd975cdf2a230ede606af96a8fbd4"]}},"ucs2length.ts":{"size":629,"offset":"810173","integrity":{"algorithm":"SHA256","hash":"a001c95dd2e835b9c61080254c117f02d425eb6760bd2c1d682ab63ed00d12f6","blockSize":4194304,"blocks":["a001c95dd2e835b9c61080254c117f02d425eb6760bd2c1d682ab63ed00d12f6"]}},"uri.ts":{"size":162,"offset":"810802","integrity":{"algorithm":"SHA256","hash":"4723aa43822e1cf2291029fe9038f317cca49ee685f59b2e48eb154f716a8edb","blockSize":4194304,"blocks":["4723aa43822e1cf2291029fe9038f317cca49ee685f59b2e48eb154f716a8edb"]}},"validation_error.ts":{"size":336,"offset":"810964","integrity":{"algorithm":"SHA256","hash":"abf8375d3a5d74512cc4d229e4839cf03b84d2e3904804401ca83cf7639e0a64","blockSize":4194304,"blocks":["abf8375d3a5d74512cc4d229e4839cf03b84d2e3904804401ca83cf7639e0a64"]}}}},"standalone":{"files":{"index.ts":{"size":4151,"offset":"811300","integrity":{"algorithm":"SHA256","hash":"3509ccea2b4677c04074ccb9f6335ef63d36f183349d4c026dacc95928d096ed","blockSize":4194304,"blocks":["3509ccea2b4677c04074ccb9f6335ef63d36f183349d4c026dacc95928d096ed"]}},"instance.ts":{"size":1272,"offset":"815451","integrity":{"algorithm":"SHA256","hash":"9fa1decae4056176ce7104da136af90419078307baafaeee947740e02eb4fc82","blockSize":4194304,"blocks":["9fa1decae4056176ce7104da136af90419078307baafaeee947740e02eb4fc82"]}}}},"types":{"files":{"index.ts":{"size":7289,"offset":"816723","integrity":{"algorithm":"SHA256","hash":"3cf1bd15564b691784b1bce4c6fa4223c0a3a8bde7b10d98270d7c66146aefa8","blockSize":4194304,"blocks":["3cf1bd15564b691784b1bce4c6fa4223c0a3a8bde7b10d98270d7c66146aefa8"]}},"json-schema.ts":{"size":6380,"offset":"824012","integrity":{"algorithm":"SHA256","hash":"4ccc0e648873df7580bb66a9d2e908604ddd96c69a88246dda60f5539e10bed8","blockSize":4194304,"blocks":["4ccc0e648873df7580bb66a9d2e908604ddd96c69a88246dda60f5539e10bed8"]}},"jtd-schema.ts":{"size":9321,"offset":"830392","integrity":{"algorithm":"SHA256","hash":"1c537a703005dbdf394539f58432861dae5135fddae6f54cebb28ae0f26f3d42","blockSize":4194304,"blocks":["1c537a703005dbdf394539f58432861dae5135fddae6f54cebb28ae0f26f3d42"]}}}},"vocabularies":{"files":{"applicator":{"files":{"additionalItems.ts":{"size":1824,"offset":"839713","integrity":{"algorithm":"SHA256","hash":"0593c60f31db5cea9022a353e56fd3066a8dac4e35607affb4e556d4d84c3f2a","blockSize":4194304,"blocks":["0593c60f31db5cea9022a353e56fd3066a8dac4e35607affb4e556d4d84c3f2a"]}},"additionalProperties.ts":{"size":3782,"offset":"841537","integrity":{"algorithm":"SHA256","hash":"1ea5e25fd12131cae2278b7fc4fda354dad5a60d65234b67aaa09adf10268f55","blockSize":4194304,"blocks":["1ea5e25fd12131cae2278b7fc4fda354dad5a60d65234b67aaa09adf10268f55"]}},"allOf.ts":{"size":717,"offset":"845319","integrity":{"algorithm":"SHA256","hash":"cce43c2f5c51e2c1f40d9e773d052fc9e73beb775c5d6c0ae93e0bdb5a2a32fa","blockSize":4194304,"blocks":["cce43c2f5c51e2c1f40d9e773d052fc9e73beb775c5d6c0ae93e0bdb5a2a32fa"]}},"anyOf.ts":{"size":380,"offset":"846036","integrity":{"algorithm":"SHA256","hash":"2449024f686a1d8d51dc414849ae039465406adcf7ba04565d8ad2ba7448f594","blockSize":4194304,"blocks":["2449024f686a1d8d51dc414849ae039465406adcf7ba04565d8ad2ba7448f594"]}},"contains.ts":{"size":3278,"offset":"846416","integrity":{"algorithm":"SHA256","hash":"731c74710381d5484725d7e2bfa97e1f809a495ddae9bd0226a7c91578aeef05","blockSize":4194304,"blocks":["731c74710381d5484725d7e2bfa97e1f809a495ddae9bd0226a7c91578aeef05"]}},"dependencies.ts":{"size":3391,"offset":"849694","integrity":{"algorithm":"SHA256","hash":"d2e648e8fe45621558c8f14ff5684954a91f6d800d1b2bf3d90f43941c84df65","blockSize":4194304,"blocks":["d2e648e8fe45621558c8f14ff5684954a91f6d800d1b2bf3d90f43941c84df65"]}},"dependentSchemas.ts":{"size":280,"offset":"853085","integrity":{"algorithm":"SHA256","hash":"ba8f82eb99b70d5e128c69719a15a703f3b5b95844923487fd8d12c5015200cc","blockSize":4194304,"blocks":["ba8f82eb99b70d5e128c69719a15a703f3b5b95844923487fd8d12c5015200cc"]}},"if.ts":{"size":2395,"offset":"853365","integrity":{"algorithm":"SHA256","hash":"676949dae0592465efcfdb3f15c8700fcc5e0b95bf0674c3b8723acbf2c3285f","blockSize":4194304,"blocks":["676949dae0592465efcfdb3f15c8700fcc5e0b95bf0674c3b8723acbf2c3285f"]}},"index.ts":{"size":1592,"offset":"855760","integrity":{"algorithm":"SHA256","hash":"85f01326e6589c9b0a8cc38939ac0520c5d213d55f6fefe2a9c23c7bdea680f6","blockSize":4194304,"blocks":["85f01326e6589c9b0a8cc38939ac0520c5d213d55f6fefe2a9c23c7bdea680f6"]}},"items.ts":{"size":1892,"offset":"857352","integrity":{"algorithm":"SHA256","hash":"9ccc7f93f03988881f366885fd3cc1a1490f36712b7932f3735f2f72136990e3","blockSize":4194304,"blocks":["9ccc7f93f03988881f366885fd3cc1a1490f36712b7932f3735f2f72136990e3"]}},"items2020.ts":{"size":1053,"offset":"859244","integrity":{"algorithm":"SHA256","hash":"939a853b1f7b3a1ba3907453435dac558d11ba5c059ffc02c87107871ed2a668","blockSize":4194304,"blocks":["939a853b1f7b3a1ba3907453435dac558d11ba5c059ffc02c87107871ed2a668"]}},"not.ts":{"size":859,"offset":"860297","integrity":{"algorithm":"SHA256","hash":"a458fd0c8a2386906e5e55a2095c6176dc02dcfa19e13ec4ba775b51e2b56971","blockSize":4194304,"blocks":["a458fd0c8a2386906e5e55a2095c6176dc02dcfa19e13ec4ba775b51e2b56971"]}},"oneOf.ts":{"size":2197,"offset":"861156","integrity":{"algorithm":"SHA256","hash":"ec3681fffbe66ae13befecacc4a400b3986b7819846b8e264320c189eff31ad0","blockSize":4194304,"blocks":["ec3681fffbe66ae13befecacc4a400b3986b7819846b8e264320c189eff31ad0"]}},"patternProperties.ts":{"size":2870,"offset":"863353","integrity":{"algorithm":"SHA256","hash":"80cb5e80c22228e2ce276b0703627f9057e40993b431a063a93abad5f92c3f75","blockSize":4194304,"blocks":["80cb5e80c22228e2ce276b0703627f9057e40993b431a063a93abad5f92c3f75"]}},"prefixItems.ts":{"size":292,"offset":"866223","integrity":{"algorithm":"SHA256","hash":"ddddd4d635a17c56713d8938e78a7dc0c7688044ce1a5de033a6fd8e8ff96b0b","blockSize":4194304,"blocks":["ddddd4d635a17c56713d8938e78a7dc0c7688044ce1a5de033a6fd8e8ff96b0b"]}},"properties.ts":{"size":1845,"offset":"866515","integrity":{"algorithm":"SHA256","hash":"76cd23a45c08a679f196d61e5b937e2a4361c92d9fc958a72d47ebc7efdba1f1","blockSize":4194304,"blocks":["76cd23a45c08a679f196d61e5b937e2a4361c92d9fc958a72d47ebc7efdba1f1"]}},"propertyNames.ts":{"size":1247,"offset":"868360","integrity":{"algorithm":"SHA256","hash":"ab1b80a1a99dbf16578091b96b1347fda8f0177bfdee7ddbec161af54d01fa8f","blockSize":4194304,"blocks":["ab1b80a1a99dbf16578091b96b1347fda8f0177bfdee7ddbec161af54d01fa8f"]}},"thenElse.ts":{"size":441,"offset":"869607","integrity":{"algorithm":"SHA256","hash":"29a4fc78180fa88c422b01d2168c29087235238a2516d4c1800542503b5060e4","blockSize":4194304,"blocks":["29a4fc78180fa88c422b01d2168c29087235238a2516d4c1800542503b5060e4"]}}}},"code.ts":{"size":5247,"offset":"870048","integrity":{"algorithm":"SHA256","hash":"f4bf46f24e44512addfc8b34e8ef1cd6320025236839e176deb59ee8b20c7ee7","blockSize":4194304,"blocks":["f4bf46f24e44512addfc8b34e8ef1cd6320025236839e176deb59ee8b20c7ee7"]}},"core":{"files":{"id.ts":{"size":224,"offset":"875295","integrity":{"algorithm":"SHA256","hash":"241606f9c18746cb35cb74c728c6d972bd6100edad70692bb27f841ac8b1b4b1","blockSize":4194304,"blocks":["241606f9c18746cb35cb74c728c6d972bd6100edad70692bb27f841ac8b1b4b1"]}},"index.ts":{"size":274,"offset":"875519","integrity":{"algorithm":"SHA256","hash":"43e089e25baac37f7665f0451e51956ec154f60a058b83f86cc3e577ab800f62","blockSize":4194304,"blocks":["43e089e25baac37f7665f0451e51956ec154f60a058b83f86cc3e577ab800f62"]}},"ref.ts":{"size":4384,"offset":"875793","integrity":{"algorithm":"SHA256","hash":"0d932d49ef57d32449923e5687e57715f4d08252f749d34d1d9410e8f88711f8","blockSize":4194304,"blocks":["0d932d49ef57d32449923e5687e57715f4d08252f749d34d1d9410e8f88711f8"]}}}},"discriminator":{"files":{"index.ts":{"size":4304,"offset":"880177","integrity":{"algorithm":"SHA256","hash":"9b89f8b9ab15e49b326bb3505424a1c0cd234397bf7db13a80e74e627fc381a3","blockSize":4194304,"blocks":["9b89f8b9ab15e49b326bb3505424a1c0cd234397bf7db13a80e74e627fc381a3"]}},"types.ts":{"size":251,"offset":"884481","integrity":{"algorithm":"SHA256","hash":"537bcd41ac270d1a43417d742a1f9f55b319e6f213323f6b00edfbe38e88e7da","blockSize":4194304,"blocks":["537bcd41ac270d1a43417d742a1f9f55b319e6f213323f6b00edfbe38e88e7da"]}}}},"draft2020.ts":{"size":698,"offset":"884732","integrity":{"algorithm":"SHA256","hash":"840c49657713cbbd6467274f270c77bf16a7ed8b3aedbee6bb5c587550282aea","blockSize":4194304,"blocks":["840c49657713cbbd6467274f270c77bf16a7ed8b3aedbee6bb5c587550282aea"]}},"draft7.ts":{"size":496,"offset":"885430","integrity":{"algorithm":"SHA256","hash":"9f8fd4fa8b2084b4cae951badc68de3a361e01eea06a158d530c4d55e92b5fb4","blockSize":4194304,"blocks":["9f8fd4fa8b2084b4cae951badc68de3a361e01eea06a158d530c4d55e92b5fb4"]}},"dynamic":{"files":{"dynamicAnchor.ts":{"size":1122,"offset":"885926","integrity":{"algorithm":"SHA256","hash":"bc8bb7636e8fff1add5d8c36577978f357731c2877fd4d4c59b620d6a8af1d8f","blockSize":4194304,"blocks":["bc8bb7636e8fff1add5d8c36577978f357731c2877fd4d4c59b620d6a8af1d8f"]}},"dynamicRef.ts":{"size":1797,"offset":"887048","integrity":{"algorithm":"SHA256","hash":"92884e9923f4053155e5c1f13d5e176c17b47f0db65616bf031a4bb93faf969d","blockSize":4194304,"blocks":["92884e9923f4053155e5c1f13d5e176c17b47f0db65616bf031a4bb93faf969d"]}},"index.ts":{"size":328,"offset":"888845","integrity":{"algorithm":"SHA256","hash":"c5188cd455c45b486350ed74bb08b6fb47db13bea6f218cce9d2cbf88044352b","blockSize":4194304,"blocks":["c5188cd455c45b486350ed74bb08b6fb47db13bea6f218cce9d2cbf88044352b"]}},"recursiveAnchor.ts":{"size":401,"offset":"889173","integrity":{"algorithm":"SHA256","hash":"7d9e31d581249212f5c831d30d5398c43b6d7ce4d3dcb735880524016b3e8d6a","blockSize":4194304,"blocks":["7d9e31d581249212f5c831d30d5398c43b6d7ce4d3dcb735880524016b3e8d6a"]}},"recursiveRef.ts":{"size":253,"offset":"889574","integrity":{"algorithm":"SHA256","hash":"6202321b7ce13fb3aec6d0180c3e78b6f91d768be57afef6b1693bd143577ee3","blockSize":4194304,"blocks":["6202321b7ce13fb3aec6d0180c3e78b6f91d768be57afef6b1693bd143577ee3"]}}}},"errors.ts":{"size":731,"offset":"889827","integrity":{"algorithm":"SHA256","hash":"ccf58af574cd4a8475346998967fa6229b163b6b52af2e9b0b30fa37338b8e2b","blockSize":4194304,"blocks":["ccf58af574cd4a8475346998967fa6229b163b6b52af2e9b0b30fa37338b8e2b"]}},"format":{"files":{"format.ts":{"size":3987,"offset":"890558","integrity":{"algorithm":"SHA256","hash":"5cd796fed502ebe7f2c650b47daae97c28967dd17fa020df56ec861986d30148","blockSize":4194304,"blocks":["5cd796fed502ebe7f2c650b47daae97c28967dd17fa020df56ec861986d30148"]}},"index.ts":{"size":148,"offset":"894545","integrity":{"algorithm":"SHA256","hash":"804a833df34f93e7cd1a1809782f65c1ac89610ac736045308d27b659264a40a","blockSize":4194304,"blocks":["804a833df34f93e7cd1a1809782f65c1ac89610ac736045308d27b659264a40a"]}}}},"jtd":{"files":{"discriminator.ts":{"size":2656,"offset":"894693","integrity":{"algorithm":"SHA256","hash":"9dd6dd40e98239c10d6771c0a0d107e238c12af4b3c5932fe623de649588de1d","blockSize":4194304,"blocks":["9dd6dd40e98239c10d6771c0a0d107e238c12af4b3c5932fe623de649588de1d"]}},"elements.ts":{"size":976,"offset":"897349","integrity":{"algorithm":"SHA256","hash":"54c00bc71c6bc0f5055c49fa0b6803db07832e5f77aadb1e55e5e045b3a4ad33","blockSize":4194304,"blocks":["54c00bc71c6bc0f5055c49fa0b6803db07832e5f77aadb1e55e5e045b3a4ad33"]}},"enum.ts":{"size":1627,"offset":"898325","integrity":{"algorithm":"SHA256","hash":"a55ae1c6b7d9ac0e9053e71da407efe41b3156cc0db7091bcd20a9d8897844dd","blockSize":4194304,"blocks":["a55ae1c6b7d9ac0e9053e71da407efe41b3156cc0db7091bcd20a9d8897844dd"]}},"error.ts":{"size":746,"offset":"899952","integrity":{"algorithm":"SHA256","hash":"e1bdb9dfada76ee42308e134f2e74027ea8398997961a3bae08cd10c792272c5","blockSize":4194304,"blocks":["e1bdb9dfada76ee42308e134f2e74027ea8398997961a3bae08cd10c792272c5"]}},"index.ts":{"size":1007,"offset":"900698","integrity":{"algorithm":"SHA256","hash":"4ca3295374abddb3c03ada3fdc52b9b7cb175046769a3eef60605bef8a6ef85a","blockSize":4194304,"blocks":["4ca3295374abddb3c03ada3fdc52b9b7cb175046769a3eef60605bef8a6ef85a"]}},"metadata.ts":{"size":716,"offset":"901705","integrity":{"algorithm":"SHA256","hash":"558fcb3d3b5e39a9a967326ea6a35160bd485755d587c5faafb644e25d0c0f01","blockSize":4194304,"blocks":["558fcb3d3b5e39a9a967326ea6a35160bd485755d587c5faafb644e25d0c0f01"]}},"nullable.ts":{"size":649,"offset":"902421","integrity":{"algorithm":"SHA256","hash":"75b370cb5ad4c36ff85a57fb9305a8018b5363666f0a5ac21c8de99d984b6bb8","blockSize":4194304,"blocks":["75b370cb5ad4c36ff85a57fb9305a8018b5363666f0a5ac21c8de99d984b6bb8"]}},"optionalProperties.ts":{"size":394,"offset":"903070","integrity":{"algorithm":"SHA256","hash":"03fdaf041fd433857e78c3b867ad1e6c1f0a964c0292498981e238b40a2a4e77","blockSize":4194304,"blocks":["03fdaf041fd433857e78c3b867ad1e6c1f0a964c0292498981e238b40a2a4e77"]}},"properties.ts":{"size":6244,"offset":"903464","integrity":{"algorithm":"SHA256","hash":"930071681288045214e10af6065f5d6c7f6ea599d07c607f345b609bac4bf8e5","blockSize":4194304,"blocks":["930071681288045214e10af6065f5d6c7f6ea599d07c607f345b609bac4bf8e5"]}},"ref.ts":{"size":2346,"offset":"909708","integrity":{"algorithm":"SHA256","hash":"f7dc8a31ad5764cc0c44725713130d5b656ead77483429226507da4dfd24ad2d","blockSize":4194304,"blocks":["f7dc8a31ad5764cc0c44725713130d5b656ead77483429226507da4dfd24ad2d"]}},"type.ts":{"size":2547,"offset":"912054","integrity":{"algorithm":"SHA256","hash":"0e6c6bb43fa81bff1cb4ba3f4d6d73379f3e013efaa01b790768fa0a5095cd45","blockSize":4194304,"blocks":["0e6c6bb43fa81bff1cb4ba3f4d6d73379f3e013efaa01b790768fa0a5095cd45"]}},"union.ts":{"size":292,"offset":"914601","integrity":{"algorithm":"SHA256","hash":"1dd265ce69eebbd46cd395b0b9d98ca22d8e681d0ab787e6409cb126450c9536","blockSize":4194304,"blocks":["1dd265ce69eebbd46cd395b0b9d98ca22d8e681d0ab787e6409cb126450c9536"]}},"values.ts":{"size":1681,"offset":"914893","integrity":{"algorithm":"SHA256","hash":"86236891ca9a9f77f7df5d399be026406d0f375c0a5d8f6d0749859dea245cdd","blockSize":4194304,"blocks":["86236891ca9a9f77f7df5d399be026406d0f375c0a5d8f6d0749859dea245cdd"]}}}},"metadata.ts":{"size":304,"offset":"916574","integrity":{"algorithm":"SHA256","hash":"a0b32538e6d2c93c7fd10aef9963d990d24d9579d2494350a23f3501300817d1","blockSize":4194304,"blocks":["a0b32538e6d2c93c7fd10aef9963d990d24d9579d2494350a23f3501300817d1"]}},"next.ts":{"size":320,"offset":"916878","integrity":{"algorithm":"SHA256","hash":"b953c63e395e4e0c95e048ae8778473a744e1d7a7b5fa8c57733c1bfbf7ce443","blockSize":4194304,"blocks":["b953c63e395e4e0c95e048ae8778473a744e1d7a7b5fa8c57733c1bfbf7ce443"]}},"unevaluated":{"files":{"index.ts":{"size":257,"offset":"917198","integrity":{"algorithm":"SHA256","hash":"0d44afd298469f01304d72a5cf7da11303367fa506200c46785cee4bd3350f40","blockSize":4194304,"blocks":["0d44afd298469f01304d72a5cf7da11303367fa506200c46785cee4bd3350f40"]}},"unevaluatedItems.ts":{"size":1524,"offset":"917455","integrity":{"algorithm":"SHA256","hash":"c19c3d3e0b290171f674d3dbacc52d946f9e4325f2223355a055e741c5dbbbb2","blockSize":4194304,"blocks":["c19c3d3e0b290171f674d3dbacc52d946f9e4325f2223355a055e741c5dbbbb2"]}},"unevaluatedProperties.ts":{"size":2440,"offset":"918979","integrity":{"algorithm":"SHA256","hash":"7d725ffb348774d31cc697cc6b632a43431b3d2d92edb819fd7341902340c6de","blockSize":4194304,"blocks":["7d725ffb348774d31cc697cc6b632a43431b3d2d92edb819fd7341902340c6de"]}}}},"validation":{"files":{"const.ts":{"size":863,"offset":"921419","integrity":{"algorithm":"SHA256","hash":"9dc3c40d6260158b2ee34dadadbc0e738cad939fc725cc1d2f5120bd43768ed5","blockSize":4194304,"blocks":["9dc3c40d6260158b2ee34dadadbc0e738cad939fc725cc1d2f5120bd43768ed5"]}},"dependentRequired.ts":{"size":510,"offset":"922282","integrity":{"algorithm":"SHA256","hash":"082d569e899aca88dbe28bdf6a0c6c2efa120e107fe4d1244ecf3a0b17fef45b","blockSize":4194304,"blocks":["082d569e899aca88dbe28bdf6a0c6c2efa120e107fe4d1244ecf3a0b17fef45b"]}},"enum.ts":{"size":1837,"offset":"922792","integrity":{"algorithm":"SHA256","hash":"f62f760dda52c2dbc053ef7b7012aa9db10d3af65e8b1dc5defcaf2ba9c25911","blockSize":4194304,"blocks":["f62f760dda52c2dbc053ef7b7012aa9db10d3af65e8b1dc5defcaf2ba9c25911"]}},"index.ts":{"size":1271,"offset":"924629","integrity":{"algorithm":"SHA256","hash":"72a7be83642b3da6317dc9661bfbc8a8f521773812ac6e5c58ddee1c4386a86c","blockSize":4194304,"blocks":["72a7be83642b3da6317dc9661bfbc8a8f521773812ac6e5c58ddee1c4386a86c"]}},"limitContains.ts":{"size":485,"offset":"925900","integrity":{"algorithm":"SHA256","hash":"3097c6f451ff7a527cbce136a08817114ee615f1b29221195cee45dfc89675e5","blockSize":4194304,"blocks":["3097c6f451ff7a527cbce136a08817114ee615f1b29221195cee45dfc89675e5"]}},"limitItems.ts":{"size":812,"offset":"926385","integrity":{"algorithm":"SHA256","hash":"32098cc56bcd9ff44bfa83b1015a3bc2bb7d2f8f7eecb3113929df732faa8176","blockSize":4194304,"blocks":["32098cc56bcd9ff44bfa83b1015a3bc2bb7d2f8f7eecb3113929df732faa8176"]}},"limitLength.ts":{"size":1025,"offset":"927197","integrity":{"algorithm":"SHA256","hash":"72afbaaa2718abe23156d8bb4af09fdc98a12054fe3c559b82e22718dbedb7de","blockSize":4194304,"blocks":["72afbaaa2718abe23156d8bb4af09fdc98a12054fe3c559b82e22718dbedb7de"]}},"limitNumber.ts":{"size":1350,"offset":"928222","integrity":{"algorithm":"SHA256","hash":"61bedba4a12924a84924b096f3b401356805cc24593f4b800bab4ad05be06298","blockSize":4194304,"blocks":["61bedba4a12924a84924b096f3b401356805cc24593f4b800bab4ad05be06298"]}},"limitProperties.ts":{"size":851,"offset":"929572","integrity":{"algorithm":"SHA256","hash":"d55088c19cd829be5ff23dc7bb98dde9bb0bc9fb3baa2a4a141797044a668048","blockSize":4194304,"blocks":["d55088c19cd829be5ff23dc7bb98dde9bb0bc9fb3baa2a4a141797044a668048"]}},"multipleOf.ts":{"size":1072,"offset":"930423","integrity":{"algorithm":"SHA256","hash":"5130cb4147d60dbec590b1e153f0f69b3c7ab552da9dd12eb2e1c22ca36daf7c","blockSize":4194304,"blocks":["5130cb4147d60dbec590b1e153f0f69b3c7ab552da9dd12eb2e1c22ca36daf7c"]}},"pattern.ts":{"size":1299,"offset":"931495","integrity":{"algorithm":"SHA256","hash":"7de916ef56aba5ef4d0b03e69b0e206224d1226728700afc7ccd76d216ff7829","blockSize":4194304,"blocks":["7de916ef56aba5ef4d0b03e69b0e206224d1226728700afc7ccd76d216ff7829"]}},"required.ts":{"size":2961,"offset":"932794","integrity":{"algorithm":"SHA256","hash":"73f26a08d78ace7a164eca526843086bfbb986799d9a7ecc02fb67a87d2456aa","blockSize":4194304,"blocks":["73f26a08d78ace7a164eca526843086bfbb986799d9a7ecc02fb67a87d2456aa"]}},"uniqueItems.ts":{"size":2690,"offset":"935755","integrity":{"algorithm":"SHA256","hash":"9d978fd6b3dc81c07c60f5067253490b54962571a4b510e18f4e257508809ee0","blockSize":4194304,"blocks":["9d978fd6b3dc81c07c60f5067253490b54962571a4b510e18f4e257508809ee0"]}}}}}}}},"package.json":{"size":2245,"offset":"938445","integrity":{"algorithm":"SHA256","hash":"c5fd7a1142f859e6d9216647c8dccdb51f2f1af17e7a6a9622ad0257af62ef84","blockSize":4194304,"blocks":["c5fd7a1142f859e6d9216647c8dccdb51f2f1af17e7a6a9622ad0257af62ef84"]}}}},"ajv-formats":{"files":{"LICENSE":{"size":1074,"offset":"940690","integrity":{"algorithm":"SHA256","hash":"9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf","blockSize":4194304,"blocks":["9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf"]}},"dist":{"files":{"formats.js":{"size":12263,"offset":"941764","integrity":{"algorithm":"SHA256","hash":"b61693a26869970a92cc1fe832c931ccd3afe8b6d66802b19c48306349e84880","blockSize":4194304,"blocks":["b61693a26869970a92cc1fe832c931ccd3afe8b6d66802b19c48306349e84880"]}},"formats.js.map":{"size":7070,"offset":"954027","integrity":{"algorithm":"SHA256","hash":"572005eb8eca5a6bf6a82bb08fe5b96d001afd801a71c4f0c60dc98ec4e72e87","blockSize":4194304,"blocks":["572005eb8eca5a6bf6a82bb08fe5b96d001afd801a71c4f0c60dc98ec4e72e87"]}},"index.js":{"size":1508,"offset":"961097","integrity":{"algorithm":"SHA256","hash":"3f3014150293846086d11058bb8bf43e669e354a98b37adcf10281454d5e753b","blockSize":4194304,"blocks":["3f3014150293846086d11058bb8bf43e669e354a98b37adcf10281454d5e753b"]}},"index.js.map":{"size":1534,"offset":"962605","integrity":{"algorithm":"SHA256","hash":"b954274ddd48215db2779c9da8b6353d3a327166de369219d45762378b30e5b5","blockSize":4194304,"blocks":["b954274ddd48215db2779c9da8b6353d3a327166de369219d45762378b30e5b5"]}},"limit.js":{"size":2900,"offset":"964139","integrity":{"algorithm":"SHA256","hash":"ffc374031a55c3f6e39dc3fe69e663f8251b9d9d7ddb8f513a6807c985c18bb8","blockSize":4194304,"blocks":["ffc374031a55c3f6e39dc3fe69e663f8251b9d9d7ddb8f513a6807c985c18bb8"]}},"limit.js.map":{"size":2868,"offset":"967039","integrity":{"algorithm":"SHA256","hash":"1f7c052543625258c85ac43a754478960655ad4954a23846bc841a47e6fdf8e4","blockSize":4194304,"blocks":["1f7c052543625258c85ac43a754478960655ad4954a23846bc841a47e6fdf8e4"]}}}},"package.json":{"size":1307,"offset":"969907","integrity":{"algorithm":"SHA256","hash":"8c5c76968c3a2108d27867ab9be75c284ababfc5157c279522faff39feccc936","blockSize":4194304,"blocks":["8c5c76968c3a2108d27867ab9be75c284ababfc5157c279522faff39feccc936"]}},"src":{"files":{"formats.ts":{"size":12928,"offset":"971214","integrity":{"algorithm":"SHA256","hash":"fec0bb3f73fd3ea487205c9fa783dca3d088d8f402829ab14c207567d00f0f8e","blockSize":4194304,"blocks":["fec0bb3f73fd3ea487205c9fa783dca3d088d8f402829ab14c207567d00f0f8e"]}},"index.ts":{"size":1793,"offset":"984142","integrity":{"algorithm":"SHA256","hash":"fb330a47ec7d2c8498d03078834603dab1a0689f40ca15875e6d57d740c5ff71","blockSize":4194304,"blocks":["fb330a47ec7d2c8498d03078834603dab1a0689f40ca15875e6d57d740c5ff71"]}},"limit.ts":{"size":3074,"offset":"985935","integrity":{"algorithm":"SHA256","hash":"62402e4fcb3bd9a0f4a22d2b228f1371897d47982e67ecd62950fdadb46261e6","blockSize":4194304,"blocks":["62402e4fcb3bd9a0f4a22d2b228f1371897d47982e67ecd62950fdadb46261e6"]}}}}}},"applescript":{"files":{"History.md":{"size":1504,"offset":"989009","integrity":{"algorithm":"SHA256","hash":"b583e5b5bd45267e9816a461fae4e32dc376b003af60fd0ef5f82e56e46eb166","blockSize":4194304,"blocks":["b583e5b5bd45267e9816a461fae4e32dc376b003af60fd0ef5f82e56e46eb166"]}},"LICENSE":{"size":1077,"offset":"990513","integrity":{"algorithm":"SHA256","hash":"1d597a17d76f3f5af08ba34b53e4606648f28fdad7586c77adac557dec93d115","blockSize":4194304,"blocks":["1d597a17d76f3f5af08ba34b53e4606648f28fdad7586c77adac557dec93d115"]}},"lib":{"files":{"applescript-parser.js":{"size":3650,"offset":"991590","integrity":{"algorithm":"SHA256","hash":"02dea84e3a07a4c6c6a7684baeddc0c40cf859a993b8cd799eaf593f6218847d","blockSize":4194304,"blocks":["02dea84e3a07a4c6c6a7684baeddc0c40cf859a993b8cd799eaf593f6218847d"]}},"applescript.js":{"size":1823,"offset":"995240","integrity":{"algorithm":"SHA256","hash":"ab6a8eac37fe67e188e73d9e36f20f567e497f1f1b6fb98f70651d9e94f48f44","blockSize":4194304,"blocks":["ab6a8eac37fe67e188e73d9e36f20f567e497f1f1b6fb98f70651d9e94f48f44"]}}}},"package.json":{"size":221,"offset":"997063","integrity":{"algorithm":"SHA256","hash":"b5f3c2250f0914d324fdfa4557cb9b8588180c21602007cfb0625b0b7ac798ea","blockSize":4194304,"blocks":["b5f3c2250f0914d324fdfa4557cb9b8588180c21602007cfb0625b0b7ac798ea"]}},"samples":{"files":{"execFile.js":{"size":897,"offset":"997284","integrity":{"algorithm":"SHA256","hash":"401928b129fc99ef6afce353f095038268e62c2bddd493da6ec2a2f5085fc448","blockSize":4194304,"blocks":["401928b129fc99ef6afce353f095038268e62c2bddd493da6ec2a2f5085fc448"]}},"execString.js":{"size":629,"offset":"998181","integrity":{"algorithm":"SHA256","hash":"db07583d68db46b61a4086875005dc702b7b19e68687e604fb3225b7f16f0b37","blockSize":4194304,"blocks":["db07583d68db46b61a4086875005dc702b7b19e68687e604fb3225b7f16f0b37"]}},"fail-case.applescript":{"size":54,"offset":"998810","integrity":{"algorithm":"SHA256","hash":"603c153fae611bdb0626367ff0c56f36f7c4c6b81ad66a5372716f00f1551099","blockSize":4194304,"blocks":["603c153fae611bdb0626367ff0c56f36f7c4c6b81ad66a5372716f00f1551099"]}},"locationCurrentTrack.applescript":{"size":69,"offset":"998864","integrity":{"algorithm":"SHA256","hash":"af1e52ae868d75c09ca7651ca0d2c4573dae1494678d38cb996533a100b739a2","blockSize":4194304,"blocks":["af1e52ae868d75c09ca7651ca0d2c4573dae1494678d38cb996533a100b739a2"]}}}}}},"argparse":{"files":{"LICENSE":{"size":12775,"offset":"998933","integrity":{"algorithm":"SHA256","hash":"de4d1f2d2ad5ad0cfd1657a106476b31cb5db5ef9d1ff842b237c0c81f0c8a23","blockSize":4194304,"blocks":["de4d1f2d2ad5ad0cfd1657a106476b31cb5db5ef9d1ff842b237c0c81f0c8a23"]}},"argparse.js":{"size":129714,"offset":"1011708","integrity":{"algorithm":"SHA256","hash":"2e73e7a3167ba840dbcf41feeafc3544a3e2b39220b5e997133c519861febf16","blockSize":4194304,"blocks":["2e73e7a3167ba840dbcf41feeafc3544a3e2b39220b5e997133c519861febf16"]}},"lib":{"files":{"sub.js":{"size":2252,"offset":"1141422","integrity":{"algorithm":"SHA256","hash":"2bc4ef9e87c47f1a4e0cfcb3706d886e0d73edce88149e300d2364066f396ed6","blockSize":4194304,"blocks":["2bc4ef9e87c47f1a4e0cfcb3706d886e0d73edce88149e300d2364066f396ed6"]}},"textwrap.js":{"size":17391,"offset":"1143674","integrity":{"algorithm":"SHA256","hash":"2550466c9a0425fa583a70e25bb93e190fe09b61f7de4861ea8ec54b7b899db0","blockSize":4194304,"blocks":["2550466c9a0425fa583a70e25bb93e190fe09b61f7de4861ea8ec54b7b899db0"]}}}},"package.json":{"size":448,"offset":"1161065","integrity":{"algorithm":"SHA256","hash":"800e809f5cdb0a7dec1834e1d2c0a165b1b63c2d6d7b2a97034b8c668de24a8f","blockSize":4194304,"blocks":["800e809f5cdb0a7dec1834e1d2c0a165b1b63c2d6d7b2a97034b8c668de24a8f"]}}}},"atomically":{"files":{"dist":{"files":{"constants.js":{"size":1008,"offset":"1161513","integrity":{"algorithm":"SHA256","hash":"5c222689b8b9332ac4aa140262002548d7ba8606ea67d3d8b53c51d5878ffc6c","blockSize":4194304,"blocks":["5c222689b8b9332ac4aa140262002548d7ba8606ea67d3d8b53c51d5878ffc6c"]}},"index.js":{"size":8463,"offset":"1162521","integrity":{"algorithm":"SHA256","hash":"fbbfdcb314eb0ec147beca36753b7b0213fc16ed8db1d5135e5fe793e7e9b3ab","blockSize":4194304,"blocks":["fbbfdcb314eb0ec147beca36753b7b0213fc16ed8db1d5135e5fe793e7e9b3ab"]}},"types.js":{"size":22,"offset":"1170984","integrity":{"algorithm":"SHA256","hash":"d99f969d7455894d5b3ee7632c54f4ffb79d666c0dd8dc49dfa6e7815f74196c","blockSize":4194304,"blocks":["d99f969d7455894d5b3ee7632c54f4ffb79d666c0dd8dc49dfa6e7815f74196c"]}},"utils":{"files":{"lang.js":{"size":410,"offset":"1171006","integrity":{"algorithm":"SHA256","hash":"0e26cf5de753bce2a097f734c77aeb10a1c93bb80f8be9b6d2521006b5348036","blockSize":4194304,"blocks":["0e26cf5de753bce2a097f734c77aeb10a1c93bb80f8be9b6d2521006b5348036"]}},"scheduler.js":{"size":787,"offset":"1171416","integrity":{"algorithm":"SHA256","hash":"e5894c2e5d6d684ea89086421b35a75363288c74e672f7a97f124a7b81bfefad","blockSize":4194304,"blocks":["e5894c2e5d6d684ea89086421b35a75363288c74e672f7a97f124a7b81bfefad"]}},"temp.js":{"size":2479,"offset":"1172203","integrity":{"algorithm":"SHA256","hash":"ad2f918838672a1e1c08204b73ffda5f6df519defffcad277295dcf7e95d1f20","blockSize":4194304,"blocks":["ad2f918838672a1e1c08204b73ffda5f6df519defffcad277295dcf7e95d1f20"]}}}}}},"license":{"size":1091,"offset":"1174682","integrity":{"algorithm":"SHA256","hash":"716bd9213ef82d9017ed813688703837aaa99fc56de205a7b97475d40056a500","blockSize":4194304,"blocks":["716bd9213ef82d9017ed813688703837aaa99fc56de205a7b97475d40056a500"]}},"package.json":{"size":604,"offset":"1175773","integrity":{"algorithm":"SHA256","hash":"761e39b9690f5bc16012b6acb697479e997eb9beb99d6443b0cd7eb9345eb1c8","blockSize":4194304,"blocks":["761e39b9690f5bc16012b6acb697479e997eb9beb99d6443b0cd7eb9345eb1c8"]}}}},"auto-launch":{"files":{"LICENSE.md":{"size":1069,"offset":"1176377","integrity":{"algorithm":"SHA256","hash":"ec7cf95931ad67fb5647400a85d3cd819b0ae1fc72735660794b369436ef64eb","blockSize":4194304,"blocks":["ec7cf95931ad67fb5647400a85d3cd819b0ae1fc72735660794b369436ef64eb"]}},"dist":{"files":{"AutoLaunchLinux.js":{"size":1151,"offset":"1177446","integrity":{"algorithm":"SHA256","hash":"1309704c4d07c9785def0c1f874ccadfe23b77552c4ce1862fe5ae159a145c43","blockSize":4194304,"blocks":["1309704c4d07c9785def0c1f874ccadfe23b77552c4ce1862fe5ae159a145c43"]}},"AutoLaunchMac.js":{"size":2855,"offset":"1178597","integrity":{"algorithm":"SHA256","hash":"3b220003e14aca63cf6f720f8e646b32b8dea6fc6ffce719d37e35d0ecdfdf53","blockSize":4194304,"blocks":["3b220003e14aca63cf6f720f8e646b32b8dea6fc6ffce719d37e35d0ecdfdf53"]}},"AutoLaunchWindows.js":{"size":1997,"offset":"1181452","integrity":{"algorithm":"SHA256","hash":"73617c01348c10dd894a59c6b3301d60e6ccec4bc9d21a8602324a09562c1545","blockSize":4194304,"blocks":["73617c01348c10dd894a59c6b3301d60e6ccec4bc9d21a8602324a09562c1545"]}},"fileBasedUtilities.js":{"size":1443,"offset":"1183449","integrity":{"algorithm":"SHA256","hash":"a649ef6c2787fc2eb03e29e9ba6f7c6f245a2b15bdc8699df8ed555dd0cab8be","blockSize":4194304,"blocks":["a649ef6c2787fc2eb03e29e9ba6f7c6f245a2b15bdc8699df8ed555dd0cab8be"]}},"index.js":{"size":3412,"offset":"1184892","integrity":{"algorithm":"SHA256","hash":"43e94d4cd4acc7da14b53ad36d5161933e2e3dacb334d00400f3ac241cfbdea2","blockSize":4194304,"blocks":["43e94d4cd4acc7da14b53ad36d5161933e2e3dacb334d00400f3ac241cfbdea2"]}}}},"package.json":{"size":917,"offset":"1188304","integrity":{"algorithm":"SHA256","hash":"d58866d362b86b3cadb9451ca0a35f1040aa9a9c806d6f27ee7901deab47eaba","blockSize":4194304,"blocks":["d58866d362b86b3cadb9451ca0a35f1040aa9a9c806d6f27ee7901deab47eaba"]}}}},"builder-util-runtime":{"files":{"LICENSE":{"size":1084,"offset":"1189221","integrity":{"algorithm":"SHA256","hash":"bed8d0ab3e6031817f775a641ff37313b0f5591bc8ba0ed79b978dafbd4231ce","blockSize":4194304,"blocks":["bed8d0ab3e6031817f775a641ff37313b0f5591bc8ba0ed79b978dafbd4231ce"]}},"out":{"files":{"CancellationToken.js":{"size":3199,"offset":"1190305","integrity":{"algorithm":"SHA256","hash":"054512fdee2fe810ef46d5ce7fdc2c39d3582ee8c3d463a4ee6c954bca8ec7d5","blockSize":4194304,"blocks":["054512fdee2fe810ef46d5ce7fdc2c39d3582ee8c3d463a4ee6c954bca8ec7d5"]}},"CancellationToken.js.map":{"size":5648,"offset":"1193504","integrity":{"algorithm":"SHA256","hash":"9fdf32eccac29b57c7703a23cd1201ca6a04c1b81b349900177ec1b948317c89","blockSize":4194304,"blocks":["9fdf32eccac29b57c7703a23cd1201ca6a04c1b81b349900177ec1b948317c89"]}},"MemoLazy.js":{"size":1504,"offset":"1199152","integrity":{"algorithm":"SHA256","hash":"f92e496315210399d4f58381b25ab4ca17f42991b4a50a0353c7e0acd92836a3","blockSize":4194304,"blocks":["f92e496315210399d4f58381b25ab4ca17f42991b4a50a0353c7e0acd92836a3"]}},"MemoLazy.js.map":{"size":2756,"offset":"1200656","integrity":{"algorithm":"SHA256","hash":"1603666315d0de55b5553b7223abfba2fdc113fc765f61c5e74d60ed4c3c7a9b","blockSize":4194304,"blocks":["1603666315d0de55b5553b7223abfba2fdc113fc765f61c5e74d60ed4c3c7a9b"]}},"ProgressCallbackTransform.js":{"size":1949,"offset":"1203412","integrity":{"algorithm":"SHA256","hash":"35503895f7e7dd4329b94dd69eb48674ac55d9d6646d0ea42eada5378d433d32","blockSize":4194304,"blocks":["35503895f7e7dd4329b94dd69eb48674ac55d9d6646d0ea42eada5378d433d32"]}},"ProgressCallbackTransform.js.map":{"size":3693,"offset":"1205361","integrity":{"algorithm":"SHA256","hash":"7e42abdec49293ecbd388e36213ccf743a0b12a018af5045dd23cd0ed495c7ff","blockSize":4194304,"blocks":["7e42abdec49293ecbd388e36213ccf743a0b12a018af5045dd23cd0ed495c7ff"]}},"blockMapApi.js":{"size":116,"offset":"1209054","integrity":{"algorithm":"SHA256","hash":"84e270ead20b81c2c527c7cea8c295819fd015c120f67fd686c29534e036c239","blockSize":4194304,"blocks":["84e270ead20b81c2c527c7cea8c295819fd015c120f67fd686c29534e036c239"]}},"blockMapApi.js.map":{"size":403,"offset":"1209170","integrity":{"algorithm":"SHA256","hash":"cbc5bfdd044fd2f70dd6edaf55449890497bdf67a05686e847da71ac96b94a33","blockSize":4194304,"blocks":["cbc5bfdd044fd2f70dd6edaf55449890497bdf67a05686e847da71ac96b94a33"]}},"error.js":{"size":255,"offset":"1209573","integrity":{"algorithm":"SHA256","hash":"820464dee13ae1ca3c40d6a0f35bd49cabb154af63f872e9ed3488a0b95cca49","blockSize":4194304,"blocks":["820464dee13ae1ca3c40d6a0f35bd49cabb154af63f872e9ed3488a0b95cca49"]}},"error.js.map":{"size":454,"offset":"1209828","integrity":{"algorithm":"SHA256","hash":"64580cca1bb760bd55809c02ee1b3789dd6bd3499bee30e82ed8986e3413ef95","blockSize":4194304,"blocks":["64580cca1bb760bd55809c02ee1b3789dd6bd3499bee30e82ed8986e3413ef95"]}},"httpExecutor.js":{"size":20832,"offset":"1210282","integrity":{"algorithm":"SHA256","hash":"f6bafd9365a9017d7b47a13e3a8fef3cc9a4096e5ffa9e7dbd2913bca9a6321d","blockSize":4194304,"blocks":["f6bafd9365a9017d7b47a13e3a8fef3cc9a4096e5ffa9e7dbd2913bca9a6321d"]}},"httpExecutor.js.map":{"size":39273,"offset":"1231114","integrity":{"algorithm":"SHA256","hash":"4dfebb672be24fa9c50745e573117bf5ba7e506d241c931a7e04957b22c9a415","blockSize":4194304,"blocks":["4dfebb672be24fa9c50745e573117bf5ba7e506d241c931a7e04957b22c9a415"]}},"index.js":{"size":4959,"offset":"1270387","integrity":{"algorithm":"SHA256","hash":"2b3edddea3c2f5e4e0bf7544f2932c9637531c8a2326a275a1d9e421227ddba3","blockSize":4194304,"blocks":["2b3edddea3c2f5e4e0bf7544f2932c9637531c8a2326a275a1d9e421227ddba3"]}},"index.js.map":{"size":2468,"offset":"1275346","integrity":{"algorithm":"SHA256","hash":"a262f59bdbb2a104746d9795b43c5b78ea8f34be6354ae6e8a6efcab9960e0f9","blockSize":4194304,"blocks":["a262f59bdbb2a104746d9795b43c5b78ea8f34be6354ae6e8a6efcab9960e0f9"]}},"objects.js":{"size":2173,"offset":"1277814","integrity":{"algorithm":"SHA256","hash":"a43b9a711b9a184038629683c8159aa51a189341434469783ded426de216999f","blockSize":4194304,"blocks":["a43b9a711b9a184038629683c8159aa51a189341434469783ded426de216999f"]}},"objects.js.map":{"size":4538,"offset":"1279987","integrity":{"algorithm":"SHA256","hash":"df80b80fcbf2b3256e55f84b702419504faefaf92fbd7e2ab2b54e9ca282cab9","blockSize":4194304,"blocks":["df80b80fcbf2b3256e55f84b702419504faefaf92fbd7e2ab2b54e9ca282cab9"]}},"publishOptions.js":{"size":2505,"offset":"1284525","integrity":{"algorithm":"SHA256","hash":"48e9aa4f6e2eab4b7f2e412f26784950c4701b036a72ae451c6cef3d1eb22435","blockSize":4194304,"blocks":["48e9aa4f6e2eab4b7f2e412f26784950c4701b036a72ae451c6cef3d1eb22435"]}},"publishOptions.js.map":{"size":17843,"offset":"1287030","integrity":{"algorithm":"SHA256","hash":"7e9e8e9deb02b129e6c15dbe7e85f7f340f24226428b17e34e258f77771544b2","blockSize":4194304,"blocks":["7e9e8e9deb02b129e6c15dbe7e85f7f340f24226428b17e34e258f77771544b2"]}},"retry.js":{"size":941,"offset":"1304873","integrity":{"algorithm":"SHA256","hash":"f89a0e871d04334725d54112c101475b423ea93ae4db2878b6cc2404791b5b40","blockSize":4194304,"blocks":["f89a0e871d04334725d54112c101475b423ea93ae4db2878b6cc2404791b5b40"]}},"retry.js.map":{"size":1750,"offset":"1305814","integrity":{"algorithm":"SHA256","hash":"94f3f24d0bc8360c9a0d8eccc766713c5d59557eff573cc1ec8bae1a5cf05c29","blockSize":4194304,"blocks":["94f3f24d0bc8360c9a0d8eccc766713c5d59557eff573cc1ec8bae1a5cf05c29"]}},"rfc2253Parser.js":{"size":2264,"offset":"1307564","integrity":{"algorithm":"SHA256","hash":"a8a6966c3bc3e6cc0df40128aa591747859257563f46f56b83d76148f8e170c4","blockSize":4194304,"blocks":["a8a6966c3bc3e6cc0df40128aa591747859257563f46f56b83d76148f8e170c4"]}},"rfc2253Parser.js.map":{"size":4168,"offset":"1309828","integrity":{"algorithm":"SHA256","hash":"8bcf678951773404906d4b9ceb1e6afead0c6db8a15c73b6f273f1f135b176b6","blockSize":4194304,"blocks":["8bcf678951773404906d4b9ceb1e6afead0c6db8a15c73b6f273f1f135b176b6"]}},"updateInfo.js":{"size":115,"offset":"1313996","integrity":{"algorithm":"SHA256","hash":"935693e55dcf8a1e0ad653bbee7d456594835fdee0b99c9f7559befe1387043a","blockSize":4194304,"blocks":["935693e55dcf8a1e0ad653bbee7d456594835fdee0b99c9f7559befe1387043a"]}},"updateInfo.js.map":{"size":2338,"offset":"1314111","integrity":{"algorithm":"SHA256","hash":"3069ad55dd2ee1fe12d69db4b43a78da7970c5a1a3886b5e27265c1b4565337a","blockSize":4194304,"blocks":["3069ad55dd2ee1fe12d69db4b43a78da7970c5a1a3886b5e27265c1b4565337a"]}},"uuid.js":{"size":6393,"offset":"1316449","integrity":{"algorithm":"SHA256","hash":"5a58134245d8e5ae587e995195d3ca33d9f9e273fc077d700e675f4c4005c029","blockSize":4194304,"blocks":["5a58134245d8e5ae587e995195d3ca33d9f9e273fc077d700e675f4c4005c029"]}},"uuid.js.map":{"size":12236,"offset":"1322842","integrity":{"algorithm":"SHA256","hash":"3f8dc910c8f65bcd60d13787829931ec270933c7009ee667c854a0911e84d338","blockSize":4194304,"blocks":["3f8dc910c8f65bcd60d13787829931ec270933c7009ee667c854a0911e84d338"]}},"xml.js":{"size":3549,"offset":"1335078","integrity":{"algorithm":"SHA256","hash":"8f637be20077f0634bf36cac8a464973a6e1530e51f4efcfaec0f2c64df6ceb0","blockSize":4194304,"blocks":["8f637be20077f0634bf36cac8a464973a6e1530e51f4efcfaec0f2c64df6ceb0"]}},"xml.js.map":{"size":6987,"offset":"1338627","integrity":{"algorithm":"SHA256","hash":"405331ede8c0bfb52033a9829b6ae9ca7f87c36b1c663c220309dad6fc8f0ca1","blockSize":4194304,"blocks":["405331ede8c0bfb52033a9829b6ae9ca7f87c36b1c663c220309dad6fc8f0ca1"]}}}},"package.json":{"size":630,"offset":"1345614","integrity":{"algorithm":"SHA256","hash":"c4d21b31bebc1db25de2d0ae118dd49fc6256afc8d79a3148ca3d6e0371d86f5","blockSize":4194304,"blocks":["c4d21b31bebc1db25de2d0ae118dd49fc6256afc8d79a3148ca3d6e0371d86f5"]}}}},"conf":{"files":{"dist":{"files":{"source":{"files":{"index.js":{"size":26614,"offset":"1346244","integrity":{"algorithm":"SHA256","hash":"938d76441bf7708a6dfb6292c3349ee91e71a7f8b6eb46d2fc0eb25df89200aa","blockSize":4194304,"blocks":["938d76441bf7708a6dfb6292c3349ee91e71a7f8b6eb46d2fc0eb25df89200aa"]}},"types.js":{"size":11,"offset":"1372858","integrity":{"algorithm":"SHA256","hash":"8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881","blockSize":4194304,"blocks":["8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881"]}}}}}},"license":{"size":1117,"offset":"1372869","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":1218,"offset":"1373986","integrity":{"algorithm":"SHA256","hash":"f17885bfdc0fe4ee0f5fdd68fad6afdc220193b8a8485a72fa6a47f1cb970983","blockSize":4194304,"blocks":["f17885bfdc0fe4ee0f5fdd68fad6afdc220193b8a8485a72fa6a47f1cb970983"]}}}},"debounce-fn":{"files":{"index.js":{"size":1840,"offset":"1375204","integrity":{"algorithm":"SHA256","hash":"611604c2c625c921b870bbf9ed3801bd1360140a87871f1b817d9d1af2fcc3dd","blockSize":4194304,"blocks":["611604c2c625c921b870bbf9ed3801bd1360140a87871f1b817d9d1af2fcc3dd"]}},"license":{"size":1117,"offset":"1377044","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":716,"offset":"1378161","integrity":{"algorithm":"SHA256","hash":"b2c4770c6feab3b62fc13f97845c9a2bc1c36d69522957fa21070b889c91ead2","blockSize":4194304,"blocks":["b2c4770c6feab3b62fc13f97845c9a2bc1c36d69522957fa21070b889c91ead2"]}}}},"debug":{"files":{"LICENSE":{"size":1139,"offset":"1378877","integrity":{"algorithm":"SHA256","hash":"3a61c6c96caf5c1d9b623fb9b04c822b783dfcb78aa7e49c76a3f643e6ed7f95","blockSize":4194304,"blocks":["3a61c6c96caf5c1d9b623fb9b04c822b783dfcb78aa7e49c76a3f643e6ed7f95"]}},"package.json":{"size":910,"offset":"1380016","integrity":{"algorithm":"SHA256","hash":"4fa45a8c74dc73528da99d9cec0e130fe4e606b2a970d6e65d274e9ec393126f","blockSize":4194304,"blocks":["4fa45a8c74dc73528da99d9cec0e130fe4e606b2a970d6e65d274e9ec393126f"]}},"src":{"files":{"browser.js":{"size":6103,"offset":"1380926","integrity":{"algorithm":"SHA256","hash":"19920671f5902f64ad8ea11767fa50ea9d7a71ae0b7dff7ba5693c0075afc763","blockSize":4194304,"blocks":["19920671f5902f64ad8ea11767fa50ea9d7a71ae0b7dff7ba5693c0075afc763"]}},"common.js":{"size":6915,"offset":"1387029","integrity":{"algorithm":"SHA256","hash":"dbe83d2bb5837f3c4d7fe537b8004c585987270eceed5b06b8e078deb0ae214a","blockSize":4194304,"blocks":["dbe83d2bb5837f3c4d7fe537b8004c585987270eceed5b06b8e078deb0ae214a"]}},"index.js":{"size":314,"offset":"1393944","integrity":{"algorithm":"SHA256","hash":"aa127ff1752b7d9c7415c5c7bb6994d9aa722b81bcbcab4bd48316b013d23bf3","blockSize":4194304,"blocks":["aa127ff1752b7d9c7415c5c7bb6994d9aa722b81bcbcab4bd48316b013d23bf3"]}},"node.js":{"size":4728,"offset":"1394258","integrity":{"algorithm":"SHA256","hash":"d7b26d7c92f8ea7794b77ce11f3c11cd18c9084df7c357e3c7025344fa28aac6","blockSize":4194304,"blocks":["d7b26d7c92f8ea7794b77ce11f3c11cd18c9084df7c357e3c7025344fa28aac6"]}}}}}},"dot-prop":{"files":{"index.js":{"size":12139,"offset":"1398986","integrity":{"algorithm":"SHA256","hash":"3b0376bd3942b76ddfb6d8acc16968fb834d7a577a67b22ac37814b4ee05b7be","blockSize":4194304,"blocks":["3b0376bd3942b76ddfb6d8acc16968fb834d7a577a67b22ac37814b4ee05b7be"]}},"license":{"size":1117,"offset":"1411125","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":814,"offset":"1412242","integrity":{"algorithm":"SHA256","hash":"b98fe3cd6feb3369d03dbf8c8eafe79fa31c4192a416a2b9bb60007d8fdc14aa","blockSize":4194304,"blocks":["b98fe3cd6feb3369d03dbf8c8eafe79fa31c4192a416a2b9bb60007d8fdc14aa"]}}}},"electron-log":{"files":{"LICENSE":{"size":1082,"offset":"1413056","integrity":{"algorithm":"SHA256","hash":"8a7030a9df0eac3ba1948991278d847d3e4c8dc4908a777b5868692c975ccfa8","blockSize":4194304,"blocks":["8a7030a9df0eac3ba1948991278d847d3e4c8dc4908a777b5868692c975ccfa8"]}},"main.js":{"size":75,"offset":"1414138","integrity":{"algorithm":"SHA256","hash":"fae41b809b95f890613ddda64561cd0fa4b3cc1de2c5aa2df753b31b02123365","blockSize":4194304,"blocks":["fae41b809b95f890613ddda64561cd0fa4b3cc1de2c5aa2df753b31b02123365"]}},"node.js":{"size":75,"offset":"1414213","integrity":{"algorithm":"SHA256","hash":"3fdad739e0f2096fef0196a841d4a5fd7b84a355a1e07247fe0ada59e3215bed","blockSize":4194304,"blocks":["3fdad739e0f2096fef0196a841d4a5fd7b84a355a1e07247fe0ada59e3215bed"]}},"package.json":{"size":1495,"offset":"1414288","integrity":{"algorithm":"SHA256","hash":"61967c15062709a6692b1b80abf36e7a4f897e55ca7661e6d85cf0db44dacc67","blockSize":4194304,"blocks":["61967c15062709a6692b1b80abf36e7a4f897e55ca7661e6d85cf0db44dacc67"]}},"preload.js":{"size":106,"offset":"1415783","integrity":{"algorithm":"SHA256","hash":"cfbc921386f62a953a6aa967b047b6aae1a6fd2268ea02f6fea6da164da34d30","blockSize":4194304,"blocks":["cfbc921386f62a953a6aa967b047b6aae1a6fd2268ea02f6fea6da164da34d30"]}},"renderer.js":{"size":87,"offset":"1415889","integrity":{"algorithm":"SHA256","hash":"5a21e4441e3894b7e786482d3c7ea770874a307d4673ba180fa9a6591bbb8cfa","blockSize":4194304,"blocks":["5a21e4441e3894b7e786482d3c7ea770874a307d4673ba180fa9a6591bbb8cfa"]}},"src":{"files":{"core":{"files":{"Buffering.js":{"size":613,"offset":"1415976","integrity":{"algorithm":"SHA256","hash":"1554b35c7baba7c1d91dee9458e66d5163be59bfc1f2c713589e379d7516983d","blockSize":4194304,"blocks":["1554b35c7baba7c1d91dee9458e66d5163be59bfc1f2c713589e379d7516983d"]}},"Logger.js":{"size":5471,"offset":"1416589","integrity":{"algorithm":"SHA256","hash":"2572098d75d2737989517b5d27bd37bf6eab1ca846271d69a96d625e60a64255","blockSize":4194304,"blocks":["2572098d75d2737989517b5d27bd37bf6eab1ca846271d69a96d625e60a64255"]}},"scope.js":{"size":854,"offset":"1422060","integrity":{"algorithm":"SHA256","hash":"5a57c42dd543207fd96056b101df00eb97f3f19dffffc17c826b9e2a026a0c04","blockSize":4194304,"blocks":["5a57c42dd543207fd96056b101df00eb97f3f19dffffc17c826b9e2a026a0c04"]}},"transforms":{"files":{"format.js":{"size":4094,"offset":"1422914","integrity":{"algorithm":"SHA256","hash":"2163c8bcaf2e74f8167b4bcb84dd2211d7451f558844721c7944ff884ff1b7f8","blockSize":4194304,"blocks":["2163c8bcaf2e74f8167b4bcb84dd2211d7451f558844721c7944ff884ff1b7f8"]}},"style.js":{"size":1520,"offset":"1427008","integrity":{"algorithm":"SHA256","hash":"d786b2dbb92743dfdc33bec9a12ce215b911aaef59f8d88d6bb282d4bd593b02","blockSize":4194304,"blocks":["d786b2dbb92743dfdc33bec9a12ce215b911aaef59f8d88d6bb282d4bd593b02"]}},"transform.js":{"size":372,"offset":"1428528","integrity":{"algorithm":"SHA256","hash":"d41edd15ea18c66efc749f05848357afecfa36b42f65167827f7e795578784d8","blockSize":4194304,"blocks":["d41edd15ea18c66efc749f05848357afecfa36b42f65167827f7e795578784d8"]}}}}}},"index.js":{"size":513,"offset":"1428900","integrity":{"algorithm":"SHA256","hash":"9554d4b13d8c2a36378d4853a8e1b28563f03fa3f610a692e755df04d64ba53f","blockSize":4194304,"blocks":["9554d4b13d8c2a36378d4853a8e1b28563f03fa3f610a692e755df04d64ba53f"]}},"main":{"files":{"ElectronExternalApi.js":{"size":4692,"offset":"1429413","integrity":{"algorithm":"SHA256","hash":"1b06b5416e5c874ed8fc6325794599a8bfa6bd524d3a2e266dea4e50faaaa1a7","blockSize":4194304,"blocks":["1b06b5416e5c874ed8fc6325794599a8bfa6bd524d3a2e266dea4e50faaaa1a7"]}},"index.js":{"size":1204,"offset":"1434105","integrity":{"algorithm":"SHA256","hash":"9232a0dd58735cf11489fb21b35506619faf723b7cb3a1bf699ee0965a929325","blockSize":4194304,"blocks":["9232a0dd58735cf11489fb21b35506619faf723b7cb3a1bf699ee0965a929325"]}},"initialize.js":{"size":2459,"offset":"1435309","integrity":{"algorithm":"SHA256","hash":"7d5e6c1d18bd56ef030f12008fdd688c2dc5f40949b9d6fa997caa739a6ed4bf","blockSize":4194304,"blocks":["7d5e6c1d18bd56ef030f12008fdd688c2dc5f40949b9d6fa997caa739a6ed4bf"]}}}},"node":{"files":{"ErrorHandler.js":{"size":3311,"offset":"1437768","integrity":{"algorithm":"SHA256","hash":"42052a03eda2f33163ea5f46d4d78dac799e801539ae474ab1b730a507a1b7ee","blockSize":4194304,"blocks":["42052a03eda2f33163ea5f46d4d78dac799e801539ae474ab1b730a507a1b7ee"]}},"EventLogger.js":{"size":5836,"offset":"1441079","integrity":{"algorithm":"SHA256","hash":"9f82f44f0dbc60c9ac2276699f1d6fda1a46c605dd28a8e8c32f2af186919e97","blockSize":4194304,"blocks":["9f82f44f0dbc60c9ac2276699f1d6fda1a46c605dd28a8e8c32f2af186919e97"]}},"NodeExternalApi.js":{"size":4951,"offset":"1446915","integrity":{"algorithm":"SHA256","hash":"9eb39da5689391cc7fc8a7779967db3186beab3bf241c1611774caf0c486089a","blockSize":4194304,"blocks":["9eb39da5689391cc7fc8a7779967db3186beab3bf241c1611774caf0c486089a"]}},"createDefaultLogger.js":{"size":1205,"offset":"1451866","integrity":{"algorithm":"SHA256","hash":"832b6e548db30fcf367b7ee5afff2dd7325a377af5ea9f00404cdc083ea54d96","blockSize":4194304,"blocks":["832b6e548db30fcf367b7ee5afff2dd7325a377af5ea9f00404cdc083ea54d96"]}},"index.js":{"size":290,"offset":"1453071","integrity":{"algorithm":"SHA256","hash":"a950d587bb76139ddfbcfa9d80f869e00e6d0299664758631d6977198cc5b2a6","blockSize":4194304,"blocks":["a950d587bb76139ddfbcfa9d80f869e00e6d0299664758631d6977198cc5b2a6"]}},"packageJson.js":{"size":2349,"offset":"1453361","integrity":{"algorithm":"SHA256","hash":"0c2a87c76002dedd9778d04a2e360d10009fc8561dc2d649e41f9196ffa8668e","blockSize":4194304,"blocks":["0c2a87c76002dedd9778d04a2e360d10009fc8561dc2d649e41f9196ffa8668e"]}},"transforms":{"files":{"object.js":{"size":2906,"offset":"1455710","integrity":{"algorithm":"SHA256","hash":"990e63a431feef1addad96aa8525fa4d0e797583244a04f527776869a0be6d4d","blockSize":4194304,"blocks":["990e63a431feef1addad96aa8525fa4d0e797583244a04f527776869a0be6d4d"]}}}},"transports":{"files":{"console.js":{"size":2517,"offset":"1458616","integrity":{"algorithm":"SHA256","hash":"1225cc6aa07c73f442c75b96c6df2990ac2b7a550d5430910056b114e1608272","blockSize":4194304,"blocks":["1225cc6aa07c73f442c75b96c6df2990ac2b7a550d5430910056b114e1608272"]}},"file":{"files":{"File.js":{"size":3299,"offset":"1461133","integrity":{"algorithm":"SHA256","hash":"c993861cbe264159b7d77cf6489ea875e1b248f4cdf95bb8a338fcb63b0b48a4","blockSize":4194304,"blocks":["c993861cbe264159b7d77cf6489ea875e1b248f4cdf95bb8a338fcb63b0b48a4"]}},"FileRegistry.js":{"size":1789,"offset":"1464432","integrity":{"algorithm":"SHA256","hash":"e3b6ab7aeb35b08072b3be580dcfb1c0ebbb8e892f2d412f2f22279e129f74a9","blockSize":4194304,"blocks":["e3b6ab7aeb35b08072b3be580dcfb1c0ebbb8e892f2d412f2f22279e129f74a9"]}},"NullFile.js":{"size":232,"offset":"1466221","integrity":{"algorithm":"SHA256","hash":"f59571c2745779b7ab0c1fb54f2e219964444adac1d1d03de8fbc9e633d78a32","blockSize":4194304,"blocks":["f59571c2745779b7ab0c1fb54f2e219964444adac1d1d03de8fbc9e633d78a32"]}},"index.js":{"size":4417,"offset":"1466453","integrity":{"algorithm":"SHA256","hash":"678db06d5434325ee12f208d6c4de5db12c7a99205812800af664d3993e9c1ec","blockSize":4194304,"blocks":["678db06d5434325ee12f208d6c4de5db12c7a99205812800af664d3993e9c1ec"]}}}},"ipc.js":{"size":808,"offset":"1470870","integrity":{"algorithm":"SHA256","hash":"e9c86603ad45226c86cfb77fd631b93c47df3f76c06312d684c23ac0931e447e","blockSize":4194304,"blocks":["e9c86603ad45226c86cfb77fd631b93c47df3f76c06312d684c23ac0931e447e"]}},"remote.js":{"size":2114,"offset":"1471678","integrity":{"algorithm":"SHA256","hash":"4d3d566a5cf821a80da7fc5a19748bd47128148f0a44709beb3164e3f95af705","blockSize":4194304,"blocks":["4d3d566a5cf821a80da7fc5a19748bd47128148f0a44709beb3164e3f95af705"]}}}}}},"renderer":{"files":{"electron-log-preload.js":{"size":2054,"offset":"1473792","integrity":{"algorithm":"SHA256","hash":"6e488d9b11ea738f05f51c2a22cc68c8add00ba5126f797f9192cc92ae899d13","blockSize":4194304,"blocks":["6e488d9b11ea738f05f51c2a22cc68c8add00ba5126f797f9192cc92ae899d13"]}},"index.js":{"size":2027,"offset":"1475846","integrity":{"algorithm":"SHA256","hash":"7207aa5cde3a7d0980dec28405364cb659eec0dc7c78e5e3f06df970b44cd3de","blockSize":4194304,"blocks":["7207aa5cde3a7d0980dec28405364cb659eec0dc7c78e5e3f06df970b44cd3de"]}},"lib":{"files":{"RendererErrorHandler.js":{"size":1998,"offset":"1477873","integrity":{"algorithm":"SHA256","hash":"5656699c9b819e572e3631f833e6b612e64648fefc43d2d7bc388932c58fa247","blockSize":4194304,"blocks":["5656699c9b819e572e3631f833e6b612e64648fefc43d2d7bc388932c58fa247"]}},"transports":{"files":{"console.js":{"size":2569,"offset":"1479871","integrity":{"algorithm":"SHA256","hash":"c6ced3b63c96dfd820fb942fc44cd6c223ed884d198618331ac03d7d2414f25d","blockSize":4194304,"blocks":["c6ced3b63c96dfd820fb942fc44cd6c223ed884d198618331ac03d7d2414f25d"]}},"ipc.js":{"size":2701,"offset":"1482440","integrity":{"algorithm":"SHA256","hash":"c9f48611211d81edfb9f18910626637f53bf42e666031c1342449cfc1f01ebe9","blockSize":4194304,"blocks":["c9f48611211d81edfb9f18910626637f53bf42e666031c1342449cfc1f01ebe9"]}}}}}}}}}}}},"electron-store":{"files":{"index.js":{"size":1869,"offset":"1485141","integrity":{"algorithm":"SHA256","hash":"e43cb7da3225388def8348aa0c6eca1e4d80cd7f3bae156f0a46b09056b1f775","blockSize":4194304,"blocks":["e43cb7da3225388def8348aa0c6eca1e4d80cd7f3bae156f0a46b09056b1f775"]}},"license":{"size":1117,"offset":"1487010","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":999,"offset":"1488127","integrity":{"algorithm":"SHA256","hash":"129017cb328190d9e6244c7d569cbafaa53112f574d4d8964991826464501189","blockSize":4194304,"blocks":["129017cb328190d9e6244c7d569cbafaa53112f574d4d8964991826464501189"]}}}},"electron-updater":{"files":{"LICENSE":{"size":1084,"offset":"1489126","integrity":{"algorithm":"SHA256","hash":"bed8d0ab3e6031817f775a641ff37313b0f5591bc8ba0ed79b978dafbd4231ce","blockSize":4194304,"blocks":["bed8d0ab3e6031817f775a641ff37313b0f5591bc8ba0ed79b978dafbd4231ce"]}},"out":{"files":{"AppAdapter.js":{"size":740,"offset":"1490210","integrity":{"algorithm":"SHA256","hash":"2fd4359fe091d7a42e2e2df8327e03aa52e202cbf593b11d9bc891cefd09caa8","blockSize":4194304,"blocks":["2fd4359fe091d7a42e2e2df8327e03aa52e202cbf593b11d9bc891cefd09caa8"]}},"AppAdapter.js.map":{"size":1814,"offset":"1490950","integrity":{"algorithm":"SHA256","hash":"8e3dbb32bcedad41e5b863d6a21eb2f858d84a82185b5006ac259b3a688c5529","blockSize":4194304,"blocks":["8e3dbb32bcedad41e5b863d6a21eb2f858d84a82185b5006ac259b3a688c5529"]}},"AppImageUpdater.js":{"size":5675,"offset":"1492764","integrity":{"algorithm":"SHA256","hash":"59dc2fee82511b18c8cfc1d301e663feb77674932c40808a155ba4db95cc8d61","blockSize":4194304,"blocks":["59dc2fee82511b18c8cfc1d301e663feb77674932c40808a155ba4db95cc8d61"]}},"AppImageUpdater.js.map":{"size":9265,"offset":"1498439","integrity":{"algorithm":"SHA256","hash":"fa4be85b2b97e134f62ed07a399eb6830609172ae50399ba2dfd8879cb39f34d","blockSize":4194304,"blocks":["fa4be85b2b97e134f62ed07a399eb6830609172ae50399ba2dfd8879cb39f34d"]}},"AppUpdater.js":{"size":33190,"offset":"1507704","integrity":{"algorithm":"SHA256","hash":"99921022d181fbd0637878fdebc74177be167d4d56a92c9a87d828f89ab67344","blockSize":4194304,"blocks":["99921022d181fbd0637878fdebc74177be167d4d56a92c9a87d828f89ab67344"]}},"AppUpdater.js.map":{"size":57020,"offset":"1540894","integrity":{"algorithm":"SHA256","hash":"8192aa87b01cbe4b248255f18becc60ac0569819d398a7cf9ee9fd14244d0d6c","blockSize":4194304,"blocks":["8192aa87b01cbe4b248255f18becc60ac0569819d398a7cf9ee9fd14244d0d6c"]}},"BaseUpdater.js":{"size":6035,"offset":"1597914","integrity":{"algorithm":"SHA256","hash":"9cff8b894ed709f6d9a5b938614fc377be89e1ea5bd1cc1f4cd6143048d918a3","blockSize":4194304,"blocks":["9cff8b894ed709f6d9a5b938614fc377be89e1ea5bd1cc1f4cd6143048d918a3"]}},"BaseUpdater.js.map":{"size":10539,"offset":"1603949","integrity":{"algorithm":"SHA256","hash":"17f78a05184434c5d9c973f173e86c06c8c4d147618740d6720e06dc33aa2d90","blockSize":4194304,"blocks":["17f78a05184434c5d9c973f173e86c06c8c4d147618740d6720e06dc33aa2d90"]}},"DebUpdater.js":{"size":3594,"offset":"1614488","integrity":{"algorithm":"SHA256","hash":"5f59636cd9a3b065c454c2ebecfdef268998fe2489c6700905f867fd0e1e63b4","blockSize":4194304,"blocks":["5f59636cd9a3b065c454c2ebecfdef268998fe2489c6700905f867fd0e1e63b4"]}},"DebUpdater.js.map":{"size":6061,"offset":"1618082","integrity":{"algorithm":"SHA256","hash":"71d2813cf2d925e8e19e94ce08f709028f3e2ebb2362d14eb2603be87bedc554","blockSize":4194304,"blocks":["71d2813cf2d925e8e19e94ce08f709028f3e2ebb2362d14eb2603be87bedc554"]}},"DownloadedUpdateHelper.js":{"size":6907,"offset":"1624143","integrity":{"algorithm":"SHA256","hash":"81d816fdfddf4711218f78c7625e22122b2159ec7c83209613dfb9e71a552e4d","blockSize":4194304,"blocks":["81d816fdfddf4711218f78c7625e22122b2159ec7c83209613dfb9e71a552e4d"]}},"DownloadedUpdateHelper.js.map":{"size":12251,"offset":"1631050","integrity":{"algorithm":"SHA256","hash":"cef2750982fd63ef843c4a274938682a1f8e2abd1eac794f1b612fdb496b1d00","blockSize":4194304,"blocks":["cef2750982fd63ef843c4a274938682a1f8e2abd1eac794f1b612fdb496b1d00"]}},"ElectronAppAdapter.js":{"size":1180,"offset":"1643301","integrity":{"algorithm":"SHA256","hash":"fa8fbf1de1c69924942aa3926878d391fba95007095836abe5f5b878506d4931","blockSize":4194304,"blocks":["fa8fbf1de1c69924942aa3926878d391fba95007095836abe5f5b878506d4931"]}},"ElectronAppAdapter.js.map":{"size":2289,"offset":"1644481","integrity":{"algorithm":"SHA256","hash":"f5b740ccc773315579ac1cc893db314f1bf589d4c499073755c625e8cdfa99a0","blockSize":4194304,"blocks":["f5b740ccc773315579ac1cc893db314f1bf589d4c499073755c625e8cdfa99a0"]}},"LinuxUpdater.js":{"size":5089,"offset":"1646770","integrity":{"algorithm":"SHA256","hash":"47a95d960724e5977b1d81d0e7a35b386fcd5a8ee286fa95f5a19a759e1c6558","blockSize":4194304,"blocks":["47a95d960724e5977b1d81d0e7a35b386fcd5a8ee286fa95f5a19a759e1c6558"]}},"LinuxUpdater.js.map":{"size":8236,"offset":"1651859","integrity":{"algorithm":"SHA256","hash":"919fc747abe6f00f486f15cde98064d32aa0e076f849fa54bfadbf2c17d22d79","blockSize":4194304,"blocks":["919fc747abe6f00f486f15cde98064d32aa0e076f849fa54bfadbf2c17d22d79"]}},"MacUpdater.js":{"size":12866,"offset":"1660095","integrity":{"algorithm":"SHA256","hash":"4824eb5d8c600f61ae69f14221f5252470b46da5be049645fa5ec10a42a5214b","blockSize":4194304,"blocks":["4824eb5d8c600f61ae69f14221f5252470b46da5be049645fa5ec10a42a5214b"]}},"MacUpdater.js.map":{"size":21163,"offset":"1672961","integrity":{"algorithm":"SHA256","hash":"ae785369e1dacc09cfaf567352790124b3a3b522c983f6da6e92dee52d5afbda","blockSize":4194304,"blocks":["ae785369e1dacc09cfaf567352790124b3a3b522c983f6da6e92dee52d5afbda"]}},"NsisUpdater.js":{"size":9416,"offset":"1694124","integrity":{"algorithm":"SHA256","hash":"31f36b4ef5cadd35a93df91d9454aa70044e41c0e6b4c799783dca4302cd03b6","blockSize":4194304,"blocks":["31f36b4ef5cadd35a93df91d9454aa70044e41c0e6b4c799783dca4302cd03b6"]}},"NsisUpdater.js.map":{"size":15024,"offset":"1703540","integrity":{"algorithm":"SHA256","hash":"99eb686f31a06877064a9b6b991898ac63649c9d35d1089f95d6007c4821283e","blockSize":4194304,"blocks":["99eb686f31a06877064a9b6b991898ac63649c9d35d1089f95d6007c4821283e"]}},"PacmanUpdater.js":{"size":2796,"offset":"1718564","integrity":{"algorithm":"SHA256","hash":"e4d76d7072d81503b49de126385c10e8592711d3a10c36e9c23fbd125d298320","blockSize":4194304,"blocks":["e4d76d7072d81503b49de126385c10e8592711d3a10c36e9c23fbd125d298320"]}},"PacmanUpdater.js.map":{"size":4838,"offset":"1721360","integrity":{"algorithm":"SHA256","hash":"c51dfac79e9c9c0d01ad178ecb5554c4e0555d3d16ccba9d5890ed89df9fb309","blockSize":4194304,"blocks":["c51dfac79e9c9c0d01ad178ecb5554c4e0555d3d16ccba9d5890ed89df9fb309"]}},"RpmUpdater.js":{"size":2891,"offset":"1726198","integrity":{"algorithm":"SHA256","hash":"1e05f4be81a4ac304b53d0df1f6d83dd2de7e75aee95896ce67ef8c49cf736e7","blockSize":4194304,"blocks":["1e05f4be81a4ac304b53d0df1f6d83dd2de7e75aee95896ce67ef8c49cf736e7"]}},"RpmUpdater.js.map":{"size":5376,"offset":"1729089","integrity":{"algorithm":"SHA256","hash":"e38408e553e3ad88683fd53cdb0172ea9c49eb27a79bd806766dab4df59e1aa0","blockSize":4194304,"blocks":["e38408e553e3ad88683fd53cdb0172ea9c49eb27a79bd806766dab4df59e1aa0"]}},"differentialDownloader":{"files":{"DataSplitter.js":{"size":9396,"offset":"1734465","integrity":{"algorithm":"SHA256","hash":"a1d74dc923cc779b1cc8b8bd6bce24879b7266b8d6f659f09f53d5e5275e9ab4","blockSize":4194304,"blocks":["a1d74dc923cc779b1cc8b8bd6bce24879b7266b8d6f659f09f53d5e5275e9ab4"]}},"DataSplitter.js.map":{"size":16649,"offset":"1743861","integrity":{"algorithm":"SHA256","hash":"7e082ae113a7187cce9b8b86d02d6c1ab4c352a0e45914ef61a8e6f808798acb","blockSize":4194304,"blocks":["7e082ae113a7187cce9b8b86d02d6c1ab4c352a0e45914ef61a8e6f808798acb"]}},"DifferentialDownloader.js":{"size":12517,"offset":"1760510","integrity":{"algorithm":"SHA256","hash":"428ada90afe644da1a7517670ba07aa8cc307f36587e00f2f748f8f6dbc992bd","blockSize":4194304,"blocks":["428ada90afe644da1a7517670ba07aa8cc307f36587e00f2f748f8f6dbc992bd"]}},"DifferentialDownloader.js.map":{"size":21368,"offset":"1773027","integrity":{"algorithm":"SHA256","hash":"f64b2d213f3a9822e37b27e9a70604673c80e689f3ae61a15e67861015ab5b67","blockSize":4194304,"blocks":["f64b2d213f3a9822e37b27e9a70604673c80e689f3ae61a15e67861015ab5b67"]}},"FileWithEmbeddedBlockMapDifferentialDownloader.js":{"size":1861,"offset":"1794395","integrity":{"algorithm":"SHA256","hash":"8f3c12c0d7e6e0284b9c9af068a0c6caa56f691997c763bb5850b8fa98c19650","blockSize":4194304,"blocks":["8f3c12c0d7e6e0284b9c9af068a0c6caa56f691997c763bb5850b8fa98c19650"]}},"FileWithEmbeddedBlockMapDifferentialDownloader.js.map":{"size":3213,"offset":"1796256","integrity":{"algorithm":"SHA256","hash":"f21cdffe96e592998d830c9cf3d62cb1c209cc5aa0697dbff1e5e7b3dc7156f4","blockSize":4194304,"blocks":["f21cdffe96e592998d830c9cf3d62cb1c209cc5aa0697dbff1e5e7b3dc7156f4"]}},"GenericDifferentialDownloader.js":{"size":524,"offset":"1799469","integrity":{"algorithm":"SHA256","hash":"62ca9a1d3ca12deca41ad902a24d8fec34ec150cdc194478d5b4fc987a66921b","blockSize":4194304,"blocks":["62ca9a1d3ca12deca41ad902a24d8fec34ec150cdc194478d5b4fc987a66921b"]}},"GenericDifferentialDownloader.js.map":{"size":709,"offset":"1799993","integrity":{"algorithm":"SHA256","hash":"37a09dab5af73258527d65396a02363f10df71c1d4c60555b4492ee5c847aada","blockSize":4194304,"blocks":["37a09dab5af73258527d65396a02363f10df71c1d4c60555b4492ee5c847aada"]}},"ProgressDifferentialDownloadCallbackTransform.js":{"size":3824,"offset":"1800702","integrity":{"algorithm":"SHA256","hash":"d4b62c2f8eec10bb8edcc0227cde609734ef344bd3e727a48cdb806ea3608ef4","blockSize":4194304,"blocks":["d4b62c2f8eec10bb8edcc0227cde609734ef344bd3e727a48cdb806ea3608ef4"]}},"ProgressDifferentialDownloadCallbackTransform.js.map":{"size":6590,"offset":"1804526","integrity":{"algorithm":"SHA256","hash":"c7d2540b01b43b9a8ffde20eecd5a20d0343265d95ce3dc8cb0a32ecfcb6b304","blockSize":4194304,"blocks":["c7d2540b01b43b9a8ffde20eecd5a20d0343265d95ce3dc8cb0a32ecfcb6b304"]}},"downloadPlanBuilder.js":{"size":5517,"offset":"1811116","integrity":{"algorithm":"SHA256","hash":"4ee0506c1431e86c6e693a5d118c2909f7638cc27000e3c7569cd43da08bfbf4","blockSize":4194304,"blocks":["4ee0506c1431e86c6e693a5d118c2909f7638cc27000e3c7569cd43da08bfbf4"]}},"downloadPlanBuilder.js.map":{"size":10248,"offset":"1816633","integrity":{"algorithm":"SHA256","hash":"f05e73a087686a5d06a1a2ce77f539ee1250653fd192949e3dd466b328fc4898","blockSize":4194304,"blocks":["f05e73a087686a5d06a1a2ce77f539ee1250653fd192949e3dd466b328fc4898"]}},"multipleRangeDownloader.js":{"size":5066,"offset":"1826881","integrity":{"algorithm":"SHA256","hash":"acb4cc89c273776d5bfc0409e032f234a4aafd1f02cc442734d6c4a5db4be4cc","blockSize":4194304,"blocks":["acb4cc89c273776d5bfc0409e032f234a4aafd1f02cc442734d6c4a5db4be4cc"]}},"multipleRangeDownloader.js.map":{"size":9247,"offset":"1831947","integrity":{"algorithm":"SHA256","hash":"89b02ec3b2e23bc1e378eb73e1c6f9fb4eaa0ae592166486ae3a88f97fa6f23d","blockSize":4194304,"blocks":["89b02ec3b2e23bc1e378eb73e1c6f9fb4eaa0ae592166486ae3a88f97fa6f23d"]}}}},"electronHttpExecutor.js":{"size":3258,"offset":"1841194","integrity":{"algorithm":"SHA256","hash":"907bc7f2c71c1f964fe83f71337a520073e753f3f35ea00076f5676aebaa6404","blockSize":4194304,"blocks":["907bc7f2c71c1f964fe83f71337a520073e753f3f35ea00076f5676aebaa6404"]}},"electronHttpExecutor.js.map":{"size":5547,"offset":"1844452","integrity":{"algorithm":"SHA256","hash":"3e6eafc704edaa106700ef5ce03e621a33c86a974e5499d3a3551a18e4851e8a","blockSize":4194304,"blocks":["3e6eafc704edaa106700ef5ce03e621a33c86a974e5499d3a3551a18e4851e8a"]}},"main.js":{"size":4494,"offset":"1849999","integrity":{"algorithm":"SHA256","hash":"c0f5cc41a2ef973672066222109850ac22fc70bcca1880e5c3cb8311f7ab05e5","blockSize":4194304,"blocks":["c0f5cc41a2ef973672066222109850ac22fc70bcca1880e5c3cb8311f7ab05e5"]}},"main.js.map":{"size":4427,"offset":"1854493","integrity":{"algorithm":"SHA256","hash":"3b9ef6f5494138aa2e5f13a6d29cc07d8c9ee5546b7a278d233b0d0f9318c243","blockSize":4194304,"blocks":["3b9ef6f5494138aa2e5f13a6d29cc07d8c9ee5546b7a278d233b0d0f9318c243"]}},"providerFactory.js":{"size":3363,"offset":"1858920","integrity":{"algorithm":"SHA256","hash":"b1f323d02b37f9b27439704cd48c06f41159c289cd0b3cd4e4b536231e7d5daa","blockSize":4194304,"blocks":["b1f323d02b37f9b27439704cd48c06f41159c289cd0b3cd4e4b536231e7d5daa"]}},"providerFactory.js.map":{"size":5450,"offset":"1862283","integrity":{"algorithm":"SHA256","hash":"1f180fd23f1b1ce6f1b0f56e7ea8d92ecc3e86f2d53ec798ec224151c475cd29","blockSize":4194304,"blocks":["1f180fd23f1b1ce6f1b0f56e7ea8d92ecc3e86f2d53ec798ec224151c475cd29"]}},"providers":{"files":{"BitbucketProvider.js":{"size":1969,"offset":"1867733","integrity":{"algorithm":"SHA256","hash":"d918e2d9a98797a36dfa777b380689282187dadf9c881e94b7e2073c8d325416","blockSize":4194304,"blocks":["d918e2d9a98797a36dfa777b380689282187dadf9c881e94b7e2073c8d325416"]}},"BitbucketProvider.js.map":{"size":3454,"offset":"1869702","integrity":{"algorithm":"SHA256","hash":"bf4e8f4f4efbf1c89aa4cb4979d10e4b329cffee9726a12795bb1c5cf324703a","blockSize":4194304,"blocks":["bf4e8f4f4efbf1c89aa4cb4979d10e4b329cffee9726a12795bb1c5cf324703a"]}},"GenericProvider.js":{"size":2252,"offset":"1873156","integrity":{"algorithm":"SHA256","hash":"c0d1f1aed62d7418e4d292118b3e079f9680914c554fe7604786b73771297d8a","blockSize":4194304,"blocks":["c0d1f1aed62d7418e4d292118b3e079f9680914c554fe7604786b73771297d8a"]}},"GenericProvider.js.map":{"size":3777,"offset":"1875408","integrity":{"algorithm":"SHA256","hash":"32687ae2a040a8a153135d9aced2afbffe42d1ad337ce8ca53f2e899a6900640","blockSize":4194304,"blocks":["32687ae2a040a8a153135d9aced2afbffe42d1ad337ce8ca53f2e899a6900640"]}},"GitHubProvider.js":{"size":11423,"offset":"1879185","integrity":{"algorithm":"SHA256","hash":"17c0ae98c1fb7943057fe88c0cc951a84acc81988813dba1aca20e911f82f601","blockSize":4194304,"blocks":["17c0ae98c1fb7943057fe88c0cc951a84acc81988813dba1aca20e911f82f601"]}},"GitHubProvider.js.map":{"size":19391,"offset":"1890608","integrity":{"algorithm":"SHA256","hash":"fd3e616628b2450be2cb1e3286bf92d96a3fc63f1d50d441836a4598ef3d16b9","blockSize":4194304,"blocks":["fd3e616628b2450be2cb1e3286bf92d96a3fc63f1d50d441836a4598ef3d16b9"]}},"GitLabProvider.js":{"size":13769,"offset":"1909999","integrity":{"algorithm":"SHA256","hash":"21c84980d19f6de252971c240c66bdd0362fb3928b20d87dca7fcc6cbe34ffd7","blockSize":4194304,"blocks":["21c84980d19f6de252971c240c66bdd0362fb3928b20d87dca7fcc6cbe34ffd7"]}},"GitLabProvider.js.map":{"size":22371,"offset":"1923768","integrity":{"algorithm":"SHA256","hash":"90180590efd4f222c45a2bd5e8af8476d0f3a2444c2cc8aeda488ef948b37258","blockSize":4194304,"blocks":["90180590efd4f222c45a2bd5e8af8476d0f3a2444c2cc8aeda488ef948b37258"]}},"KeygenProvider.js":{"size":2205,"offset":"1946139","integrity":{"algorithm":"SHA256","hash":"361cd9b7c29c6db9b94ac74947a6d4c7b48ac01a74c6b7950d9ff256ec783568","blockSize":4194304,"blocks":["361cd9b7c29c6db9b94ac74947a6d4c7b48ac01a74c6b7950d9ff256ec783568"]}},"KeygenProvider.js.map":{"size":3892,"offset":"1948344","integrity":{"algorithm":"SHA256","hash":"a5082b0cd3893d9e77fbbb62cdc8a2ffa3f701c9f65c3b7ab1279eea662b3bb5","blockSize":4194304,"blocks":["a5082b0cd3893d9e77fbbb62cdc8a2ffa3f701c9f65c3b7ab1279eea662b3bb5"]}},"PrivateGitHubProvider.js":{"size":4378,"offset":"1952236","integrity":{"algorithm":"SHA256","hash":"2dff56a9875d783cc0883b6a60dfbf5cfc6d4097201b3b968858f1570b6d0d2f","blockSize":4194304,"blocks":["2dff56a9875d783cc0883b6a60dfbf5cfc6d4097201b3b968858f1570b6d0d2f"]}},"PrivateGitHubProvider.js.map":{"size":8136,"offset":"1956614","integrity":{"algorithm":"SHA256","hash":"af0b5ab6b329450031a9f19c54013d577183f920c2ea804a0a2dc0794d19a8ae","blockSize":4194304,"blocks":["af0b5ab6b329450031a9f19c54013d577183f920c2ea804a0a2dc0794d19a8ae"]}},"Provider.js":{"size":6002,"offset":"1964750","integrity":{"algorithm":"SHA256","hash":"48601c5ceb7aaaeec096b84186a1155964128e64bbe8c009dd2d9cb9afccda37","blockSize":4194304,"blocks":["48601c5ceb7aaaeec096b84186a1155964128e64bbe8c009dd2d9cb9afccda37"]}},"Provider.js.map":{"size":11692,"offset":"1970752","integrity":{"algorithm":"SHA256","hash":"a131fb662af5e7164c84b64b71402e3d84e6a3f09404a204d871f973285ea7e8","blockSize":4194304,"blocks":["a131fb662af5e7164c84b64b71402e3d84e6a3f09404a204d871f973285ea7e8"]}}}},"types.js":{"size":1551,"offset":"1982444","integrity":{"algorithm":"SHA256","hash":"b92b36b9fd6ad4790a05d8ef0c1e65b875923ff098e5371a59076b20b17f2e3b","blockSize":4194304,"blocks":["b92b36b9fd6ad4790a05d8ef0c1e65b875923ff098e5371a59076b20b17f2e3b"]}},"types.js.map":{"size":3619,"offset":"1983995","integrity":{"algorithm":"SHA256","hash":"3f31519e9ef41568d2308ccb5a2a7c08e54bffcd43c7547610727235babd2b3e","blockSize":4194304,"blocks":["3f31519e9ef41568d2308ccb5a2a7c08e54bffcd43c7547610727235babd2b3e"]}},"util.js":{"size":1278,"offset":"1987614","integrity":{"algorithm":"SHA256","hash":"104ee9520aecd56ec9311e2ac8980d02f86b07b20010b6b59a280c61478ce1a1","blockSize":4194304,"blocks":["104ee9520aecd56ec9311e2ac8980d02f86b07b20010b6b59a280c61478ce1a1"]}},"util.js.map":{"size":2040,"offset":"1988892","integrity":{"algorithm":"SHA256","hash":"1cc2ff8a950733d982b74c7f0f5f0d3a2b8af6c8a8acb255908dd14fa7058cc0","blockSize":4194304,"blocks":["1cc2ff8a950733d982b74c7f0f5f0d3a2b8af6c8a8acb255908dd14fa7058cc0"]}},"windowsExecutableCodeSignatureVerifier.js":{"size":7539,"offset":"1990932","integrity":{"algorithm":"SHA256","hash":"4738e446904710a2497fd3408fdf6416c5515d9177c0add0f2427bd725969c21","blockSize":4194304,"blocks":["4738e446904710a2497fd3408fdf6416c5515d9177c0add0f2427bd725969c21"]}},"windowsExecutableCodeSignatureVerifier.js.map":{"size":11364,"offset":"1998471","integrity":{"algorithm":"SHA256","hash":"ba0c5ba99b1b429a720b350e7802af84bae782b150beef9c169143758ea9115c","blockSize":4194304,"blocks":["ba0c5ba99b1b429a720b350e7802af84bae782b150beef9c169143758ea9115c"]}}}},"package.json":{"size":1037,"offset":"2009835","integrity":{"algorithm":"SHA256","hash":"6473e23d77f0bc3143fb0cef28acf7385b1b1e739bae4e1254d5d64ff274227f","blockSize":4194304,"blocks":["6473e23d77f0bc3143fb0cef28acf7385b1b1e739bae4e1254d5d64ff274227f"]}},"node_modules":{"files":{"semver":{"files":{"LICENSE":{"size":765,"offset":"2010872","integrity":{"algorithm":"SHA256","hash":"4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b","blockSize":4194304,"blocks":["4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b"]}},"bin":{"files":{"semver.js":{"size":4748,"offset":"2011637","integrity":{"algorithm":"SHA256","hash":"82c28f9bc9e598d255edd507d1e9b157f37b8dac0f2da25a813b5e7121600be8","blockSize":4194304,"blocks":["82c28f9bc9e598d255edd507d1e9b157f37b8dac0f2da25a813b5e7121600be8"]}}}},"classes":{"files":{"comparator.js":{"size":3631,"offset":"2016385","integrity":{"algorithm":"SHA256","hash":"054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac","blockSize":4194304,"blocks":["054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac"]}},"index.js":{"size":143,"offset":"2020016","integrity":{"algorithm":"SHA256","hash":"3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17","blockSize":4194304,"blocks":["3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17"]}},"range.js":{"size":14977,"offset":"2020159","integrity":{"algorithm":"SHA256","hash":"cf8f8eb6934663ae2a9d04838d4d71555427a2abd3c8748ee5219507969a6b46","blockSize":4194304,"blocks":["cf8f8eb6934663ae2a9d04838d4d71555427a2abd3c8748ee5219507969a6b46"]}},"semver.js":{"size":9480,"offset":"2035136","integrity":{"algorithm":"SHA256","hash":"d5ba57e5c93f031b1d234fca4bb746746fcd1fe51be7e5ee895601e2c12e2083","blockSize":4194304,"blocks":["d5ba57e5c93f031b1d234fca4bb746746fcd1fe51be7e5ee895601e2c12e2083"]}}}},"functions":{"files":{"clean.js":{"size":205,"offset":"2044616","integrity":{"algorithm":"SHA256","hash":"4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f","blockSize":4194304,"blocks":["4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f"]}},"cmp.js":{"size":961,"offset":"2044821","integrity":{"algorithm":"SHA256","hash":"a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3","blockSize":4194304,"blocks":["a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3"]}},"coerce.js":{"size":2004,"offset":"2045782","integrity":{"algorithm":"SHA256","hash":"28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a","blockSize":4194304,"blocks":["28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a"]}},"compare-build.js":{"size":281,"offset":"2047786","integrity":{"algorithm":"SHA256","hash":"5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c","blockSize":4194304,"blocks":["5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c"]}},"compare-loose.js":{"size":132,"offset":"2048067","integrity":{"algorithm":"SHA256","hash":"07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78","blockSize":4194304,"blocks":["07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78"]}},"compare.js":{"size":170,"offset":"2048199","integrity":{"algorithm":"SHA256","hash":"d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c","blockSize":4194304,"blocks":["d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c"]}},"diff.js":{"size":1423,"offset":"2048369","integrity":{"algorithm":"SHA256","hash":"7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31","blockSize":4194304,"blocks":["7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31"]}},"eq.js":{"size":126,"offset":"2049792","integrity":{"algorithm":"SHA256","hash":"b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936","blockSize":4194304,"blocks":["b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936"]}},"gt.js":{"size":124,"offset":"2049918","integrity":{"algorithm":"SHA256","hash":"135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93","blockSize":4194304,"blocks":["135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93"]}},"gte.js":{"size":127,"offset":"2050042","integrity":{"algorithm":"SHA256","hash":"991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d","blockSize":4194304,"blocks":["991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d"]}},"inc.js":{"size":478,"offset":"2050169","integrity":{"algorithm":"SHA256","hash":"952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493","blockSize":4194304,"blocks":["952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493"]}},"lt.js":{"size":124,"offset":"2050647","integrity":{"algorithm":"SHA256","hash":"1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25","blockSize":4194304,"blocks":["1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25"]}},"lte.js":{"size":127,"offset":"2050771","integrity":{"algorithm":"SHA256","hash":"3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800","blockSize":4194304,"blocks":["3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800"]}},"major.js":{"size":136,"offset":"2050898","integrity":{"algorithm":"SHA256","hash":"5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276","blockSize":4194304,"blocks":["5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276"]}},"minor.js":{"size":136,"offset":"2051034","integrity":{"algorithm":"SHA256","hash":"1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6","blockSize":4194304,"blocks":["1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6"]}},"neq.js":{"size":128,"offset":"2051170","integrity":{"algorithm":"SHA256","hash":"a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127","blockSize":4194304,"blocks":["a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127"]}},"parse.js":{"size":331,"offset":"2051298","integrity":{"algorithm":"SHA256","hash":"29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad","blockSize":4194304,"blocks":["29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad"]}},"patch.js":{"size":136,"offset":"2051629","integrity":{"algorithm":"SHA256","hash":"f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd","blockSize":4194304,"blocks":["f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd"]}},"prerelease.js":{"size":234,"offset":"2051765","integrity":{"algorithm":"SHA256","hash":"baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593","blockSize":4194304,"blocks":["baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593"]}},"rcompare.js":{"size":132,"offset":"2051999","integrity":{"algorithm":"SHA256","hash":"84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0","blockSize":4194304,"blocks":["84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0"]}},"rsort.js":{"size":163,"offset":"2052131","integrity":{"algorithm":"SHA256","hash":"6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3","blockSize":4194304,"blocks":["6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3"]}},"satisfies.js":{"size":247,"offset":"2052294","integrity":{"algorithm":"SHA256","hash":"8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946","blockSize":4194304,"blocks":["8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946"]}},"sort.js":{"size":161,"offset":"2052541","integrity":{"algorithm":"SHA256","hash":"c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8","blockSize":4194304,"blocks":["c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8"]}},"valid.js":{"size":176,"offset":"2052702","integrity":{"algorithm":"SHA256","hash":"0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025","blockSize":4194304,"blocks":["0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025"]}}}},"index.js":{"size":2630,"offset":"2052878","integrity":{"algorithm":"SHA256","hash":"646e0b707f56dca7cb90cebc6fe687278bcc1a16fdcc83756dbe23083ff15e06","blockSize":4194304,"blocks":["646e0b707f56dca7cb90cebc6fe687278bcc1a16fdcc83756dbe23083ff15e06"]}},"internal":{"files":{"constants.js":{"size":873,"offset":"2055508","integrity":{"algorithm":"SHA256","hash":"38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9","blockSize":4194304,"blocks":["38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9"]}},"debug.js":{"size":240,"offset":"2056381","integrity":{"algorithm":"SHA256","hash":"8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3","blockSize":4194304,"blocks":["8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3"]}},"identifiers.js":{"size":525,"offset":"2056621","integrity":{"algorithm":"SHA256","hash":"b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7","blockSize":4194304,"blocks":["b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7"]}},"lrucache.js":{"size":802,"offset":"2057146","integrity":{"algorithm":"SHA256","hash":"14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f","blockSize":4194304,"blocks":["14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f"]}},"parse-options.js":{"size":338,"offset":"2057948","integrity":{"algorithm":"SHA256","hash":"fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01","blockSize":4194304,"blocks":["fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01"]}},"re.js":{"size":8138,"offset":"2058286","integrity":{"algorithm":"SHA256","hash":"6a47e73c279fa8c4011f670471f50830a39922b43797b2884e6cc03f65b64d6c","blockSize":4194304,"blocks":["6a47e73c279fa8c4011f670471f50830a39922b43797b2884e6cc03f65b64d6c"]}}}},"package.json":{"size":1350,"offset":"2066424","integrity":{"algorithm":"SHA256","hash":"783e44dd42d6021177385b15de76f71d49d472f79b60ab22ed69f336d5e0f9d9","blockSize":4194304,"blocks":["783e44dd42d6021177385b15de76f71d49d472f79b60ab22ed69f336d5e0f9d9"]}},"preload.js":{"size":83,"offset":"2067774","integrity":{"algorithm":"SHA256","hash":"edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba","blockSize":4194304,"blocks":["edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba"]}},"range.bnf":{"size":619,"offset":"2067857","integrity":{"algorithm":"SHA256","hash":"ed628fdaff64be366d07f6cc4559eae4de109826f743ea7f5e1588c370bca49a","blockSize":4194304,"blocks":["ed628fdaff64be366d07f6cc4559eae4de109826f743ea7f5e1588c370bca49a"]}},"ranges":{"files":{"gtr.js":{"size":231,"offset":"2068476","integrity":{"algorithm":"SHA256","hash":"8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19","blockSize":4194304,"blocks":["8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19"]}},"intersects.js":{"size":224,"offset":"2068707","integrity":{"algorithm":"SHA256","hash":"fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f","blockSize":4194304,"blocks":["fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f"]}},"ltr.js":{"size":227,"offset":"2068931","integrity":{"algorithm":"SHA256","hash":"e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038","blockSize":4194304,"blocks":["e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038"]}},"max-satisfying.js":{"size":593,"offset":"2069158","integrity":{"algorithm":"SHA256","hash":"e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416","blockSize":4194304,"blocks":["e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416"]}},"min-satisfying.js":{"size":591,"offset":"2069751","integrity":{"algorithm":"SHA256","hash":"2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca","blockSize":4194304,"blocks":["2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca"]}},"min-version.js":{"size":1514,"offset":"2070342","integrity":{"algorithm":"SHA256","hash":"fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b","blockSize":4194304,"blocks":["fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b"]}},"outside.js":{"size":2204,"offset":"2071856","integrity":{"algorithm":"SHA256","hash":"3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca","blockSize":4194304,"blocks":["3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca"]}},"simplify.js":{"size":1355,"offset":"2074060","integrity":{"algorithm":"SHA256","hash":"7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934","blockSize":4194304,"blocks":["7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934"]}},"subset.js":{"size":7524,"offset":"2075415","integrity":{"algorithm":"SHA256","hash":"87387952fbe154f5874d5f09dd2173e782e894a76fa8370ce23f4120e2ae7eae","blockSize":4194304,"blocks":["87387952fbe154f5874d5f09dd2173e782e894a76fa8370ce23f4120e2ae7eae"]}},"to-comparators.js":{"size":282,"offset":"2082939","integrity":{"algorithm":"SHA256","hash":"6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9","blockSize":4194304,"blocks":["6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9"]}},"valid.js":{"size":326,"offset":"2083221","integrity":{"algorithm":"SHA256","hash":"5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac","blockSize":4194304,"blocks":["5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac"]}}}}}}}}}},"env-paths":{"files":{"index.js":{"size":2027,"offset":"2083547","integrity":{"algorithm":"SHA256","hash":"52d9fa02d2c9c01a9a1505103cb79ed3cefda2d043f31dc43890fb42bc0125bb","blockSize":4194304,"blocks":["52d9fa02d2c9c01a9a1505103cb79ed3cefda2d043f31dc43890fb42bc0125bb"]}},"license":{"size":1117,"offset":"2085574","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":627,"offset":"2086691","integrity":{"algorithm":"SHA256","hash":"adcc53a719cba20c66b74c17d18ddcc5ca3763349cc6e05fda0cfccdbc54bfb0","blockSize":4194304,"blocks":["adcc53a719cba20c66b74c17d18ddcc5ca3763349cc6e05fda0cfccdbc54bfb0"]}}}},"fast-deep-equal":{"files":{"LICENSE":{"size":1074,"offset":"2087318","integrity":{"algorithm":"SHA256","hash":"7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a","blockSize":4194304,"blocks":["7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]}},"es6":{"files":{"index.js":{"size":1935,"offset":"2088392","integrity":{"algorithm":"SHA256","hash":"d7f027497048c75e17268dbc66b670579d4f70f2dc0e019cdc9edf5078c247d6","blockSize":4194304,"blocks":["d7f027497048c75e17268dbc66b670579d4f70f2dc0e019cdc9edf5078c247d6"]}},"react.js":{"size":2209,"offset":"2090327","integrity":{"algorithm":"SHA256","hash":"366779cbb7821d26d18b9eaa12b6788cbb101cdbbabcae36f2919a5f48534ef0","blockSize":4194304,"blocks":["366779cbb7821d26d18b9eaa12b6788cbb101cdbbabcae36f2919a5f48534ef0"]}}}},"index.js":{"size":1177,"offset":"2092536","integrity":{"algorithm":"SHA256","hash":"eb469e206280321a3878f2335ec98aa2104a155079d8ed83a23029098dccd215","blockSize":4194304,"blocks":["eb469e206280321a3878f2335ec98aa2104a155079d8ed83a23029098dccd215"]}},"package.json":{"size":754,"offset":"2093713","integrity":{"algorithm":"SHA256","hash":"8364d2abc7912ad54eba3447f9da67767652c15bd65c0f7b7f35646bb4556758","blockSize":4194304,"blocks":["8364d2abc7912ad54eba3447f9da67767652c15bd65c0f7b7f35646bb4556758"]}},"react.js":{"size":1451,"offset":"2094467","integrity":{"algorithm":"SHA256","hash":"37cbd168dbd42c73119ce7326556bddef40b3a5fbd2e215cf81a7c78fb73ff9a","blockSize":4194304,"blocks":["37cbd168dbd42c73119ce7326556bddef40b3a5fbd2e215cf81a7c78fb73ff9a"]}}}},"fast-uri":{"files":{"LICENSE":{"size":1813,"offset":"2095918","integrity":{"algorithm":"SHA256","hash":"b010b0dfdfdb23d7396e03b82cd4621fc9bb8f95d6b0aea70b9c24e12074c786","blockSize":4194304,"blocks":["b010b0dfdfdb23d7396e03b82cd4621fc9bb8f95d6b0aea70b9c24e12074c786"]}},"benchmark":{"files":{"benchmark.mjs":{"size":4421,"offset":"2097731","integrity":{"algorithm":"SHA256","hash":"45ba9783c3258e448b05bd371161ef9fcbeed332ba1e9455ca9c98edb24e1f33","blockSize":4194304,"blocks":["45ba9783c3258e448b05bd371161ef9fcbeed332ba1e9455ca9c98edb24e1f33"]}},"equal.mjs":{"size":1305,"offset":"2102152","integrity":{"algorithm":"SHA256","hash":"36eb5b2acea9c4e969ab8fe028e88b781aa948e597368655a13528c3a93f1d39","blockSize":4194304,"blocks":["36eb5b2acea9c4e969ab8fe028e88b781aa948e597368655a13528c3a93f1d39"]}},"non-simple-domain.mjs":{"size":838,"offset":"2103457","integrity":{"algorithm":"SHA256","hash":"303eb41faa6c2489b5086f3d2764bf6ecaf3b937b385647c6e8b14aaf2582524","blockSize":4194304,"blocks":["303eb41faa6c2489b5086f3d2764bf6ecaf3b937b385647c6e8b14aaf2582524"]}},"package.json":{"size":220,"offset":"2104295","integrity":{"algorithm":"SHA256","hash":"7e88fa1a8044e61f8784ba64266d4d097b878867cf3b9d82fa13ea6f2022e310","blockSize":4194304,"blocks":["7e88fa1a8044e61f8784ba64266d4d097b878867cf3b9d82fa13ea6f2022e310"]}},"string-array-to-hex-stripped.mjs":{"size":819,"offset":"2104515","integrity":{"algorithm":"SHA256","hash":"693d4a312b0e275e02ef5531d707ff7df6cddf14cd83bc09a79909ea2008bfd4","blockSize":4194304,"blocks":["693d4a312b0e275e02ef5531d707ff7df6cddf14cd83bc09a79909ea2008bfd4"]}},"ws-is-secure.mjs":{"size":1891,"offset":"2105334","integrity":{"algorithm":"SHA256","hash":"6f105dc633aadd4bd4b8362765f4a1d44fb31fe0c8754cb11d73f27ff7d6527b","blockSize":4194304,"blocks":["6f105dc633aadd4bd4b8362765f4a1d44fb31fe0c8754cb11d73f27ff7d6527b"]}}}},"eslint.config.js":{"size":135,"offset":"2107225","integrity":{"algorithm":"SHA256","hash":"52e3a2601a98f23c954d664ab8de95fddb390789f8b067815e484b010d3da2d0","blockSize":4194304,"blocks":["52e3a2601a98f23c954d664ab8de95fddb390789f8b067815e484b010d3da2d0"]}},"index.js":{"size":12232,"offset":"2107360","integrity":{"algorithm":"SHA256","hash":"f5f641da3dfef3405e01a0fb21dd546bb86dc7fb553f6b26a541265eb22def55","blockSize":4194304,"blocks":["f5f641da3dfef3405e01a0fb21dd546bb86dc7fb553f6b26a541265eb22def55"]}},"lib":{"files":{"schemes.js":{"size":7122,"offset":"2119592","integrity":{"algorithm":"SHA256","hash":"0f9497f8e43c9b002d79c8a916709daa4ae8a6462735b1b5dc6ad587a28a5064","blockSize":4194304,"blocks":["0f9497f8e43c9b002d79c8a916709daa4ae8a6462735b1b5dc6ad587a28a5064"]}},"utils.js":{"size":10762,"offset":"2126714","integrity":{"algorithm":"SHA256","hash":"3394986f9670b821493943faafe5d83ccc15109aba908f1b5dd017e27b0d0ea7","blockSize":4194304,"blocks":["3394986f9670b821493943faafe5d83ccc15109aba908f1b5dd017e27b0d0ea7"]}}}},"package.json":{"size":827,"offset":"2137476","integrity":{"algorithm":"SHA256","hash":"02fbed4d0d483c2598fe54079b53a82f1f7e79953c05e6d47b5b5d3df0db66c4","blockSize":4194304,"blocks":["02fbed4d0d483c2598fe54079b53a82f1f7e79953c05e6d47b5b5d3df0db66c4"]}},"tsconfig.json":{"size":166,"offset":"2138303","integrity":{"algorithm":"SHA256","hash":"6bbba68684f6d6f1613d9ae79de617c25d8d749f30942307faee46a6d2fd721f","blockSize":4194304,"blocks":["6bbba68684f6d6f1613d9ae79de617c25d8d749f30942307faee46a6d2fd721f"]}},"types":{"files":{"index.test-d.ts":{"size":479,"offset":"2138469","integrity":{"algorithm":"SHA256","hash":"ad36147194c3ecfaecf55d75dd22f0b2c6b4ca476d6450cd307dceaf39012b46","blockSize":4194304,"blocks":["ad36147194c3ecfaecf55d75dd22f0b2c6b4ca476d6450cd307dceaf39012b46"]}}}}}},"fs-extra":{"files":{"LICENSE":{"size":1084,"offset":"2138948","integrity":{"algorithm":"SHA256","hash":"1e76029602ae9b21cc4e612db2496d92febed882ba13ba745f8b3309e85f9d39","blockSize":4194304,"blocks":["1e76029602ae9b21cc4e612db2496d92febed882ba13ba745f8b3309e85f9d39"]}},"lib":{"files":{"copy":{"files":{"copy-sync.js":{"size":5776,"offset":"2140032","integrity":{"algorithm":"SHA256","hash":"a50856fe7fab3d1d22e8fbf5f32543d46342257cad5e31df8f2a7409fdf19c97","blockSize":4194304,"blocks":["a50856fe7fab3d1d22e8fbf5f32543d46342257cad5e31df8f2a7409fdf19c97"]}},"copy.js":{"size":7756,"offset":"2145808","integrity":{"algorithm":"SHA256","hash":"b1ef00cadd368ea903c9a86927e40636cd832d8fa64344637c96e0e223faf876","blockSize":4194304,"blocks":["b1ef00cadd368ea903c9a86927e40636cd832d8fa64344637c96e0e223faf876"]}},"index.js":{"size":147,"offset":"2153564","integrity":{"algorithm":"SHA256","hash":"f94ad0b8c5f5131a682be2d0427189c260e49fa748fb6f6bcc1f78678354e5d2","blockSize":4194304,"blocks":["f94ad0b8c5f5131a682be2d0427189c260e49fa748fb6f6bcc1f78678354e5d2"]}}}},"empty":{"files":{"index.js":{"size":747,"offset":"2153711","integrity":{"algorithm":"SHA256","hash":"1096edcb5ec0ed015b36914beff0826f6cd5d7ce2645ee9dee60c0b272e57856","blockSize":4194304,"blocks":["1096edcb5ec0ed015b36914beff0826f6cd5d7ce2645ee9dee60c0b272e57856"]}}}},"ensure":{"files":{"file.js":{"size":1709,"offset":"2154458","integrity":{"algorithm":"SHA256","hash":"a104ff42c9aefd0e34556b9df2e4b5c9cd15315b0b0f70b07938901428b3c608","blockSize":4194304,"blocks":["a104ff42c9aefd0e34556b9df2e4b5c9cd15315b0b0f70b07938901428b3c608"]}},"index.js":{"size":542,"offset":"2156167","integrity":{"algorithm":"SHA256","hash":"77ccb9b4d1eab607ce7ba8d3d5bed59b0cb9cc4748d02aa896a2413b71dbfe60","blockSize":4194304,"blocks":["77ccb9b4d1eab607ce7ba8d3d5bed59b0cb9cc4748d02aa896a2413b71dbfe60"]}},"link.js":{"size":1652,"offset":"2156709","integrity":{"algorithm":"SHA256","hash":"339ce737e858367c65f79c0960bc6d1d617638aae07d396ac8ae5c8670b500c3","blockSize":4194304,"blocks":["339ce737e858367c65f79c0960bc6d1d617638aae07d396ac8ae5c8670b500c3"]}},"symlink-paths.js":{"size":3374,"offset":"2158361","integrity":{"algorithm":"SHA256","hash":"5595b764059fb90ce4a13f5cdf43988da97e636521d3c599ce5260681d75bdfc","blockSize":4194304,"blocks":["5595b764059fb90ce4a13f5cdf43988da97e636521d3c599ce5260681d75bdfc"]}},"symlink-type.js":{"size":694,"offset":"2161735","integrity":{"algorithm":"SHA256","hash":"17abe9590176305dd04316b2ac5c972dcf54cea32d279f955fbcf25098743dc8","blockSize":4194304,"blocks":["17abe9590176305dd04316b2ac5c972dcf54cea32d279f955fbcf25098743dc8"]}},"symlink.js":{"size":2522,"offset":"2162429","integrity":{"algorithm":"SHA256","hash":"8b1fa73e5b5554380b710ccfbb4fe23764e53f0e5ce046689741310a82a19e21","blockSize":4194304,"blocks":["8b1fa73e5b5554380b710ccfbb4fe23764e53f0e5ce046689741310a82a19e21"]}}}},"fs":{"files":{"index.js":{"size":3373,"offset":"2164951","integrity":{"algorithm":"SHA256","hash":"620b6e703880fd6718c354c5359a5c37a2379054c037269dbcf7afd2503e4a6f","blockSize":4194304,"blocks":["620b6e703880fd6718c354c5359a5c37a2379054c037269dbcf7afd2503e4a6f"]}}}},"index.js":{"size":358,"offset":"2168324","integrity":{"algorithm":"SHA256","hash":"4967e903b3dc290f2b401b81bfcad8b2d94fd68c1bf4563df63ac082af0e1dae","blockSize":4194304,"blocks":["4967e903b3dc290f2b401b81bfcad8b2d94fd68c1bf4563df63ac082af0e1dae"]}},"json":{"files":{"index.js":{"size":508,"offset":"2168682","integrity":{"algorithm":"SHA256","hash":"c5ac6a8005308e5bb36619fed225c987872300d356fa95d0d56878029ebbdc45","blockSize":4194304,"blocks":["c5ac6a8005308e5bb36619fed225c987872300d356fa95d0d56878029ebbdc45"]}},"jsonfile.js":{"size":238,"offset":"2169190","integrity":{"algorithm":"SHA256","hash":"a986ad3c13166f3bf8f30b18140bfc8ea1754760ab3802aa7c8c3780d54f07ba","blockSize":4194304,"blocks":["a986ad3c13166f3bf8f30b18140bfc8ea1754760ab3802aa7c8c3780d54f07ba"]}},"output-json-sync.js":{"size":276,"offset":"2169428","integrity":{"algorithm":"SHA256","hash":"a68fde22ad1a194755de03e90861805248f883342e05bd685258e76a90e7a6ab","blockSize":4194304,"blocks":["a68fde22ad1a194755de03e90861805248f883342e05bd685258e76a90e7a6ab"]}},"output-json.js":{"size":277,"offset":"2169704","integrity":{"algorithm":"SHA256","hash":"b738aaf8ff9aae265b0512cb2554e1f8ce8605d21dc6230189a9be6980079fc8","blockSize":4194304,"blocks":["b738aaf8ff9aae265b0512cb2554e1f8ce8605d21dc6230189a9be6980079fc8"]}}}},"mkdirs":{"files":{"index.js":{"size":328,"offset":"2169981","integrity":{"algorithm":"SHA256","hash":"adcd576e2e3868b94adb1bad6d1e3cf2312ffdfa71e49a57fe6247e116e75ecf","blockSize":4194304,"blocks":["adcd576e2e3868b94adb1bad6d1e3cf2312ffdfa71e49a57fe6247e116e75ecf"]}},"make-dir.js":{"size":545,"offset":"2170309","integrity":{"algorithm":"SHA256","hash":"23c7ce8a3d6b39d1c7cf5d16ba6447c1690a6fdaa8c5f41e6b76526b7afe96f3","blockSize":4194304,"blocks":["23c7ce8a3d6b39d1c7cf5d16ba6447c1690a6fdaa8c5f41e6b76526b7afe96f3"]}},"utils.js":{"size":1655,"offset":"2170854","integrity":{"algorithm":"SHA256","hash":"5372a36f4b2c5023788c23dbc6639155cb016a1b111e8fc1d6bf97cbaf11b1f8","blockSize":4194304,"blocks":["5372a36f4b2c5023788c23dbc6639155cb016a1b111e8fc1d6bf97cbaf11b1f8"]}}}},"move":{"files":{"index.js":{"size":147,"offset":"2172509","integrity":{"algorithm":"SHA256","hash":"274f9fd31ac65cdc7dd9a6c568fb1163c2b043f6d5fcad30d5177961e9e3e240","blockSize":4194304,"blocks":["274f9fd31ac65cdc7dd9a6c568fb1163c2b043f6d5fcad30d5177961e9e3e240"]}},"move-sync.js":{"size":1485,"offset":"2172656","integrity":{"algorithm":"SHA256","hash":"10c9f85215adcbc49661e5629d81ab4a5dbae552dd59032836d28cb2836d1cce","blockSize":4194304,"blocks":["10c9f85215adcbc49661e5629d81ab4a5dbae552dd59032836d28cb2836d1cce"]}},"move.js":{"size":2010,"offset":"2174141","integrity":{"algorithm":"SHA256","hash":"5487cd460cb8af3e0b2ed0055d61185e56bea35d08c01972b7f1a87e0433aabe","blockSize":4194304,"blocks":["5487cd460cb8af3e0b2ed0055d61185e56bea35d08c01972b7f1a87e0433aabe"]}}}},"output-file":{"files":{"index.js":{"size":947,"offset":"2176151","integrity":{"algorithm":"SHA256","hash":"a27d1a72ed1ecddffc57e70187a4b72467ed0dd34092b7e3d2817b9f4359ab5d","blockSize":4194304,"blocks":["a27d1a72ed1ecddffc57e70187a4b72467ed0dd34092b7e3d2817b9f4359ab5d"]}}}},"path-exists":{"files":{"index.js":{"size":263,"offset":"2177098","integrity":{"algorithm":"SHA256","hash":"5ce096c95daec0259817248921b39a9e0df4d342db171138ccb62440cc7a0cbe","blockSize":4194304,"blocks":["5ce096c95daec0259817248921b39a9e0df4d342db171138ccb62440cc7a0cbe"]}}}},"remove":{"files":{"index.js":{"size":489,"offset":"2177361","integrity":{"algorithm":"SHA256","hash":"ad79431e3d1cae731565d3e7403f619aee21f3b276d3541fe794ec7fd59ab0da","blockSize":4194304,"blocks":["ad79431e3d1cae731565d3e7403f619aee21f3b276d3541fe794ec7fd59ab0da"]}},"rimraf.js":{"size":7443,"offset":"2177850","integrity":{"algorithm":"SHA256","hash":"931cd85d1564a59db583841196cf2773940e7eee30830514b448d2d4919cc534","blockSize":4194304,"blocks":["931cd85d1564a59db583841196cf2773940e7eee30830514b448d2d4919cc534"]}}}},"util":{"files":{"stat.js":{"size":5226,"offset":"2185293","integrity":{"algorithm":"SHA256","hash":"fe33d6c739866764c937e8aaeb518bbda7a36b0f3c006855b26c5bdd846081c3","blockSize":4194304,"blocks":["fe33d6c739866764c937e8aaeb518bbda7a36b0f3c006855b26c5bdd846081c3"]}},"utimes.js":{"size":615,"offset":"2190519","integrity":{"algorithm":"SHA256","hash":"4a049bcd580984957b8690fb05f7a6bf5c7e59bfc78d6817882945c35f3a44d4","blockSize":4194304,"blocks":["4a049bcd580984957b8690fb05f7a6bf5c7e59bfc78d6817882945c35f3a44d4"]}}}}}},"package.json":{"size":950,"offset":"2191134","integrity":{"algorithm":"SHA256","hash":"8625f8d6674f3dacbdd5ed9fc553d9583234a6403ef90b1612f786b8fad17711","blockSize":4194304,"blocks":["8625f8d6674f3dacbdd5ed9fc553d9583234a6403ef90b1612f786b8fad17711"]}}}},"graceful-fs":{"files":{"LICENSE":{"size":791,"offset":"2192084","integrity":{"algorithm":"SHA256","hash":"f65c5d9f22a317b2a10803bd1868461ce6499c2ed7217bc80c0cc772a748789c","blockSize":4194304,"blocks":["f65c5d9f22a317b2a10803bd1868461ce6499c2ed7217bc80c0cc772a748789c"]}},"clone.js":{"size":496,"offset":"2192875","integrity":{"algorithm":"SHA256","hash":"7258eca52e65d69845759503f9fdd66c252f40e5eafb76db5d481172e31ac9ed","blockSize":4194304,"blocks":["7258eca52e65d69845759503f9fdd66c252f40e5eafb76db5d481172e31ac9ed"]}},"graceful-fs.js":{"size":12680,"offset":"2193371","integrity":{"algorithm":"SHA256","hash":"7da35669b6b6b0e4aafee31674c033f2cebb0c8f9ae010f709dcc185d3f17786","blockSize":4194304,"blocks":["7da35669b6b6b0e4aafee31674c033f2cebb0c8f9ae010f709dcc185d3f17786"]}},"legacy-streams.js":{"size":2655,"offset":"2206051","integrity":{"algorithm":"SHA256","hash":"60a6a7ecf7c3e55a3ffaae13433b6cff388b7205bba6daf393c863f77a949e36","blockSize":4194304,"blocks":["60a6a7ecf7c3e55a3ffaae13433b6cff388b7205bba6daf393c863f77a949e36"]}},"package.json":{"size":600,"offset":"2208706","integrity":{"algorithm":"SHA256","hash":"5f558a45ee1f8ea431e950ab3864f842b9de5325e30a31ba1bd68f6f768457ed","blockSize":4194304,"blocks":["5f558a45ee1f8ea431e950ab3864f842b9de5325e30a31ba1bd68f6f768457ed"]}},"polyfills.js":{"size":10141,"offset":"2209306","integrity":{"algorithm":"SHA256","hash":"66ea1687ed5edf39d67296d26edccc8da695d9a869303a78d0e580cd770aca27","blockSize":4194304,"blocks":["66ea1687ed5edf39d67296d26edccc8da695d9a869303a78d0e580cd770aca27"]}}}},"js-yaml":{"files":{"LICENSE":{"size":1084,"offset":"2219447","integrity":{"algorithm":"SHA256","hash":"a07bc24468b9654ce76a547d47a2db282d07733b715db4c73a98bd63961f9550","blockSize":4194304,"blocks":["a07bc24468b9654ce76a547d47a2db282d07733b715db4c73a98bd63961f9550"]}},"bin":{"files":{"js-yaml.js":{"size":2658,"offset":"2220531","integrity":{"algorithm":"SHA256","hash":"b3e6a451bd8bc5cba3a12851396d15fc109faf0a5a018d96b5535fe1fcfedb54","blockSize":4194304,"blocks":["b3e6a451bd8bc5cba3a12851396d15fc109faf0a5a018d96b5535fe1fcfedb54"]}}}},"dist":{"files":{"js-yaml.js":{"size":95428,"offset":"2223189","integrity":{"algorithm":"SHA256","hash":"5c8c1c6e710cb787339d91fbdcefeaf2895defca5e86401690ef15558563d548","blockSize":4194304,"blocks":["5c8c1c6e710cb787339d91fbdcefeaf2895defca5e86401690ef15558563d548"]}},"js-yaml.js.map":{"size":173857,"offset":"2318617","integrity":{"algorithm":"SHA256","hash":"05844db271bf74ff63fdfaa58bbfed5e1c2ef2f6f6d98742bc709eec21e14b35","blockSize":4194304,"blocks":["05844db271bf74ff63fdfaa58bbfed5e1c2ef2f6f6d98742bc709eec21e14b35"]}},"js-yaml.min.js":{"size":43461,"offset":"2492474","integrity":{"algorithm":"SHA256","hash":"da1e8c845d515c586ca48897a26bf180494a21d34e2f92b0c2e2d51e7c55a53d","blockSize":4194304,"blocks":["da1e8c845d515c586ca48897a26bf180494a21d34e2f92b0c2e2d51e7c55a53d"]}},"js-yaml.min.js.map":{"size":169202,"offset":"2535935","integrity":{"algorithm":"SHA256","hash":"a4fe54d809bf89a6dad540de146ab3a2d10661c289470163322cb1067f5df3f1","blockSize":4194304,"blocks":["a4fe54d809bf89a6dad540de146ab3a2d10661c289470163322cb1067f5df3f1"]}},"js-yaml.mjs":{"size":92323,"offset":"2705137","integrity":{"algorithm":"SHA256","hash":"5b4536e72a2203aa6f159630caeefde35a95d8f95620f5a1d3c48efe3a0e76fa","blockSize":4194304,"blocks":["5b4536e72a2203aa6f159630caeefde35a95d8f95620f5a1d3c48efe3a0e76fa"]}},"js-yaml.mjs.map":{"size":173851,"offset":"2797460","integrity":{"algorithm":"SHA256","hash":"8261ca0d7719e88ee5f3e3f460936144d5b84c38b7e7e0cd763402a08f15393b","blockSize":4194304,"blocks":["8261ca0d7719e88ee5f3e3f460936144d5b84c38b7e7e0cd763402a08f15393b"]}}}},"index.js":{"size":1585,"offset":"2971311","integrity":{"algorithm":"SHA256","hash":"e85d524fcd45466669dfc37618284e0c53ccaaf3f4bef1e23cd25ec6c43120bc","blockSize":4194304,"blocks":["e85d524fcd45466669dfc37618284e0c53ccaaf3f4bef1e23cd25ec6c43120bc"]}},"lib":{"files":{"common.js":{"size":1094,"offset":"2972896","integrity":{"algorithm":"SHA256","hash":"72216ccee36a52ece3f21f2d58a679c14c1483201ef6cbbfc4a1aa9cb6d34c9c","blockSize":4194304,"blocks":["72216ccee36a52ece3f21f2d58a679c14c1483201ef6cbbfc4a1aa9cb6d34c9c"]}},"dumper.js":{"size":30967,"offset":"2973990","integrity":{"algorithm":"SHA256","hash":"695c80b3c310ef3f6fbd232bbcd3f82464917a008c24f1e05b560f35c20116a0","blockSize":4194304,"blocks":["695c80b3c310ef3f6fbd232bbcd3f82464917a008c24f1e05b560f35c20116a0"]}},"exception.js":{"size":1285,"offset":"3004957","integrity":{"algorithm":"SHA256","hash":"9ef16628112beacc7497c3f3d0ab001c66c2db501f9e21fad4c30e7cd21d1d10","blockSize":4194304,"blocks":["9ef16628112beacc7497c3f3d0ab001c66c2db501f9e21fad4c30e7cd21d1d10"]}},"index_vite_proxy.tmp.mjs":{"size":434,"offset":"3006242","integrity":{"algorithm":"SHA256","hash":"a846cc31e1d31c304edaf94c48624568b699803a79ae2ee88d6e5c66e49552f7","blockSize":4194304,"blocks":["a846cc31e1d31c304edaf94c48624568b699803a79ae2ee88d6e5c66e49552f7"]}},"loader.js":{"size":50851,"offset":"3006676","integrity":{"algorithm":"SHA256","hash":"6e482c6aa13953303ffb6fa54ac5e388ca358b228e8ff978acabeb3568dcd61f","blockSize":4194304,"blocks":["6e482c6aa13953303ffb6fa54ac5e388ca358b228e8ff978acabeb3568dcd61f"]}},"schema.js":{"size":3257,"offset":"3057527","integrity":{"algorithm":"SHA256","hash":"dd26a9e56d934099eb53e04f242ed1962660e4e64697c300ff5c4bc1a83165da","blockSize":4194304,"blocks":["dd26a9e56d934099eb53e04f242ed1962660e4e64697c300ff5c4bc1a83165da"]}},"schema":{"files":{"core.js":{"size":284,"offset":"3060784","integrity":{"algorithm":"SHA256","hash":"201ffb119aad04c9397df088452e00910becab9a43a3b3a392370878646c06ad","blockSize":4194304,"blocks":["201ffb119aad04c9397df088452e00910becab9a43a3b3a392370878646c06ad"]}},"default.js":{"size":534,"offset":"3061068","integrity":{"algorithm":"SHA256","hash":"1c4c9573b4c05ce47391c6bcba10401385d8d6a4d596c1c0fd1d6ea664f97ea2","blockSize":4194304,"blocks":["1c4c9573b4c05ce47391c6bcba10401385d8d6a4d596c1c0fd1d6ea664f97ea2"]}},"failsafe.js":{"size":274,"offset":"3061602","integrity":{"algorithm":"SHA256","hash":"8e109fccabab5c066b66113f5d68bb74372f48bf589de39e44ed26432a98a27a","blockSize":4194304,"blocks":["8e109fccabab5c066b66113f5d68bb74372f48bf589de39e44ed26432a98a27a"]}},"json.js":{"size":519,"offset":"3061876","integrity":{"algorithm":"SHA256","hash":"b08f46efd2c45c46c6d3eaf9b05489356d80391c5f7d5094fb8ec7713e796281","blockSize":4194304,"blocks":["b08f46efd2c45c46c6d3eaf9b05489356d80391c5f7d5094fb8ec7713e796281"]}}}},"snippet.js":{"size":3063,"offset":"3062395","integrity":{"algorithm":"SHA256","hash":"c9180c66091356e16a750c07cbc21ee477d6d07e7c39b6a8622e5882cf85326d","blockSize":4194304,"blocks":["c9180c66091356e16a750c07cbc21ee477d6d07e7c39b6a8622e5882cf85326d"]}},"type.js":{"size":1736,"offset":"3065458","integrity":{"algorithm":"SHA256","hash":"a595092ee9fb6901769201ff7e5a485ee5f501bd1519d209af93b37dd2314a32","blockSize":4194304,"blocks":["a595092ee9fb6901769201ff7e5a485ee5f501bd1519d209af93b37dd2314a32"]}},"type":{"files":{"binary.js":{"size":2853,"offset":"3067194","integrity":{"algorithm":"SHA256","hash":"9dd6a70eb318a123fdc11a36d613419d79535b6ecf105bd865de3a5cbbb60e7c","blockSize":4194304,"blocks":["9dd6a70eb318a123fdc11a36d613419d79535b6ecf105bd865de3a5cbbb60e7c"]}},"bool.js":{"size":967,"offset":"3070047","integrity":{"algorithm":"SHA256","hash":"cc0d255ac6c55064421c19bbea312dcb9e22aee49fa9f8461723d9fbf7a0f8b3","blockSize":4194304,"blocks":["cc0d255ac6c55064421c19bbea312dcb9e22aee49fa9f8461723d9fbf7a0f8b3"]}},"float.js":{"size":2492,"offset":"3071014","integrity":{"algorithm":"SHA256","hash":"8f2ef65ab3228bd871a15b2ddaa5402287e5a4117783a6d92940d22002d2018c","blockSize":4194304,"blocks":["8f2ef65ab3228bd871a15b2ddaa5402287e5a4117783a6d92940d22002d2018c"]}},"int.js":{"size":3346,"offset":"3073506","integrity":{"algorithm":"SHA256","hash":"fc6f173d17b67778790a1d6a60d2b8306eb9fa89a508f910a0fae58cd532a16a","blockSize":4194304,"blocks":["fc6f173d17b67778790a1d6a60d2b8306eb9fa89a508f910a0fae58cd532a16a"]}},"map.js":{"size":188,"offset":"3076852","integrity":{"algorithm":"SHA256","hash":"6dd30a02cabaccf71c230464537bda5785093da80cd3319ed3a6481206e2ec7d","blockSize":4194304,"blocks":["6dd30a02cabaccf71c230464537bda5785093da80cd3319ed3a6481206e2ec7d"]}},"merge.js":{"size":229,"offset":"3077040","integrity":{"algorithm":"SHA256","hash":"4cd0343e63f3c3d7cea620cf122e3dd8f8d1c4c4105d384e8d82d35ae154d1e2","blockSize":4194304,"blocks":["4cd0343e63f3c3d7cea620cf122e3dd8f8d1c4c4105d384e8d82d35ae154d1e2"]}},"null.js":{"size":791,"offset":"3077269","integrity":{"algorithm":"SHA256","hash":"5eea804da258ba10fa736199ed0cef9d89dbb01eac1c1bd3609a79a132d1885e","blockSize":4194304,"blocks":["5eea804da258ba10fa736199ed0cef9d89dbb01eac1c1bd3609a79a132d1885e"]}},"omap.js":{"size":999,"offset":"3078060","integrity":{"algorithm":"SHA256","hash":"711911528cddf768c4b800c565e15168e72d2433670094c8936b7693c126867f","blockSize":4194304,"blocks":["711911528cddf768c4b800c565e15168e72d2433670094c8936b7693c126867f"]}},"pairs.js":{"size":1031,"offset":"3079059","integrity":{"algorithm":"SHA256","hash":"f9eb5d2dc3cdbf7dd802e0a62b5aa2d09eedeb0509b71a247ebdad223315d6a5","blockSize":4194304,"blocks":["f9eb5d2dc3cdbf7dd802e0a62b5aa2d09eedeb0509b71a247ebdad223315d6a5"]}},"seq.js":{"size":189,"offset":"3080090","integrity":{"algorithm":"SHA256","hash":"3a38b7f3242737c2e21462c42a8da1682325686cb2b30dc3630e515cf9c45522","blockSize":4194304,"blocks":["3a38b7f3242737c2e21462c42a8da1682325686cb2b30dc3630e515cf9c45522"]}},"set.js":{"size":547,"offset":"3080279","integrity":{"algorithm":"SHA256","hash":"fa5b815c6334def52dae5b58193d3798f8e53558f6c7f48a643898e996333dd7","blockSize":4194304,"blocks":["fa5b815c6334def52dae5b58193d3798f8e53558f6c7f48a643898e996333dd7"]}},"str.js":{"size":187,"offset":"3080826","integrity":{"algorithm":"SHA256","hash":"1f8725eac2dc7bed4b91610f21796ed3c057cee44b81a1ae8cc9beb9cd6c63ff","blockSize":4194304,"blocks":["1f8725eac2dc7bed4b91610f21796ed3c057cee44b81a1ae8cc9beb9cd6c63ff"]}},"timestamp.js":{"size":2364,"offset":"3081013","integrity":{"algorithm":"SHA256","hash":"54e2070e0319d7fa3becd426dd5bfdb822b9602bd4a3c366976cbaa2278bdb5c","blockSize":4194304,"blocks":["54e2070e0319d7fa3becd426dd5bfdb822b9602bd4a3c366976cbaa2278bdb5c"]}}}}}},"package.json":{"size":1169,"offset":"3083377","integrity":{"algorithm":"SHA256","hash":"6f00738d7642e641589d41cc9be6583bc29c70710421366bf310e7cd939eb3cc","blockSize":4194304,"blocks":["6f00738d7642e641589d41cc9be6583bc29c70710421366bf310e7cd939eb3cc"]}}}},"json-schema-traverse":{"files":{".eslintrc.yml":{"size":630,"offset":"3084546","integrity":{"algorithm":"SHA256","hash":"b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc","blockSize":4194304,"blocks":["b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc"]}},"LICENSE":{"size":1074,"offset":"3085176","integrity":{"algorithm":"SHA256","hash":"7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a","blockSize":4194304,"blocks":["7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]}},"index.js":{"size":2428,"offset":"3086250","integrity":{"algorithm":"SHA256","hash":"024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350","blockSize":4194304,"blocks":["024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350"]}},"package.json":{"size":553,"offset":"3088678","integrity":{"algorithm":"SHA256","hash":"c15049794f847b95bd0a31cea8f8e5fc4d760cab482b3aaa91597e44091ab262","blockSize":4194304,"blocks":["c15049794f847b95bd0a31cea8f8e5fc4d760cab482b3aaa91597e44091ab262"]}},"spec":{"files":{".eslintrc.yml":{"size":91,"offset":"3089231","integrity":{"algorithm":"SHA256","hash":"8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c","blockSize":4194304,"blocks":["8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c"]}},"fixtures":{"files":{"schema.js":{"size":5544,"offset":"3089322","integrity":{"algorithm":"SHA256","hash":"0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27","blockSize":4194304,"blocks":["0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27"]}}}},"index.spec.js":{"size":6042,"offset":"3094866","integrity":{"algorithm":"SHA256","hash":"40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69","blockSize":4194304,"blocks":["40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69"]}}}}}},"json-schema-typed":{"files":{"LICENSE.md":{"size":2859,"offset":"3100908","integrity":{"algorithm":"SHA256","hash":"bbe87b573c12bda5baf18742117330efa177e0886b3b0a278dacf8f236e1e129","blockSize":4194304,"blocks":["bbe87b573c12bda5baf18742117330efa177e0886b3b0a278dacf8f236e1e129"]}},"draft_07.js":{"size":11838,"offset":"3103767","integrity":{"algorithm":"SHA256","hash":"a9e32908d8b16f922d5dcba661d56ed14533b86b9568cc298b677347f5ba439f","blockSize":4194304,"blocks":["a9e32908d8b16f922d5dcba661d56ed14533b86b9568cc298b677347f5ba439f"]}},"draft_2019_09.js":{"size":12528,"offset":"3115605","integrity":{"algorithm":"SHA256","hash":"40311ccb8a44e9d091a39abbddf92fea1968eb0e8bd7fb73ff30c94945af473e","blockSize":4194304,"blocks":["40311ccb8a44e9d091a39abbddf92fea1968eb0e8bd7fb73ff30c94945af473e"]}},"draft_2020_12.js":{"size":12641,"offset":"3128133","integrity":{"algorithm":"SHA256","hash":"7ce66c211792cb776e52b2e76699f7a0d1c67b8ce37fb4a616ec07b1b581b953","blockSize":4194304,"blocks":["7ce66c211792cb776e52b2e76699f7a0d1c67b8ce37fb4a616ec07b1b581b953"]}},"package.json":{"size":965,"offset":"3140774","integrity":{"algorithm":"SHA256","hash":"ce77596edb58d7d2d02e20927e5a9f568ba514379dce6412dbcf48cb62feb9d8","blockSize":4194304,"blocks":["ce77596edb58d7d2d02e20927e5a9f568ba514379dce6412dbcf48cb62feb9d8"]}}}},"jsonfile":{"files":{"LICENSE":{"size":1110,"offset":"3141739","integrity":{"algorithm":"SHA256","hash":"a9801fb52ba22ef808682a094da8a7a480584b7ed0dfd0d888ab543616335031","blockSize":4194304,"blocks":["a9801fb52ba22ef808682a094da8a7a480584b7ed0dfd0d888ab543616335031"]}},"index.js":{"size":1900,"offset":"3142849","integrity":{"algorithm":"SHA256","hash":"2cdf22ffb5a170ad2cf10cbdf647e2a9366b6afa11e9b4c2370d0cf5b1f700b1","blockSize":4194304,"blocks":["2cdf22ffb5a170ad2cf10cbdf647e2a9366b6afa11e9b4c2370d0cf5b1f700b1"]}},"package.json":{"size":558,"offset":"3144749","integrity":{"algorithm":"SHA256","hash":"97dd73da7fecf4b16cf7bb766cbfee7d55de9c7e2b864b982a0936247310eac8","blockSize":4194304,"blocks":["97dd73da7fecf4b16cf7bb766cbfee7d55de9c7e2b864b982a0936247310eac8"]}},"utils.js":{"size":498,"offset":"3145307","integrity":{"algorithm":"SHA256","hash":"b0c188696676561411f3c5784d7de61bf21927f9c334e0cfb9136a8b7c82be5d","blockSize":4194304,"blocks":["b0c188696676561411f3c5784d7de61bf21927f9c334e0cfb9136a8b7c82be5d"]}}}},"lazy-val":{"files":{"out":{"files":{"main.js":{"size":605,"offset":"3145805","integrity":{"algorithm":"SHA256","hash":"358fa8cba70c9140edafa85c0b7b25c7261939480186167e6b3440905f5b47da","blockSize":4194304,"blocks":["358fa8cba70c9140edafa85c0b7b25c7261939480186167e6b3440905f5b47da"]}},"main.js.map":{"size":1156,"offset":"3146410","integrity":{"algorithm":"SHA256","hash":"aa3e70f08a0ce115832e5324c4b96aa1475a3b8b36728f50091ebd22aa0f6646","blockSize":4194304,"blocks":["aa3e70f08a0ce115832e5324c4b96aa1475a3b8b36728f50091ebd22aa0f6646"]}}}},"package.json":{"size":330,"offset":"3147566","integrity":{"algorithm":"SHA256","hash":"a6f4140d0187f32d95545835aca38684e18d0fcfbecb51709b0aaa54decd3c0b","blockSize":4194304,"blocks":["a6f4140d0187f32d95545835aca38684e18d0fcfbecb51709b0aaa54decd3c0b"]}}}},"lodash.escaperegexp":{"files":{"LICENSE":{"size":1951,"offset":"3147896","integrity":{"algorithm":"SHA256","hash":"ffd8b33b354585f4ce119f19c53728281e48a97b074491eb6bf6d5c5ff305272","blockSize":4194304,"blocks":["ffd8b33b354585f4ce119f19c53728281e48a97b074491eb6bf6d5c5ff305272"]}},"index.js":{"size":4398,"offset":"3149847","integrity":{"algorithm":"SHA256","hash":"584de6ec78e35344eaef8291338a671f223ec225c4df4220b6f91d8f0c004d8d","blockSize":4194304,"blocks":["584de6ec78e35344eaef8291338a671f223ec225c4df4220b6f91d8f0c004d8d"]}},"package.json":{"size":356,"offset":"3154245","integrity":{"algorithm":"SHA256","hash":"c71b659d3f3f5dfab55d736b6bd17d97f822b13bcf9b1edbce479f8e691e7892","blockSize":4194304,"blocks":["c71b659d3f3f5dfab55d736b6bd17d97f822b13bcf9b1edbce479f8e691e7892"]}}}},"lodash.isequal":{"files":{"LICENSE":{"size":1950,"offset":"3154601","integrity":{"algorithm":"SHA256","hash":"e159c6d48c989185448658f276375bfb2300362ec6d4ae5525a2d49c4bcb947d","blockSize":4194304,"blocks":["e159c6d48c989185448658f276375bfb2300362ec6d4ae5525a2d49c4bcb947d"]}},"index.js":{"size":49598,"offset":"3156551","integrity":{"algorithm":"SHA256","hash":"e552928a511748303101cfd03826a777cfa359eade6a4a60f92c923edbf9184c","blockSize":4194304,"blocks":["e552928a511748303101cfd03826a777cfa359eade6a4a60f92c923edbf9184c"]}},"package.json":{"size":346,"offset":"3206149","integrity":{"algorithm":"SHA256","hash":"6e84ac44b54c17317d096a280e9d0bd72d736e0a0245095cc7c5d72657890406","blockSize":4194304,"blocks":["6e84ac44b54c17317d096a280e9d0bd72d736e0a0245095cc7c5d72657890406"]}}}},"mimic-function":{"files":{"index.js":{"size":3038,"offset":"3206495","integrity":{"algorithm":"SHA256","hash":"4f92a36c1ba7305bf71571137695132022f5b9ebb499770610280f8e901f2c94","blockSize":4194304,"blocks":["4f92a36c1ba7305bf71571137695132022f5b9ebb499770610280f8e901f2c94"]}},"license":{"size":1117,"offset":"3209533","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":657,"offset":"3210650","integrity":{"algorithm":"SHA256","hash":"da1283cc7557b0017497f0ec9805077ca03ee1eec77cb834c5fd2c8457984d90","blockSize":4194304,"blocks":["da1283cc7557b0017497f0ec9805077ca03ee1eec77cb834c5fd2c8457984d90"]}}}},"minimist":{"files":{".nycrc":{"size":229,"offset":"3211307","integrity":{"algorithm":"SHA256","hash":"eaacff31c45b07c9b5e804d4e0e8eb35e0c430faf9f79fdd98d43b26c42e93df","blockSize":4194304,"blocks":["eaacff31c45b07c9b5e804d4e0e8eb35e0c430faf9f79fdd98d43b26c42e93df"]}},"LICENSE":{"size":1073,"offset":"3211536","integrity":{"algorithm":"SHA256","hash":"435a6722c786b0a56fbe7387028f1d9d3f3a2d0fb615bb8fee118727c3f59b7b","blockSize":4194304,"blocks":["435a6722c786b0a56fbe7387028f1d9d3f3a2d0fb615bb8fee118727c3f59b7b"]}},"index.js":{"size":6196,"offset":"3212609","integrity":{"algorithm":"SHA256","hash":"9cf5e83d36697a92d8af11e000f513ac30a3464bbb024850f9ffdeb1edf59848","blockSize":4194304,"blocks":["9cf5e83d36697a92d8af11e000f513ac30a3464bbb024850f9ffdeb1edf59848"]}},"package.json":{"size":1247,"offset":"3218805","integrity":{"algorithm":"SHA256","hash":"3154549dd6d41d1e074108fbd587e0078c54ce85d9d51c167a43c78cb178f76c","blockSize":4194304,"blocks":["3154549dd6d41d1e074108fbd587e0078c54ce85d9d51c167a43c78cb178f76c"]}}}},"mkdirp":{"files":{"LICENSE":{"size":1141,"offset":"3220052","integrity":{"algorithm":"SHA256","hash":"05991c2e8f070b69ec5b656c2c12fd07cd0153dd157d39b050b82af59b319a01","blockSize":4194304,"blocks":["05991c2e8f070b69ec5b656c2c12fd07cd0153dd157d39b050b82af59b319a01"]}},"bin":{"files":{"cmd.js":{"size":731,"offset":"3221193","integrity":{"algorithm":"SHA256","hash":"24b028bccb1773f02cf0d0fb3dca5468f1b5d22a06cbc5cbf351e1eb3accefb1","blockSize":4194304,"blocks":["24b028bccb1773f02cf0d0fb3dca5468f1b5d22a06cbc5cbf351e1eb3accefb1"]}},"usage.txt":{"size":315,"offset":"3221924","integrity":{"algorithm":"SHA256","hash":"5575eeea7b83971ed81729048e24b8f5a56b902ab2e1bd43ed031a502eb84759","blockSize":4194304,"blocks":["5575eeea7b83971ed81729048e24b8f5a56b902ab2e1bd43ed031a502eb84759"]}}}},"index.js":{"size":2825,"offset":"3222239","integrity":{"algorithm":"SHA256","hash":"df33312136061eee26701a34ca4f9be043b9675d359a115503dc2df909106432","blockSize":4194304,"blocks":["df33312136061eee26701a34ca4f9be043b9675d359a115503dc2df909106432"]}},"package.json":{"size":524,"offset":"3225064","integrity":{"algorithm":"SHA256","hash":"dcdb2fd365d28ffadcd5de98859b6a544e9cd455077f921346c78a83c5493596","blockSize":4194304,"blocks":["dcdb2fd365d28ffadcd5de98859b6a544e9cd455077f921346c78a83c5493596"]}}}},"ms":{"files":{"index.js":{"size":3024,"offset":"3225588","integrity":{"algorithm":"SHA256","hash":"e5f0b6a946a9b2b356a28557728410717df54ea2f599edb619f9839df6b7b0e9","blockSize":4194304,"blocks":["e5f0b6a946a9b2b356a28557728410717df54ea2f599edb619f9839df6b7b0e9"]}},"license.md":{"size":1079,"offset":"3228612","integrity":{"algorithm":"SHA256","hash":"1662fae9b5314d11cf51284e2dcd1f006a354f7343f08712a730fcff9a359801","blockSize":4194304,"blocks":["1662fae9b5314d11cf51284e2dcd1f006a354f7343f08712a730fcff9a359801"]}},"package.json":{"size":497,"offset":"3229691","integrity":{"algorithm":"SHA256","hash":"f983ec581f1dd5a47b7f12b58f97c0b44c4e0cce56cbecc40140031aeef99bdf","blockSize":4194304,"blocks":["f983ec581f1dd5a47b7f12b58f97c0b44c4e0cce56cbecc40140031aeef99bdf"]}}}},"path-is-absolute":{"files":{"index.js":{"size":611,"offset":"3230188","integrity":{"algorithm":"SHA256","hash":"4eb1119c3eeccc4d8e8841b77d062abaf4572b332801f5b16175bc3311b5d8f1","blockSize":4194304,"blocks":["4eb1119c3eeccc4d8e8841b77d062abaf4572b332801f5b16175bc3311b5d8f1"]}},"license":{"size":1119,"offset":"3230799","integrity":{"algorithm":"SHA256","hash":"6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c","blockSize":4194304,"blocks":["6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c"]}},"package.json":{"size":424,"offset":"3231918","integrity":{"algorithm":"SHA256","hash":"1d0ad40ecaa004d97b4db97bc3462e3c7751aa144bcd161151ea08e4feedfa18","blockSize":4194304,"blocks":["1d0ad40ecaa004d97b4db97bc3462e3c7751aa144bcd161151ea08e4feedfa18"]}}}},"require-from-string":{"files":{"index.js":{"size":866,"offset":"3232342","integrity":{"algorithm":"SHA256","hash":"cb059342a762b955997bf780f3693add176922727f2fa9f11fcaf1b3fc323239","blockSize":4194304,"blocks":["cb059342a762b955997bf780f3693add176922727f2fa9f11fcaf1b3fc323239"]}},"license":{"size":1128,"offset":"3233208","integrity":{"algorithm":"SHA256","hash":"6ee0feb1f6ef996ff5a68600f8cf98909cf412d39ef3cdceaefd87d636fa1b7f","blockSize":4194304,"blocks":["6ee0feb1f6ef996ff5a68600f8cf98909cf412d39ef3cdceaefd87d636fa1b7f"]}},"package.json":{"size":442,"offset":"3234336","integrity":{"algorithm":"SHA256","hash":"bbd907e5490c34cc6b814f56cd2180edb03bc594b88cdf1e112ed94d0d6218a3","blockSize":4194304,"blocks":["bbd907e5490c34cc6b814f56cd2180edb03bc594b88cdf1e112ed94d0d6218a3"]}}}},"sax":{"files":{"LICENSE":{"size":2031,"offset":"3234778","integrity":{"algorithm":"SHA256","hash":"e8bf477df410baa41d44132e676d16a5372cf1798599fac2823376dc95e94eee","blockSize":4194304,"blocks":["e8bf477df410baa41d44132e676d16a5372cf1798599fac2823376dc95e94eee"]}},"lib":{"files":{"sax.js":{"size":44774,"offset":"3236809","integrity":{"algorithm":"SHA256","hash":"e221d28f41ed2b3d7122cf5962772cffe43ae976d8c060cc116470d5cedf54c0","blockSize":4194304,"blocks":["e221d28f41ed2b3d7122cf5962772cffe43ae976d8c060cc116470d5cedf54c0"]}}}},"package.json":{"size":483,"offset":"3281583","integrity":{"algorithm":"SHA256","hash":"97adb7c524eb2900a54a31f535b543e24aea848e3ff2e4af20810dfef8aeffd0","blockSize":4194304,"blocks":["97adb7c524eb2900a54a31f535b543e24aea848e3ff2e4af20810dfef8aeffd0"]}}}},"semver":{"files":{"LICENSE":{"size":765,"offset":"3282066","integrity":{"algorithm":"SHA256","hash":"4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b","blockSize":4194304,"blocks":["4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b"]}},"bin":{"files":{"semver.js":{"size":4957,"offset":"3282831","integrity":{"algorithm":"SHA256","hash":"bd6c871026985937dc945011fc54b74b47f5998154216d7b8d40d5ed782e4402","blockSize":4194304,"blocks":["bd6c871026985937dc945011fc54b74b47f5998154216d7b8d40d5ed782e4402"]}}}},"classes":{"files":{"comparator.js":{"size":3631,"offset":"3287788","integrity":{"algorithm":"SHA256","hash":"054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac","blockSize":4194304,"blocks":["054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac"]}},"index.js":{"size":143,"offset":"3291419","integrity":{"algorithm":"SHA256","hash":"3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17","blockSize":4194304,"blocks":["3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17"]}},"range.js":{"size":15207,"offset":"3291562","integrity":{"algorithm":"SHA256","hash":"ade30be1c8b58bde2b643e25f73dda21fd64d291e31ef9ddfbef07da6321ab30","blockSize":4194304,"blocks":["ade30be1c8b58bde2b643e25f73dda21fd64d291e31ef9ddfbef07da6321ab30"]}},"semver.js":{"size":9480,"offset":"3306769","integrity":{"algorithm":"SHA256","hash":"d5ba57e5c93f031b1d234fca4bb746746fcd1fe51be7e5ee895601e2c12e2083","blockSize":4194304,"blocks":["d5ba57e5c93f031b1d234fca4bb746746fcd1fe51be7e5ee895601e2c12e2083"]}}}},"functions":{"files":{"clean.js":{"size":205,"offset":"3316249","integrity":{"algorithm":"SHA256","hash":"4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f","blockSize":4194304,"blocks":["4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f"]}},"cmp.js":{"size":961,"offset":"3316454","integrity":{"algorithm":"SHA256","hash":"a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3","blockSize":4194304,"blocks":["a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3"]}},"coerce.js":{"size":2004,"offset":"3317415","integrity":{"algorithm":"SHA256","hash":"28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a","blockSize":4194304,"blocks":["28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a"]}},"compare-build.js":{"size":281,"offset":"3319419","integrity":{"algorithm":"SHA256","hash":"5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c","blockSize":4194304,"blocks":["5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c"]}},"compare-loose.js":{"size":132,"offset":"3319700","integrity":{"algorithm":"SHA256","hash":"07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78","blockSize":4194304,"blocks":["07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78"]}},"compare.js":{"size":170,"offset":"3319832","integrity":{"algorithm":"SHA256","hash":"d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c","blockSize":4194304,"blocks":["d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c"]}},"diff.js":{"size":1423,"offset":"3320002","integrity":{"algorithm":"SHA256","hash":"7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31","blockSize":4194304,"blocks":["7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31"]}},"eq.js":{"size":126,"offset":"3321425","integrity":{"algorithm":"SHA256","hash":"b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936","blockSize":4194304,"blocks":["b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936"]}},"gt.js":{"size":124,"offset":"3321551","integrity":{"algorithm":"SHA256","hash":"135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93","blockSize":4194304,"blocks":["135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93"]}},"gte.js":{"size":127,"offset":"3321675","integrity":{"algorithm":"SHA256","hash":"991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d","blockSize":4194304,"blocks":["991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d"]}},"inc.js":{"size":478,"offset":"3321802","integrity":{"algorithm":"SHA256","hash":"952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493","blockSize":4194304,"blocks":["952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493"]}},"lt.js":{"size":124,"offset":"3322280","integrity":{"algorithm":"SHA256","hash":"1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25","blockSize":4194304,"blocks":["1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25"]}},"lte.js":{"size":127,"offset":"3322404","integrity":{"algorithm":"SHA256","hash":"3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800","blockSize":4194304,"blocks":["3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800"]}},"major.js":{"size":136,"offset":"3322531","integrity":{"algorithm":"SHA256","hash":"5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276","blockSize":4194304,"blocks":["5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276"]}},"minor.js":{"size":136,"offset":"3322667","integrity":{"algorithm":"SHA256","hash":"1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6","blockSize":4194304,"blocks":["1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6"]}},"neq.js":{"size":128,"offset":"3322803","integrity":{"algorithm":"SHA256","hash":"a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127","blockSize":4194304,"blocks":["a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127"]}},"parse.js":{"size":331,"offset":"3322931","integrity":{"algorithm":"SHA256","hash":"29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad","blockSize":4194304,"blocks":["29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad"]}},"patch.js":{"size":136,"offset":"3323262","integrity":{"algorithm":"SHA256","hash":"f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd","blockSize":4194304,"blocks":["f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd"]}},"prerelease.js":{"size":234,"offset":"3323398","integrity":{"algorithm":"SHA256","hash":"baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593","blockSize":4194304,"blocks":["baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593"]}},"rcompare.js":{"size":132,"offset":"3323632","integrity":{"algorithm":"SHA256","hash":"84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0","blockSize":4194304,"blocks":["84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0"]}},"rsort.js":{"size":163,"offset":"3323764","integrity":{"algorithm":"SHA256","hash":"6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3","blockSize":4194304,"blocks":["6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3"]}},"satisfies.js":{"size":247,"offset":"3323927","integrity":{"algorithm":"SHA256","hash":"8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946","blockSize":4194304,"blocks":["8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946"]}},"sort.js":{"size":161,"offset":"3324174","integrity":{"algorithm":"SHA256","hash":"c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8","blockSize":4194304,"blocks":["c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8"]}},"truncate.js":{"size":1021,"offset":"3324335","integrity":{"algorithm":"SHA256","hash":"e145833a250311927c92f424f56498c52f1b7bb1271ce6afbf006db87773ff43","blockSize":4194304,"blocks":["e145833a250311927c92f424f56498c52f1b7bb1271ce6afbf006db87773ff43"]}},"valid.js":{"size":176,"offset":"3325356","integrity":{"algorithm":"SHA256","hash":"0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025","blockSize":4194304,"blocks":["0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025"]}}}},"index.js":{"size":2691,"offset":"3325532","integrity":{"algorithm":"SHA256","hash":"4b3e57d3d40e29e0706002eba113d09f35aea593578376bbeec83b777b9912ab","blockSize":4194304,"blocks":["4b3e57d3d40e29e0706002eba113d09f35aea593578376bbeec83b777b9912ab"]}},"internal":{"files":{"constants.js":{"size":873,"offset":"3328223","integrity":{"algorithm":"SHA256","hash":"38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9","blockSize":4194304,"blocks":["38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9"]}},"debug.js":{"size":240,"offset":"3329096","integrity":{"algorithm":"SHA256","hash":"8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3","blockSize":4194304,"blocks":["8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3"]}},"identifiers.js":{"size":525,"offset":"3329336","integrity":{"algorithm":"SHA256","hash":"b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7","blockSize":4194304,"blocks":["b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7"]}},"lrucache.js":{"size":802,"offset":"3329861","integrity":{"algorithm":"SHA256","hash":"14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f","blockSize":4194304,"blocks":["14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f"]}},"parse-options.js":{"size":338,"offset":"3330663","integrity":{"algorithm":"SHA256","hash":"fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01","blockSize":4194304,"blocks":["fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01"]}},"re.js":{"size":8139,"offset":"3331001","integrity":{"algorithm":"SHA256","hash":"5833262888e2b5d843a69193f83c05e374818dbe55379b497819b5bf58e48cd8","blockSize":4194304,"blocks":["5833262888e2b5d843a69193f83c05e374818dbe55379b497819b5bf58e48cd8"]}}}},"package.json":{"size":1348,"offset":"3339140","integrity":{"algorithm":"SHA256","hash":"b6ac2d2503d8e8bf7d07782ce8b88b7009d9be31e972f34fd9cdba4b90a22df4","blockSize":4194304,"blocks":["b6ac2d2503d8e8bf7d07782ce8b88b7009d9be31e972f34fd9cdba4b90a22df4"]}},"preload.js":{"size":83,"offset":"3340488","integrity":{"algorithm":"SHA256","hash":"edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba","blockSize":4194304,"blocks":["edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba"]}},"range.bnf":{"size":702,"offset":"3340571","integrity":{"algorithm":"SHA256","hash":"15d0baf9b7b98e6d862c0cb9e822d2533d2bc23e136bb75314d802ca1fcb0392","blockSize":4194304,"blocks":["15d0baf9b7b98e6d862c0cb9e822d2533d2bc23e136bb75314d802ca1fcb0392"]}},"ranges":{"files":{"gtr.js":{"size":231,"offset":"3341273","integrity":{"algorithm":"SHA256","hash":"8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19","blockSize":4194304,"blocks":["8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19"]}},"intersects.js":{"size":224,"offset":"3341504","integrity":{"algorithm":"SHA256","hash":"fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f","blockSize":4194304,"blocks":["fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f"]}},"ltr.js":{"size":227,"offset":"3341728","integrity":{"algorithm":"SHA256","hash":"e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038","blockSize":4194304,"blocks":["e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038"]}},"max-satisfying.js":{"size":593,"offset":"3341955","integrity":{"algorithm":"SHA256","hash":"e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416","blockSize":4194304,"blocks":["e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416"]}},"min-satisfying.js":{"size":591,"offset":"3342548","integrity":{"algorithm":"SHA256","hash":"2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca","blockSize":4194304,"blocks":["2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca"]}},"min-version.js":{"size":1514,"offset":"3343139","integrity":{"algorithm":"SHA256","hash":"fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b","blockSize":4194304,"blocks":["fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b"]}},"outside.js":{"size":2204,"offset":"3344653","integrity":{"algorithm":"SHA256","hash":"3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca","blockSize":4194304,"blocks":["3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca"]}},"simplify.js":{"size":1355,"offset":"3346857","integrity":{"algorithm":"SHA256","hash":"7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934","blockSize":4194304,"blocks":["7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934"]}},"subset.js":{"size":7478,"offset":"3348212","integrity":{"algorithm":"SHA256","hash":"ceb9eb6ed5bfc6c7ac7af7f47e5c3535444a4e66a0e2b58cdad4bd02a35d454d","blockSize":4194304,"blocks":["ceb9eb6ed5bfc6c7ac7af7f47e5c3535444a4e66a0e2b58cdad4bd02a35d454d"]}},"to-comparators.js":{"size":282,"offset":"3355690","integrity":{"algorithm":"SHA256","hash":"6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9","blockSize":4194304,"blocks":["6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9"]}},"valid.js":{"size":326,"offset":"3355972","integrity":{"algorithm":"SHA256","hash":"5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac","blockSize":4194304,"blocks":["5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac"]}}}}}},"stubborn-fs":{"files":{"dist":{"files":{"constants.js":{"size":499,"offset":"3356298","integrity":{"algorithm":"SHA256","hash":"138dd5878d7857fd79738d5c3643454c121f5f8a52a88ad6f06d943475f87294","blockSize":4194304,"blocks":["138dd5878d7857fd79738d5c3643454c121f5f8a52a88ad6f06d943475f87294"]}},"handlers.js":{"size":1093,"offset":"3356797","integrity":{"algorithm":"SHA256","hash":"470c72ebee3e5394cfbd404baeb20064c48414d5c541bad63c3fda4c0358961f","blockSize":4194304,"blocks":["470c72ebee3e5394cfbd404baeb20064c48414d5c541bad63c3fda4c0358961f"]}},"index.js":{"size":2919,"offset":"3357890","integrity":{"algorithm":"SHA256","hash":"1dd2b4b64747584b97b9ee25516a9273b639eb57eac4d93c99b960c82538999a","blockSize":4194304,"blocks":["1dd2b4b64747584b97b9ee25516a9273b639eb57eac4d93c99b960c82538999a"]}}}},"license":{"size":1091,"offset":"3360809","integrity":{"algorithm":"SHA256","hash":"d98bee8913f421380c0771121d2a58deaa806e4513581d02887c3f65b9ee558f","blockSize":4194304,"blocks":["d98bee8913f421380c0771121d2a58deaa806e4513581d02887c3f65b9ee558f"]}},"package.json":{"size":498,"offset":"3361900","integrity":{"algorithm":"SHA256","hash":"a0a28d26a98a45fbad9c2b7e750cd1eaa1171b005f01d7d16a1f4814c4cdbbb2","blockSize":4194304,"blocks":["a0a28d26a98a45fbad9c2b7e750cd1eaa1171b005f01d7d16a1f4814c4cdbbb2"]}}}},"stubborn-utils":{"files":{"dist":{"files":{"attemptify_async.js":{"size":262,"offset":"3362398","integrity":{"algorithm":"SHA256","hash":"aca347f0bd66763681f18a0113c57e273e0cca230c8c24a0aff488a3daa009c1","blockSize":4194304,"blocks":["aca347f0bd66763681f18a0113c57e273e0cca230c8c24a0aff488a3daa009c1"]}},"attemptify_sync.js":{"size":342,"offset":"3362660","integrity":{"algorithm":"SHA256","hash":"add30f21147cf5ba6fca784d6b73ab3ea80620c2f41ad6cf2eb83a98acee1f5a","blockSize":4194304,"blocks":["add30f21147cf5ba6fca784d6b73ab3ea80620c2f41ad6cf2eb83a98acee1f5a"]}},"constants.js":{"size":79,"offset":"3363002","integrity":{"algorithm":"SHA256","hash":"ad9f75b5f870c6846973c4019efe6ab61b49706928c973673834e469eb14706f","blockSize":4194304,"blocks":["ad9f75b5f870c6846973c4019efe6ab61b49706928c973673834e469eb14706f"]}},"index.js":{"size":299,"offset":"3363081","integrity":{"algorithm":"SHA256","hash":"7bdd5b57b1fc47158d3334770855d2f96e0b52e4290edf80c31e2ea69e02431f","blockSize":4194304,"blocks":["7bdd5b57b1fc47158d3334770855d2f96e0b52e4290edf80c31e2ea69e02431f"]}},"retryify_async.js":{"size":1080,"offset":"3363380","integrity":{"algorithm":"SHA256","hash":"e96f8613e4bf2707ff86d56f532082c2e97712081d4e9bc129423d0a17382b9e","blockSize":4194304,"blocks":["e96f8613e4bf2707ff86d56f532082c2e97712081d4e9bc129423d0a17382b9e"]}},"retryify_sync.js":{"size":723,"offset":"3364460","integrity":{"algorithm":"SHA256","hash":"544246cd4bfa113b199417102f9c7e9c313a873b6724cc34288f8c39073c2d11","blockSize":4194304,"blocks":["544246cd4bfa113b199417102f9c7e9c313a873b6724cc34288f8c39073c2d11"]}},"types.js":{"size":22,"offset":"3365183","integrity":{"algorithm":"SHA256","hash":"d99f969d7455894d5b3ee7632c54f4ffb79d666c0dd8dc49dfa6e7815f74196c","blockSize":4194304,"blocks":["d99f969d7455894d5b3ee7632c54f4ffb79d666c0dd8dc49dfa6e7815f74196c"]}}}},"license":{"size":1091,"offset":"3365205","integrity":{"algorithm":"SHA256","hash":"0cb826ec0d67e9918daeb89ac839aba3b85cfd7579ee96208b1d81bef46593fd","blockSize":4194304,"blocks":["0cb826ec0d67e9918daeb89ac839aba3b85cfd7579ee96208b1d81bef46593fd"]}},"package.json":{"size":447,"offset":"3366296","integrity":{"algorithm":"SHA256","hash":"19f60198b275c44312fa73dead28db18a7bf68280841592b288c2f996071ddf5","blockSize":4194304,"blocks":["19f60198b275c44312fa73dead28db18a7bf68280841592b288c2f996071ddf5"]}}}},"tagged-tag":{"files":{"license":{"size":1117,"offset":"3366743","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":558,"offset":"3367860","integrity":{"algorithm":"SHA256","hash":"0a05edaa34313f146f72210552aa4f9b86b599df98e0de2cc11c34360680aa7c","blockSize":4194304,"blocks":["0a05edaa34313f146f72210552aa4f9b86b599df98e0de2cc11c34360680aa7c"]}}}},"tiny-typed-emitter":{"files":{"LICENSE":{"size":1104,"offset":"3368418","integrity":{"algorithm":"SHA256","hash":"4b3faf884ee71eec3df920b66c98fc6618af28e824cf3a32ef3d8774048cc76d","blockSize":4194304,"blocks":["4b3faf884ee71eec3df920b66c98fc6618af28e824cf3a32ef3d8774048cc76d"]}},"lib":{"files":{"index.js":{"size":132,"offset":"3369522","integrity":{"algorithm":"SHA256","hash":"1401fdda105ed67f365bd775397aedb2f5f9e43ace031288f0f6868f9ab041be","blockSize":4194304,"blocks":["1401fdda105ed67f365bd775397aedb2f5f9e43ace031288f0f6868f9ab041be"]}}}},"package.json":{"size":395,"offset":"3369654","integrity":{"algorithm":"SHA256","hash":"eb7f51a4a5a7f41baf54271c726724a047f60d45762d650dc00439a10c37645b","blockSize":4194304,"blocks":["eb7f51a4a5a7f41baf54271c726724a047f60d45762d650dc00439a10c37645b"]}}}},"type-fest":{"files":{"license-cc0":{"size":7048,"offset":"3370049","integrity":{"algorithm":"SHA256","hash":"a2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499","blockSize":4194304,"blocks":["a2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499"]}},"license-mit":{"size":1117,"offset":"3377097","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":1189,"offset":"3378214","integrity":{"algorithm":"SHA256","hash":"86a9e4e9f8fb8df0f3c655c0d678dbbf2b8255db7b44c4b7b5df267b71e13c83","blockSize":4194304,"blocks":["86a9e4e9f8fb8df0f3c655c0d678dbbf2b8255db7b44c4b7b5df267b71e13c83"]}}}},"uint8array-extras":{"files":{"index.js":{"size":7373,"offset":"3379403","integrity":{"algorithm":"SHA256","hash":"e208db170cd4ae6c61c564bbd418de54f30020ea738f8b02cd93cc781841c37b","blockSize":4194304,"blocks":["e208db170cd4ae6c61c564bbd418de54f30020ea738f8b02cd93cc781841c37b"]}},"license":{"size":1117,"offset":"3386776","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":719,"offset":"3387893","integrity":{"algorithm":"SHA256","hash":"6b32dd80b892c0e3d182b4bf2c414d3e1fd619027bc87766ddb1d34501910295","blockSize":4194304,"blocks":["6b32dd80b892c0e3d182b4bf2c414d3e1fd619027bc87766ddb1d34501910295"]}}}},"universalify":{"files":{"LICENSE":{"size":1100,"offset":"3388612","integrity":{"algorithm":"SHA256","hash":"3fda5977c0904e226190b4e21d64340c1731e2142d6fe5f3dee0090a216b8b63","blockSize":4194304,"blocks":["3fda5977c0904e226190b4e21d64340c1731e2142d6fe5f3dee0090a216b8b63"]}},"index.js":{"size":706,"offset":"3389712","integrity":{"algorithm":"SHA256","hash":"83b02adb3872f6c482db4e57c300fa39b5cad65e317fc2f70b9de7d305c035a1","blockSize":4194304,"blocks":["83b02adb3872f6c482db4e57c300fa39b5cad65e317fc2f70b9de7d305c035a1"]}},"package.json":{"size":618,"offset":"3390418","integrity":{"algorithm":"SHA256","hash":"5b39e9c6305a5ba27c76caf4817244dd1a308b68c7559dfe15471173466cf06e","blockSize":4194304,"blocks":["5b39e9c6305a5ba27c76caf4817244dd1a308b68c7559dfe15471173466cf06e"]}}}},"untildify":{"files":{"index.js":{"size":239,"offset":"3391036","integrity":{"algorithm":"SHA256","hash":"19c47b650baea2c48e776f8b00b4943dcdf13e7649064cdb8cef168409482c94","blockSize":4194304,"blocks":["19c47b650baea2c48e776f8b00b4943dcdf13e7649064cdb8cef168409482c94"]}},"license":{"size":1119,"offset":"3391275","integrity":{"algorithm":"SHA256","hash":"6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c","blockSize":4194304,"blocks":["6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c"]}},"package.json":{"size":450,"offset":"3392394","integrity":{"algorithm":"SHA256","hash":"69f0de13f0c0ac9886753053b48d7cd74fdd82ebe4dc900b45d00086cc9458af","blockSize":4194304,"blocks":["69f0de13f0c0ac9886753053b48d7cd74fdd82ebe4dc900b45d00086cc9458af"]}}}},"uuid":{"files":{"LICENSE.md":{"size":1109,"offset":"3392844","integrity":{"algorithm":"SHA256","hash":"beaa6b04fb82e41dd2ad679e19e27953afb5999b1abbb455b6564e78ebfeb332","blockSize":4194304,"blocks":["beaa6b04fb82e41dd2ad679e19e27953afb5999b1abbb455b6564e78ebfeb332"]}},"dist-node":{"files":{"bin":{"files":{"uuid":{"size":45,"offset":"3393953","integrity":{"algorithm":"SHA256","hash":"a9dc67d05c3b08842280064e7e65fab9de3f4257b1dfd88e6e51d5afd967bdf4","blockSize":4194304,"blocks":["a9dc67d05c3b08842280064e7e65fab9de3f4257b1dfd88e6e51d5afd967bdf4"]}}}},"index.js":{"size":636,"offset":"3393998","integrity":{"algorithm":"SHA256","hash":"65e9fae8f22278e6c9ac5b016dbe1ead01b8014f66ce08a807741885d4bf01f1","blockSize":4194304,"blocks":["65e9fae8f22278e6c9ac5b016dbe1ead01b8014f66ce08a807741885d4bf01f1"]}},"max.js":{"size":55,"offset":"3394634","integrity":{"algorithm":"SHA256","hash":"8f81a7b2a5f8704ea1b4e8f83d36659856fdf3d122b2bd16fe1b5c47c97b6ffa","blockSize":4194304,"blocks":["8f81a7b2a5f8704ea1b4e8f83d36659856fdf3d122b2bd16fe1b5c47c97b6ffa"]}},"md5.js":{"size":305,"offset":"3394689","integrity":{"algorithm":"SHA256","hash":"9e143aad0b68e277fa3552a6f783052320bcd5d61d1d8c45fc64aac10113279c","blockSize":4194304,"blocks":["9e143aad0b68e277fa3552a6f783052320bcd5d61d1d8c45fc64aac10113279c"]}},"nil.js":{"size":55,"offset":"3394994","integrity":{"algorithm":"SHA256","hash":"a6f8ac293df0b75af2946e5190d8f00336b826bb1340b96d669a09beb8885ff8","blockSize":4194304,"blocks":["a6f8ac293df0b75af2946e5190d8f00336b826bb1340b96d669a09beb8885ff8"]}},"parse.js":{"size":612,"offset":"3395049","integrity":{"algorithm":"SHA256","hash":"a383f50a691c05533a40bbb4a87f718daa050abbc96debc9715efdc74d8538b4","blockSize":4194304,"blocks":["a383f50a691c05533a40bbb4a87f718daa050abbc96debc9715efdc74d8538b4"]}},"regex.js":{"size":171,"offset":"3395661","integrity":{"algorithm":"SHA256","hash":"774bc4bc767a58458dfdd252430d96b71b3d380ac241b50df6cb757aaa1b4783","blockSize":4194304,"blocks":["774bc4bc767a58458dfdd252430d96b71b3d380ac241b50df6cb757aaa1b4783"]}},"rng.js":{"size":110,"offset":"3395832","integrity":{"algorithm":"SHA256","hash":"69d169609cd3f16d85b120b1d88e247216a59c7c5a27b321290c0604627db5c3","blockSize":4194304,"blocks":["69d169609cd3f16d85b120b1d88e247216a59c7c5a27b321290c0604627db5c3"]}},"sha1.js":{"size":308,"offset":"3395942","integrity":{"algorithm":"SHA256","hash":"445563946f94669cb7efb10fbfa6d24b825d466ee99faad3e58d939f3ee46c5e","blockSize":4194304,"blocks":["445563946f94669cb7efb10fbfa6d24b825d466ee99faad3e58d939f3ee46c5e"]}},"stringify.js":{"size":1093,"offset":"3396250","integrity":{"algorithm":"SHA256","hash":"bb592b599f2b00be6ca9fb2ac2fb7350abf3a6e6e274201cf6865c8c15e52b6a","blockSize":4194304,"blocks":["bb592b599f2b00be6ca9fb2ac2fb7350abf3a6e6e274201cf6865c8c15e52b6a"]}},"types.js":{"size":11,"offset":"3397343","integrity":{"algorithm":"SHA256","hash":"8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881","blockSize":4194304,"blocks":["8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881"]}},"uuid-bin.js":{"size":1971,"offset":"3397354","integrity":{"algorithm":"SHA256","hash":"40ab2c3c4a7fe2932875b5e073d2d1a19b6d205363b3baef81f95e9fae0174bf","blockSize":4194304,"blocks":["40ab2c3c4a7fe2932875b5e073d2d1a19b6d205363b3baef81f95e9fae0174bf"]}},"v1.js":{"size":2683,"offset":"3399325","integrity":{"algorithm":"SHA256","hash":"a3cd1c783a64f6e010af00593ac8e7e28c127a5e63266da4809b5687f1a081aa","blockSize":4194304,"blocks":["a3cd1c783a64f6e010af00593ac8e7e28c127a5e63266da4809b5687f1a081aa"]}},"v1ToV6.js":{"size":842,"offset":"3402008","integrity":{"algorithm":"SHA256","hash":"f0a2d19ee0d4398607808fcfc3eebeb1ea7af08a0c17d71d42fc612f97241a3f","blockSize":4194304,"blocks":["f0a2d19ee0d4398607808fcfc3eebeb1ea7af08a0c17d71d42fc612f97241a3f"]}},"v3.js":{"size":259,"offset":"3402850","integrity":{"algorithm":"SHA256","hash":"3b65ad31501886af057e13aeec03afedc54f1f85cc8d332b0eb89800b11fbce4","blockSize":4194304,"blocks":["3b65ad31501886af057e13aeec03afedc54f1f85cc8d332b0eb89800b11fbce4"]}},"v35.js":{"size":1503,"offset":"3403109","integrity":{"algorithm":"SHA256","hash":"ce090c2ea41db958cff64383cdcd09de21b577d33a57fa281cad1dde2c87b02d","blockSize":4194304,"blocks":["ce090c2ea41db958cff64383cdcd09de21b577d33a57fa281cad1dde2c87b02d"]}},"v4.js":{"size":926,"offset":"3404612","integrity":{"algorithm":"SHA256","hash":"eb4b917bb2bfcb3e723fedf3c5d0256b83578a9285e85ebf4c60caa953aa3d39","blockSize":4194304,"blocks":["eb4b917bb2bfcb3e723fedf3c5d0256b83578a9285e85ebf4c60caa953aa3d39"]}},"v5.js":{"size":262,"offset":"3405538","integrity":{"algorithm":"SHA256","hash":"daaf09616ea3b145ccd6a1dfea190b65d546267a9916c5741e026d4290c61ae9","blockSize":4194304,"blocks":["daaf09616ea3b145ccd6a1dfea190b65d546267a9916c5741e026d4290c61ae9"]}},"v6.js":{"size":630,"offset":"3405800","integrity":{"algorithm":"SHA256","hash":"32f4c875353e043cb8d790f2d63d46e7b23d592fa3d5d09ace6afcff1dd44e03","blockSize":4194304,"blocks":["32f4c875353e043cb8d790f2d63d46e7b23d592fa3d5d09ace6afcff1dd44e03"]}},"v6ToV1.js":{"size":842,"offset":"3406430","integrity":{"algorithm":"SHA256","hash":"78475a282beaea6e8c45e5f2586134929be2e21728f159fb8559df06d7288475","blockSize":4194304,"blocks":["78475a282beaea6e8c45e5f2586134929be2e21728f159fb8559df06d7288475"]}},"v7.js":{"size":2129,"offset":"3407272","integrity":{"algorithm":"SHA256","hash":"38208cc85d447b13d7fc9e75377d4f82e17ad982334786396623c57c1406a257","blockSize":4194304,"blocks":["38208cc85d447b13d7fc9e75377d4f82e17ad982334786396623c57c1406a257"]}},"validate.js":{"size":142,"offset":"3409401","integrity":{"algorithm":"SHA256","hash":"78ba6a91a3c2d219e3a6980d7704c0998e8152cabcaece0f5a04989025d0e60c","blockSize":4194304,"blocks":["78ba6a91a3c2d219e3a6980d7704c0998e8152cabcaece0f5a04989025d0e60c"]}},"version.js":{"size":208,"offset":"3409543","integrity":{"algorithm":"SHA256","hash":"5a43d6eb8496806fd5e152f92edda603dbb1f77108045edcf034f22c9e320ce8","blockSize":4194304,"blocks":["5a43d6eb8496806fd5e152f92edda603dbb1f77108045edcf034f22c9e320ce8"]}}}},"dist":{"files":{"index.js":{"size":636,"offset":"3409751","integrity":{"algorithm":"SHA256","hash":"65e9fae8f22278e6c9ac5b016dbe1ead01b8014f66ce08a807741885d4bf01f1","blockSize":4194304,"blocks":["65e9fae8f22278e6c9ac5b016dbe1ead01b8014f66ce08a807741885d4bf01f1"]}},"max.js":{"size":55,"offset":"3410387","integrity":{"algorithm":"SHA256","hash":"8f81a7b2a5f8704ea1b4e8f83d36659856fdf3d122b2bd16fe1b5c47c97b6ffa","blockSize":4194304,"blocks":["8f81a7b2a5f8704ea1b4e8f83d36659856fdf3d122b2bd16fe1b5c47c97b6ffa"]}},"md5.js":{"size":5774,"offset":"3410442","integrity":{"algorithm":"SHA256","hash":"dd40eb52bd4841e869444c2998779319b9db3cedd397717895c0ee6e2451e2a1","blockSize":4194304,"blocks":["dd40eb52bd4841e869444c2998779319b9db3cedd397717895c0ee6e2451e2a1"]}},"nil.js":{"size":55,"offset":"3416216","integrity":{"algorithm":"SHA256","hash":"a6f8ac293df0b75af2946e5190d8f00336b826bb1340b96d669a09beb8885ff8","blockSize":4194304,"blocks":["a6f8ac293df0b75af2946e5190d8f00336b826bb1340b96d669a09beb8885ff8"]}},"parse.js":{"size":612,"offset":"3416271","integrity":{"algorithm":"SHA256","hash":"a383f50a691c05533a40bbb4a87f718daa050abbc96debc9715efdc74d8538b4","blockSize":4194304,"blocks":["a383f50a691c05533a40bbb4a87f718daa050abbc96debc9715efdc74d8538b4"]}},"regex.js":{"size":171,"offset":"3416883","integrity":{"algorithm":"SHA256","hash":"774bc4bc767a58458dfdd252430d96b71b3d380ac241b50df6cb757aaa1b4783","blockSize":4194304,"blocks":["774bc4bc767a58458dfdd252430d96b71b3d380ac241b50df6cb757aaa1b4783"]}},"rng.js":{"size":110,"offset":"3417054","integrity":{"algorithm":"SHA256","hash":"69d169609cd3f16d85b120b1d88e247216a59c7c5a27b321290c0604627db5c3","blockSize":4194304,"blocks":["69d169609cd3f16d85b120b1d88e247216a59c7c5a27b321290c0604627db5c3"]}},"sha1.js":{"size":2343,"offset":"3417164","integrity":{"algorithm":"SHA256","hash":"c75c3ea675e5af8552ed41662cf6544daa0021eb04cee5c30589e837272a0016","blockSize":4194304,"blocks":["c75c3ea675e5af8552ed41662cf6544daa0021eb04cee5c30589e837272a0016"]}},"stringify.js":{"size":1093,"offset":"3419507","integrity":{"algorithm":"SHA256","hash":"bb592b599f2b00be6ca9fb2ac2fb7350abf3a6e6e274201cf6865c8c15e52b6a","blockSize":4194304,"blocks":["bb592b599f2b00be6ca9fb2ac2fb7350abf3a6e6e274201cf6865c8c15e52b6a"]}},"types.js":{"size":11,"offset":"3420600","integrity":{"algorithm":"SHA256","hash":"8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881","blockSize":4194304,"blocks":["8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881"]}},"uuid-bin.js":{"size":1971,"offset":"3420611","integrity":{"algorithm":"SHA256","hash":"40ab2c3c4a7fe2932875b5e073d2d1a19b6d205363b3baef81f95e9fae0174bf","blockSize":4194304,"blocks":["40ab2c3c4a7fe2932875b5e073d2d1a19b6d205363b3baef81f95e9fae0174bf"]}},"v1.js":{"size":2683,"offset":"3422582","integrity":{"algorithm":"SHA256","hash":"a3cd1c783a64f6e010af00593ac8e7e28c127a5e63266da4809b5687f1a081aa","blockSize":4194304,"blocks":["a3cd1c783a64f6e010af00593ac8e7e28c127a5e63266da4809b5687f1a081aa"]}},"v1ToV6.js":{"size":842,"offset":"3425265","integrity":{"algorithm":"SHA256","hash":"f0a2d19ee0d4398607808fcfc3eebeb1ea7af08a0c17d71d42fc612f97241a3f","blockSize":4194304,"blocks":["f0a2d19ee0d4398607808fcfc3eebeb1ea7af08a0c17d71d42fc612f97241a3f"]}},"v3.js":{"size":259,"offset":"3426107","integrity":{"algorithm":"SHA256","hash":"3b65ad31501886af057e13aeec03afedc54f1f85cc8d332b0eb89800b11fbce4","blockSize":4194304,"blocks":["3b65ad31501886af057e13aeec03afedc54f1f85cc8d332b0eb89800b11fbce4"]}},"v35.js":{"size":1503,"offset":"3426366","integrity":{"algorithm":"SHA256","hash":"ce090c2ea41db958cff64383cdcd09de21b577d33a57fa281cad1dde2c87b02d","blockSize":4194304,"blocks":["ce090c2ea41db958cff64383cdcd09de21b577d33a57fa281cad1dde2c87b02d"]}},"v4.js":{"size":926,"offset":"3427869","integrity":{"algorithm":"SHA256","hash":"eb4b917bb2bfcb3e723fedf3c5d0256b83578a9285e85ebf4c60caa953aa3d39","blockSize":4194304,"blocks":["eb4b917bb2bfcb3e723fedf3c5d0256b83578a9285e85ebf4c60caa953aa3d39"]}},"v5.js":{"size":262,"offset":"3428795","integrity":{"algorithm":"SHA256","hash":"daaf09616ea3b145ccd6a1dfea190b65d546267a9916c5741e026d4290c61ae9","blockSize":4194304,"blocks":["daaf09616ea3b145ccd6a1dfea190b65d546267a9916c5741e026d4290c61ae9"]}},"v6.js":{"size":630,"offset":"3429057","integrity":{"algorithm":"SHA256","hash":"32f4c875353e043cb8d790f2d63d46e7b23d592fa3d5d09ace6afcff1dd44e03","blockSize":4194304,"blocks":["32f4c875353e043cb8d790f2d63d46e7b23d592fa3d5d09ace6afcff1dd44e03"]}},"v6ToV1.js":{"size":842,"offset":"3429687","integrity":{"algorithm":"SHA256","hash":"78475a282beaea6e8c45e5f2586134929be2e21728f159fb8559df06d7288475","blockSize":4194304,"blocks":["78475a282beaea6e8c45e5f2586134929be2e21728f159fb8559df06d7288475"]}},"v7.js":{"size":2129,"offset":"3430529","integrity":{"algorithm":"SHA256","hash":"38208cc85d447b13d7fc9e75377d4f82e17ad982334786396623c57c1406a257","blockSize":4194304,"blocks":["38208cc85d447b13d7fc9e75377d4f82e17ad982334786396623c57c1406a257"]}},"validate.js":{"size":142,"offset":"3432658","integrity":{"algorithm":"SHA256","hash":"78ba6a91a3c2d219e3a6980d7704c0998e8152cabcaece0f5a04989025d0e60c","blockSize":4194304,"blocks":["78ba6a91a3c2d219e3a6980d7704c0998e8152cabcaece0f5a04989025d0e60c"]}},"version.js":{"size":208,"offset":"3432800","integrity":{"algorithm":"SHA256","hash":"5a43d6eb8496806fd5e152f92edda603dbb1f77108045edcf034f22c9e320ce8","blockSize":4194304,"blocks":["5a43d6eb8496806fd5e152f92edda603dbb1f77108045edcf034f22c9e320ce8"]}}}},"package.json":{"size":1686,"offset":"3433008","integrity":{"algorithm":"SHA256","hash":"ead6cf01cd70d43097bc79445d7f1ec65b3b416840eed7624e95cfb3ecc1ecbb","blockSize":4194304,"blocks":["ead6cf01cd70d43097bc79445d7f1ec65b3b416840eed7624e95cfb3ecc1ecbb"]}}}},"when-exit":{"files":{"dist":{"files":{"browser":{"files":{"index.js":{"size":145,"offset":"3434694","integrity":{"algorithm":"SHA256","hash":"ef19505e2ec31c272e7c96d55c2bfa7a938eaddcd157c6245c00d966a24950e2","blockSize":4194304,"blocks":["ef19505e2ec31c272e7c96d55c2bfa7a938eaddcd157c6245c00d966a24950e2"]}},"interceptor.js":{"size":661,"offset":"3434839","integrity":{"algorithm":"SHA256","hash":"105bdb20f66b93f3642c28f72b145fe67b573f0687de34213db9b6e3c13e67af","blockSize":4194304,"blocks":["105bdb20f66b93f3642c28f72b145fe67b573f0687de34213db9b6e3c13e67af"]}}}},"node":{"files":{"constants.js":{"size":206,"offset":"3435500","integrity":{"algorithm":"SHA256","hash":"0d7d8c35b894f1fee4c42086f8eb04891fa02e31538f71ed93bb6008693f48e3","blockSize":4194304,"blocks":["0d7d8c35b894f1fee4c42086f8eb04891fa02e31538f71ed93bb6008693f48e3"]}},"index.js":{"size":145,"offset":"3435706","integrity":{"algorithm":"SHA256","hash":"ef19505e2ec31c272e7c96d55c2bfa7a938eaddcd157c6245c00d966a24950e2","blockSize":4194304,"blocks":["ef19505e2ec31c272e7c96d55c2bfa7a938eaddcd157c6245c00d966a24950e2"]}},"interceptor.js":{"size":1557,"offset":"3435851","integrity":{"algorithm":"SHA256","hash":"1b62c12b93742c6ad66d0702c10659abbfb7f395cc2140436ab690af42f604bc","blockSize":4194304,"blocks":["1b62c12b93742c6ad66d0702c10659abbfb7f395cc2140436ab690af42f604bc"]}},"signals.js":{"size":498,"offset":"3437408","integrity":{"algorithm":"SHA256","hash":"b834392b3a109e687f8907640bfad69fb04ed5df76648e19ce349a9d8c2c1553","blockSize":4194304,"blocks":["b834392b3a109e687f8907640bfad69fb04ed5df76648e19ce349a9d8c2c1553"]}}}},"types.js":{"size":22,"offset":"3437906","integrity":{"algorithm":"SHA256","hash":"d99f969d7455894d5b3ee7632c54f4ffb79d666c0dd8dc49dfa6e7815f74196c","blockSize":4194304,"blocks":["d99f969d7455894d5b3ee7632c54f4ffb79d666c0dd8dc49dfa6e7815f74196c"]}}}},"license":{"size":1091,"offset":"3437928","integrity":{"algorithm":"SHA256","hash":"d98bee8913f421380c0771121d2a58deaa806e4513581d02887c3f65b9ee558f","blockSize":4194304,"blocks":["d98bee8913f421380c0771121d2a58deaa806e4513581d02887c3f65b9ee558f"]}},"package.json":{"size":519,"offset":"3439019","integrity":{"algorithm":"SHA256","hash":"6a33986a51b0c761c2e9597dd25f76bec00a10ecba5e8eb9763b0f5ce4cfba7d","blockSize":4194304,"blocks":["6a33986a51b0c761c2e9597dd25f76bec00a10ecba5e8eb9763b0f5ce4cfba7d"]}}}},"winreg":{"files":{"jsdoc.conf.json":{"size":1912,"offset":"3439538","integrity":{"algorithm":"SHA256","hash":"4d250dd09f064cf8301f93c8ff0fda9312c150ed1c69e6561be6254f1ca5945e","blockSize":4194304,"blocks":["4d250dd09f064cf8301f93c8ff0fda9312c150ed1c69e6561be6254f1ca5945e"]}},"lib":{"files":{"registry.js":{"size":26282,"offset":"3441450","integrity":{"algorithm":"SHA256","hash":"dfa7af53900ad6e02f88dfd1ad083817712be7efa71cfa8825e47a5afed3266c","blockSize":4194304,"blocks":["dfa7af53900ad6e02f88dfd1ad083817712be7efa71cfa8825e47a5afed3266c"]}}}},"package.json":{"size":546,"offset":"3467732","integrity":{"algorithm":"SHA256","hash":"b4f44fde8e57126a2a2fb6fa3e23452492b3a509bcf9a3e1bbc7436764d187b9","blockSize":4194304,"blocks":["b4f44fde8e57126a2a2fb6fa3e23452492b3a509bcf9a3e1bbc7436764d187b9"]}}}}}},"package.json":{"size":878,"offset":"3468278","integrity":{"algorithm":"SHA256","hash":"ac64fe69c7b264f8612c1fb65534184f0e8b80c6c12de2e6a8bac8fb6637d72f","blockSize":4194304,"blocks":["ac64fe69c7b264f8612c1fb65534184f0e8b80c6c12de2e6a8bac8fb6637d72f"]}},"public":{"files":{"auto-launch.js":{"size":1122,"offset":"3469156","integrity":{"algorithm":"SHA256","hash":"04a8e29e91750ae2d7fffc148c4de0eca55407fc14ca95607ea125a726a20ee8","blockSize":4194304,"blocks":["04a8e29e91750ae2d7fffc148c4de0eca55407fc14ca95607ea125a726a20ee8"]}},"config.js":{"size":3673,"offset":"3470278","integrity":{"algorithm":"SHA256","hash":"ee17661bb63911c052931698d23d815b99a6d1ed52713da915f2c7e3f126b092","blockSize":4194304,"blocks":["ee17661bb63911c052931698d23d815b99a6d1ed52713da915f2c7e3f126b092"]}},"electron.js":{"size":19335,"offset":"3473951","integrity":{"algorithm":"SHA256","hash":"9e850db1ab160a6fce7cdb93e39162f70812ffbf8d3a8bad23b109fd45b4296a","blockSize":4194304,"blocks":["9e850db1ab160a6fce7cdb93e39162f70812ffbf8d3a8bad23b109fd45b4296a"]}},"favicon.ico":{"size":147041,"offset":"3493286","integrity":{"algorithm":"SHA256","hash":"56557cb792063a58413be110474c8bd74094a1733af1532e951c6b4db621c247","blockSize":4194304,"blocks":["56557cb792063a58413be110474c8bd74094a1733af1532e951c6b4db621c247"]}},"index.html":{"size":1870,"offset":"3640327","integrity":{"algorithm":"SHA256","hash":"0c0e17c9a922decf5c1d24517b4969c4279df3ceee77ed0b812b61d5e3fb7f3b","blockSize":4194304,"blocks":["0c0e17c9a922decf5c1d24517b4969c4279df3ceee77ed0b812b61d5e3fb7f3b"]}},"logo192.png":{"size":10049,"offset":"3642197","integrity":{"algorithm":"SHA256","hash":"269c109814a3d337b5bd7a92cf1272f181fc5f468acf7a08489e6198b2b6c0fe","blockSize":4194304,"blocks":["269c109814a3d337b5bd7a92cf1272f181fc5f468acf7a08489e6198b2b6c0fe"]}},"logo512.png":{"size":21395,"offset":"3652246","integrity":{"algorithm":"SHA256","hash":"301c3d2262dea4686f69cf9213e02c7571dd02ece33b84c1b318db16283a8729","blockSize":4194304,"blocks":["301c3d2262dea4686f69cf9213e02c7571dd02ece33b84c1b318db16283a8729"]}},"manifest.json":{"size":517,"offset":"3673641","integrity":{"algorithm":"SHA256","hash":"33fdb99cc2cd3ad8e1815b18b7005eb3f58048990d80ee7c73aed28ab69a4e19","blockSize":4194304,"blocks":["33fdb99cc2cd3ad8e1815b18b7005eb3f58048990d80ee7c73aed28ab69a4e19"]}},"notifications.js":{"size":883,"offset":"3674158","integrity":{"algorithm":"SHA256","hash":"c72c0e3bc65e8d728f461321618a4b02f97a8821e42927a9aaa78f55e07c6676","blockSize":4194304,"blocks":["c72c0e3bc65e8d728f461321618a4b02f97a8821e42927a9aaa78f55e07c6676"]}},"preload.js":{"size":336,"offset":"3675041","integrity":{"algorithm":"SHA256","hash":"a379df2a8d332f5b29800ef3755c7dde930b0f04d3b9ebca03825a6a9e1c0a68","blockSize":4194304,"blocks":["a379df2a8d332f5b29800ef3755c7dde930b0f04d3b9ebca03825a6a9e1c0a68"]}},"robots.txt":{"size":59,"offset":"3675377","integrity":{"algorithm":"SHA256","hash":"dfde1b750ade7a990d8c61e0d9ad728a1fae56e4f6638761683412b848dfc145","blockSize":4194304,"blocks":["dfde1b750ade7a990d8c61e0d9ad728a1fae56e4f6638761683412b848dfc145"]}},"server.js":{"size":8260,"offset":"3675436","integrity":{"algorithm":"SHA256","hash":"30d36c21fa78ed49c5ecb1bb835387ca6637cccf7175a7dcfebaeb0ece18bde7","blockSize":4194304,"blocks":["30d36c21fa78ed49c5ecb1bb835387ca6637cccf7175a7dcfebaeb0ece18bde7"]}},"utils.js":{"size":1542,"offset":"3683696","integrity":{"algorithm":"SHA256","hash":"bd06928893e0591d0597d9f18da644940edf11a66b3fb7272221e0743f8846b6","blockSize":4194304,"blocks":["bd06928893e0591d0597d9f18da644940edf11a66b3fb7272221e0743f8846b6"]}}}}}}const Ajv = require("ajv") const ajv = new Ajv({allErrors: true}) const schema = { type: "object", properties: { foo: {type: "string"}, bar: {type: "number", maximum: 3}, }, required: ["foo", "bar"], additionalProperties: false, } const validate = ajv.compile(schema) test({foo: "abc", bar: 2}) test({foo: 2, bar: 4}) function test(data) { const valid = validate(data) if (valid) console.log("Valid!") else console.log("Invalid: " + ajv.errorsText(validate.errors)) } The MIT License (MIT) Copyright (c) 2015-2021 Evgeny Poberezkin 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; const core_1 = require("./core"); const draft7_1 = require("./vocabularies/draft7"); const dynamic_1 = require("./vocabularies/dynamic"); const next_1 = require("./vocabularies/next"); const unevaluated_1 = require("./vocabularies/unevaluated"); const discriminator_1 = require("./vocabularies/discriminator"); const json_schema_2019_09_1 = require("./refs/json-schema-2019-09"); const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; class Ajv2019 extends core_1.default { constructor(opts = {}) { super({ ...opts, dynamicRef: true, next: true, unevaluated: true, }); } _addVocabularies() { super._addVocabularies(); this.addVocabulary(dynamic_1.default); draft7_1.default.forEach((v) => this.addVocabulary(v)); this.addVocabulary(next_1.default); this.addVocabulary(unevaluated_1.default); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); const { $data, meta } = this.opts; if (!meta) return; json_schema_2019_09_1.default.call(this, $data); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); } } exports.Ajv2019 = Ajv2019; module.exports = exports = Ajv2019; module.exports.Ajv2019 = Ajv2019; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv2019; var validate_1 = require("./compile/validate"); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); var codegen_1 = require("./compile/codegen"); Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); var validation_error_1 = require("./runtime/validation_error"); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); var ref_error_1 = require("./compile/ref_error"); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); //# sourceMappingURL=2019.js.map{"version":3,"file":"2019.js","sourceRoot":"","sources":["../lib/2019.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAEvC,kDAAsD;AACtD,oDAAsD;AACtD,8CAAgD;AAChD,4DAA8D;AAC9D,gEAAwD;AACxD,oEAA0D;AAE1D,MAAM,cAAc,GAAG,8CAA8C,CAAA;AAErE,MAAa,OAAQ,SAAQ,cAAO;IAClC,YAAY,OAAgB,EAAE;QAC5B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,UAAU,EAAE,IAAI;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,IAAI;SAClB,CAAC,CAAA;IACJ,CAAC;IAED,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,IAAI,CAAC,aAAa,CAAC,iBAAiB,CAAC,CAAA;QACrC,gBAAkB,CAAC,O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AAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; const core_1 = require("./core"); const draft2020_1 = require("./vocabularies/draft2020"); const discriminator_1 = require("./vocabularies/discriminator"); const json_schema_2020_12_1 = require("./refs/json-schema-2020-12"); const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; class Ajv2020 extends core_1.default { constructor(opts = {}) { super({ ...opts, dynamicRef: true, next: true, unevaluated: true, }); } _addVocabularies() { super._addVocabularies(); draft2020_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); const { $data, meta } = this.opts; if (!meta) return; json_schema_2020_12_1.default.call(this, $data); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); } } exports.Ajv2020 = Ajv2020; module.exports = exports = Ajv2020; module.exports.Ajv2020 = Ajv2020; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv2020; var validate_1 = require("./compile/validate"); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); var codegen_1 = require("./compile/codegen"); Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); var validation_error_1 = require("./runtime/validation_error"); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); var ref_error_1 = require("./compile/ref_error"); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); //# sourceMappingURL=2020.js.map{"version":3,"file":"2020.js","sourceRoot":"","sources":["../lib/2020.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAEvC,wDAA4D;AAC5D,gEAAwD;AACxD,oEAA0D;AAE1D,MAAM,cAAc,GAAG,8CAA8C,CAAA;AAErE,MAAa,OAAQ,SAAQ,cAAO;IAClC,YAAY,OAAgB,EAAE;QAC5B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,UAAU,EAAE,IAAI;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,IAAI;SAClB,CAAC,CAAA;IACJ,CAAC;IAED,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,mBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QAC3D,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa;YAAE,IAAI,CAAC,UAAU,CAAC,uBAAa,CAAC,CAAA;IAC7D,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,MAAM,EAAC,KAAK,EAAE,IAAI,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;QAC/B,IAAI,CAAC,IAAI;YAAE,OAAM;QACjB,6BAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACnC,IAAI,CAAC,IAAI,CAAC,+BAA+B,CAAC,GAAG,cAAc,CAAA;IAC7D,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAC3B,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IACzF,CAAC;CACF;AA5BD,0BA4BC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,OAAO,CAAA;AAClC,MAAM,CAAC,OAAO,CAAC,OAAO,GAAG,OAAO,CAAA;AAChC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,OAAO,CAAA;AAyBtB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; const core_1 = require("./core"); const draft7_1 = require("./vocabularies/draft7"); const discriminator_1 = require("./vocabularies/discriminator"); const draft7MetaSchema = require("./refs/json-schema-draft-07.json"); const META_SUPPORT_DATA = ["/properties"]; const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; class Ajv extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); } } exports.Ajv = Ajv; module.exports = exports = Ajv; module.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv; var validate_1 = require("./compile/validate"); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); var codegen_1 = require("./compile/codegen"); Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); var validation_error_1 = require("./runtime/validation_error"); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); var ref_error_1 = require("./compile/ref_error"); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); //# sourceMappingURL=ajv.js.map{"version":3,"file":"ajv.js","sourceRoot":"","sources":["../lib/ajv.ts"],"names":[],"mappings":";;;AACA,iCAA4B;AAC5B,kDAAsD;AACtD,gEAAwD;AACxD,qEAAoE;AAEpE,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,MAAM,cAAc,GAAG,wCAAwC,CAAA;AAE/D,MAAa,GAAI,SAAQ,cAAO;IAC9B,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,gBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC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,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; // eslint-disable-next-line @typescript-eslint/no-extraneous-class class _CodeOrName { } exports._CodeOrName = _CodeOrName; exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; class Name extends _CodeOrName { constructor(s) { super(); if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } } exports.Name = Name; class _Code extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a; return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, ""))); } get names() { var _a; return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}))); } } exports._Code = _Code; exports.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports._ = _; const plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== undefined) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`; } exports.strConcat = strConcat; // TODO do not allow arrays here function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports.stringify = stringify; function safeStringify(x) { return JSON.stringify(x) .replace(/\u2028/g, "\\u2028") .replace(/\u2029/g, "\\u2029"); } exports.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`; } exports.getProperty = getProperty; //Does best effort to format the name properly function getEsmExportName(key) { if (typeof key == "string" && exports.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports.regexpCode = regexpCode; //# sourceMappingURL=code.js.map{"version":3,"file":"code.js","sourceRoot":"","sources":["../../../lib/compile/codegen/code.ts"],"names":[],"mappings":";;;AAAA,kEAAkE;AAClE,MAAsB,WAAW;CAKhC;AALD,kCAKC;AAEY,QAAA,UAAU,GAAG,uBAAuB,CAAA;AAEjD,MAAa,IAAK,SAAQ,WAAW;IAEnC,YAAY,CAAS;QACnB,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,kBAAU,CAAC,IAAI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;AACvD,CAAC;AAED,SAAgB,SAAS,CAAC,CAAU;IAClC,OAAO,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;AACpC,CAAC;AAFD,8BAEC;AAED,SAAgB,aAAa,CAAC,CAAU;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AAClC,CAAC;AAJD,sCAIC;AAED,SAAgB,WAAW,CAAC,GAA2B;IACrD,OAAO,OAAO,GAAG,IAAI,QAAQ,IAAI,kBAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,IAAI,GAAG,GAAG,CAAA;AAC5F,CAAC;AAFD,kCAEC;AAED,8CAA8C;AAC9C,SAAgB,gBAAgB,CAAC,GAA2B;IAC1D,IAAI,OAAO,GAAG,IAAI,QAAQ,IAAI,kBAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACnD,OAAO,IAAI,KAAK,CAAC,GAAG,GAAG,EAAE,CAAC,CAAA;IAC5B,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,iCAAiC,GAAG,iCAAiC,CAAC,CAAA;AACxF,CAAC;AALD,4CAKC;AAED,SAAgB,UAAU,CAAC,EAAU;IACnC,OAAO,IAAI,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;AACjC,CAAC;AAFD,gCAEC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; const code_1 = require("./code"); const scope_1 = require("./scope"); var code_2 = require("./code"); Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } }); Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } }); Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } }); Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } }); var scope_2 = require("./scope"); Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } }); Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } }); Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } }); Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } }); exports.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+"), }; class Node { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } } class Def extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } } class Assign extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } } class AssignOp extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } } class Label extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } } class Break extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } } class Throw extends Node { constructor(error) { super(); this.error = error; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } } class AnyCode extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : undefined; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } } class ParentNode extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : undefined; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { // iterating backwards improves 1-pass optimization const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : undefined; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } } class BlockNode extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } } class Root extends ParentNode { } class Else extends BlockNode { } Else.kind = "else"; class If extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; // else is ignored here let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof If ? e : e.nodes; if (this.nodes.length) return this; return new If(not(cond), e instanceof If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return undefined; return this; } optimizeNames(names, constants) { var _a; this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } } If.kind = "if"; class For extends BlockNode { } For.kind = "for"; class ForLoop extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } } class ForRange extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } } class ForIter extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } } class Func extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } } Func.kind = "func"; class Return extends ParentNode { render(opts) { return "return " + super.render(opts); } } Return.kind = "return"; class Try extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a, _b; super.optimizeNodes(); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a, _b; super.optimizeNames(names, constants); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } } class Catch extends BlockNode { constructor(error) { super(); this.error = error; } render(opts) { return `catch(${this.error})` + super.render(opts); } } Catch.kind = "catch"; class Finally extends BlockNode { render(opts) { return "finally" + super.render(opts); } } Finally.kind = "finally"; class CodeGen { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== undefined && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => { this.var(name, (0, code_1._) `${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error = this.name("e"); this._currNode = node.catch = new Catch(error); catchCode(error); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error) { return this._leafNode(new Throw(error)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === undefined) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || (N2 && n instanceof N2)) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } } exports.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === undefined || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return (e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined)); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`; } exports.not = not; const andCode = mappend(exports.operators.AND); // boolean AND (&&) expression with the passed arguments function and(...args) { return args.reduce(andCode); } exports.and = and; const orCode = mappend(exports.operators.OR); // boolean OR (||) expression with the passed arguments function or(...args) { return args.reduce(orCode); } exports.or = or; function mappend(op) { return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`); } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`; } //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/codegen/index.ts"],"names":[],"mappings":";;;AACA,iCAA8F;AAC9F,mCAAuC;AAEvC,+BAA6F;AAArF,yFAAA,CAAC,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,mGAAA,WAAW,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,kGAAA,UAAU,OAAA;AAAE,4FAAA,IAAI,OAAA;AACxE,iCAA+F;AAAvF,8FAAA,KAAK,OAAA;AAAc,mGAAA,UAAU,OAAA;AAAE,uGAAA,cAAc,OAAA;AAAkB,iGAAA,QAAQ,OAAA;AAQlE,QAAA,SAAS,GAAG;IACvB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,KAAK,CAAC;IACpB,GAAG,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AC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AACjF,CAAC;AAED,SAAS,GAAG,CAAC,CAAO;IAClB,OAAO,CAAC,YAAY,WAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,IAAI,CAAC,GAAG,CAAA;AAC1C,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; const code_1 = require("./code"); class ValueError extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } } var UsedValueState; (function (UsedValueState) { UsedValueState[UsedValueState["Started"] = 0] = "Started"; UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); exports.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var"), }; class Scope { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a, _b; if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return (this._names[prefix] = { prefix, index: 0 }); } } exports.Scope = Scope; class ValueScopeName extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`; } } exports.ValueScopeName = ValueScopeName; const line = (0, code_1._) `\n`; class ValueScope extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a; if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._) `${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`; } else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) { code = (0, code_1._) `${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } } exports.ValueScope = ValueScope; //# sourceMappingURL=scope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AM,OAAO,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC,CAAA;YACtE,EAAE,CAAC,OAAO,CAAC,CAAC,IAAoB,EAAE,EAAE;gBAClC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;oBAAE,OAAM;gBAC7B,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,OAAO,CAAC,CAAA;gBACzC,IAAI,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,CAAA;gBACvB,IAAI,CAAC,EAAE,CAAC;oBACN,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,KAAK,CAAA;oBACzD,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACxD,CAAC;qBAAM,IAAI,CAAC,CAAC,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,IAAI,CAAC,CAAC,EAAE,CAAC;oBACjC,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACtC,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,UAAU,CAAC,IAAI,CAAC,CAAA;gBAC5B,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,SAAS,CAAC,CAAA;YAC7C,CAAC,CAAC,CAAA;QACJ,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAjGD,gCAiGC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; const codegen_1 = require("./codegen"); const util_1 = require("./util"); const names_1 = require("./names"); exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`, }; exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`, }; function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._) `[${errObj}]`); } } exports.reportError = reportError; function reportExtraError(cxt, error = exports.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) { /* istanbul ignore if */ if (errsCount === undefined) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._) `${err}.schema`, schemaValue); gen.assign((0, codegen_1._) `${err}.data`, data); } }); } exports.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._) `${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._) `${validateName}.errors`, errs); gen.return(false); } } const E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema"), }; function errorObjectCode(cxt, error, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._) `{}`; return errorObject(cxt, error, errorPaths); } function errorObject(cxt, error, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths), ]; extraErrorProps(cxt, error, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } //# sourceMappingURL=errors.js.map{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/compile/errors.ts"],"names":[],"mappings":";;;AAEA,uCAAgE;AAEhE,iCAAyC;AACzC,mCAAuB;AAEV,QAAA,YAAY,GAA2B;IAClD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,cAAc,OAAO,sBAAsB;CACvE,CAAA;AAEY,QAAA,iBAAiB,GAA2B;IACvD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CACjC,UAAU;QACR,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,qBAAqB,UAAU,UAAU;QACzD,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,8BAA8B;CACnD,CAAA;AAQD,SAAgB,WAAW,CACzB,GAAoB,EACpB,QAAgC,oBAAY,EAC5C,UAAuB,EACvB,iBAA2B;IAE3B,MAAM,EAAC,EAAE,EAAC,GAAG,GAAG,CAAA;IAChB,MAAM,EAAC,GAAG,EAAE,aAAa,EAAE,SAAS,EAAC,GAAG,EAAE,CAAA;IAC1C,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,EAAE,KAAK,EAAE,UAAU,CAAC,CAAA;IACtD,IAAI,iBAAiB,aAAjB,iBAAiB,cAAjB,iBAAiB,GAAI,CAAC,aAAa,IAAI,SAAS,CAAC,EAAE,CAAC;QACtD,QAAQ,CAAC,GAAG,EAAE,MA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CAAC,CAAC,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAA;AAClE,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; const codegen_1 = require("./codegen"); const validation_error_1 = require("../runtime/validation_error"); const names_1 = require("./names"); const resolve_1 = require("./resolve"); const util_1 = require("./util"); const validate_1 = require("./validate"); class SchemaEnv { constructor(env) { var _a; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } } exports.SchemaEnv = SchemaEnv; // let codeSize = 0 // let nodeCount = 0 // Compiles schema in SchemaEnv function compileSchema(sch) { // TODO refactor - remove compilations const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`, }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._) `""`, opts: this.opts, self: this, }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); // gen.optimize(1) const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); // console.log("\n\n\n *** \n", sourceCode) const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate }); validate.errors = null; validate.schema = sch.schema; validate.schemaEnv = sch; if (sch.$async) validate.$async = true; if (this.opts.code.source === true) { validate.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate.evaluated = { props: props instanceof codegen_1.Name ? undefined : props, items: items instanceof codegen_1.Name ? undefined : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name, }; if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); } sch.validate = validate; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); // console.log("\n\n\n *** \n", sourceCode, this.opts) throw e; } finally { this._compilations.delete(sch); } } exports.compileSchema = compileSchema; function resolveRef(root, baseId, ref) { var _a; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve.call(this, root, ref); if (_sch === undefined) { const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === undefined) return; return (root.refs[ref] = inlineOrCompile.call(this, _sch)); } exports.resolveRef = resolveRef; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } // Index of schema compilation in the currently compiled list function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } // resolve and compile the references ($ref) // TODO returns AnySchemaObject (if the schema can be inlined) or validation function function resolve(root, // information about the root schema for the current schema ref // reference to resolve ) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } // Resolve schema, its root and baseId function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it ref // reference to resolve ) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined); // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports.resolveSchema = resolveSchema; const PREVENT_SCOPE_CHANGE = new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions", ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a; if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === undefined) return; schema = partSchema; // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } // even though resolution failed we need to return SchemaEnv to throw exception // so that compileAsync loads missing schema. const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return undefined; } //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/compile/index.ts"],"names":[],"mappings":";;;AAUA,uCAAgF;AAChF,kEAAyD;AACzD,mCAAuB;AACvB,uCAAkG;AAClG,iCAA6D;AAC7D,yCAA+C;AA0D/C,MAAa,SAAS;IAkBpB,YAAY,GAAkB;;QATrB,SAAI,GAAe,EAAE,CAAA;QACrB,mBAAc,GAA6B,EAAE,CAAA;QASpD,IAAI,MAAmC,CAAA;QACvC,IAAI,OAAO,GAAG,CAAC,MAAM,IAAI,QAAQ;YAAE,MAAM,GAAG,GAAG,CAAC,MAAM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;QAC3D,CAAC;IACH,CAAC;IACD,IAAI,GAA0B,CAAA;IAC9B,IAAI,OAAO,MAAM,IAAI,SAAS,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,IAAA,2BAAoB,EAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3F,MAAM,IAAI,GAAG,IAAA,oBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,CAAA;QACnE,GAAG,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;IAC5C,CAAC;IACD,+EAA+E;IAC/E,6CAA6C;IAC7C,MAAM,EAAC,QAAQ,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IAC5B,GAAG,GAAG,GAAG,IAAI,IAAI,SAAS,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAC,CAAC,CAAA;IAC5D,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,GAAG,CAAA;IAC9C,OAAO,SAAS,CAAA;AAClB,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const types_1 = require("./types"); const __1 = require(".."); const codegen_1 = require("../codegen"); const ref_error_1 = require("../ref_error"); const names_1 = require("../names"); const code_1 = require("../../vocabularies/code"); const ref_1 = require("../../vocabularies/jtd/ref"); const type_1 = require("../../vocabularies/jtd/type"); const parseJson_1 = require("../../runtime/parseJson"); const util_1 = require("../util"); const timestamp_1 = require("../../runtime/timestamp"); const genParse = { elements: parseElements, values: parseValues, discriminator: parseDiscriminator, properties: parseProperties, optionalProperties: parseProperties, enum: parseEnum, type: parseType, ref: parseRef, }; function compileParser(sch, definitions) { const _sch = __1.getCompilingSchema.call(this, sch); if (_sch) return _sch; const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); const parseName = gen.scopeName("parse"); const cxt = { self: this, gen, schema: sch.schema, schemaEnv: sch, definitions, data: names_1.default.data, parseName, char: gen.name("c"), }; let sourceCode; try { this._compilations.add(sch); sch.parseName = parseName; parserFunction(cxt); gen.optimize(this.opts.code.optimize); const parseFuncCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`; const makeParse = new Function(`${names_1.default.scope}`, sourceCode); const parse = makeParse(this.scope.get()); this.scope.value(parseName, { ref: parse }); sch.parse = parse; } catch (e) { if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode); delete sch.parse; delete sch.parseName; throw e; } finally { this._compilations.delete(sch); } return sch; } exports.default = compileParser; const undef = (0, codegen_1._) `undefined`; function parserFunction(cxt) { const { gen, parseName, char } = cxt; gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => { gen.let(names_1.default.data); gen.let(char); gen.assign((0, codegen_1._) `${parseName}.message`, undef); gen.assign((0, codegen_1._) `${parseName}.position`, undef); gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`); gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`); parseCode(cxt); skipWhitespace(cxt); gen.if(names_1.default.jsonPart, () => { gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos); gen.return(names_1.default.data); }); gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data)); jsonSyntaxError(cxt); }); } function parseCode(cxt) { let form; for (const key of types_1.jtdForms) { if (key in cxt.schema) { form = key; break; } } if (form) parseNullable(cxt, genParse[form]); else parseEmpty(cxt); } const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)); function parseNullable(cxt, parseForm) { const { gen, schema, data } = cxt; if (!schema.nullable) return parseForm(cxt); tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)); } function parseElements(cxt) { const { gen, schema, data } = cxt; parseToken(cxt, "["); const ix = gen.let("i", 0); gen.assign(data, (0, codegen_1._) `[]`); parseItems(cxt, "]", () => { const el = gen.let("el"); parseCode({ ...cxt, schema: schema.elements, data: el }); gen.assign((0, codegen_1._) `${data}[${ix}++]`, el); }); } function parseValues(cxt) { const { gen, schema, data } = cxt; parseToken(cxt, "{"); gen.assign(data, (0, codegen_1._) `{}`); parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)); } function parseItems(cxt, endToken, block) { tryParseItems(cxt, endToken, block); parseToken(cxt, endToken); } function tryParseItems(cxt, endToken, block) { const { gen } = cxt; gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { block(); tryParseToken(cxt, ",", () => gen.break(), hasItem); }); function hasItem() { tryParseToken(cxt, endToken, () => { }, jsonSyntaxError); } } function parseKeyValue(cxt, schema) { const { gen } = cxt; const key = gen.let("key"); parseString({ ...cxt, data: key }); parseToken(cxt, ":"); parsePropertyValue(cxt, key, schema); } function parseDiscriminator(cxt) { const { gen, data, schema } = cxt; const { discriminator, mapping } = schema; parseToken(cxt, "{"); gen.assign(data, (0, codegen_1._) `{}`); const startPos = gen.const("pos", names_1.default.jsonPos); const value = gen.let("value"); const tag = gen.let("tag"); tryParseItems(cxt, "}", () => { const key = gen.let("key"); parseString({ ...cxt, data: key }); parseToken(cxt, ":"); gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => { parseString({ ...cxt, data: tag }); gen.assign((0, codegen_1._) `${data}[${key}]`, tag); gen.break(); }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped ); }); gen.assign(names_1.default.jsonPos, startPos); gen.if((0, codegen_1._) `${tag} === undefined`); parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator); } gen.else(); parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`); gen.endIf(); } function parseProperties(cxt) { const { gen, data } = cxt; parseToken(cxt, "{"); gen.assign(data, (0, codegen_1._) `{}`); parseSchemaProperties(cxt); } function parseSchemaProperties(cxt, discriminator) { const { gen, schema, data } = cxt; const { properties, optionalProperties, additionalProperties } = schema; parseItems(cxt, "}", () => { const key = gen.let("key"); parseString({ ...cxt, data: key }); parseToken(cxt, ":"); gen.if(false); parseDefinedProperty(cxt, key, properties); parseDefinedProperty(cxt, key, optionalProperties); if (discriminator) { gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`); const tag = gen.let("tag"); parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned } gen.else(); if (additionalProperties) { parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` }); } else { parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`); } gen.endIf(); }); if (properties) { const hasProp = (0, code_1.hasPropFunc)(gen); const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`)); gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`)); } } function parseDefinedProperty(cxt, key, schemas = {}) { const { gen } = cxt; for (const prop in schemas) { gen.elseIf((0, codegen_1._) `${key} === ${prop}`); parsePropertyValue(cxt, key, schemas[prop]); } } function parsePropertyValue(cxt, key, schema) { parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` }); } function parseType(cxt) { const { gen, schema, data, self } = cxt; switch (schema.type) { case "boolean": parseBoolean(cxt); break; case "string": parseString(cxt); break; case "timestamp": { parseString(cxt); const vts = (0, util_1.useFunc)(gen, timestamp_1.default); const { allowDate, parseDate } = self.opts; const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`; const fail = parseDate ? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`) : notValid; gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`)); break; } case "float32": case "float64": parseNumber(cxt); break; default: { const t = schema.type; if (!self.opts.int32range && (t === "int32" || t === "uint32")) { parseNumber(cxt, 16); // 2 ** 53 - max safe integer if (t === "uint32") { gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`)); } } else { const [min, max, maxDigits] = type_1.intRange[t]; parseNumber(cxt, maxDigits); gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`)); } } } } function parseString(cxt) { parseToken(cxt, '"'); parseWith(cxt, parseJson_1.parseJsonString); } function parseEnum(cxt) { const { gen, data, schema } = cxt; const enumSch = schema.enum; parseToken(cxt, '"'); // TODO loopEnum gen.if(false); for (const value of enumSch) { const valueStr = JSON.stringify(value).slice(1); // remove starting quote gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`); gen.assign(data, (0, codegen_1.str) `${value}`); gen.add(names_1.default.jsonPos, valueStr.length); } gen.else(); jsonSyntaxError(cxt); gen.endIf(); } function parseNumber(cxt, maxDigits) { const { gen } = cxt; skipWhitespace(cxt); gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits)); } function parseBooleanToken(bool, fail) { return (cxt) => { const { gen, data } = cxt; tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool)); }; } function parseRef(cxt) { const { gen, self, definitions, schema, schemaEnv } = cxt; const { ref } = schema; const refSchema = definitions[ref]; if (!refSchema) throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); if (!(0, ref_1.hasRef)(refSchema)) return parseCode({ ...cxt, schema: refSchema }); const { root } = schemaEnv; const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); partialParse(cxt, getParser(gen, sch), true); } function getParser(gen, sch) { return sch.parse ? gen.scopeValue("parse", { ref: sch.parse }) : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`; } function parseEmpty(cxt) { parseWith(cxt, parseJson_1.parseJson); } function parseWith(cxt, parseFunc, args) { partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args); } function partialParse(cxt, parseFunc, args) { const { gen, data } = cxt; gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`); gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`); gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`)); } function parseToken(cxt, tok) { tryParseToken(cxt, tok, jsonSyntaxError); } function tryParseToken(cxt, tok, fail, success) { const { gen } = cxt; const n = tok.length; skipWhitespace(cxt); gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => { gen.add(names_1.default.jsonPos, n); success === null || success === void 0 ? void 0 : success(cxt); }, () => fail(cxt)); } function skipWhitespace({ gen, char: c }) { gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`); } function jsonSlice(len) { return len === 1 ? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]` : (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`; } function jsonSyntaxError(cxt) { parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`); } function parsingError({ gen, parseName }, msg) { gen.assign((0, codegen_1._) `${parseName}.message`, msg); gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos); gen.return(undef); } //# sourceMappingURL=parse.js.map{"version":3,"file":"parse.js","sourceRoot":"","sources":["../../../lib/compile/jtd/parse.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAmF;AACnF,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAmD;AACnD,oDAAiD;AACjD,sDAA6D;AAC7D,uDAAmF;AACnF,kCAA+B;AAC/B,uDAAoD;AAIpD,MAAM,QAAQ,GAA+B;IAC3C,QAAQ,EAAE,aAAa;IACvB,MAAM,EAAE,WAAW;IACnB,aAAa,EAAE,kBAAkB;IACjC,UAAU,EAAE,eAAe;IAC3B,kBAAkB,EAAE,eAAe;IACnC,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,QAAQ;CACd,CAAA;AAaD,SAAwB,aAAa,CAEnC,GAAc,EACd,WAA4B;IAE5B,MAAM,IAAI,GAAG,sBAAkB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC/C,IAAI,IAAI;QAAE,OAAO,IAAI,CAAA;IACrB,MAAM,EAAC,GAAG,EAAE,KAAK,EAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;IACnC,MAAM,EAAC,aAAa,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IACjC,MAAM,GAAG,GAAG,IAAI,iBAAO,CAAC,IAAI,CAAC,KAAK,EAAE,EAAC,GAAG,EAAE,KAAK,EAAE,aAAa,EAAC,CAAC,CAAA;IAChE,MAAM,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;IACxC,MAAM,GAAG,GAAa;QACpB,IAAI,EAAE,IAAI;QACV,GAAG;QACH,MAAM,EAAE,GAAG,CAAC,MAAsB;QAClC,SAAS,EAAE,GAAG;QACd,WAAW;QACX,IAAI,EAAE,eAAC,CAAC,IAAI;QACZ,SAAS;QACT,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC;KACp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AA,WAAC,EAAA,GAAG,SAAS,WAAW,EAAE,eAAC,CAAC,OAAO,CAAC,CAAA;IAC/C,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AACnB,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const types_1 = require("./types"); const __1 = require(".."); const codegen_1 = require("../codegen"); const ref_error_1 = require("../ref_error"); const names_1 = require("../names"); const code_1 = require("../../vocabularies/code"); const ref_1 = require("../../vocabularies/jtd/ref"); const util_1 = require("../util"); const quote_1 = require("../../runtime/quote"); const genSerialize = { elements: serializeElements, values: serializeValues, discriminator: serializeDiscriminator, properties: serializeProperties, optionalProperties: serializeProperties, enum: serializeString, type: serializeType, ref: serializeRef, }; function compileSerializer(sch, definitions) { const _sch = __1.getCompilingSchema.call(this, sch); if (_sch) return _sch; const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); const serializeName = gen.scopeName("serialize"); const cxt = { self: this, gen, schema: sch.schema, schemaEnv: sch, definitions, data: names_1.default.data, }; let sourceCode; try { this._compilations.add(sch); sch.serializeName = serializeName; gen.func(serializeName, names_1.default.data, false, () => { gen.let(names_1.default.json, (0, codegen_1.str) ``); serializeCode(cxt); gen.return(names_1.default.json); }); gen.optimize(this.opts.code.optimize); const serializeFuncCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`; const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode); const serialize = makeSerialize(this.scope.get()); this.scope.value(serializeName, { ref: serialize }); sch.serialize = serialize; } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode); delete sch.serialize; delete sch.serializeName; throw e; } finally { this._compilations.delete(sch); } return sch; } exports.default = compileSerializer; function serializeCode(cxt) { let form; for (const key of types_1.jtdForms) { if (key in cxt.schema) { form = key; break; } } serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty); } function serializeNullable(cxt, serializeForm) { const { gen, schema, data } = cxt; if (!schema.nullable) return serializeForm(cxt); gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt)); } function serializeElements(cxt) { const { gen, schema, data } = cxt; gen.add(names_1.default.json, (0, codegen_1.str) `[`); const first = gen.let("first", true); gen.forOf("el", data, (el) => { addComma(cxt, first); serializeCode({ ...cxt, schema: schema.elements, data: el }); }); gen.add(names_1.default.json, (0, codegen_1.str) `]`); } function serializeValues(cxt) { const { gen, schema, data } = cxt; gen.add(names_1.default.json, (0, codegen_1.str) `{`); const first = gen.let("first", true); gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)); gen.add(names_1.default.json, (0, codegen_1.str) `}`); } function serializeKeyValue(cxt, key, schema, first) { const { gen, data } = cxt; addComma(cxt, first); serializeString({ ...cxt, data: key }); gen.add(names_1.default.json, (0, codegen_1.str) `:`); const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`); serializeCode({ ...cxt, schema, data: value }); } function serializeDiscriminator(cxt) { const { gen, schema, data } = cxt; const { discriminator } = schema; gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`); const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`); serializeString({ ...cxt, data: tag }); gen.if(false); for (const tagValue in schema.mapping) { gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); const sch = schema.mapping[tagValue]; serializeSchemaProperties({ ...cxt, schema: sch }, discriminator); } gen.endIf(); gen.add(names_1.default.json, (0, codegen_1.str) `}`); } function serializeProperties(cxt) { const { gen } = cxt; gen.add(names_1.default.json, (0, codegen_1.str) `{`); serializeSchemaProperties(cxt); gen.add(names_1.default.json, (0, codegen_1.str) `}`); } function serializeSchemaProperties(cxt, discriminator) { const { gen, schema, data } = cxt; const { properties, optionalProperties } = schema; const props = keys(properties); const optProps = keys(optionalProperties); const allProps = allProperties(props.concat(optProps)); let first = !discriminator; let firstProp; for (const key of props) { if (first) first = false; else gen.add(names_1.default.json, (0, codegen_1.str) `,`); serializeProperty(key, properties[key], keyValue(key)); } if (first) firstProp = gen.let("first", true); for (const key of optProps) { const value = keyValue(key); gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => { addComma(cxt, firstProp); serializeProperty(key, optionalProperties[key], value); }); } if (schema.additionalProperties) { gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))); } function keys(ps) { return ps ? Object.keys(ps) : []; } function allProperties(ps) { if (discriminator) ps.push(discriminator); if (new Set(ps).size !== ps.length) { throw new Error("JTD: properties/optionalProperties/disciminator overlap"); } return ps; } function keyValue(key) { return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`); } function serializeProperty(key, propSchema, value) { gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`); serializeCode({ ...cxt, schema: propSchema, data: value }); } function isAdditional(key, ps) { return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true; } } function serializeType(cxt) { const { gen, schema, data } = cxt; switch (schema.type) { case "boolean": gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`); break; case "string": serializeString(cxt); break; case "timestamp": gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt)); break; default: serializeNumber(cxt); } } function serializeString({ gen, data }) { gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`); } function serializeNumber({ gen, data, self }) { const condition = (0, codegen_1._) `${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`; if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") { gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`); } else { // specialNumbers === "null" gen.if(condition, () => gen.add(names_1.default.json, (0, codegen_1._) `null`), () => gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`)); } } function serializeRef(cxt) { const { gen, self, data, definitions, schema, schemaEnv } = cxt; const { ref } = schema; const refSchema = definitions[ref]; if (!refSchema) throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); if (!(0, ref_1.hasRef)(refSchema)) return serializeCode({ ...cxt, schema: refSchema }); const { root } = schemaEnv; const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`); } function getSerialize(gen, sch) { return sch.serialize ? gen.scopeValue("serialize", { ref: sch.serialize }) : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`; } function serializeEmpty({ gen, data }) { gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`); } function addComma({ gen }, first) { if (first) { gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`)); } else { gen.add(names_1.default.json, (0, codegen_1.str) `,`); } } //# sourceMappingURL=serialize.js.map{"version":3,"file":"serialize.js","sourceRoot":"","sources":["../../../lib/compile/jtd/serialize.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAwE;AACxE,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAqD;AACrD,oDAAiD;AACjD,kCAA+B;AAC/B,+CAAuC;AAEvC,MAAM,YAAY,GAAkD;IAClE,QAAQ,EAAE,iBAAiB;IAC3B,MAAM,EAAE,eAAe;IACvB,aAAa,EAAE,sBAAsB;IACrC,UAAU,EAAE,mBAAmB;IAC/B,kBAAkB,EAAE,mBAAmB;IACvC,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE,aAAa;IACnB,GAAG,EAAE,YAAY;CAClB,CAAA;AAWD,SAAwB,iBAAiB,CAEvC,GAAc,EACd,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AC,CAAA;IAC/F,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,CAAA;AACxD,CAAC;AAED,SAAS,YAAY,CAAC,GAAY,EAAE,GAAc;IAChD,OAAO,GAAG,CAAC,SAAS;QAClB,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,EAAC,GAAG,EAAE,GAAG,CAAC,SAAS,EAAC,CAAC;QACnD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,CAAC,YAAY,CAAA;AAC3D,CAAC;AAED,SAAS,cAAc,CAAC,EAAC,GAAG,EAAE,IAAI,EAAe;IAC/C,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,kBAAkB,IAAI,GAAG,CAAC,CAAA;AAC7C,CAAC;AAED,SAAS,QAAQ,CAAC,EAAC,GAAG,EAAe,EAAE,KAAY;IACjD,IAAI,KAAK,EAAE,CAAC;QACV,GAAG,CAAC,EAAE,CACJ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAC9B,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAC9B,CAAA;IACH,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACzB,CAAC;AACH,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jtdForms = void 0; exports.jtdForms = [ "elements", "values", "discriminator", "properties", "optionalProperties", "enum", "type", "ref", ]; //# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/compile/jtd/types.ts"],"names":[],"mappings":";;;AAIa,QAAA,QAAQ,GAAG;IACtB,UAAU;IACV,QAAQ;IACR,eAAe;IACf,YAAY;IACZ,oBAAoB;IACpB,MAAM;IACN,MAAM;IACN,KAAK;CACG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("./codegen"); const names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart"), }; exports.default = names; //# sourceMappingURL=names.js.map{"version":3,"file":"names.js","sourceRoot":"","sources":["../../lib/compile/names.ts"],"names":[],"mappings":";;AAAA,uCAA8B;AAE9B,MAAM,KAAK,GAAG;IACZ,gCAAgC;IAChC,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC,EAAE,qCAAqC;IAC7D,sCAAsC;IACtC,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+FAA+F;IAC3H,YAAY,EAAE,IAAI,cAAI,CAAC,cAAc,CAAC;IACtC,UAAU,EAAE,IAAI,cAAI,CAAC,YAAY,CAAC;IAClC,kBAAkB,EAAE,IAAI,cAAI,CAAC,oBAAoB,CAAC;IAClD,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC,EAAE,2EAA2E;IAC3G,cAAc,EAAE,IAAI,cAAI,CAAC,gBAAgB,CAAC,EAAE,8CAA8C;IAC1F,4BAA4B;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC,EAAE,qCAAqC;IACnE,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+BAA+B;IAC3D,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,YAAY;IACZ,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,KAAK,EAAE,IAAI,cAAI,CAAC,OAAO,CAAC;IACxB,wDAAwD;IACxD,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC;CAC/B,CAAA;AAED,kBAAe,KAAK,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const resolve_1 = require("./resolve"); class MissingRefError extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } } exports.default = MissingRefError; //# sourceMappingURL=ref_error.js.map{"version":3,"file":"ref_error.js","sourceRoot":"","sources":["../../lib/compile/ref_error.ts"],"names":[],"mappings":";;AAAA,uCAA8D;AAG9D,MAAqB,eAAgB,SAAQ,KAAK;IAIhD,YAAY,QAAqB,EAAE,MAAc,EAAE,GAAW,EAAE,GAAY;QAC1E,KAAK,CAAC,GAAG,IAAI,2BAA2B,GAAG,YAAY,MAAM,EAAE,CAAC,CAAA;QAChE,IAAI,CAAC,UAAU,GAAG,IAAA,oBAAU,EAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAA;QACnD,IAAI,CAAC,aAAa,GAAG,IAAA,qBAAW,EAAC,IAAA,qBAAW,EAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AATD,kCASC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; const util_1 = require("./util"); const equal = require("fast-deep-equal"); const traverse = require("json-schema-traverse"); // TODO refactor to use keyword definitions const SIMPLE_INLINED = new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const", ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports.inlineRef = inlineRef; const REF_KEYWORDS = new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor", ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch))); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports._getFullPath = _getFullPath; const TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports.resolveUrl = resolveUrl; const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === undefined) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { // eslint-disable-next-line @typescript-eslint/unbound-method const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports.getSchemaRefs = getSchemaRefs; //# sourceMappingURL=resolve.js.map{"version":3,"file":"resolve.js","sourceRoot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AQ,CAAA;gBAC3B,CAAC;YACH,CAAC;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;QAED,SAAS,SAAS,CAAY,MAAe;YAC3C,IAAI,OAAO,MAAM,IAAI,QAAQ,EAAE,CAAC;gBAC9B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,MAAM,GAAG,CAAC,CAAA;gBACvE,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,MAAM,EAAE,CAAC,CAAA;YACjC,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAA;IAEF,OAAO,SAAS,CAAA;IAEhB,SAAS,gBAAgB,CAAC,IAAe,EAAE,IAA2B,EAAE,GAAW;QACjF,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;YAAE,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnE,CAAC;IAED,SAAS,QAAQ,CAAC,GAAW;QAC3B,OAAO,IAAI,KAAK,CAAC,cAAc,GAAG,oCAAoC,CAAC,CAAA;IACzE,CAAC;AACH,CAAC;AAxDD,sCAwDC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRules = exports.isJSONType = void 0; const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; const jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] }, }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {}, }; } exports.getRules = getRules; //# sourceMappingURL=rules.js.map{"version":3,"file":"rules.js","sourceRoot":"","sources":["../../lib/compile/rules.ts"],"names":[],"mappings":";;;AAEA,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAU,CAAA;AAIjG,MAAM,SAAS,GAAgB,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;AAElD,SAAgB,UAAU,CAAC,CAAU;IACnC,OAAO,OAAO,CAAC,IAAI,QAAQ,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC;AAFD,gCAEC;AAyBD,SAAgB,QAAQ;IACtB,MAAM,MAAM,GAAgE;QAC1E,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,KAAK,EAAE,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAC;QACjC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;KACpC,CAAA;IACD,OAAO;QACL,KAAK,EAAE,EAAC,GAAG,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAC;QAC5D,KAAK,EAAE,CAAC,EAAC,KAAK,EAAE,EAAE,EAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QAC/E,IAAI,EAAE,EAAC,KAAK,EAAE,EAAE,EAAC;QACjB,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,EAAE;KACb,CAAA;AACH,CAAC;AAdD,4BAcC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; const codegen_1 = require("./codegen"); const code_1 = require("./codegen/code"); // TODO refactor to use Set function toHash(arr) { const hash = {}; for (const item of arr) hash[item] = true; return hash; } exports.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._) `${schema}`; } return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) { return (gen, from, to, toName) => { const res = to === undefined ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._) `${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => (from === true ? true : { ...from, ...to }), resultToName: evaluatedPropsToName, }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), resultToName: (gen, items) => gen.var("items", items), }), }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._) `{}`); if (ps !== undefined) setEvaluated(gen, props, ps); return props; } exports.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true)); } exports.setEvaluated = setEvaluated; const snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)), }); } exports.useFunc = useFunc; var Type; (function (Type) { Type[Type["Num"] = 0] = "Num"; Type[Type["Str"] = 1] = "Str"; })(Type || (exports.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { // let path if (dataProp instanceof codegen_1.Name) { const isNumber = dataPropType === Type.Num; return jsPropertySyntax ? isNumber ? (0, codegen_1._) `"[" + ${dataProp} + "]"` : (0, codegen_1._) `"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._) `"/" + ${dataProp}` : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports.checkStrictMode = checkStrictMode; //# sourceMappingURL=util.js.map{"version":3,"file":"util.js","sourceRoot":"","sources":["../../lib/compile/util.ts"],"names":[],"mappings":";;;AAEA,uCAA6D;AAC7D,yCAAoC;AAGpC,2BAA2B;AAC3B,SAAgB,MAAM,CAA4B,GAAQ;IACxD,MAAM,IAAI,GAAsB,EAAE,CAAA;IAClC,KAAK,MAAM,IAAI,IAAI,GAAG;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IACzC,OAAO,IAAI,CAAA;AACb,CAAC;AAJD,wBAIC;AAED,SAAgB,iBAAiB,CAAC,EAAa,EAAE,MAAiB;IAChE,IAAI,OAAO,MAAM,IAAI,SAAS;QAAE,OAAO,MAAM,CAAA;IAC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;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,IAAA,qBAAW,EAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAChG,CAAC;AAjBD,oCAiBC;AAED,SAAgB,eAAe,CAC7B,EAAa,EACb,GAAW,EACX,OAAwB,EAAE,CAAC,IAAI,CAAC,YAAY;IAE5C,IAAI,CAAC,IAAI;QAAE,OAAM;IACjB,GAAG,GAAG,gBAAgB,GAAG,EAAE,CAAA;IAC3B,IAAI,IAAI,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;IACvC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AATD,0CASC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a; return (schema[rule.keyword] !== undefined || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined))); } exports.shouldUseRule = shouldUseRule; //# sourceMappingURL=applicability.js.map{"version":3,"file":"applicability.js","sourceRoot":"","sources":["../../../lib/compile/validate/applicability.ts"],"names":[],"mappings":";;;AAIA,SAAgB,qBAAqB,CACnC,EAAC,MAAM,EAAE,IAAI,EAAe,EAC5B,IAAc;IAEd,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IACpC,OAAO,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;AACjE,CAAC;AAND,sDAMC;AAED,SAAgB,cAAc,CAAC,MAAuB,EAAE,KAAgB;IACtE,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;AAChE,CAAC;AAFD,wCAEC;AAED,SAAgB,aAAa,CAAC,MAAuB,EAAE,IAAU;;IAC/D,OAAO,CACL,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,SAAS;SAClC,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC,CAAA,CACrE,CAAA;AACH,CAAC;AALD,sCAKC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; const errors_1 = require("../errors"); const codegen_1 = require("../codegen"); const names_1 = require("../names"); const boolError = { message: "boolean schema is false", }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._) `${validateName}.errors`, null); gen.return(true); } } exports.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); // TODO var falseSchemaError(it); } else { gen.var(valid, true); // TODO var } } exports.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; // TODO maybe some other interface should be used for non-keyword validation errors... const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it, }; (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors); } //# sourceMappingURL=boolSchema.js.map{"version":3,"file":"boolSchema.js","sourceRoot":"","sources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G,GAAoB;QAC3B,GAAG;QACH,OAAO,EAAE,cAAc;QACvB,IAAI;QACJ,MAAM,EAAE,KAAK;QACb,UAAU,EAAE,KAAK;QACjB,WAAW,EAAE,KAAK;QAClB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;IACD,IAAA,oBAAW,EAAC,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAA;AAC3D,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; const rules_1 = require("../rules"); const applicability_1 = require("./applicability"); const errors_1 = require("../errors"); const codegen_1 = require("../codegen"); const util_1 = require("../util"); var DataType; (function (DataType) { DataType[DataType["Correct"] = 0] = "Correct"; DataType[DataType["Wrong"] = 1] = "Wrong"; })(DataType || (exports.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== undefined) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports.getSchemaTypes = getSchemaTypes; // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports.coerceAndCheckDataType = coerceAndCheckDataType; const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._) `undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen .assign(data, (0, codegen_1._) `${data}[0]`) .assign(dataType, (0, codegen_1._) `typeof ${data}`) .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._) `${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._) `${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`) .assign(coerced, (0, codegen_1._) `"" + ${data}`) .elseIf((0, codegen_1._) `${data} === null`) .assign(coerced, (0, codegen_1._) `""`); return; case "number": gen .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`) .assign(coerced, (0, codegen_1._) `+${data}`); return; case "integer": gen .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`) .assign(coerced, (0, codegen_1._) `+${data}`); return; case "boolean": gen .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`) .assign(coerced, false) .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`) .assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`) .assign(coerced, (0, codegen_1._) `[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { // TODO use gen.property gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._) `${data} ${EQ} null`; case "array": cond = (0, codegen_1._) `Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil); } } exports.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._) `typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports.checkDataTypes = checkDataTypes; const typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`, }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it, }; } //# sourceMappingURL=dataType.js.map{"version":3,"file":"dataType.js","sourceRoot":"","sources":["../../../lib/compile/validate/dataType.ts"],"names":[],"mappings":";;;AAOA,oCAA6C;AAC7C,mDAAqD;AACrD,sCAAqC;AACrC,wCAAkE;AAClE,kCAA8C;AAE9C,IAAY,QAGX;AAHD,WAAY,QAAQ;IAClB,6CAAO,CAAA;IACP,yCAAK,CAAA;AACP,CAAC,EAHW,QAAQ,wBAAR,QAAQ,QAGnB;AAED,SAAgB,cAAc,CAAC,MAAuB;IACpD,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACvC,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;IACtC,IAAI,OAAO,EAAE,CAAC;QACZ,IAAI,MAAM,CAAC,QAAQ,KAAK,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAA;IAC1F,CAAC;SAAM,CAAC;QACN,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACnD,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;QAC7D,CAAC;QACD,IAAI,MAAM,CAAC,QAAQ,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IAClD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAZD,wCAYC;AAED,6EAA6E;AAC7E,SAAgB,YAAY,CAAC,EAAuB;IAClD,MAAM,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C,WAAW,MAAM,EAAE;IAC1C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,WAAW,EAAC,EAAE,EAAE,CAChC,OAAO,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,UAAU,MAAM,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,UAAU,WAAW,GAAG;CAC/E,CAAA;AAED,SAAgB,eAAe,CAAC,EAAgB;IAC9C,MAAM,GAAG,GAAG,mBAAmB,CAAC,EAAE,CAAC,CAAA;IACnC,IAAA,oBAAW,EAAC,GAAG,EAAE,SAAS,CAAC,CAAA;AAC7B,CAAC;AAHD,0CAGC;AAED,SAAS,mBAAmB,CAAC,EAAgB;IAC3C,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAC,GAAG,EAAE,CAAA;IAC9B,MAAM,UAAU,GAAG,IAAA,qBAAc,EAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IACrD,OAAO;QACL,GAAG;QACH,OAAO,EAAE,MAAM;QACf,IAAI;QACJ,MAAM,EAAE,MAAM,CAAC,IAAI;QACnB,UAAU;QACV,WAAW,EAAE,UAAU;QACvB,YAAY,EAAE,MAAM;QACpB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;AACH,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assignDefaults = void 0; const codegen_1 = require("../codegen"); const util_1 = require("../util"); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === undefined) return; const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._) `${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`; } // `${childData} === undefined` + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } //# sourceMappingURL=defaults.js.map{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../../lib/compile/validate/defaults.ts"],"names":[],"mappings":";;;AACA,wCAAoD;AACpD,kCAAuC;AAEvC,SAAgB,cAAc,CAAC,EAAgB,EAAE,EAAW;IAC1D,MAAM,EAAC,UAAU,EAAE,KAAK,EAAC,GAAG,EAAE,CAAC,MAAM,CAAA;IACrC,IAAI,EAAE,KAAK,QAAQ,IAAI,UAAU,EAAE,CAAC;QAClC,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;YAC7B,aAAa,CAAC,EAAE,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAA;QACjD,CAAC;IACH,CAAC;SAAM,IAAI,EAAE,KAAK,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAClD,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAS,EAAE,EAAE,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAA;IACtE,CAAC;AACH,CAAC;AATD,wCASC;AAED,SAAS,aAAa,CAAC,EAAgB,EAAE,IAAqB,EAAE,YAAqB;IACnF,MAAM,EAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;IAC3C,IAAI,YAAY,KAAK,SAAS;QAAE,OAAM;IACtC,MAAM,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,IAAI,CAAC,EAAE,CAAA;IAChD,IAAI,aAAa,EAAE,CAAC;QAClB,IAAA,sBAAe,EAAC,EAAE,EAAE,2BAA2B,SAAS,EAAE,CAAC,CAAA;QAC3D,OAAM;IACR,CAAC;IAED,IAAI,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,SAAS,gBAAgB,CAAA;IAC7C,IAAI,IAAI,CAAC,WAAW,KAAK,OAAO,EAAE,CAAC;QACjC,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,SAAS,OAAO,SAAS,gBAAgB,SAAS,SAAS,CAAA;IAC7E,CAAC;IACD,iCAAiC;IACjC,2FAA2F;IAC3F,GAAG,CAAC,EAAE,CAAC,SAAS,EAAE,IAAA,WAAC,EAAA,GAAG,SAAS,MAAM,IAAA,mBAAS,EAAC,YAAY,CAAC,EAAE,CAAC,CAAA;AACjE,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; const boolSchema_1 = require("./boolSchema"); const dataType_1 = require("./dataType"); const applicability_1 = require("./applicability"); const dataType_2 = require("./dataType"); const defaults_1 = require("./defaults"); const keyword_1 = require("./keyword"); const subschema_1 = require("./subschema"); const codegen_1 = require("../codegen"); const names_1 = require("../names"); const resolve_1 = require("../resolve"); const util_1 = require("../util"); const errors_1 = require("../errors"); // schema compilation - generates validation function, subschemaCode (below) is used for subschemas function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._) `""`); gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`); gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`)); gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil; } // schema compilation - this function is used recursively to generate code for sub-schemas function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); // TODO var gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { // TODO assign unevaluated gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._) `${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._) `${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._) `${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } // TODO make it "ok" call? if (!allErrors) gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults }, } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")); } function includesType(ts, t) { return ts.includes(t) || (t === "integer" && ts.includes("number")); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } class KeywordCxt { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), undefined, failAction); } fail(condition) { if (condition === undefined) { this.error(); if (!this.allErrors) this.gen.if(false); // this branch will be removed by gen.optimize return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== undefined) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== undefined) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } } exports.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment of segments) { if (segment) { data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; expr = (0, codegen_1._) `${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports.getData = getData; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot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I,CAAC,WAAW;YAAE,OAAO,IAAI,CAAA;IAC/B,CAAC;IAED,IAAI,IAAI,GAAG,IAAI,CAAA;IACf,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACvC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,IAAA,0BAAmB,EAAC,OAAO,CAAC,CAAC,EAAE,CAAA;YAC7D,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,OAAO,IAAI,EAAE,CAAA;QAC9B,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;IAEX,SAAS,QAAQ,CAAC,WAAmB,EAAE,EAAU;QAC/C,OAAO,iBAAiB,WAAW,IAAI,EAAE,gCAAgC,SAAS,EAAE,CAAA;IACtF,CAAC;AACH,CAAC;AAtCD,0BAsCC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; const codegen_1 = require("../codegen"); const names_1 = require("../names"); const code_1 = require("../../vocabularies/code"); const errors_1 = require("../errors"); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true, }, valid); cxt.pass(valid, () => cxt.error(true)); } exports.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._) `${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !(("compile" in def && !$data) || def.schema === false); gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a; gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); } } exports.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => { gen .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`) .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { // TODO add tests return (!schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || (allowUndefined && typeof schema == "undefined"))); } exports.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { /* istanbul ignore if */ if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports.validateKeywordUsage = validateKeywordUsage; //# sourceMappingURL=keyword.js.map{"version":3,"file":"keyword.js","sourceRoot":"","sources":["../../../lib/compile/validate/keyword.ts"],"names":[],"mappings":";;;AAUA,wCAAsE;AACtE,oCAAwB;AAExB,kDAAwD;AACxD,sCAAsC;AAItC,SAAgB,gBAAgB,CAAC,GAAe,EAAE,GAA2B;IAC3E,MAAM,EAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IACpD,MAAM,WAAW,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,CAAC,CAAA;IACrE,MAAM,SAA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cAAc,EAAE,CAAC;QACvB,MAAM,KAAK,GAAG,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAA;QACjD,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,GAAG,GACP,YAAY,OAAO,+BAA+B,aAAa,KAAK;gBACpE,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;YAC5C,IAAI,IAAI,CAAC,cAAc,KAAK,KAAK;gBAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;;gBACpD,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;QAC3B,CAAC;IACH,CAAC;AACH,CAAC;AAzBD,oDAyBC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; const codegen_1 = require("../codegen"); const util_1 = require("../util"); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== undefined && schema !== undefined) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== undefined) { const sch = it.schema[keyword]; return schemaProp === undefined ? { schema: sch, schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}`, } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`, }; } if (schema !== undefined) { if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath, }; } throw new Error('either "keyword" or "schema" must be passed'); } exports.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== undefined && dataProp !== undefined) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== undefined) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== undefined) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once? dataContextProps(nextData); if (propertyName !== undefined) subschema.propertyName = propertyName; // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== undefined) subschema.compositeRule = compositeRule; if (createErrors !== undefined) subschema.createErrors = createErrors; if (allErrors !== undefined) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; // not inherited subschema.jtdMetadata = jtdMetadata; // not inherited } exports.extendSubschemaMode = extendSubschemaMode; //# sourceMappingURL=subschema.js.map{"version":3,"file":"subschema.js","sourceRoot":"","sources":["../../../lib/compile/validate/subschema.ts"],"names":[],"mappings":";;;AAEA,wCAA0D;AAC1D,kCAA0D;AA6C1D,SAAgB,YAAY,CAC1B,EAAgB,EAChB,EAAC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAgB;IAErF,IAAI,OA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AAI,SAAS;QAAE,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;IAE9C,SAAS,gBAAgB,CAAC,SAAe;QACvC,SAAS,CAAC,IAAI,GAAG,SAAS,CAAA;QAC1B,SAAS,CAAC,SAAS,GAAG,EAAE,CAAC,SAAS,GAAG,CAAC,CAAA;QACtC,SAAS,CAAC,SAAS,GAAG,EAAE,CAAA;QACxB,EAAE,CAAC,iBAAiB,GAAG,IAAI,GAAG,EAAU,CAAA;QACxC,SAAS,CAAC,UAAU,GAAG,EAAE,CAAC,IAAI,CAAA;QAC9B,SAAS,CAAC,SAAS,GAAG,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;IACpD,CAAC;AACH,CAAC;AArCD,kDAqCC;AAED,SAAgB,mBAAmB,CACjC,SAA2B,EAC3B,EAAC,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,YAAY,EAAE,SAAS,EAAgB;IAEtF,IAAI,aAAa,KAAK,SAAS;QAAE,SAAS,CAAC,aAAa,GAAG,aAAa,CAAA;IACxE,IAAI,YAAY,KAAK,SAAS;QAAE,SAAS,CAAC,YAAY,GAAG,YAAY,CAAA;IACrE,IAAI,SAAS,KAAK,SAAS;QAAE,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5D,SAAS,CAAC,gBAAgB,GAAG,gBAAgB,CAAA,CAAC,gBAAgB;IAC9D,SAAS,CAAC,WAAW,GAAG,WAAW,CAAA,CAAC,gBAAgB;AACtD,CAAC;AATD,kDASC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; var validate_1 = require("./compile/validate"); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); var codegen_1 = require("./compile/codegen"); Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); const validation_error_1 = require("./runtime/validation_error"); const ref_error_1 = require("./compile/ref_error"); const rules_1 = require("./compile/rules"); const compile_1 = require("./compile"); const codegen_2 = require("./compile/codegen"); const resolve_1 = require("./compile/resolve"); const dataType_1 = require("./compile/validate/dataType"); const util_1 = require("./compile/util"); const $dataRefSchema = require("./refs/data.json"); const uri_1 = require("./runtime/uri"); const defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; const EXT_SCOPE_NAMES = new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error", ]); const removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now.", }; const deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.', }; const MAX_EXPRESSION = 200; // eslint-disable-next-line complexity function requiredOptions(o) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver: uriResolver, }; } class Ajv { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = Object.create(null); this._compilations = new Set(); this._loading = {}; this._cache = new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta, schemaId } = this.opts; return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined); } validate(schemaKeyRef, // key, ref or schema object // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents data // to be validated ) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return (sch.validate || this._compileSchemaEnv(sch)); } compileAsync(schema, meta) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, // If array is passed, `key` will be ignored key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. ) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== undefined && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, // schema key _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema ) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== undefined && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === undefined) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return (sch.validate || this._compileSchemaEnv(sch)); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey = schemaKeyRef; this._cache.delete(cacheKey); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def // deprecated ) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === undefined) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType), }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { // TODO return type should be Ajv const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, // optional array of validation errors { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar` ) { if (!errors || errors.length === 0) return "No errors"; return errors .map((e) => `${dataVar}${e.instancePath} ${e.message}`) .reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); // first segment is an empty string let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== undefined) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); /* istanbul ignore if */ if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } } Ajv.ValidationError = validation_error_1.default; Ajv.MissingRefError = ref_error_1.default; exports.default = Ajv; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } const noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === undefined) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType), }, }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === undefined) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } //# sourceMappingURL=core.js.map{"version":3,"file":"core.js","sourceRoot":"","sources":["../lib/core.ts"],"names":[],"mappings":";;;AA4BA,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAKlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAsBnD,iEAAwD;AACxD,mDAAiD;AACjD,2CAAoF;AACpF,uCAAiE;AACjE,+CAAkD;AAClD,+CAA4D;AAC5D,0DAAwD;AACxD,yCAAuC;AACvC,mDAAkD;AAElD,uCAA8C;AAE9C,MAAM,aAAa,GAAiB,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;AAC1E,aAAa,CAAC,IAAI,GAAG,YAAY,CAAA;AAEjC,MAAM,mBAAmB,GAAsB,CAAC,kBAAkB,EAAE,aAAa,EAAE,aAAa,CAAC,CAAA;AACjG,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,UAAU;IACV,WAAW;IACX,OAAO;IACP,SAAS;IACT,MAAM;IACN,QAAQ;IACR,SAAS;IACT,S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,IAAI,EAAE,gFAAgF;CACvF,CAAA;AAED,SAAS,YAAY,CAAC,MAAiB;IACrC,OAAO,EAAC,KAAK,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAC,CAAA;AACpC,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; const core_1 = require("./core"); const jtd_1 = require("./vocabularies/jtd"); const jtd_schema_1 = require("./refs/jtd-schema"); const serialize_1 = require("./compile/jtd/serialize"); const parse_1 = require("./compile/jtd/parse"); const META_SCHEMA_ID = "JTD-meta-schema"; class Ajv extends core_1.default { constructor(opts = {}) { super({ ...opts, jtd: true, }); } _addVocabularies() { super._addVocabularies(); this.addVocabulary(jtd_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false); } defaultMeta() { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); } compileSerializer(schema) { const sch = this._addSchema(schema); return sch.serialize || this._compileSerializer(sch); } compileParser(schema) { const sch = this._addSchema(schema); return (sch.parse || this._compileParser(sch)); } _compileSerializer(sch) { serialize_1.default.call(this, sch, sch.schema.definitions || {}); /* istanbul ignore if */ if (!sch.serialize) throw new Error("ajv implementation error"); return sch.serialize; } _compileParser(sch) { parse_1.default.call(this, sch, sch.schema.definitions || {}); /* istanbul ignore if */ if (!sch.parse) throw new Error("ajv implementation error"); return sch.parse; } } exports.Ajv = Ajv; module.exports = exports = Ajv; module.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv; var validate_1 = require("./compile/validate"); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); var codegen_1 = require("./compile/codegen"); Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); var validation_error_1 = require("./runtime/validation_error"); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); var ref_error_1 = require("./compile/ref_error"); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); //# sourceMappingURL=jtd.js.map{"version":3,"file":"jtd.js","sourceRoot":"","sources":["../lib/jtd.ts"],"names":[],"mappings":";;;AAEA,iCAA8C;AAC9C,4CAA8C;AAC9C,kDAA6C;AAC7C,uDAAuD;AACvD,+CAA+C;AAG/C,MAAM,cAAc,GAAG,iBAAiB,CAAA;AA4BxC,MAAa,GAAI,SAAQ,cAAO;IAC9B,YAAY,OAAmB,EAAE;QAC/B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,GAAG,EAAE,IAAI;SACV,CAAC,CAAA;IACJ,CAAC;IAED,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,IAAI,CAAC,aAAa,CAAC,aAAa,CAAC,CAAA;IACnC,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAM;QAC3B,IAAI,CAAC,aAAa,CAAC,oBAAa,EAAE,cAAc,EAAE,KAAK,CAAC,CAAA;IAC1D,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAC3B,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS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AAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,GAAG,CAAA;AA0BlB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAElB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAInD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"}{ "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", "type": "object", "required": ["$data"], "properties": { "$data": { "type": "string", "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}] } }, "additionalProperties": false } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const metaSchema = require("./schema.json"); const applicator = require("./meta/applicator.json"); const content = require("./meta/content.json"); const core = require("./meta/core.json"); const format = require("./meta/format.json"); const metadata = require("./meta/meta-data.json"); const validation = require("./meta/validation.json"); const META_SUPPORT_DATA = ["/properties"]; function addMetaSchema2019($data) { ; [ metaSchema, applicator, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)); return this; function with$data(ajv, sch) { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; } } exports.default = addMetaSchema2019; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2019-09/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,+CAA8C;AAC9C,yCAAwC;AACxC,6CAA4C;AAC5C,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAfD,oCAeC"}{ "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/applicator", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, "$recursiveAnchor": true, "title": "Applicator vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "additionalItems": {"$recursiveRef": "#"}, "unevaluatedItems": {"$recursiveRef": "#"}, "items": { "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] }, "contains": {"$recursiveRef": "#"}, "additionalProperties": {"$recursiveRef": "#"}, "unevaluatedProperties": {"$recursiveRef": "#"}, "properties": { "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "propertyNames": {"format": "regex"}, "default": {} }, "dependentSchemas": { "type": "object", "additionalProperties": { "$recursiveRef": "#" } }, "propertyNames": {"$recursiveRef": "#"}, "if": {"$recursiveRef": "#"}, "then": {"$recursiveRef": "#"}, "else": {"$recursiveRef": "#"}, "allOf": {"$ref": "#/$defs/schemaArray"}, "anyOf": {"$ref": "#/$defs/schemaArray"}, "oneOf": {"$ref": "#/$defs/schemaArray"}, "not": {"$recursiveRef": "#"} }, "$defs": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$recursiveRef": "#"} } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/content", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, "$recursiveAnchor": true, "title": "Content vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "contentMediaType": {"type": "string"}, "contentEncoding": {"type": "string"}, "contentSchema": {"$recursiveRef": "#"} } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/core", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, "$recursiveAnchor": true, "title": "Core vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference", "$comment": "Non-empty fragments not allowed.", "pattern": "^[^#]*#?$" }, "$schema": { "type": "string", "format": "uri" }, "$anchor": { "type": "string", "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" }, "$ref": { "type": "string", "format": "uri-reference" }, "$recursiveRef": { "type": "string", "format": "uri-reference" }, "$recursiveAnchor": { "type": "boolean", "default": false }, "$vocabulary": { "type": "object", "propertyNames": { "type": "string", "format": "uri" }, "additionalProperties": { "type": "boolean" } }, "$comment": { "type": "string" }, "$defs": { "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "default": {} } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/format", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, "$recursiveAnchor": true, "title": "Format vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "format": {"type": "string"} } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, "$recursiveAnchor": true, "title": "Meta-data vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "deprecated": { "type": "boolean", "default": false }, "readOnly": { "type": "boolean", "default": false }, "writeOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/validation", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, "$recursiveAnchor": true, "title": "Validation vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, "minContains": { "$ref": "#/$defs/nonNegativeInteger", "default": 1 }, "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/$defs/stringArray"}, "dependentRequired": { "type": "object", "additionalProperties": { "$ref": "#/$defs/stringArray" } }, "const": true, "enum": { "type": "array", "items": true }, "type": { "anyOf": [ {"$ref": "#/$defs/simpleTypes"}, { "type": "array", "items": {"$ref": "#/$defs/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] } }, "$defs": { "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "$ref": "#/$defs/nonNegativeInteger", "default": 0 }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/schema", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true, "https://json-schema.org/draft/2019-09/vocab/applicator": true, "https://json-schema.org/draft/2019-09/vocab/validation": true, "https://json-schema.org/draft/2019-09/vocab/meta-data": true, "https://json-schema.org/draft/2019-09/vocab/format": false, "https://json-schema.org/draft/2019-09/vocab/content": true }, "$recursiveAnchor": true, "title": "Core and Validation specifications meta-schema", "allOf": [ {"$ref": "meta/core"}, {"$ref": "meta/applicator"}, {"$ref": "meta/validation"}, {"$ref": "meta/meta-data"}, {"$ref": "meta/format"}, {"$ref": "meta/content"} ], "type": ["object", "boolean"], "properties": { "definitions": { "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "default": {} }, "dependencies": { "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", "type": "object", "additionalProperties": { "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] } } } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const metaSchema = require("./schema.json"); const applicator = require("./meta/applicator.json"); const unevaluated = require("./meta/unevaluated.json"); const content = require("./meta/content.json"); const core = require("./meta/core.json"); const format = require("./meta/format-annotation.json"); const metadata = require("./meta/meta-data.json"); const validation = require("./meta/validation.json"); const META_SUPPORT_DATA = ["/properties"]; function addMetaSchema2020($data) { ; [ metaSchema, applicator, unevaluated, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)); return this; function with$data(ajv, sch) { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; } } exports.default = addMetaSchema2020; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2020-12/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,uDAAsD;AACtD,+CAA8C;AAC9C,yCAAwC;AACxC,wDAAuD;AACvD,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,WAAW;QACX,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAhBD,oCAgBC"}{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/applicator", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, "$dynamicAnchor": "meta", "title": "Applicator vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "prefixItems": {"$ref": "#/$defs/schemaArray"}, "items": {"$dynamicRef": "#meta"}, "contains": {"$dynamicRef": "#meta"}, "additionalProperties": {"$dynamicRef": "#meta"}, "properties": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "propertyNames": {"format": "regex"}, "default": {} }, "dependentSchemas": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "default": {} }, "propertyNames": {"$dynamicRef": "#meta"}, "if": {"$dynamicRef": "#meta"}, "then": {"$dynamicRef": "#meta"}, "else": {"$dynamicRef": "#meta"}, "allOf": {"$ref": "#/$defs/schemaArray"}, "anyOf": {"$ref": "#/$defs/schemaArray"}, "oneOf": {"$ref": "#/$defs/schemaArray"}, "not": {"$dynamicRef": "#meta"} }, "$defs": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$dynamicRef": "#meta"} } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/content", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, "$dynamicAnchor": "meta", "title": "Content vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "contentEncoding": {"type": "string"}, "contentMediaType": {"type": "string"}, "contentSchema": {"$dynamicRef": "#meta"} } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/core", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, "$dynamicAnchor": "meta", "title": "Core vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "$id": { "$ref": "#/$defs/uriReferenceString", "$comment": "Non-empty fragments not allowed.", "pattern": "^[^#]*#?$" }, "$schema": {"$ref": "#/$defs/uriString"}, "$ref": {"$ref": "#/$defs/uriReferenceString"}, "$anchor": {"$ref": "#/$defs/anchorString"}, "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, "$vocabulary": { "type": "object", "propertyNames": {"$ref": "#/$defs/uriString"}, "additionalProperties": { "type": "boolean" } }, "$comment": { "type": "string" }, "$defs": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"} } }, "$defs": { "anchorString": { "type": "string", "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" }, "uriString": { "type": "string", "format": "uri" }, "uriReferenceString": { "type": "string", "format": "uri-reference" } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, "$dynamicAnchor": "meta", "title": "Format vocabulary meta-schema for annotation results", "type": ["object", "boolean"], "properties": { "format": {"type": "string"} } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, "$dynamicAnchor": "meta", "title": "Meta-data vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "deprecated": { "type": "boolean", "default": false }, "readOnly": { "type": "boolean", "default": false }, "writeOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, "$dynamicAnchor": "meta", "title": "Unevaluated applicator vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "unevaluatedItems": {"$dynamicRef": "#meta"}, "unevaluatedProperties": {"$dynamicRef": "#meta"} } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/validation", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, "$dynamicAnchor": "meta", "title": "Validation vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "type": { "anyOf": [ {"$ref": "#/$defs/simpleTypes"}, { "type": "array", "items": {"$ref": "#/$defs/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] }, "const": true, "enum": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, "minContains": { "$ref": "#/$defs/nonNegativeInteger", "default": 1 }, "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/$defs/stringArray"}, "dependentRequired": { "type": "object", "additionalProperties": { "$ref": "#/$defs/stringArray" } } }, "$defs": { "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "$ref": "#/$defs/nonNegativeInteger", "default": 0 }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/schema", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true, "https://json-schema.org/draft/2020-12/vocab/applicator": true, "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, "https://json-schema.org/draft/2020-12/vocab/validation": true, "https://json-schema.org/draft/2020-12/vocab/meta-data": true, "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, "https://json-schema.org/draft/2020-12/vocab/content": true }, "$dynamicAnchor": "meta", "title": "Core and Validation specifications meta-schema", "allOf": [ {"$ref": "meta/core"}, {"$ref": "meta/applicator"}, {"$ref": "meta/unevaluated"}, {"$ref": "meta/validation"}, {"$ref": "meta/meta-data"}, {"$ref": "meta/format-annotation"}, {"$ref": "meta/content"} ], "type": ["object", "boolean"], "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", "properties": { "definitions": { "$comment": "\"definitions\" has been replaced by \"$defs\".", "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "deprecated": true, "default": {} }, "dependencies": { "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", "type": "object", "additionalProperties": { "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] }, "deprecated": true, "default": {} }, "$recursiveAnchor": { "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", "$ref": "meta/core#/$defs/anchorString", "deprecated": true }, "$recursiveRef": { "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", "$ref": "meta/core#/$defs/uriReferenceString", "deprecated": true } } } { "$schema": "http://json-schema.org/draft-06/schema#", "$id": "http://json-schema.org/draft-06/schema#", "title": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$ref": "#"} }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } }, "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": {}, "examples": { "type": "array", "items": {} }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "additionalItems": {"$ref": "#"}, "items": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], "default": {} }, "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "contains": {"$ref": "#"}, "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/definitions/stringArray"}, "additionalProperties": {"$ref": "#"}, "definitions": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "properties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] } }, "propertyNames": {"$ref": "#"}, "const": {}, "enum": { "type": "array", "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [ {"$ref": "#/definitions/simpleTypes"}, { "type": "array", "items": {"$ref": "#/definitions/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] }, "format": {"type": "string"}, "allOf": {"$ref": "#/definitions/schemaArray"}, "anyOf": {"$ref": "#/definitions/schemaArray"}, "oneOf": {"$ref": "#/definitions/schemaArray"}, "not": {"$ref": "#"} }, "default": {} } { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "http://json-schema.org/draft-07/schema#", "title": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$ref": "#"} }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } }, "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "$comment": { "type": "string" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "readOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "additionalItems": {"$ref": "#"}, "items": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], "default": true }, "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "contains": {"$ref": "#"}, "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/definitions/stringArray"}, "additionalProperties": {"$ref": "#"}, "definitions": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "properties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$ref": "#"}, "propertyNames": {"format": "regex"}, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] } }, "propertyNames": {"$ref": "#"}, "const": true, "enum": { "type": "array", "items": true, "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [ {"$ref": "#/definitions/simpleTypes"}, { "type": "array", "items": {"$ref": "#/definitions/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] }, "format": {"type": "string"}, "contentMediaType": {"type": "string"}, "contentEncoding": {"type": "string"}, "if": {"$ref": "#"}, "then": {"$ref": "#"}, "else": {"$ref": "#"}, "allOf": {"$ref": "#/definitions/schemaArray"}, "anyOf": {"$ref": "#/definitions/schemaArray"}, "oneOf": {"$ref": "#/definitions/schemaArray"}, "not": {"$ref": "#"} }, "default": true } { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#", "title": "Meta-schema for the security assessment of JSON Schemas", "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$ref": "#"} } }, "dependencies": { "patternProperties": { "description": "prevent slow validation of large property names", "required": ["propertyNames"], "properties": { "propertyNames": { "required": ["maxLength"] } } }, "uniqueItems": { "description": "prevent slow validation of large non-scalar arrays", "if": { "properties": { "uniqueItems": {"const": true}, "items": { "properties": { "type": { "anyOf": [ { "enum": ["object", "array"] }, { "type": "array", "contains": {"enum": ["object", "array"]} } ] } } } } }, "then": { "required": ["maxItems"] } }, "pattern": { "description": "prevent slow pattern matching of large strings", "required": ["maxLength"] }, "format": { "description": "prevent slow format validation of large strings", "required": ["maxLength"] } }, "properties": { "additionalItems": {"$ref": "#"}, "additionalProperties": {"$ref": "#"}, "dependencies": { "additionalProperties": { "anyOf": [{"type": "array"}, {"$ref": "#"}] } }, "items": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}] }, "definitions": { "additionalProperties": {"$ref": "#"} }, "patternProperties": { "additionalProperties": {"$ref": "#"} }, "properties": { "additionalProperties": {"$ref": "#"} }, "if": {"$ref": "#"}, "then": {"$ref": "#"}, "else": {"$ref": "#"}, "allOf": {"$ref": "#/definitions/schemaArray"}, "anyOf": {"$ref": "#/definitions/schemaArray"}, "oneOf": {"$ref": "#/definitions/schemaArray"}, "not": {"$ref": "#"}, "contains": {"$ref": "#"}, "propertyNames": {"$ref": "#"} } } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const shared = (root) => { const sch = { nullable: { type: "boolean" }, metadata: { optionalProperties: { union: { elements: { ref: "schema" } }, }, additionalProperties: true, }, }; if (root) sch.definitions = { values: { ref: "schema" } }; return sch; }; const emptyForm = (root) => ({ optionalProperties: shared(root), }); const refForm = (root) => ({ properties: { ref: { type: "string" }, }, optionalProperties: shared(root), }); const typeForm = (root) => ({ properties: { type: { enum: [ "boolean", "timestamp", "string", "float32", "float64", "int8", "uint8", "int16", "uint16", "int32", "uint32", ], }, }, optionalProperties: shared(root), }); const enumForm = (root) => ({ properties: { enum: { elements: { type: "string" } }, }, optionalProperties: shared(root), }); const elementsForm = (root) => ({ properties: { elements: { ref: "schema" }, }, optionalProperties: shared(root), }); const propertiesForm = (root) => ({ properties: { properties: { values: { ref: "schema" } }, }, optionalProperties: { optionalProperties: { values: { ref: "schema" } }, additionalProperties: { type: "boolean" }, ...shared(root), }, }); const optionalPropertiesForm = (root) => ({ properties: { optionalProperties: { values: { ref: "schema" } }, }, optionalProperties: { additionalProperties: { type: "boolean" }, ...shared(root), }, }); const discriminatorForm = (root) => ({ properties: { discriminator: { type: "string" }, mapping: { values: { metadata: { union: [propertiesForm(false), optionalPropertiesForm(false)], }, }, }, }, optionalProperties: shared(root), }); const valuesForm = (root) => ({ properties: { values: { ref: "schema" }, }, optionalProperties: shared(root), }); const schema = (root) => ({ metadata: { union: [ emptyForm, refForm, typeForm, enumForm, elementsForm, propertiesForm, optionalPropertiesForm, discriminatorForm, valuesForm, ].map((s) => s(root)), }, }); const jtdMetaSchema = { definitions: { schema: schema(false), }, ...schema(true), }; exports.default = jtdMetaSchema; //# sourceMappingURL=jtd-schema.js.map{"version":3,"file":"jtd-schema.js","sourceRoot":"","sources":["../../lib/refs/jtd-schema.ts"],"names":[],"mappings":";;AAIA,MAAM,MAAM,GAAe,CAAC,IAAI,EAAE,EAAE;IAClC,MAAM,GAAG,GAAiB;QACxB,QAAQ,EAAE,EAAC,IAAI,EAAE,SAAS,EAAC;QAC3B,QAAQ,EAAE;YACR,kBAAkB,EAAE;gBAClB,KAAK,EAAE,EAAC,QAAQ,EAAE,EAAC,GAAG,EAAE,QAAQ,EAAC,EAAC;aACnC;YACD,oBAAoB,EAAE,IAAI;SAC3B;KACF,CAAA;IACD,IAAI,IAAI;QAAE,GAAG,CAAC,WAAW,GAAG,EA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L,SAAS;YACT,OAAO;YACP,QAAQ;YACR,QAAQ;YACR,YAAY;YACZ,cAAc;YACd,sBAAsB;YACtB,iBAAiB;YACjB,UAAU;SACX,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;KACtB;CACF,CAAC,CAAA;AAEF,MAAM,aAAa,GAAiB;IAClC,WAAW,EAAE;QACX,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC;KACtB;IACD,GAAG,MAAM,CAAC,IAAI,CAAC;CAChB,CAAA;AAED,kBAAe,aAAa,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // https://github.com/ajv-validator/ajv/issues/889 const equal = require("fast-deep-equal"); equal.code = 'require("ajv/dist/runtime/equal").default'; exports.default = equal; //# sourceMappingURL=equal.js.map{"version":3,"file":"equal.js","sourceRoot":"","sources":["../../lib/runtime/equal.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAClD,yCAAwC;AAGtC,KAAe,CAAC,IAAI,GAAG,2CAA2C,CAAA;AAEpE,kBAAe,KAAc,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0; const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/; function parseJson(s, pos) { let endPos; parseJson.message = undefined; let matches; if (pos) s = s.slice(pos); try { parseJson.position = pos + s.length; return JSON.parse(s); } catch (e) { matches = rxParseJson.exec(e.message); if (!matches) { parseJson.message = "unexpected end"; return undefined; } endPos = +matches[1]; const c = s[endPos]; s = s.slice(0, endPos); parseJson.position = pos + endPos; try { return JSON.parse(s); } catch (e1) { parseJson.message = `unexpected token ${c}`; return undefined; } } } exports.parseJson = parseJson; parseJson.message = undefined; parseJson.position = 0; parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson'; function parseJsonNumber(s, pos, maxDigits) { let numStr = ""; let c; parseJsonNumber.message = undefined; if (s[pos] === "-") { numStr += "-"; pos++; } if (s[pos] === "0") { numStr += "0"; pos++; } else { if (!parseDigits(maxDigits)) { errorMessage(); return undefined; } } if (maxDigits) { parseJsonNumber.position = pos; return +numStr; } if (s[pos] === ".") { numStr += "."; pos++; if (!parseDigits()) { errorMessage(); return undefined; } } if (((c = s[pos]), c === "e" || c === "E")) { numStr += "e"; pos++; if (((c = s[pos]), c === "+" || c === "-")) { numStr += c; pos++; } if (!parseDigits()) { errorMessage(); return undefined; } } parseJsonNumber.position = pos; return +numStr; function parseDigits(maxLen) { let digit = false; while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) { digit = true; numStr += c; pos++; } return digit; } function errorMessage() { parseJsonNumber.position = pos; parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end"; } } exports.parseJsonNumber = parseJsonNumber; parseJsonNumber.message = undefined; parseJsonNumber.position = 0; parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber'; const escapedChars = { b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", '"': '"', "/": "/", "\\": "\\", }; const CODE_A = "a".charCodeAt(0); const CODE_0 = "0".charCodeAt(0); function parseJsonString(s, pos) { let str = ""; let c; parseJsonString.message = undefined; // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition while (true) { c = s[pos++]; if (c === '"') break; if (c === "\\") { c = s[pos]; if (c in escapedChars) { str += escapedChars[c]; pos++; } else if (c === "u") { pos++; let count = 4; let code = 0; while (count--) { code <<= 4; c = s[pos]; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (c === undefined) { errorMessage("unexpected end"); return undefined; } c = c.toLowerCase(); if (c >= "a" && c <= "f") { code += c.charCodeAt(0) - CODE_A + 10; } else if (c >= "0" && c <= "9") { code += c.charCodeAt(0) - CODE_0; } else { errorMessage(`unexpected token ${c}`); return undefined; } pos++; } str += String.fromCharCode(code); } else { errorMessage(`unexpected token ${c}`); return undefined; } // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition } else if (c === undefined) { errorMessage("unexpected end"); return undefined; } else { if (c.charCodeAt(0) >= 0x20) { str += c; } else { errorMessage(`unexpected token ${c}`); return undefined; } } } parseJsonString.position = pos; return str; function errorMessage(msg) { parseJsonString.position = pos; parseJsonString.message = msg; } } exports.parseJsonString = parseJsonString; parseJsonString.message = undefined; parseJsonString.position = 0; parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString'; //# sourceMappingURL=parseJson.js.map{"version":3,"file":"parseJson.js","sourceRoot":"","sources":["../../lib/runtime/parseJson.ts"],"names":[],"mappings":";;;AAAA,MAAM,WAAW,GAAG,+CAA+C,CAAA;AAEnE,SAAgB,SAAS,CAAC,CAAS,EAAE,GAAW;IAC9C,IAAI,MAA0B,CAAA;IAC9B,SAAS,CAAC,OAAO,GAAG,SAAS,CAAA;IAC7B,IAAI,OAA+B,CAAA;IACnC,IAAI,GAAG;QAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACzB,IAAI,CAAC;QACH,SAAS,CAAC,QAAQ,GAAG,GAAG,GAAG,CAAC,CAAC,MAAM,CAAA;QACnC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACtB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,GAAG,WAAW,CAAC,IAAI,CAAE,CAAW,CAAC,OAAO,CAAC,CAAA;QAChD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAA;YACpC,OAAO,SAAS,CAAA;QAClB,CAAC;QACD,MAAM,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;QACpB,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAA;QACnB,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;QACtB,SAAS,CAAC,QAAQ,GAAG,GAAG,GAAG,MAAM,C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CAAC,QAAQ,GAAG,GAAG,CAAA;IAC9B,OAAO,GAAG,CAAA;IAEV,SAAS,YAAY,CAAC,GAAW;QAC/B,eAAe,CAAC,QAAQ,GAAG,GAAG,CAAA;QAC9B,eAAe,CAAC,OAAO,GAAG,GAAG,CAAA;IAC/B,CAAC;AACH,CAAC;AA7DD,0CA6DC;AAED,eAAe,CAAC,OAAO,GAAG,SAA+B,CAAA;AACzD,eAAe,CAAC,QAAQ,GAAG,CAAW,CAAA;AACtC,eAAe,CAAC,IAAI,GAAG,uDAAuD,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const rxEscapable = // eslint-disable-next-line no-control-regex, no-misleading-character-class /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; const escaped = { "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\", }; function quote(s) { rxEscapable.lastIndex = 0; return ('"' + (rxEscapable.test(s) ? s.replace(rxEscapable, (a) => { const c = escaped[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) : s) + '"'); } exports.default = quote; quote.code = 'require("ajv/dist/runtime/quote").default'; //# sourceMappingURL=quote.js.map{"version":3,"file":"quote.js","sourceRoot":"","sources":["../../lib/runtime/quote.ts"],"names":[],"mappings":";;AAAA,MAAM,WAAW;AACf,2EAA2E;AAC3E,iIAAiI,CAAA;AAEnI,MAAM,OAAO,GAA6B;IACxC,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,GAAG,EAAE,KAAK;IACV,IAAI,EAAE,MAAM;CACb,CAAA;AAED,SAAwB,KAAK,CAAC,CAAS;IACrC,WAAW,CAAC,SAAS,GAAG,CAAC,CAAA;IACzB,OAAO,CACL,GAAG;QACH,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE;gBAC3B,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;gBACpB,OAAO,OAAO,CAAC,KAAK,QAAQ;oBAC1B,CAAC,CAAC,CAAC;oBACH,CAAC,CAAC,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC/D,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC,CAAC;QACN,GAAG,CACJ,CAAA;AACH,CAAC;AAdD,wBAcC;AAED,KAAK,CAAC,IAAI,GAAG,2CAA2C,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const re2 = require("re2"); re2.code = 'require("ajv/dist/runtime/re2").default'; exports.default = re2; //# sourceMappingURL=re2.js.map{"version":3,"file":"re2.js","sourceRoot":"","sources":["../../lib/runtime/re2.ts"],"names":[],"mappings":";;AAAA,2BAA0B;AAGxB,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const DT_SEPARATOR = /t|\s/i; const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i; const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function validTimestamp(str, allowDate) { // http://tools.ietf.org/html/rfc3339#section-5.6 const dt = str.split(DT_SEPARATOR); return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) || (allowDate && dt.length === 1 && validDate(dt[0]))); } exports.default = validTimestamp; function validDate(str) { const matches = DATE.exec(str); if (!matches) return false; const y = +matches[1]; const m = +matches[2]; const d = +matches[3]; return (m >= 1 && m <= 12 && d >= 1 && (d <= DAYS[m] || // leap year: https://tools.ietf.org/html/rfc3339#appendix-C (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)))); } function validTime(str) { const matches = TIME.exec(str); if (!matches) return false; const hr = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tzH = +(matches[4] || 0); const tzM = +(matches[5] || 0); return ((hr <= 23 && min <= 59 && sec <= 59) || // leap second (hr - tzH === 23 && min - tzM === 59 && sec === 60)); } validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'; //# sourceMappingURL=timestamp.js.map{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../../lib/runtime/timestamp.ts"],"names":[],"mappings":";;AAAA,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,IAAI,GAAG,4BAA4B,CAAA;AACzC,MAAM,IAAI,GAAG,gEAAgE,CAAA;AAC7E,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAA;AAEhE,SAAwB,cAAc,CAAC,GAAW,EAAE,SAAkB;IACpE,iDAAiD;IACjD,MAAM,EAAE,GAAa,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAA;IAC5C,OAAO,CACL,CAAC,EAAE,CAAC,MAAM,KAAK,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACzD,CAAC,SAAS,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CACn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AC,CAAA;IACtC,OAAO,CACL,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,CAAC;QACpC,cAAc;QACd,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,KAAK,EAAE,CAAC,CACpD,CAAA;AACH,CAAC;AAED,cAAc,CAAC,IAAI,GAAG,+CAA+C,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // https://mathiasbynens.be/notes/javascript-encoding // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 0xd800 && value <= 0xdbff && pos < len) { // high surrogate, and there is a next character value = str.charCodeAt(pos); if ((value & 0xfc00) === 0xdc00) pos++; // low surrogate } } return length; } exports.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; //# sourceMappingURL=ucs2length.js.map{"version":3,"file":"ucs2length.js","sourceRoot":"","sources":["../../lib/runtime/ucs2length.ts"],"names":[],"mappings":";;AAAA,qDAAqD;AACrD,iEAAiE;AACjE,SAAwB,UAAU,CAAC,GAAW;IAC5C,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAA;IACtB,IAAI,MAAM,GAAG,CAAC,CAAA;IACd,IAAI,GAAG,GAAG,CAAC,CAAA;IACX,IAAI,KAAa,CAAA;IACjB,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;QACjB,MAAM,EAAE,CAAA;QACR,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAA;QAC7B,IAAI,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;YACpD,gDAAgD;YAChD,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,MAAM;gBAAE,GAAG,EAAE,CAAA,CAAC,gBAAgB;QACzD,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAfD,6BAeC;AAED,UAAU,CAAC,IAAI,GAAG,gDAAgD,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const uri = require("fast-uri"); uri.code = 'require("ajv/dist/runtime/uri").default'; exports.default = uri; //# sourceMappingURL=uri.js.map{"version":3,"file":"uri.js","sourceRoot":"","sources":["../../lib/runtime/uri.ts"],"names":[],"mappings":";;AAAA,gCAA+B;AAG7B,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class ValidationError extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } } exports.default = ValidationError; //# sourceMappingURL=validation_error.js.map{"version":3,"file":"validation_error.js","sourceRoot":"","sources":["../../lib/runtime/validation_error.ts"],"names":[],"mappings":";;AAEA,MAAqB,eAAgB,SAAQ,KAAK;IAKhD,YAAY,MAA8B;QACxC,KAAK,CAAC,mBAAmB,CAAC,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;IACnC,CAAC;CACF;AAVD,kCAUC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const scope_1 = require("../compile/codegen/scope"); const code_1 = require("../compile/codegen/code"); function standaloneCode(ajv, refsOrFunc) { if (!ajv.opts.code.source) { throw new Error("moduleCode: ajv instance must have code.source option"); } const { _n } = ajv.scope.opts; return typeof refsOrFunc == "function" ? funcExportCode(refsOrFunc.source) : refsOrFunc !== undefined ? multiExportsCode(refsOrFunc, getValidate) : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema)); function getValidate(id) { const v = ajv.getSchema(id); if (!v) throw new Error(`moduleCode: no schema with id ${id}`); return v; } function funcExportCode(source) { const usedValues = {}; const n = source === null || source === void 0 ? void 0 : source.validateName; const vCode = validateCode(usedValues, source); if (ajv.opts.code.esm) { // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`; } return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`; } function multiExportsCode(schemas, getValidateFunc) { var _a; const usedValues = {}; let code = (0, code_1._) `"use strict";`; for (const name in schemas) { const v = getValidateFunc(schemas[name]); if (v) { const vCode = validateCode(usedValues, v.source); const exportSyntax = ajv.opts.code.esm ? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}` : (0, code_1._) `exports${(0, code_1.getProperty)(name)}`; code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`; } } return `${code}`; } function validateCode(usedValues, s) { if (!s) throw new Error('moduleCode: function does not have "source" property'); if (usedState(s.validateName) === scope_1.UsedValueState.Completed) return code_1.nil; setUsedState(s.validateName, scope_1.UsedValueState.Started); const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode); const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`); return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code; function refValidateCode(n) { var _a; const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref; if (n.prefix === "validate" && typeof vRef == "function") { const v = vRef; return validateCode(usedValues, v.source); } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { const { validate, validateName } = vRef; if (!validateName) throw new Error("ajv internal error"); const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`; if (usedState(validateName) === scope_1.UsedValueState.Started) return wrapper; const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); return (0, code_1._) `${wrapper}${_n}${vCode}`; } return undefined; } function usedState(name) { var _a; return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name); } function setUsedState(name, state) { const { prefix } = name; const names = (usedValues[prefix] = usedValues[prefix] || new Map()); names.set(name, state); } } } module.exports = exports = standaloneCode; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = standaloneCode; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/standalone/index.ts"],"names":[],"mappings":";;AAGA,oDAAkG;AAClG,kDAA0F;AAE1F,SAAS,cAAc,CACrB,GAAY,EACZ,UAA2D;IAE3D,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;IAC1E,CAAC;IACD,MAAM,EAAC,EAAE,EAAC,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAA;IAC3B,OAAO,OAAO,UAAU,IAAI,UAAU;QACpC,CAAC,CAAC,cAAc,CAAC,UAAU,CAAC,MAAM,CAAC;QACnC,CAAC,CAAC,UAAU,KAAK,SAAS;YAC1B,CAAC,CAAC,gBAAgB,CAAS,UAAU,EAAE,WAAW,CAAC;YACnD,CAAC,CAAC,gBAAgB,CAAY,GAAG,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAC/C,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAC/C,CAAA;IAEL,SAAS,WAAW,CAAC,EAAU;QAC7B,MAAM,CAAC,GAAG,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;QAC3B,IAAI,CAAC,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,EAAE,EAAE,C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AAC,OAAO,GAAG,OAAO,GAAG,cAAc,CAAA;AACzC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,cAAc,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const core_1 = require("../core"); const _1 = require("."); const requireFromString = require("require-from-string"); class AjvPack { constructor(ajv) { this.ajv = ajv; } validate(schemaKeyRef, data) { return core_1.default.prototype.validate.call(this, schemaKeyRef, data); } compile(schema, meta) { return this.getStandalone(this.ajv.compile(schema, meta)); } getSchema(keyRef) { const v = this.ajv.getSchema(keyRef); if (!v) return undefined; return this.getStandalone(v); } getStandalone(v) { return requireFromString((0, _1.default)(this.ajv, v)); } addSchema(...args) { this.ajv.addSchema.call(this.ajv, ...args); return this; } addKeyword(...args) { this.ajv.addKeyword.call(this.ajv, ...args); return this; } } exports.default = AjvPack; //# sourceMappingURL=instance.js.map{"version":3,"file":"instance.js","sourceRoot":"","sources":["../../lib/standalone/instance.ts"],"names":[],"mappings":";;AAAA,kCAAwE;AACxE,wBAA8B;AAC9B,yDAAwD;AAExD,MAAqB,OAAO;IAE1B,YAAqB,GAAQ;QAAR,QAAG,GAAH,GAAG,CAAK;IAAG,CAAC;IAEjC,QAAQ,CAAC,YAAgC,EAAE,IAAa;QACtD,OAAO,cAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,CAAA;IAC9D,CAAC;IAED,OAAO,CAAc,MAAiB,EAAE,IAAc;QACpD,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAI,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;IAC9D,CAAC;IAED,SAAS,CAAc,MAAc;QACnC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAI,MAAM,CAAC,CAAA;QACvC,IAAI,CAAC,CAAC;YAAE,OAAO,SAAS,CAAA;QACxB,OAAO,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;IAC9B,CAAC;IAEO,aAAa,CAAc,CAAyB;QAC1D,OAAO,iBAAiB,CAAC,IAAA,UAAc,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAA2B,CAAA;IACjF,CAAC;IAED,SAAS,CAAC,GAAG,IAAgD;QAC3D,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC1C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,UAAU,CAAC,GAAG,IAAiD;QAC7D,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC3C,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA/BD,0BA+BC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/types/index.ts"],"names":[],"mappings":""}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=json-schema.js.map{"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../lib/types/json-schema.ts"],"names":[],"mappings":""}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=jtd-schema.js.map{"version":3,"file":"jtd-schema.js","sourceRoot":"","sources":["../../lib/types/jtd-schema.ts"],"names":[],"mappings":""}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAdditionalItems = void 0; const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const error = { message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, }; const def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); }, }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._) `${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._) `${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports.validateAdditionalItems = validateAdditionalItems; exports.default = def; //# sourceMappingURL=additionalItems.js.map{"version":3,"file":"additionalItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalItems.ts"],"names":[],"mappings":";;;AAOA,mDAAuD;AACvD,6CAA2E;AAI3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,iBAA0B;IACnC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,MAAM,EAAE,aAAa;IACrB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,YAAY,EAAE,E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AAC,KAAK,CAAC,CAAA;IACf,CAAC;IAED,SAAS,aAAa,CAAC,KAAW;QAChC,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,KAAK,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE;YACzC,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,YAAY,EAAE,WAAI,CAAC,GAAG,EAAC,EAAE,KAAK,CAAC,CAAA;YACpE,IAAI,CAAC,EAAE,CAAC,SAAS;gBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;QAC1D,CAAC,CAAC,CAAA;IACJ,CAAC;AACH,CAAC;AAnBD,0DAmBC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const code_1 = require("../code"); const codegen_1 = require("../../compile/codegen"); const names_1 = require("../../compile/names"); const util_1 = require("../../compile/util"); const error = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`, }; const def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; /* istanbul ignore if */ if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { // TODO maybe an option instead of hard-coded 8? const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._) `delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str, }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false, }); } cxt.subschema(subschema, valid); } }, }; exports.default = def; //# sourceMappingURL=additionalProperties.js.map{"version":3,"file":"additionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalProperties.ts"],"names":[],"mappings":";;AAOA,kCAAsE;AACtE,mDAAiE;AACjE,+CAAmC;AAEnC,6CAA0E;AAQ1E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,qCAAqC;IAC9C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,wBAAwB,MAAM,CAAC,kBAAkB,GAAG;C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WAAI,CAAC,GAAG;aACvB,CAAA;YACD,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;gBACrB,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE;oBACvB,aAAa,EAAE,IAAI;oBACnB,YAAY,EAAE,KAAK;oBACnB,SAAS,EAAE,KAAK;iBACjB,CAAC,CAAA;YACJ,CAAC;YACD,GAAG,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;QACjC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_1 = require("../../compile/util"); const def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); }, }; exports.default = def; //# sourceMappingURL=allOf.js.map{"version":3,"file":"allOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/allOf.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,wBAAwB;QACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QACvE,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,MAAM,CAAC,OAAO,CAAC,CAAC,GAAc,EAAE,CAAS,EAAE,EAAE;YAC3C,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,GAAG,CAAC;gBAAE,OAAM;YACtC,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,EAAC,EAAE,KAAK,CAAC,CAAA;YACtE,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;YACb,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;QAC5B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const code_1 = require("../code"); const def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" }, }; exports.default = def; //# sourceMappingURL=anyOf.js.map{"version":3,"file":"anyOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/anyOf.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAIrC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const error = { message: ({ params: { min, max } }) => max === undefined ? (0, codegen_1.str) `must contain at least ${min} valid item(s)` : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`, }; const def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === undefined ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._) `${data}.length`); cxt.setParams({ min, max }); if (max === undefined && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== undefined && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._) `${len} >= ${min}`; if (max !== undefined) cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === undefined && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== undefined) gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true, }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._) `${count}++`); if (max === undefined) { gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true)); } } }, }; exports.default = def; //# sourceMappingURL=contains.js.map{"version":3,"file":"contains.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/contains.ts"],"names":[],"mappings":";;AAOA,mDAAkD;AAClD,6CAA2E;AAQ3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,EAAC,EAAE,E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E,CAAC,CAAA;YACtE,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;gBACpE,IAAI,GAAG,KAAK,CAAC;oBAAE,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;;oBACjC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,OAAO,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAA;YACnE,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const code_1 = require("../code"); exports.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}`, // TODO change to reference }; const def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); }, }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", "), }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports.validateSchemaDeps = validateSchemaDeps; exports.default = def; //# sourceMappingURL=dependencies.js.map{"version":3,"file":"dependencies.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependencies.ts"],"names":[],"mappings":";;;AAQA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAmG;AAmBtF,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAC,EAAC,EAAE,EAAE;QACjD,MAAM,YAAY,GAAG,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,YAAY,CAAA;QAChE,OAAO,IAAA,aAAG,EAAA,aAAa,YAAY,IAAI,IAAI,kBAAkB,QAAQ,aAAa,CAAA;IACpF,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,MAAM,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,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE,CAAC;QAC9B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,UAAU,CAAC,IAAI,CAAc,CAAC;YAAE,SAAQ;QAClE,GAAG,CAAC,EAAE,CACJ,IAAA,qBAAc,EAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,EACtD,GAAG,EAAE;YACH,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;YAChE,GAAG,CAAC,mBAAmB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACxC,CAAC,EACD,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,WAAW;SACvC,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;AACH,CAAC;AAfD,gDAeC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const dependencies_1 = require("./dependencies"); const def = { keyword: "dependentSchemas", type: "object", schemaType: "object", code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt), }; exports.default = def; //# sourceMappingURL=dependentSchemas.js.map{"version":3,"file":"dependentSchemas.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependentSchemas.ts"],"names":[],"mappings":";;AACA,iDAAiD;AAEjD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,iCAAkB,EAAC,GAAG,CAAC;CACvC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const error = { message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`, }; const def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === undefined && parentSchema.else === undefined) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false, }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._) `${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } }, }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema); } exports.default = def; //# sourceMappingURL=if.js.map{"version":3,"file":"if.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/if.ts"],"names":[],"mappings":";;AAQA,mDAAuD;AACvD,6CAAqE;AAIrE,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,eAAe,MAAM,CAAC,QAAQ,UAAU;IAClE,MAAM,EA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AAO,MAAM,KAAK,SAAS,IAAI,CAAC,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,CAAA;AAC/D,CAAC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const additionalItems_1 = require("./additionalItems"); const prefixItems_1 = require("./prefixItems"); const items_1 = require("./items"); const items2020_1 = require("./items2020"); const contains_1 = require("./contains"); const dependencies_1 = require("./dependencies"); const propertyNames_1 = require("./propertyNames"); const additionalProperties_1 = require("./additionalProperties"); const properties_1 = require("./properties"); const patternProperties_1 = require("./patternProperties"); const not_1 = require("./not"); const anyOf_1 = require("./anyOf"); const oneOf_1 = require("./oneOf"); const allOf_1 = require("./allOf"); const if_1 = require("./if"); const thenElse_1 = require("./thenElse"); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default, ]; // array if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports.default = getApplicator; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/index.ts"],"names":[],"mappings":";;AACA,uDAAuE;AACvE,+CAAuC;AACvC,mCAA2B;AAC3B,2CAAiD;AACjD,yCAAkD;AAClD,iDAA8D;AAC9D,mDAAiE;AACjE,iEAAsF;AACtF,6CAAqC;AACrC,2DAAmD;AACnD,+BAAiD;AACjD,mCAAyC;AACzC,mCAAyC;AACzC,mCAA2B;AAC3B,6BAA8C;AAC9C,yCAAiC;AAEjC,SAAwB,aAAa,CAAC,SAAS,GAAG,KAAK;IACrD,MAAM,UAAU,GAAG;QACjB,MAAM;QACN,aAAU;QACV,eAAK;QACL,eAAK;QACL,eAAK;QACL,YAAS;QACT,kBAAQ;QACR,SAAS;QACT,uBAAa;QACb,8BAAoB;QACpB,sBAAY;QACZ,oBAAU;QACV,2BAAiB;KAClB,CAAA;IACD,QAAQ;IACR,IAAI,SAAS;QAAE,UAAU,CAAC,IAAI,CAAC,qBAAW,EAAE,mBAAS,CAAC,CAAA;;QACjD,UAAU,CAAC,IAAI,CAAC,yBAAe,EAAE,eAAK,CAAC,CAAA;IAC5C,UAAU,CAAC,IAAI,CAAC,kBAAQ,CAAC,CAAA;IACzB,OAAO,UAAU,CAAA;AACnB,CAAC;AArBD,gCAqBC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateTuple = void 0; const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const code_1 = require("../code"); const def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); }, }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._) `${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i, }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports.validateTuple = validateTuple; exports.default = def; //# sourceMappingUR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M,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,SAAS,CAAC,CAAA;IAC/C,MAAM,CAAC,OAAO,CAAC,CAAC,GAAc,EAAE,CAAS,EAAE,EAAE;QAC3C,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,GAAG,CAAC;YAAE,OAAM;QACtC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,MAAM,CAAC,EAAE,EAAE,GAAG,EAAE,CAC5B,GAAG,CAAC,SAAS,CACX;YACE,OAAO;YACP,UAAU,EAAE,CAAC;YACb,QAAQ,EAAE,CAAC;SACZ,EACD,KAAK,CACN,CACF,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC,CAAC,CAAA;IAEF,SAAS,gBAAgB,CAAC,GAAoB;QAC5C,MAAM,EAAC,IAAI,EAAE,aAAa,EAAC,GAAG,EAAE,CAAA;QAChC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAA;QACvB,MAAM,SAAS,GAAG,CAAC,KAAK,GAAG,CAAC,QAAQ,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,UAAU,CAAC,KAAK,KAAK,CAAC,CAAA;QACzF,IAAI,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,EAAE,CAAC;YACpC,MAAM,GAAG,GAAG,IAAI,OAAO,QAAQ,CAAC,oCAAoC,UAAU,4CAA4C,aAAa,GAAG,CAAA;YAC1I,IAAA,sBAAe,EAAC,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,CAAA;QAC7C,CAAC;IACH,CAAC;AACH,CAAC;AApCD,sCAoCC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const code_1 = require("../code"); const additionalItems_1 = require("./additionalItems"); const error = { message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, }; const def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); }, }; exports.default = def; //# sourceMappingURL=items2020.js.map{"version":3,"file":"items2020.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/items2020.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAqC;AACrC,uDAAyD;AAIzD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,MAAM,EAAE,aAAa;IACrB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtC,MAAM,EAAC,WAAW,EAAC,GAAG,YAAY,CAAA;QAClC,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QACf,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,IAAI,WAAW;YAAE,IAAA,yCAAuB,EAAC,GAAG,EAAE,WAAW,CAAC,CAAA;;YACrD,GAAG,CAAC,EAAE,CAAC,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,CAAA;IACjC,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_1 = require("../../compile/util"); const def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false, }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" }, }; exports.default = def; //# sourceMappingURL=not.js.map{"version":3,"file":"not.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/not.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAIpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;YAClC,GAAG,CAAC,IAAI,EAAE,CAAA;YACV,OAAM;QACR,CAAC;QAED,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CACX;YACE,OAAO,EAAE,KAAK;YACd,aAAa,EAAE,IAAI;YACnB,YAAY,EAAE,KAAK;YACnB,SAAS,EAAE,KAAK;SACjB,EACD,KAAK,CACN,CAAA;QAED,GAAG,CAAC,UAAU,CACZ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EACjB,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CAAA;IACH,CAAC;IACD,KAAK,EAAE,EAAC,OAAO,EAAE,mBAAmB,EAAC;CACtC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const error = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`, }; const def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, it } = cxt; /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true, }, schValid); } if (i > 0) { gen .if((0, codegen_1._) `${schValid} && ${valid}`) .assign(valid, false) .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`) .else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } }, }; exports.default = def; //# sourceMappingURL=oneOf.js.map{"version":3,"file":"oneOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/oneOf.ts"],"names":[],"mappings":";;AAOA,mDAA6C;AAC7C,6CAAoD;AASpD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,wCAAwC;IACjD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,oBAAoB,MAAM,CAAC,O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AAC;qBAAM,CAAC;oBACN,MAAM,GAAG,GAAG,CAAC,SAAS,CACpB;wBACE,OAAO,EAAE,OAAO;wBAChB,UAAU,EAAE,CAAC;wBACb,aAAa,EAAE,IAAI;qBACpB,EACD,QAAQ,CACT,CAAA;gBACH,CAAC;gBAED,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;oBACV,GAAG;yBACA,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,QAAQ,OAAO,KAAK,EAAE,CAAC;yBAC9B,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC;yBACpB,MAAM,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC;yBACtC,IAAI,EAAE,CAAA;gBACX,CAAC;gBAED,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;oBACpB,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;oBACvB,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;oBACtB,IAAI,MAAM;wBAAE,GAAG,CAAC,cAAc,CAAC,MAAM,EAAE,cAAI,CAAC,CAAA;gBAC9C,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const code_1 = require("../code"); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const util_2 = require("../../compile/util"); const def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || (alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true))) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); // TODO var validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str, }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._) `${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) // or if all properties were evaluated (props === true) gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } }, }; exports.default = def; //# sourceMappingURL=patternProperties.js.map{"version":3,"file":"patternProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/patternProperties.ts"],"names":[],"mappings":";;AAEA,kCAAuD;AACvD,mDAAkD;AAClD,6CAAqE;AACrE,6CAA6D;AAG7D,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,mBAAmB;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,MAAM,EAAC,IAAI,EAAC,GAAG,EAAE,CAAA;QACjB,MAAM,QAAQ,GAAG,IAAA,0BAAmB,EAAC,MAAM,C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AAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;oBACvC,CAAC;gBACH,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const items_1 = require("./items"); const def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items"), }; exports.default = def; //# sourceMappingURL=prefixItems.js.map{"version":3,"file":"prefixItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/prefixItems.ts"],"names":[],"mappings":";;AACA,mCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,OAAO,CAAC;IACrB,MAAM,EAAE,aAAa;IACrB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,qBAAa,EAAC,GAAG,EAAE,OAAO,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const validate_1 = require("../../compile/validate"); const code_1 = require("../code"); const util_1 = require("../../compile/util"); const additionalProperties_1 = require("./additionalProperties"); const def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop, }, valid); } }, }; exports.default = def; //# sourceMappingURL=properties.js.map{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/properties.ts"],"names":[],"mappings":";;AACA,qDAAiD;AACjD,kCAA2D;AAC3D,6CAA4E;AAC5E,iEAA0C;AAE1C,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,IAAI,EAAE,CAAC,IAAI,CAAC,gBAAgB,KAAK,KAAK,IAAI,YAAY,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC1F,8BAAK,CAAC,IAAI,CAAC,IAAI,qBAAU,CAAC,EAAE,EAAE,8BAAK,EAAE,sBAAsB,CAAC,CAAC,CAAA;QAC/D,CAAC;QACD,MAAM,QAAQ,GAAG,IAAA,0BAAmB,EAAC,MAAM,CAAC,CAAA;QAC5C,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;YAC5B,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QAChC,CAAC;QACD,IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,QAAQ,CAAC,MAAM,IAAI,EAAE,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAChE,EAAE,CAAC,KA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AAmB,CAAC,IAAY;YACvC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,YAAY;gBACrB,UAAU,EAAE,IAAI;gBAChB,QAAQ,EAAE,IAAI;aACf,EACD,KAAK,CACN,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const error = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`, }; const def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true, }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); }, }; exports.default = def; //# sourceMappingURL=propertyNames.js.map{"version":3,"file":"propertyNames.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/propertyNames.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AAIpD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,6BAA6B;IACtC,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,kBAAkB,MAAM,CAAC,YAAY,GAAG;CAChE,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAE/B,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;YAC7B,GAAG,CAAC,SAAS,CAAC,EAAC,YAAY,EAAE,GAAG,EAAC,CAAC,CAAA;YAClC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,eAAe;gBACxB,IAAI,EAAE,GAAG;gBACT,SAAS,EAAE,CAAC,QAAQ,CAAC;gBACrB,YAAY,EAAE,GAAG;gBACjB,aAAa,EAAE,IAAI;aACpB,EACD,KAAK,CACN,CAAA;YACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE;gBACtB,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBACf,IAAI,CAAC,EAAE,CAAC,SAAS;oBAAE,GAAG,CAAC,KAAK,EAAE,CAAA;YAChC,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_1 = require("../../compile/util"); const def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === undefined) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); }, }; exports.default = def; //# sourceMappingURL=thenElse.js.map{"version":3,"file":"thenElse.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/thenElse.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,EAAE,KAAK,SAAS;YAAE,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,2BAA2B,CAAC,CAAA;IAChG,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; const codegen_1 = require("../compile/codegen"); const util_1 = require("../compile/util"); const names_1 = require("../compile/names"); const util_2 = require("../compile/util"); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true); cxt.error(); }); } exports.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`))); } exports.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._) `Object.prototype.hasOwnProperty`, }); } exports.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`; } exports.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } exports.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData], ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`; } exports.callValidateCode = callValidateCode; const newRegExp = (0, codegen_1._) `new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`, }); } exports.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._) `${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num, }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it } = cxt; /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true, }, schValid); gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) // or if all properties and items were evaluated (it.props === true && it.items === true) if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports.validateUnion = validateUnion; //# sourceMappingURL=code.js.map{"version":3,"file":"code.js","sourceRoot":"","sources":["../../lib/vocabularies/code.ts"],"names":[],"mappings":";;;AAGA,gDAAoG;AACpG,0CAAuD;AACvD,4CAAgC;AAChC,0CAAuC;AACvC,SAAgB,sBAAsB,CAAC,GAAe,EAAE,IAAY;IAClE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC3B,GAAG,CAAC,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE;QACpE,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,IAAA,WAAC,E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AAE,IAAA,WAAC,EAAA,GAAG,KAAK,OAAO,QAAQ,EAAE,CAAC,CAAA;QAC7C,MAAM,MAAM,GAAG,GAAG,CAAC,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACxD,+FAA+F;QAC/F,yFAAyF;QACzF,IAAI,CAAC,MAAM;YAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,CAAC,CAAA;IACjC,CAAC,CAAC,CACH,CAAA;IAED,GAAG,CAAC,MAAM,CACR,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EACjB,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CACtB,CAAA;AACH,CAAC;AAjCD,sCAiCC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); }, }; exports.default = def; //# sourceMappingURL=id.js.map{"version":3,"file":"id.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/id.ts"],"names":[],"mappings":";;AAEA,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,IAAI;IACb,IAAI;QACF,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const id_1 = require("./id"); const ref_1 = require("./ref"); const core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default, ]; exports.default = core; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/index.ts"],"names":[],"mappings":";;AACA,6BAA4B;AAC5B,+BAA8B;AAE9B,MAAM,IAAI,GAAe;IACvB,SAAS;IACT,KAAK;IACL,OAAO;IACP,aAAa;IACb,EAAC,OAAO,EAAE,UAAU,EAAC;IACrB,aAAa;IACb,YAAS;IACT,aAAU;CACX,CAAA;AAED,kBAAe,IAAI,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.callRef = exports.getValidate = void 0; const ref_error_1 = require("../../compile/ref_error"); const code_1 = require("../code"); const codegen_1 = require("../../compile/codegen"); const names_1 = require("../../compile/names"); const compile_1 = require("../../compile"); const util_1 = require("../../compile/util"); const def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === undefined) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref, }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } }, }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._) `${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a; if (!it.opts.unevaluated) return; const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; // TODO refactor if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== undefined) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== undefined) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } exports.callRef = callRef; exports.default = def; //# sourceMappingURL=ref.js.map{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/ref.ts"],"names":[],"mappings":";;;AAEA,uDAAqD;AACrD,kCAAwC;AACxC,mDAAmE;AACnE,+CAAm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,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,MAAM,kBAAkB,CAAC,CAAA;gBAC5D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,cAAI,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;QACD,IAAI,EAAE,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACtB,IAAI,YAAY,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,CAAC;gBAC/C,IAAI,YAAY,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;oBACrC,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;gBACpE,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,MAAM,kBAAkB,CAAC,CAAA;gBAC5D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,cAAI,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAhED,0BAgEC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const types_1 = require("../discriminator/types"); const compile_1 = require("../../compile"); const ref_error_1 = require("../../compile/ref_error"); const util_1 = require("../../compile/util"); const error = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, }; const def = { keyword: "discriminator", type: "object", schemaType: "object", error, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === undefined) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required }) { return Array.isArray(required) && required.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } }, }; exports.default = def; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/discriminator/index.ts"],"names":[],"mappings":";;AAEA,mDAA0D;AAC1D,kDAAgE;AAChE,2CAAmD;AACnD,uDAAqD;AACrD,6CAAuD;AAIvD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAE,OAAO,EAAC,EAAC,EAAE,EAAE,CAC3C,UAAU,KAAK,kBAAU,CAAC,GAAG;QAC3B,CAAC,CAAC,QAAQ,OAAO,kBAAkB;QACnC,CAAC,CAAC,iBAAiB,OAAO,oBAAoB;IAClD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAE,GAAG,EAAE,OAAO,EAAC,EAAC,EAAE,EAAE,CAC/C,IAAA,WAAC,EAAA,WAAW,UAAU,UAAU,OAAO,eAAe,GAAG,GAAG;CAC/D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,MAAM,EAAC,KAAK,EAAC,GAAG,YAAY,CAAA;QAC5B,IAAI,CAAC,EA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,KAAK,CAAC,8BAA8B,OAAO,+BAA+B,CAAC,CAAA;gBACvF,CAAC;YACH,CAAC;YAED,SAAS,UAAU,CAAC,QAAiB,EAAE,CAAS;gBAC9C,IAAI,OAAO,QAAQ,IAAI,QAAQ,IAAI,QAAQ,IAAI,YAAY,EAAE,CAAC;oBAC5D,MAAM,IAAI,KAAK,CAAC,mBAAmB,OAAO,iCAAiC,CAAC,CAAA;gBAC9E,CAAC;gBACD,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DiscrError = void 0; var DiscrError; (function (DiscrError) { DiscrError["Tag"] = "tag"; DiscrError["Mapping"] = "mapping"; })(DiscrError || (exports.DiscrError = DiscrError = {})); //# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/vocabularies/discriminator/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,yBAAW,CAAA;IACX,iCAAmB,CAAA;AACrB,CAAC,EAHW,UAAU,0BAAV,UAAU,QAGrB"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const core_1 = require("./core"); const validation_1 = require("./validation"); const applicator_1 = require("./applicator"); const dynamic_1 = require("./dynamic"); const next_1 = require("./next"); const unevaluated_1 = require("./unevaluated"); const format_1 = require("./format"); const metadata_1 = require("./metadata"); const draft2020Vocabularies = [ dynamic_1.default, core_1.default, validation_1.default, (0, applicator_1.default)(true), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary, next_1.default, unevaluated_1.default, ]; exports.default = draft2020Vocabularies; //# sourceMappingURL=draft2020.js.map{"version":3,"file":"draft2020.js","sourceRoot":"","sources":["../../lib/vocabularies/draft2020.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,uCAAyC;AACzC,iCAAmC;AACnC,+CAAiD;AACjD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,qBAAqB,GAAiB;IAC1C,iBAAiB;IACjB,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,EAAC,IAAI,CAAC;IAC7B,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;IACjB,cAAc;IACd,qBAAqB;CACtB,CAAA;AAED,kBAAe,qBAAqB,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const core_1 = require("./core"); const validation_1 = require("./validation"); const applicator_1 = require("./applicator"); const format_1 = require("./format"); const metadata_1 = require("./metadata"); const draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary, ]; exports.default = draft7Vocabularies; //# sourceMappingURL=draft7.js.map{"version":3,"file":"draft7.js","sourceRoot":"","sources":["../../lib/vocabularies/draft7.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,kBAAkB,GAAiB;IACvC,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,GAAE;IACzB,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;CAClB,CAAA;AAED,kBAAe,kBAAkB,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.dynamicAnchor = void 0; const codegen_1 = require("../../compile/codegen"); const names_1 = require("../../compile/names"); const compile_1 = require("../../compile"); const ref_1 = require("../core/ref"); const def = { keyword: "$dynamicAnchor", schemaType: "string", code: (cxt) => dynamicAnchor(cxt, cxt.schema), }; function dynamicAnchor(cxt, anchor) { const { gen, it } = cxt; it.schemaEnv.root.dynamicAnchors[anchor] = true; const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate)); } exports.dynamicAnchor = dynamicAnchor; function _getValidate(cxt) { const { schemaEnv, schema, self } = cxt.it; const { root, baseId, localRefs, meta } = schemaEnv.root; const { schemaId } = self.opts; const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta }); compile_1.compileSchema.call(self, sch); return (0, ref_1.getValidate)(cxt, sch); } exports.default = def; //# sourceMappingURL=dynamicAnchor.js.map{"version":3,"file":"dynamicAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicAnchor.ts"],"names":[],"mappings":";;;AAEA,mDAA0D;AAC1D,+CAAmC;AACnC,2CAAsD;AACtD,qCAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,gBAAgB;IACzB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC9C,CAAA;AAED,SAAgB,aAAa,CAAC,GAAe,EAAE,MAAc;IAC3D,MAAM,EAAC,GAAG,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IACrB,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;IAC/C,MAAM,CAAC,GAAG,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,cAAc,GAAG,IAAA,qBAAW,EAAC,MAAM,CAAC,EAAE,CAAA;IACtD,MAAM,QAAQ,GAAG,EAAE,CAAC,aAAa,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;IAC/E,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAA;AACjD,CAAC;AAND,sCAMC;AAED,SAAS,YAAY,CAAC,GAAe;IACnC,MAAM,EAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAC,EAAE,CAAA;IACxC,MAAM,EAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,GAAG,SAAS,CAAC,IAAI,CAAA;IACtD,MAAM,EAAC,QAAQ,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IAC5B,MAAM,GAAG,GAAG,IAAI,mBAAS,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,CAAC,CAAA;IAC5E,uBAAa,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC7B,OAAO,IAAA,iBAAW,EAAC,GAAG,EAAE,GAAG,CAAC,CAAA;AAC9B,CAAC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.dynamicRef = void 0; const codegen_1 = require("../../compile/codegen"); const names_1 = require("../../compile/names"); const ref_1 = require("../core/ref"); const def = { keyword: "$dynamicRef", schemaType: "string", code: (cxt) => dynamicRef(cxt, cxt.schema), }; function dynamicRef(cxt, ref) { const { gen, keyword, it } = cxt; if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); const anchor = ref.slice(1); if (it.allErrors) { _dynamicRef(); } else { const valid = gen.let("valid", false); _dynamicRef(valid); cxt.ok(valid); } function _dynamicRef(valid) { // TODO the assumption here is that `recursiveRef: #` always points to the root // of the schema object, which is not correct, because there may be $id that // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. // Because of that 2 tests in recursiveRef.json fail. // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). // (This problem is not tested in JSON-Schema-Test-Suite) if (it.schemaEnv.root.dynamicAnchors[anchor]) { const v = gen.let("_v", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); } else { _callRef(it.validateName, valid)(); } } function _callRef(validate, valid) { return valid ? () => gen.block(() => { (0, ref_1.callRef)(cxt, validate); gen.let(valid, true); }) : () => (0, ref_1.callRef)(cxt, validate); } } exports.dynamicRef = dynamicRef; exports.default = def; //# sourceMappingURL=dynamicRef.js.map{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicRef.ts"],"names":[],"mappings":";;;AAEA,mDAAgE;AAChE,+CAAmC;AACnC,qCAAmC;AAEnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC3C,CAAA;AAED,SAAgB,UAAU,CAAC,GAAe,EAAE,GAAW;IACrD,MAAM,EAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC9B,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,IAAI,OAAO,yCAAyC,CAAC,CAAA;IACzF,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC3B,IAAI,EAAE,CAAC,SAAS,EAAE,CAAC;QACjB,WAAW,EAAE,CAAA;IACf,CAAC;SAAM,CAAC;QACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;QACrC,WAAW,CAAC,KAAK,CAAC,CAAA;QAClB,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;IAED,SAAS,WAAW,CAAC,KAAY;QAC/B,+EAA+E;QAC/E,4EAA4E;QAC5E,sFAAsF;QACtF,qDAAqD;QACrD,kGAAkG;QAClG,yDAAyD;QACzD,IAAI,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC;YAC7C,MAAM,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,cAAc,GAAG,IAAA,qBAAW,EAAC,MAAM,CAAC,EAAE,CAAC,CAAA;YACrE,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC,CAAA;QACjE,CAAC;aAAM,CAAC;YACN,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,EAAE,CAAA;QACpC,CAAC;IACH,CAAC;IAED,SAAS,QAAQ,CAAC,QAAc,EAAE,KAAY;QAC5C,OAAO,KAAK;YACV,CAAC,CAAC,GAAG,EAAE,CACH,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE;gBACb,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;gBACtB,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACtB,CAAC,CAAC;YACN,CAAC,CAAC,GAAG,EAAE,CAAC,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IAClC,CAAC;AACH,CAAC;AApCD,gCAoCC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const dynamicAnchor_1 = require("./dynamicAnchor"); const dynamicRef_1 = require("./dynamicRef"); const recursiveAnchor_1 = require("./recursiveAnchor"); const recursiveRef_1 = require("./recursiveRef"); const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default]; exports.default = dynamic; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/index.ts"],"names":[],"mappings":";;AACA,mDAA2C;AAC3C,6CAAqC;AACrC,uDAA+C;AAC/C,iDAAyC;AAEzC,MAAM,OAAO,GAAe,CAAC,uBAAa,EAAE,oBAAU,EAAE,yBAAe,EAAE,sBAAY,CAAC,CAAA;AAEtF,kBAAe,OAAO,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const dynamicAnchor_1 = require("./dynamicAnchor"); const util_1 = require("../../compile/util"); const def = { keyword: "$recursiveAnchor", schemaType: "boolean", code(cxt) { if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); }, }; exports.default = def; //# sourceMappingURL=recursiveAnchor.js.map{"version":3,"file":"recursiveAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveAnchor.ts"],"names":[],"mappings":";;AACA,mDAA6C;AAC7C,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,UAAU,EAAE,SAAS;IACrB,IAAI,CAAC,GAAG;QACN,IAAI,GAAG,CAAC,MAAM;YAAE,IAAA,6BAAa,EAAC,GAAG,EAAE,EAAE,CAAC,CAAA;;YACjC,IAAA,sBAAe,EAAC,GAAG,CAAC,EAAE,EAAE,oCAAoC,CAAC,CAAA;IACpE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const dynamicRef_1 = require("./dynamicRef"); const def = { keyword: "$recursiveRef", schemaType: "string", code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema), }; exports.default = def; //# sourceMappingURL=recursiveRef.js.map{"version":3,"file":"recursiveRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveRef.ts"],"names":[],"mappings":";;AACA,6CAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,uBAAU,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=errors.js.map{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/vocabularies/errors.ts"],"names":[],"mappings":""}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const error = { message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`, }; const def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats, }); const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); // TODO simplify gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._) `${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._) `${format}(${data})`; const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : undefined; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._) `await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`; } } }, }; exports.default = def; //# sourceMappingURL=format.js.map{"version":3,"file":"format.js","sourceRoot":"","sources":["../../../lib/vocabularies/format/format.ts"],"names":[],"mappings":";;AASA,mDAAoF;AAapF,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,sBAAsB,UAAU,GAAG;IACjE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,YAAY,UAAU,GAAG;CACrD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,QAAQ;IACjB,IAAI,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC1B,UAAU,EAAE,QAAQ;IACpB,KAAK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IAAA,WAAC,EAAA,SAAS,MAAM,IAAI,IAAI,GAAG,CAAA;gBACpC,CAAC;gBACD,OAAO,OAAO,MAAM,IAAI,UAAU,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,SAAS,IAAI,GAAG,CAAA;YACzF,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const format_1 = require("./format"); const format = [format_1.default]; exports.default = format; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/format/index.ts"],"names":[],"mappings":";;AACA,qCAAoC;AAEpC,MAAM,MAAM,GAAe,CAAC,gBAAa,CAAC,CAAA;AAE1C,kBAAe,MAAM,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const metadata_1 = require("./metadata"); const nullable_1 = require("./nullable"); const error_1 = require("./error"); const types_1 = require("../discriminator/types"); const error = { message: (cxt) => { const { schema, params } = cxt; return params.discrError ? params.discrError === types_1.DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : (0, error_1.typeErrorMessage)(cxt, "object"); }, params: (cxt) => { const { schema, params } = cxt; return params.discrError ? (0, codegen_1._) `{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` : (0, error_1.typeErrorParams)(cxt, "object"); }, }; const def = { keyword: "discriminator", schemaType: "string", implements: ["mapping"], error, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, parentSchema } = cxt; const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); gen.if(cond); validateDiscriminator(); gen.elseIf((0, codegen_1.not)(valid)); cxt.error(); gen.endIf(); cxt.ok(valid); function validateDiscriminator() { const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(schema)}`); gen.if((0, codegen_1._) `${tag} === undefined`); cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }); gen.elseIf((0, codegen_1._) `typeof ${tag} == "string"`); validateMapping(tag); gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema }); gen.endIf(); } function validateMapping(tag) { gen.if(false); for (const tagValue in parentSchema.mapping) { gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(tagValue)); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); cxt.subschema({ keyword: "mapping", schemaProp, jtdDiscriminator: schema, }, _valid); return _valid; } }, }; exports.default = def; //# sourceMappingURL=discriminator.js.map{"version":3,"file":"discriminator.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/discriminator.ts"],"names":[],"mappings":";;AAEA,mDAA+D;AAC/D,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAwE;AACxE,kDAAgE;AAOhE,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,MAAM,EAAC,MAAM,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAC5B,OAAO,MAAM,CAAC,UAAU;YACtB,CAAC,CAAC,MAAM,CAAC,UAAU,KAAK,kBAAU,CAAC,GAAG;gBACpC,CAAC,CAAC,QAAQ,MAAM,kBAAkB;gBAClC,CAAC,CAAC,iBAAiB,MAAM,sBAAsB;YACjD,CAAC,CAAC,IAAA,wBAAgB,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IACrC,CAAC;IACD,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE;QACd,MAAM,EAAC,MAAM,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAC5B,OAAO,MAAM,CAAC,UAAU;YACtB,CAAC,CAAC,IAAA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Ac,CAAC,CAAA;YACxC,eAAe,CAAC,GAAG,CAAC,CAAA;YACpB,GAAG,CAAC,IAAI,EAAE,CAAA;YACV,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,EAAC,UAAU,EAAE,kBAAU,CAAC,GAAG,EAAE,GAAG,EAAC,EAAE,EAAC,YAAY,EAAE,MAAM,EAAC,CAAC,CAAA;YAC3E,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC;QAED,SAAS,eAAe,CAAC,GAAS;YAChC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;YACb,KAAK,MAAM,QAAQ,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC;gBAC5C,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,QAAQ,EAAE,CAAC,CAAA;gBACrC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAA;YAC7C,CAAC;YACD,GAAG,CAAC,IAAI,EAAE,CAAA;YACV,GAAG,CAAC,KAAK,CACP,KAAK,EACL,EAAC,UAAU,EAAE,kBAAU,CAAC,OAAO,EAAE,GAAG,EAAC,EACrC,EAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAC,CAClE,CAAA;YACD,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC;QAED,SAAS,cAAc,CAAC,UAAkB;YACxC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAChC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,SAAS;gBAClB,UAAU;gBACV,gBAAgB,EAAE,MAAM;aACzB,EACD,MAAM,CACP,CAAA;YACD,OAAO,MAAM,CAAA;QACf,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_1 = require("../../compile/util"); const code_1 = require("../code"); const codegen_1 = require("../../compile/codegen"); const metadata_1 = require("./metadata"); const nullable_1 = require("./nullable"); const error_1 = require("./error"); const def = { keyword: "elements", schemaType: "object", error: (0, error_1.typeError)("array"), code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const [valid] = (0, nullable_1.checkNullable)(cxt); gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._) `Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error())); cxt.ok(valid); }, }; exports.default = def; //# sourceMappingURL=elements.js.map{"version":3,"file":"elements.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/elements.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AACpD,kCAAqC;AACrC,mDAA4C;AAC5C,yCAAwC;AACxC,yCAAwC;AACxC,mCAAgD;AAIhD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAA,iBAAS,EAAC,OAAO,CAAC;IACzB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CACtB,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,iBAAiB,IAAI,GAAG,EACzB,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,EAC3C,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CACF,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const metadata_1 = require("./metadata"); const nullable_1 = require("./nullable"); const error = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`, }; const def = { keyword: "enum", schemaType: "array", error, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, schemaValue, parentSchema, it } = cxt; if (schema.length === 0) throw new Error("enum must have non-empty array"); if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique"); let valid; const isString = (0, codegen_1._) `typeof ${data} == "string"`; if (schema.length >= it.opts.loopEnum) { let cond; [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString); gen.if(cond, loopEnum); } else { /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._) `${data} === ${value}`))); if (parentSchema.nullable) valid = (0, codegen_1.or)((0, codegen_1._) `${data} === null`, valid); } cxt.pass(valid); function loopEnum() { gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._) `${valid} = ${data} === ${v}`, () => gen.break())); } }, }; exports.default = def; //# sourceMappingURL=enum.js.map{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/enum.ts"],"names":[],"mappings":";;AAEA,mDAAsD;AACtD,yCAAwC;AACxC,yCAAwC;AAIxC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,4CAA4C;IACrD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,mBAAmB,UAAU,GAAG;CAC5D,CAAA;AAED,MAAM,GAAG,G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AAC,EAAA,GAAG,IAAI,WAAW,EAAE,KAAK,CAAC,CAAA;QACnE,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAEf,SAAS,QAAQ;YACf,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,WAAmB,EAAE,CAAC,CAAC,EAAE,EAAE,CACxC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,MAAM,IAAI,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAC1D,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0; const codegen_1 = require("../../compile/codegen"); function typeError(t) { return { message: (cxt) => typeErrorMessage(cxt, t), params: (cxt) => typeErrorParams(cxt, t), }; } exports.typeError = typeError; function typeErrorMessage({ parentSchema }, t) { return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`; } exports.typeErrorMessage = typeErrorMessage; function typeErrorParams({ parentSchema }, t) { return (0, codegen_1._) `{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`; } exports.typeErrorParams = typeErrorParams; //# sourceMappingURL=error.js.map{"version":3,"file":"error.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/error.ts"],"names":[],"mappings":";;;AACA,mDAA6C;AAQ7C,SAAgB,SAAS,CAAC,CAAS;IACjC,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,CAAC,CAAC;QAC1C,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC;KACzC,CAAA;AACH,CAAC;AALD,8BAKC;AAED,SAAgB,gBAAgB,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACzE,OAAO,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,EAAC,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAA;AACzE,CAAC;AAFD,4CAEC;AAED,SAAgB,eAAe,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACxE,OAAO,IAAA,WAAC,EAAA,UAAU,CAAC,eAAe,CAAC,CAAC,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,CAAA,GAAG,CAAA;AAC/D,CAAC;AAFD,0CAEC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ref_1 = require("./ref"); const type_1 = require("./type"); const enum_1 = require("./enum"); const elements_1 = require("./elements"); const properties_1 = require("./properties"); const optionalProperties_1 = require("./optionalProperties"); const discriminator_1 = require("./discriminator"); const values_1 = require("./values"); const union_1 = require("./union"); const metadata_1 = require("./metadata"); const jtdVocabulary = [ "definitions", ref_1.default, type_1.default, enum_1.default, elements_1.default, properties_1.default, optionalProperties_1.default, discriminator_1.default, values_1.default, union_1.default, metadata_1.default, { keyword: "additionalProperties", schemaType: "boolean" }, { keyword: "nullable", schemaType: "boolean" }, ]; exports.default = jtdVocabulary; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/index.ts"],"names":[],"mappings":";;AACA,+BAA8B;AAC9B,iCAAgD;AAChD,iCAAgD;AAChD,yCAAqD;AACrD,6CAA2D;AAC3D,6DAAqD;AACrD,mDAAoE;AACpE,qCAA+C;AAC/C,mCAA2B;AAC3B,yCAAiC;AAEjC,MAAM,aAAa,GAAe;IAChC,aAAa;IACb,aAAU;IACV,cAAW;IACX,cAAW;IACX,kBAAQ;IACR,oBAAU;IACV,4BAAkB;IAClB,uBAAa;IACb,gBAAM;IACN,eAAK;IACL,kBAAQ;IACR,EAAC,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,SAAS,EAAC;IACxD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;CAC7C,CAAA;AAED,kBAAe,aAAa,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkMetadata = void 0; const util_1 = require("../../compile/util"); const def = { keyword: "metadata", schemaType: "object", code(cxt) { checkMetadata(cxt); const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid); cxt.ok(valid); }, }; function checkMetadata({ it, keyword }, metadata) { if (it.jtdMetadata !== metadata) { throw new Error(`JTD: "${keyword}" cannot be used in this schema location`); } } exports.checkMetadata = checkMetadata; exports.default = def; //# sourceMappingURL=metadata.js.map{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/metadata.ts"],"names":[],"mappings":";;;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,aAAa,CAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;QAC9D,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,SAAgB,aAAa,CAAC,EAAC,EAAE,EAAE,OAAO,EAAa,EAAE,QAAkB;IACzE,IAAI,EAAE,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,SAAS,OAAO,0CAA0C,CAAC,CAAA;IAC7E,CAAC;AACH,CAAC;AAJD,sCAIC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkNullableObject = exports.checkNullable = void 0; const codegen_1 = require("../../compile/codegen"); function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) { const valid = gen.name("valid"); if (parentSchema.nullable) { gen.let(valid, (0, codegen_1._) `${data} === null`); cond = (0, codegen_1.not)(valid); } else { gen.let(valid, false); } return [valid, cond]; } exports.checkNullable = checkNullable; function checkNullableObject(cxt, cond) { const [valid, cond_] = checkNullable(cxt, cond); return [valid, (0, codegen_1._) `${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]; } exports.checkNullableObject = checkNullableObject; //# sourceMappingURL=nullable.js.map{"version":3,"file":"nullable.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/nullable.ts"],"names":[],"mappings":";;;AACA,mDAA6D;AAE7D,SAAgB,aAAa,CAC3B,EAAC,GAAG,EAAE,IAAI,EAAE,YAAY,EAAa,EACrC,OAAa,aAAG;IAEhB,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,CAAC,CAAA;QACnC,IAAI,GAAG,IAAA,aAAG,EAAC,KAAK,CAAC,CAAA;IACnB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;IACvB,CAAC;IACD,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAZD,sCAYC;AAED,SAAgB,mBAAmB,CAAC,GAAe,EAAE,IAAU;IAC7D,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAC/C,OAAO,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,KAAK,cAAc,GAAG,CAAC,IAAI,kCAAkC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAA;AAC9F,CAAC;AAHD,kDAGC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const properties_1 = require("./properties"); const def = { keyword: "optionalProperties", schemaType: "object", error: properties_1.error, code(cxt) { if (cxt.parentSchema.properties) return; (0, properties_1.validateProperties)(cxt); }, }; exports.default = def; //# sourceMappingURL=optionalProperties.js.map{"version":3,"file":"optionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/optionalProperties.ts"],"names":[],"mappings":";;AAEA,6CAAsD;AAEtD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,oBAAoB;IAC7B,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,kBAAK;IACL,IAAI,CAAC,GAAe;QAClB,IAAI,GAAG,CAAC,YAAY,CAAC,UAAU;YAAE,OAAM;QACvC,IAAA,+BAAkB,EAAC,GAAG,CAAC,CAAA;IACzB,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateProperties = exports.error = void 0; const code_1 = require("../code"); const util_1 = require("../../compile/util"); const codegen_1 = require("../../compile/codegen"); const metadata_1 = require("./metadata"); const nullable_1 = require("./nullable"); const error_1 = require("./error"); var PropError; (function (PropError) { PropError["Additional"] = "additional"; PropError["Missing"] = "missing"; })(PropError || (PropError = {})); exports.error = { message: (cxt) => { const { params } = cxt; return params.propError ? params.propError === PropError.Additional ? "must NOT have additional properties" : `must have property '${params.missingProperty}'` : (0, error_1.typeErrorMessage)(cxt, "object"); }, params: (cxt) => { const { params } = cxt; return params.propError ? params.propError === PropError.Additional ? (0, codegen_1._) `{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` : (0, codegen_1._) `{error: ${params.propError}, missingProperty: ${params.missingProperty}}` : (0, error_1.typeErrorParams)(cxt, "object"); }, }; const def = { keyword: "properties", schemaType: "object", error: exports.error, code: validateProperties, }; // const error: KeywordErrorDefinition = { // message: "should NOT have additional properties", // params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, // } function validateProperties(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, parentSchema, it } = cxt; const { additionalProperties, nullable } = parentSchema; if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping"); if (commonProperties()) { throw new Error("JTD: properties and optionalProperties have common members"); } const [allProps, properties] = schemaProperties("properties"); const [allOptProps, optProperties] = schemaProperties("optionalProperties"); if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { return; } const [valid, cond] = it.jtdDiscriminator === undefined ? (0, nullable_1.checkNullableObject)(cxt, data) : [gen.let("valid", false), true]; gen.if(cond, () => gen.assign(valid, true).block(() => { validateProps(properties, "properties", true); validateProps(optProperties, "optionalProperties"); if (!additionalProperties) validateAdditional(); })); cxt.pass(valid); function commonProperties() { const props = parentSchema.properties; const optProps = parentSchema.optionalProperties; if (!(props && optProps)) return false; for (const p in props) { if (Object.prototype.hasOwnProperty.call(optProps, p)) return true; } return false; } function schemaProperties(keyword) { const schema = parentSchema[keyword]; const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : []; if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { throw new Error(`JTD: discriminator tag used in ${keyword}`); } const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); return [allPs, ps]; } function validateProps(props, keyword, required) { const _valid = gen.var("valid"); for (const prop of props) { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop)); cxt.ok(_valid); } function missingProperty(prop) { if (required) { gen.assign(_valid, false); cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop }); } else { gen.assign(_valid, true); } } } function applyPropertySchema(prop, keyword, _valid) { cxt.subschema({ keyword, schemaProp: prop, dataProp: prop, }, _valid); } function validateAdditional() { gen.forIn("key", data, (key) => { const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator); const addOptProp = isAdditional(key, allOptProps, "optionalProperties"); const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp); gen.if(extra, () => { if (it.opts.removeAdditional) { gen.code((0, codegen_1._) `delete ${data}[${key}]`); } else { cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true }); if (!it.opts.allErrors) gen.break(); } }); }); } function isAdditional(key, props, keyword, jtdDiscriminator) { let additional; if (props.length > 8) { // TODO maybe an option instead of hard-coded 8? const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword); additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key)); if (jtdDiscriminator !== undefined) { additional = (0, codegen_1.and)(additional, (0, codegen_1._) `${key} !== ${jtdDiscriminator}`); } } else if (props.length || jtdDiscriminator !== undefined) { const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props); additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)); } else { additional = true; } return additional; } } exports.validateProperties = validateProperties; exports.default = def; //# sourceMappingURL=properties.js.map{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/properties.ts"],"names":[],"mappings":";;;AAOA,kCAA0E;AAC1E,6CAAoE;AACpE,mDAA6D;AAC7D,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAwE;AAExE,IAAK,SAGJ;AAHD,WAAK,SAAS;IACZ,sCAAyB,CAAA;IACzB,gCAAmB,CAAA;AACrB,CAAC,EAHI,SAAS,KAAT,SAAS,QAGb;AAWY,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE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AC,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACpF,UAAU,GAAG,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAA;QACxD,CAAC;aAAM,CAAC;YACN,UAAU,GAAG,IAAI,CAAA;QACnB,CAAC;QACD,OAAO,UAAU,CAAA;IACnB,CAAC;AACH,CAAC;AA1HD,gDA0HC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hasRef = void 0; const compile_1 = require("../../compile"); const codegen_1 = require("../../compile/codegen"); const ref_error_1 = require("../../compile/ref_error"); const names_1 = require("../../compile/names"); const ref_1 = require("../core/ref"); const metadata_1 = require("./metadata"); const def = { keyword: "ref", schemaType: "string", code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema: ref, parentSchema, it } = cxt; const { schemaEnv: { root }, } = it; const valid = gen.name("valid"); if (parentSchema.nullable) { gen.var(valid, (0, codegen_1._) `${data} === null`); gen.if((0, codegen_1.not)(valid), validateJtdRef); } else { gen.var(valid, false); validateJtdRef(); } cxt.ok(valid); function validateJtdRef() { var _a; const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref]; if (!refSchema) { throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`); } if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema); else inlineRefSchema(refSchema); } function callValidate(schema) { const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` })); const v = (0, ref_1.getValidate)(cxt, sch); const errsCount = gen.const("_errs", names_1.default.errors); (0, ref_1.callRef)(cxt, v, sch, sch.$async); gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); } function inlineRefSchema(schema) { const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema }); cxt.subschema({ schema, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: `/definitions/${ref}`, }, valid); } }, }; function hasRef(schema) { for (const key in schema) { let sch; if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true; } return false; } exports.hasRef = hasRef; exports.default = def; //# sourceMappingURL=ref.js.map{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/ref.ts"],"names":[],"mappings":";;;AAEA,2CAAsD;AACtD,mDAA4D;AAC5D,uDAAqD;AACrD,+CAAmC;AACnC,qCAAgD;AAChD,yCAAwC;AAExC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,EACJ,SAAS,EAAE,EAAC,IAAI,EAAC,GAClB,GAAG,EAAE,CAAA;QACN,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;YAC1B,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,CAAC,CAAA;YACnC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,cAAc,CAAC,CAAA;QACpC,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;YACrB,cAAc,EAAE,CAAA;QAClB,CAAC;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QAE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,EAAE,IAAA,mBAAS,EAAC,MAAM,CAAC,EAAC,CAAC,CAAC,CAAC,EAAC,GAAG,EAAE,MAAM,EAAC,CACtF,CAAA;YACD,GAAG,CAAC,SAAS,CACX;gBACE,MAAM;gBACN,SAAS,EAAE,EAAE;gBACb,UAAU,EAAE,aAAG;gBACf,YAAY,EAAE,OAAO;gBACrB,aAAa,EAAE,gBAAgB,GAAG,EAAE;aACrC,EACD,KAAK,CACN,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,SAAgB,MAAM,CAAC,MAAuB;IAC5C,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,IAAI,GAAoB,CAAA;QACxB,IAAI,GAAG,KAAK,KAAK,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,QAAQ,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;YAAE,OAAO,IAAI,CAAA;IAC3F,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAND,wBAMC;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.intRange = void 0; const codegen_1 = require("../../compile/codegen"); const timestamp_1 = require("../../runtime/timestamp"); const util_1 = require("../../compile/util"); const metadata_1 = require("./metadata"); const error_1 = require("./error"); exports.intRange = { int8: [-128, 127, 3], uint8: [0, 255, 3], int16: [-32768, 32767, 5], uint16: [0, 65535, 5], int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10], }; const error = { message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema), }; function timestampCode(cxt) { const { gen, data, it } = cxt; const { timestamp, allowDate } = it.opts; if (timestamp === "date") return (0, codegen_1._) `${data} instanceof Date `; const vts = (0, util_1.useFunc)(gen, timestamp_1.default); const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil; const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`; return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString); } const def = { keyword: "type", schemaType: "string", error, code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { data, schema, parentSchema, it } = cxt; let cond; switch (schema) { case "boolean": case "string": cond = (0, codegen_1._) `typeof ${data} == ${schema}`; break; case "timestamp": { cond = timestampCode(cxt); break; } case "float32": case "float64": cond = (0, codegen_1._) `typeof ${data} == "number"`; break; default: { const sch = schema; cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`; if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { if (sch === "uint32") cond = (0, codegen_1._) `${cond} && ${data} >= 0`; } else { const [min, max] = exports.intRange[sch]; cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`; } } } cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond); }, }; exports.default = def; //# sourceMappingURL=type.js.map{"version":3,"file":"type.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/type.ts"],"names":[],"mappings":";;;AAEA,mDAAsD;AACtD,uDAAoD;AACpD,6CAA0C;AAC1C,yCAAwC;AACxC,mCAAwE;AAM3D,QAAA,QAAQ,GAA+C;IAClE,IAAI,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC;IACpB,KAAK,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IAClB,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACzB,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;IACrB,KAAK,EAAE,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,EAAE,CAAC;IACpC,MAAM,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,CAAC;CAC5B,CAAA;AAID,MAAM,K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"__esModule", { value: true }); const code_1 = require("../code"); const def = { keyword: "union", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in union" }, }; exports.default = def; //# sourceMappingURL=union.js.map{"version":3,"file":"union.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/union.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_1 = require("../../compile/util"); const codegen_1 = require("../../compile/codegen"); const metadata_1 = require("./metadata"); const nullable_1 = require("./nullable"); const error_1 = require("./error"); const def = { keyword: "values", schemaType: "object", error: (0, error_1.typeError)("object"), code(cxt) { (0, metadata_1.checkMetadata)(cxt); const { gen, data, schema, it } = cxt; const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); if ((0, util_1.alwaysValidSchema)(it, schema)) { gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error()); } else { gen.if(cond); gen.assign(valid, validateMap()); gen.elseIf((0, codegen_1.not)(valid)); cxt.error(); gen.endIf(); } cxt.ok(valid); function validateMap() { const _valid = gen.name("valid"); if (it.allErrors) { const validMap = gen.let("valid", true); validateValues(() => gen.assign(validMap, false)); return validMap; } gen.var(_valid, true); validateValues(() => gen.break()); return _valid; function validateValues(notValid) { gen.forIn("key", data, (key) => { cxt.subschema({ keyword: "values", dataProp: key, dataPropType: util_1.Type.Str, }, _valid); gen.if((0, codegen_1.not)(_valid), notValid); }); } } }, }; exports.default = def; //# sourceMappingURL=values.js.map{"version":3,"file":"values.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/values.ts"],"names":[],"mappings":";;AAEA,6CAA0D;AAC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AAE,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAA;gBACjD,OAAO,QAAQ,CAAA;YACjB,CAAC;YACD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YACrB,cAAc,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YACjC,OAAO,MAAM,CAAA;YAEb,SAAS,cAAc,CAAC,QAAoB;gBAC1C,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;oBAC7B,GAAG,CAAC,SAAS,CACX;wBACE,OAAO,EAAE,QAAQ;wBACjB,QAAQ,EAAE,GAAG;wBACb,YAAY,EAAE,WAAI,CAAC,GAAG;qBACvB,EACD,MAAM,CACP,CAAA;oBACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,CAAA;gBAC/B,CAAC,CAAC,CAAA;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.contentVocabulary = exports.metadataVocabulary = void 0; exports.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples", ]; exports.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema", ]; //# sourceMappingURL=metadata.js.map{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../lib/vocabularies/metadata.ts"],"names":[],"mappings":";;;AAEa,QAAA,kBAAkB,GAAe;IAC5C,OAAO;IACP,aAAa;IACb,SAAS;IACT,YAAY;IACZ,UAAU;IACV,WAAW;IACX,UAAU;CACX,CAAA;AAEY,QAAA,iBAAiB,GAAe;IAC3C,kBAAkB;IAClB,iBAAiB;IACjB,eAAe;CAChB,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const dependentRequired_1 = require("./validation/dependentRequired"); const dependentSchemas_1 = require("./applicator/dependentSchemas"); const limitContains_1 = require("./validation/limitContains"); const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default]; exports.default = next; //# sourceMappingURL=next.js.map{"version":3,"file":"next.js","sourceRoot":"","sources":["../../lib/vocabularies/next.ts"],"names":[],"mappings":";;AACA,sEAA8D;AAC9D,oEAA4D;AAC5D,8DAAsD;AAEtD,MAAM,IAAI,GAAe,CAAC,2BAAiB,EAAE,0BAAgB,EAAE,uBAAa,CAAC,CAAA;AAE7E,kBAAe,IAAI,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const unevaluatedProperties_1 = require("./unevaluatedProperties"); const unevaluatedItems_1 = require("./unevaluatedItems"); const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; exports.default = unevaluated; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/index.ts"],"names":[],"mappings":";;AACA,mEAA2D;AAC3D,yDAAiD;AAEjD,MAAM,WAAW,GAAe,CAAC,+BAAqB,EAAE,0BAAgB,CAAC,CAAA;AAEzE,kBAAe,WAAW,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const error = { message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, }; const def = { keyword: "unevaluatedItems", type: "array", schemaType: ["boolean", "object"], error, code(cxt) { const { gen, schema, data, it } = cxt; const items = it.items || 0; if (items === true) return; const len = gen.const("len", (0, codegen_1._) `${data}.length`); if (schema === false) { cxt.setParams({ len: items }); cxt.fail((0, codegen_1._) `${len} > ${items}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); cxt.ok(valid); } it.items = true; function validateItems(valid, from) { gen.forRange("i", from, len, (i) => { cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } }, }; exports.default = def; //# sourceMappingURL=unevaluatedItems.js.map{"version":3,"file":"unevaluatedItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/unevaluatedItems.ts"],"names":[],"mappings":";;AAOA,mDAAuD;AACvD,6CAA0D;AAI1D,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,MAAM,KAAK,GAAG,EAAE,CAAC,KAAK,IAAI,CAAC,CAAA;QAC3B,IAAI,KAAK,KAAK,IAAI;YAAE,OAAM;QAC1B,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,SAAS,CAAC,CAAA;QAC/C,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;YACrB,GAAG,CAAC,SAAS,CAAC,EAAC,GAAG,EAAE,KAAK,EAAC,CAAC,CAAA;YAC3B,GAAG,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,MAAM,KAAK,EAAE,CAAC,CAAA;QAChC,CAAC;aAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,IAAI,CAAC,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;YACvE,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,GAAG,OAAO,KAAK,EAAE,CAAC,CAAA;YACrD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;YACrD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QACf,CAAC;QACD,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QAEf,SAAS,aAAa,CAAC,KAAW,EAAE,IAAmB;YACrD,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE;gBACjC,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,CAAC,EAAE,YAAY,EAAE,WAAI,CAAC,GAAG,EAAC,EAAE,KAAK,CAAC,CAAA;gBACxF,IAAI,CAAC,EAAE,CAAC,SAAS;oBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YAC1D,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const names_1 = require("../../compile/names"); const error = { message: "must NOT have unevaluated properties", params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`, }; const def = { keyword: "unevaluatedProperties", type: "object", schemaType: ["boolean", "object"], trackErrors: true, error, code(cxt) { const { gen, schema, data, errsCount, it } = cxt; /* istanbul ignore if */ if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, props } = it; if (props instanceof codegen_1.Name) { gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); } else if (props !== true) { gen.forIn("key", data, (key) => props === undefined ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); } it.props = true; cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); function unevaluatedPropCode(key) { if (schema === false) { cxt.setParams({ unevaluatedProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (!(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); cxt.subschema({ keyword: "unevaluatedProperties", dataProp: key, dataPropType: util_1.Type.Str, }, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } function unevaluatedDynamic(evaluatedProps, key) { return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`; } function unevaluatedStatic(evaluatedProps, key) { const ps = []; for (const p in evaluatedProps) { if (evaluatedProps[p] === true) ps.push((0, codegen_1._) `${key} !== ${p}`); } return (0, codegen_1.and)(...ps); } }, }; exports.default = def; //# sourceMappingURL=unevaluatedProperties.js.map{"version":3,"file":"unevaluatedProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/unevaluatedProperties.ts"],"names":[],"mappings":";;AAMA,mDAA6D;AAC7D,6CAA0D;AAC1D,+CAAmC;AAQnC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,sCAAsC;IAC/C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,yBAAyB,MAAM,CAAC,mBAAmB,GAAG;CAC9E,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC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AAA;QACnB,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const equal_1 = require("../../runtime/equal"); const error = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`, }; const def = { keyword: "const", $data: true, error, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || (schema && typeof schema == "object")) { cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._) `${schema} !== ${data}`); } }, }; exports.default = def; //# sourceMappingURL=const.js.map{"version":3,"file":"const.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/const.ts"],"names":[],"mappings":";;AAEA,mDAAuC;AACvC,6CAA0C;AAC1C,+CAAuC;AAIvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,2BAA2B;IACpC,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,kBAAkB,UAAU,GAAG;CAC3D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAClD,IAAI,KAAK,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,CAAC,EAAE,CAAC;YACnD,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,IAAI,IAAI,KAAK,UAAU,GAAG,CAAC,CAAA;QACnE,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,QAAQ,IAAI,EAAE,CAAC,CAAA;QACpC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const dependencies_1 = require("../applicator/dependencies"); const def = { keyword: "dependentRequired", type: "object", schemaType: "object", error: dependencies_1.error, code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt), }; exports.default = def; //# sourceMappingURL=dependentRequired.js.map{"version":3,"file":"dependentRequired.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/dependentRequired.ts"],"names":[],"mappings":";;AACA,6DAKmC;AAQnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,mBAAmB;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,oBAAK;IACL,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,mCAAoB,EAAC,GAAG,CAAC;CACzC,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const equal_1 = require("../../runtime/equal"); const error = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`, }; const def = { keyword: "enum", schemaType: "array", $data: true, error, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default))); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._) `${data} === ${sch}`; } }, }; exports.default = def; //# sourceMappingURL=enum.js.map{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/enum.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AACvD,6CAA0C;AAC1C,+CAAuC;AAIvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,4CAA4C;IACrD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,mBAAmB,UAAU,GAAG;CAC5D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM;IACf,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;QACpF,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAA;QACjD,IAAI,GAAqB,CAAA;QACzB,MAAM,MAAM,GAAG,GAAS,EAAE,CAAC,CAAC,GAAG,aAAH,GAAG,cAAH,GAAG,IAAH,GAAG,GAAK,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,EAAC,CAAA;QAExD,IAAI,KAAW,CAAA;QACf,IAAI,OAAO,IAAI,KAAK,EAAE,CAAC;YACrB,KAAK,GAAG,GAAG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AG,EAAE,CAAA;QAC3B,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const limitNumber_1 = require("./limitNumber"); const multipleOf_1 = require("./multipleOf"); const limitLength_1 = require("./limitLength"); const pattern_1 = require("./pattern"); const limitProperties_1 = require("./limitProperties"); const required_1 = require("./required"); const limitItems_1 = require("./limitItems"); const uniqueItems_1 = require("./uniqueItems"); const const_1 = require("./const"); const enum_1 = require("./enum"); const validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default, ]; exports.default = validation; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/index.ts"],"names":[],"mappings":";;AACA,+CAA2D;AAC3D,6CAAwD;AACxD,+CAAuC;AACvC,uCAA+C;AAC/C,uDAA+C;AAC/C,yCAAkD;AAClD,6CAAqC;AACrC,+CAA2D;AAC3D,mCAAgD;AAChD,iCAA6C;AAE7C,MAAM,UAAU,GAAe;IAC7B,SAAS;IACT,qBAAW;IACX,oBAAU;IACV,SAAS;IACT,qBAAW;IACX,iBAAO;IACP,SAAS;IACT,yBAAe;IACf,kBAAQ;IACR,QAAQ;IACR,oBAAU;IACV,qBAAW;IACX,MAAM;IACN,EAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAC;IAClD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;IAC5C,eAAY;IACZ,cAAW;CACZ,CAAA;AAED,kBAAe,UAAU,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_1 = require("../../compile/util"); const def = { keyword: ["maxContains", "minContains"], type: "array", schemaType: "number", code({ keyword, parentSchema, it }) { if (parentSchema.contains === undefined) { (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); } }, }; exports.default = def; //# sourceMappingURL=limitContains.js.map{"version":3,"file":"limitContains.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitContains.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,aAAa,EAAE,aAAa,CAAC;IACvC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACxC,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,iCAAiC,CAAC,CAAA;QACnE,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const error = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, }; const def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`); }, }; exports.default = def; //# sourceMappingURL=limitItems.js.map{"version":3,"file":"limitItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitItems.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QACtD,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,QAAQ,CAAA;IAC5D,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,UAAU,EAAE,UAAU,CAAC;IACjC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QAC/D,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACtD,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const ucs2length_1 = require("../../runtime/ucs2length"); const error = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, }; const def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`); }, }; exports.default = def; //# sourceMappingURL=limitLength.js.map{"version":3,"file":"limitLength.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitLength.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AACvD,6CAA0C;AAC1C,yDAAiD;AAEjD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QACvD,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,aAAa,CAAA;IACjE,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,WAAW,EAAE,WAAW,CAAC;IACnC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC3C,MAAM,EAAE,GAAG,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QAChE,MAAM,GAAG,GACP,EAAE,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAA,cAAO,EAAC,GAAG,CAAC,GAAG,EAAE,oBAAU,CAAC,IAAI,IAAI,GAAG,CAAA;QAC7F,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,IAAI,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IAC9C,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const ops = codegen_1.operators; const KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, }; const error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, }; const def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); }, }; exports.default = def; //# sourceMappingURL=limitNumber.js.map{"version":3,"file":"limitNumber.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitNumber.ts"],"names":[],"mappings":";;AAEA,mDAA6D;AAE7D,MAAM,GAAG,GAAG,mBAAS,CAAA;AAMrB,MAAM,IAAI,GAA4D;IACpE,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;IACzD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;CAC1D,CAAA;AAQD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,WAAW,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,IAAI,UAAU,EAAE;IAC5F,MAAM,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAChC,IAAA,WAAC,EAAA,gBAAgB,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,YAAY,UAAU,GAAG;CACvE,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;IAC1B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,IAAI,CAAC,OAAc,CAAC,CAAC,IAAI,IAAI,UAAU,aAAa,IAAI,GAAG,CAAC,CAAA;IACxF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const error = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, }; const def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`); }, }; exports.default = def; //# sourceMappingURL=limitProperties.js.map{"version":3,"file":"limitProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitProperties.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QAC3D,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,aAAa,CAAA;IACjE,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,eAAe,EAAE,eAAe,CAAC;IAC3C,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QACpE,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,eAAe,IAAI,YAAY,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACnE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1 = require("../../compile/codegen"); const error = { message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`, }; const def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error, code(cxt) { const { gen, data, schemaCode, it } = cxt; // const bdt = bad$DataType(schemaCode, def.schemaType, $data) const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._) `${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); }, }; exports.default = def; //# sourceMappingURL=multipleOf.js.map{"version":3,"file":"multipleOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/multipleOf.ts"],"names":[],"mappings":";;AAEA,mDAA4C;AAQ5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,EAAE;IACjE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,gBAAgB,UAAU,GAAG;CACzD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACvC,sEAAsE;QACtE,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAA;QACxC,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC1B,MAAM,OAAO,GAAG,IAAI;YAClB,CAAC,CAAC,IAAA,WAAC,EAAA,uBAAuB,GAAG,OAAO,GAAG,UAAU,IAAI,EAAE;YACvD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,iBAAiB,GAAG,GAAG,CAAA;QAClC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,UAAU,cAAc,GAAG,MAAM,IAAI,IAAI,UAAU,KAAK,OAAO,IAAI,CAAC,CAAA;IACzF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const code_1 = require("../code"); const util_1 = require("../../compile/util"); const codegen_1 = require("../../compile/codegen"); const error = { message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`, }; const def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; if ($data) { const { regExp } = it.opts.code; const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp); const valid = gen.let("valid"); gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); cxt.fail$data((0, codegen_1._) `!${valid}`); } else { const regExp = (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`); } }, }; exports.default = def; //# sourceMappingURL=pattern.js.map{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/pattern.ts"],"names":[],"mappings":";;AAEA,kCAAkC;AAClC,6CAA0C;AAC1C,mDAA4C;AAI5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,GAAG;IAClE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,aAAa,UAAU,GAAG;CACtD,CA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C;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const code_1 = require("../code"); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const error = { message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`, }; const def = { keyword: "required", type: "object", schemaType: "array", $data: true, error, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } }, }; exports.default = def; //# sourceMappingURL=required.js.map{"version":3,"file":"required.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/required.ts"],"names":[],"mappings":";;AAEA,kCAMgB;AAChB,mDAAkE;AAClE,6CAAkD;AAQlD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,gCAAgC,eAAe,GAAG;IAC/F,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,qBAAqB,eAAe,GAAG;CAClF,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,EAAC,IAAI,EAAC,GAAG,EAAE,CAAA;QACjB,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAM;QACzC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,CAAA;QAClD,IAAI,EAAE,CAAC,SAAS;YAAE,aAAa,EAAE,CAAA;;YAC5B,eAAe,EAAE,CAAA;QAEtB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,KAAK,GAAG,GAAG,CAAC,YAAY,CAAC,UAAU,CAAA;YACzC,MAAM,EAAC,iBAAiB,EAAC,GAAG,GAAG,CAAC,EAAE,CAAA;YAClC,KAAK,MAAM,WAAW,IAAI,MAAM,EAAE,CAAC;gBACjC,IAAI,CAA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,CAAC,CAAA;gBAC/B,GAAG,CAAC,IAAI,EAAE,CAAA;YACZ,CAAC;QACH,CAAC;QAED,SAAS,eAAe;YACtB,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,UAAkB,EAAE,CAAC,IAAI,EAAE,EAAE;gBAC7C,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,IAAI,EAAC,CAAC,CAAA;gBACtC,GAAG,CAAC,EAAE,CAAC,IAAA,uBAAgB,EAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YAClF,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,SAAS,gBAAgB,CAAC,OAAa,EAAE,KAAW;YAClD,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,OAAO,EAAC,CAAC,CAAA;YACzC,GAAG,CAAC,KAAK,CACP,OAAO,EACP,UAAkB,EAClB,GAAG,EAAE;gBACH,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,qBAAc,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAA;gBACzE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE;oBACtB,GAAG,CAAC,KAAK,EAAE,CAAA;oBACX,GAAG,CAAC,KAAK,EAAE,CAAA;gBACb,CAAC,CAAC,CAAA;YACJ,CAAC,EACD,aAAG,CACJ,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const dataType_1 = require("../../compile/validate/dataType"); const codegen_1 = require("../../compile/codegen"); const util_1 = require("../../compile/util"); const equal_1 = require("../../runtime/equal"); const error = { message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`, }; const def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._) `${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._) `{}`); gen.for((0, codegen_1._) `;${i}--;`, () => { gen.let(item, (0, codegen_1._) `${data}[${i}]`); gen.if(wrongType, (0, codegen_1._) `continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`); gen .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._) `${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }) .code((0, codegen_1._) `${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } }, }; exports.default = def; //# sourceMappingURL=uniqueItems.js.map{"version":3,"file":"uniqueItems.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BACX,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;YACvC,CAAC,CAAC,CACH,CACF,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"}import type {AnySchemaObject} from "./types" import AjvCore, {Options} from "./core" import draft7Vocabularies from "./vocabularies/draft7" import dynamicVocabulary from "./vocabularies/dynamic" import nextVocabulary from "./vocabularies/next" import unevaluatedVocabulary from "./vocabularies/unevaluated" import discriminator from "./vocabularies/discriminator" import addMetaSchema2019 from "./refs/json-schema-2019-09" const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema" export class Ajv2019 extends AjvCore { constructor(opts: Options = {}) { super({ ...opts, dynamicRef: true, next: true, unevaluated: true, }) } _addVocabularies(): void { super._addVocabularies() this.addVocabulary(dynamicVocabulary) draft7Vocabularies.forEach((v) => this.addVocabulary(v)) this.addVocabulary(nextVocabulary) this.addVocabulary(unevaluatedVocabulary) if (this.opts.discriminator) this.addKeyword(discriminator) } _addDefaultMetaSchema(): void { super._addDefaultMetaSchema() const {$data, meta} = this.opts if (!meta) return addMetaSchema2019.call(this, $data) this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID } defaultMeta(): string | AnySchemaObject | undefined { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) } } module.exports = exports = Ajv2019 module.exports.Ajv2019 = Ajv2019 Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv2019 export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, } from "./types" export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" export {SchemaCxt, SchemaObjCxt} from "./compile" export {KeywordCxt} from "./compile/validate" export {DefinedError} from "./vocabularies/errors" export {JSONType} from "./compile/rules" export {JSONSchemaType} from "./types/json-schema" export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" export {default as ValidationError} from "./runtime/validation_error" export {default as MissingRefError} from "./compile/ref_error" import type {AnySchemaObject} from "./types" import AjvCore, {Options} from "./core" import draft2020Vocabularies from "./vocabularies/draft2020" import discriminator from "./vocabularies/discriminator" import addMetaSchema2020 from "./refs/json-schema-2020-12" const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema" export class Ajv2020 extends AjvCore { constructor(opts: Options = {}) { super({ ...opts, dynamicRef: true, next: true, unevaluated: true, }) } _addVocabularies(): void { super._addVocabularies() draft2020Vocabularies.forEach((v) => this.addVocabulary(v)) if (this.opts.discriminator) this.addKeyword(discriminator) } _addDefaultMetaSchema(): void { super._addDefaultMetaSchema() const {$data, meta} = this.opts if (!meta) return addMetaSchema2020.call(this, $data) this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID } defaultMeta(): string | AnySchemaObject | undefined { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) } } module.exports = exports = Ajv2020 module.exports.Ajv2020 = Ajv2020 Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv2020 export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, } from "./types" export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" export {SchemaCxt, SchemaObjCxt} from "./compile" export {KeywordCxt} from "./compile/validate" export {DefinedError} from "./vocabularies/errors" export {JSONType} from "./compile/rules" export {JSONSchemaType} from "./types/json-schema" export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" export {default as ValidationError} from "./runtime/validation_error" export {default as MissingRefError} from "./compile/ref_error" import type {AnySchemaObject} from "./types" import AjvCore from "./core" import draft7Vocabularies from "./vocabularies/draft7" import discriminator from "./vocabularies/discriminator" import * as draft7MetaSchema from "./refs/json-schema-draft-07.json" const META_SUPPORT_DATA = ["/properties"] const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema" export class Ajv extends AjvCore { _addVocabularies(): void { super._addVocabularies() draft7Vocabularies.forEach((v) => this.addVocabulary(v)) if (this.opts.discriminator) this.addKeyword(discriminator) } _addDefaultMetaSchema(): void { super._addDefaultMetaSchema() if (!this.opts.meta) return const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema this.addMetaSchema(metaSchema, META_SCHEMA_ID, false) this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID } defaultMeta(): string | AnySchemaObject | undefined { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) } } module.exports = exports = Ajv module.exports.Ajv = Ajv Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, SchemaValidateFunction, ErrorObject, ErrorNoParams, } from "./types" export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" export {SchemaCxt, SchemaObjCxt} from "./compile" export {KeywordCxt} from "./compile/validate" export {DefinedError} from "./vocabularies/errors" export {JSONType} from "./compile/rules" export {JSONSchemaType} from "./types/json-schema" export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" export {default as ValidationError} from "./runtime/validation_error" export {default as MissingRefError} from "./compile/ref_error" // eslint-disable-next-line @typescript-eslint/no-extraneous-class export abstract class _CodeOrName { abstract readonly str: string abstract readonly names: UsedNames abstract toString(): string abstract emptyStr(): boolean } export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i export class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } } export class _Code extends _CodeOrName { readonly _items: readonly CodeItem[] private _str?: string private _names?: UsedNames constructor(code: string | readonly CodeItem[]) { super() this._items = typeof code === "string" ? [code] : code } toString(): string { return this.str } emptyStr(): boolean { if (this._items.length > 1) return false const item = this._items[0] return item === "" || item === '""' } get str(): string { return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, "")) } get names(): UsedNames { return (this._names ??= this._items.reduce((names: UsedNames, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1 return names }, {})) } } export type CodeItem = Name | string | number | boolean | null export type UsedNames = Record export type Code = _Code | Name export type SafeExpr = Code | number | boolean | null export const nil = new _Code("") type CodeArg = SafeExpr | string | undefined export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code { const code: CodeItem[] = [strs[0]] let i = 0 while (i < args.length) { addCodeArg(code, args[i]) code.push(strs[++i]) } return new _Code(code) } const plus = new _Code("+") export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code { const expr: CodeItem[] = [safeStringify(strs[0])] let i = 0 while (i < args.length) { expr.push(plus) addCodeArg(expr, args[i]) expr.push(plus, safeStringify(strs[++i])) } optimize(expr) return new _Code(expr) } export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void { if (arg instanceof _Code) code.push(...arg._items) else if (arg instanceof Name) code.push(arg) else code.push(interpolate(arg)) } function optimize(expr: CodeItem[]): void { let i = 1 while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]) if (res !== undefined) { expr.splice(i - 1, 3, res) continue } expr[i++] = "+" } i++ } } function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined { if (b === '""') return a if (a === '""') return b if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return if (typeof b != "string") return `${a.slice(0, -1)}${b}"` if (b[0] === '"') return a.slice(0, -1) + b.slice(1) return } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}` return } export function strConcat(c1: Code, c2: Code): Code { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}` } // TODO do not allow arrays here function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x) } export function stringify(x: unknown): Code { return new _Code(safeStringify(x)) } export function safeStringify(x: unknown): string { return JSON.stringify(x) .replace(/\u2028/g, "\\u2028") .replace(/\u2029/g, "\\u2029") } export function getProperty(key: Code | string | number): Code { return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]` } //Does best effort to format the name properly export function getEsmExportName(key: Code | string | number): Code { if (typeof key == "string" && IDENTIFIER.test(key)) { return new _Code(`${key}`) } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`) } export function regexpCode(rx: RegExp): Code { return new _Code(rx.toString()) } import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope" import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code" import {Scope, varKinds} from "./scope" export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code" export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope" // type for expressions that can be safely inserted in code without quotes export type SafeExpr = Code | number | boolean | null // type that is either Code of function that adds code to CodeGen instance using its methods export type Block = Code | (() => void) export const operators = { GT: new _Code(">"), GTE: new _Code(">="), LT: new _Code("<"), LTE: new _Code("<="), EQ: new _Code("==="), NEQ: new _Code("!=="), NOT: new _Code("!"), OR: new _Code("||"), AND: new _Code("&&"), ADD: new _Code("+"), } abstract class Node { abstract readonly names: UsedNames optimizeNodes(): this | ChildNode | ChildNode[] | undefined { return this } optimizeNames(_names: UsedNames, _constants: Constants): this | undefined { return this } // get count(): number { // return 1 // } } class Def extends Node { constructor( private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr ) { super() } render({es5, _n}: CGOptions): string { const varKind = es5 ? varKinds.var : this.varKind const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}` return `${varKind} ${this.name}${rhs};` + _n } optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (!names[this.name.str]) return if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants) return this } get names(): UsedNames { return this.rhs instanceof _CodeOrName ? this.rhs.names : {} } } class Assign extends Node { constructor( readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean ) { super() } render({_n}: CGOptions): string { return `${this.lhs} = ${this.rhs};` + _n } optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return this.rhs = optimizeExpr(this.rhs, names, constants) return this } get names(): UsedNames { const names = this.lhs instanceof Name ? {} : {...this.lhs.names} return addExprNames(names, this.rhs) } } class AssignOp extends Assign { constructor( lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean ) { super(lhs, rhs, sideEffects) } render({_n}: CGOptions): string { return `${this.lhs} ${this.op}= ${this.rhs};` + _n } } class Label extends Node { readonly names: UsedNames = {} constructor(readonly label: Name) { super() } render({_n}: CGOptions): string { return `${this.label}:` + _n } } class Break extends Node { readonly names: UsedNames = {} constructor(readonly label?: Code) { super() } render({_n}: CGOptions): string { const label = this.label ? ` ${this.label}` : "" return `break${label};` + _n } } class Throw extends Node { constructor(readonly error: Code) { super() } render({_n}: CGOptions): string { return `throw ${this.error};` + _n } get names(): UsedNames { return this.error.names } } class AnyCode extends Node { constructor(private code: SafeExpr) { super() } render({_n}: CGOptions): string { return `${this.code};` + _n } optimizeNodes(): this | undefined { return `${this.code}` ? this : undefined } optimizeNames(names: UsedNames, constants: Constants): this { this.code = optimizeExpr(this.code, names, constants) return this } get names(): UsedNames { return this.code instanceof _CodeOrName ? this.code.names : {} } } abstract class ParentNode extends Node { constructor(readonly nodes: ChildNode[] = []) { super() } render(opts: CGOptions): string { return this.nodes.reduce((code, n) => code + n.render(opts), "") } optimizeNodes(): this | ChildNode | ChildNode[] | undefined { const {nodes} = this let i = nodes.length while (i--) { const n = nodes[i].optimizeNodes() if (Array.isArray(n)) nodes.splice(i, 1, ...n) else if (n) nodes[i] = n else nodes.splice(i, 1) } return nodes.length > 0 ? this : undefined } optimizeNames(names: UsedNames, constants: Constants): this | undefined { const {nodes} = this let i = nodes.length while (i--) { // iterating backwards improves 1-pass optimization const n = nodes[i] if (n.optimizeNames(names, constants)) continue subtractNames(names, n.names) nodes.splice(i, 1) } return nodes.length > 0 ? this : undefined } get names(): UsedNames { return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {}) } // get count(): number { // return this.nodes.reduce((c, n) => c + n.count, 1) // } } abstract class BlockNode extends ParentNode { render(opts: CGOptions): string { return "{" + opts._n + super.render(opts) + "}" + opts._n } } class Root extends ParentNode {} class Else extends BlockNode { static readonly kind = "else" } class If extends BlockNode { static readonly kind = "if" else?: If | Else constructor( private condition: Code | boolean, nodes?: ChildNode[] ) { super(nodes) } render(opts: CGOptions): string { let code = `if(${this.condition})` + super.render(opts) if (this.else) code += "else " + this.else.render(opts) return code } optimizeNodes(): If | ChildNode[] | undefined { super.optimizeNodes() const cond = this.condition if (cond === true) return this.nodes // else is ignored here let e = this.else if (e) { const ns = e.optimizeNodes() e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined) } if (e) { if (cond === false) return e instanceof If ? e : e.nodes if (this.nodes.length) return this return new If(not(cond), e instanceof If ? [e] : e.nodes) } if (cond === false || !this.nodes.length) return undefined return this } optimizeNames(names: UsedNames, constants: Constants): this | undefined { this.else = this.else?.optimizeNames(names, constants) if (!(super.optimizeNames(names, constants) || this.else)) return this.condition = optimizeExpr(this.condition, names, constants) return this } get names(): UsedNames { const names = super.names addExprNames(names, this.condition) if (this.else) addNames(names, this.else.names) return names } // get count(): number { // return super.count + (this.else?.count || 0) // } } abstract class For extends BlockNode { static readonly kind = "for" } class ForLoop extends For { constructor(private iteration: Code) { super() } render(opts: CGOptions): string { return `for(${this.iteration})` + super.render(opts) } optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (!super.optimizeNames(names, constants)) return this.iteration = optimizeExpr(this.iteration, names, constants) return this } get names(): UsedNames { return addNames(super.names, this.iteration.names) } } class ForRange extends For { constructor( private readonly varKind: Name, private readonly name: Name, private readonly from: SafeExpr, private readonly to: SafeExpr ) { super() } render(opts: CGOptions): string { const varKind = opts.es5 ? varKinds.var : this.varKind const {name, from, to} = this return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts) } get names(): UsedNames { const names = addExprNames(super.names, this.from) return addExprNames(names, this.to) } } class ForIter extends For { constructor( private readonly loop: "of" | "in", private readonly varKind: Name, private readonly name: Name, private iterable: Code ) { super() } render(opts: CGOptions): string { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts) } optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (!super.optimizeNames(names, constants)) return this.iterable = optimizeExpr(this.iterable, names, constants) return this } get names(): UsedNames { return addNames(super.names, this.iterable.names) } } class Func extends BlockNode { static readonly kind = "func" constructor( public name: Name, public args: Code, public async?: boolean ) { super() } render(opts: CGOptions): string { const _async = this.async ? "async " : "" return `${_async}function ${this.name}(${this.args})` + super.render(opts) } } class Return extends ParentNode { static readonly kind = "return" render(opts: CGOptions): string { return "return " + super.render(opts) } } class Try extends BlockNode { catch?: Catch finally?: Finally render(opts: CGOptions): string { let code = "try" + super.render(opts) if (this.catch) code += this.catch.render(opts) if (this.finally) code += this.finally.render(opts) return code } optimizeNodes(): this { super.optimizeNodes() this.catch?.optimizeNodes() as Catch | undefined this.finally?.optimizeNodes() as Finally | undefined return this } optimizeNames(names: UsedNames, constants: Constants): this { super.optimizeNames(names, constants) this.catch?.optimizeNames(names, constants) this.finally?.optimizeNames(names, constants) return this } get names(): UsedNames { const names = super.names if (this.catch) addNames(names, this.catch.names) if (this.finally) addNames(names, this.finally.names) return names } // get count(): number { // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0) // } } class Catch extends BlockNode { static readonly kind = "catch" constructor(readonly error: Name) { super() } render(opts: CGOptions): string { return `catch(${this.error})` + super.render(opts) } } class Finally extends BlockNode { static readonly kind = "finally" render(opts: CGOptions): string { return "finally" + super.render(opts) } } type StartBlockNode = If | For | Func | Return | Try type LeafNode = Def | Assign | Label | Break | Throw | AnyCode type ChildNode = StartBlockNode | LeafNode type EndBlockNodeType = | typeof If | typeof Else | typeof For | typeof Func | typeof Return | typeof Catch | typeof Finally type Constants = Record export interface CodeGenOptions { es5?: boolean lines?: boolean ownProperties?: boolean } interface CGOptions extends CodeGenOptions { _n: "\n" | "" } export class CodeGen { readonly _scope: Scope readonly _extScope: ValueScope readonly _values: ScopeValueSets = {} private readonly _nodes: ParentNode[] private readonly _blockStarts: number[] = [] private readonly _constants: Constants = {} private readonly opts: CGOptions constructor(extScope: ValueScope, opts: CodeGenOptions = {}) { this.opts = {...opts, _n: opts.lines ? "\n" : ""} this._extScope = extScope this._scope = new Scope({parent: extScope}) this._nodes = [new Root()] } toString(): string { return this._root.render(this.opts) } // returns unique name in the internal scope name(prefix: string): Name { return this._scope.name(prefix) } // reserves unique name in the external scope scopeName(prefix: string): ValueScopeName { return this._extScope.name(prefix) } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name { const name = this._extScope.value(prefixOrName, value) const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()) vs.add(name) return name } getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { return this._extScope.getValue(prefix, keyOrRef) } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName: Name): Code { return this._extScope.scopeRefs(scopeName, this._values) } scopeCode(): Code { return this._extScope.scopeCode(this._values) } private _def( varKind: Name, nameOrPrefix: Name | string, rhs?: SafeExpr, constant?: boolean ): Name { const name = this._scope.toName(nameOrPrefix) if (rhs !== undefined && constant) this._constants[name.str] = rhs this._leafNode(new Def(varKind, name, rhs)) return name } // `const` declaration (`var` in es5 mode) const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.const, nameOrPrefix, rhs, _constant) } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.let, nameOrPrefix, rhs, _constant) } // `var` declaration with optional assignment var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.var, nameOrPrefix, rhs, _constant) } // assignment code assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen { return this._leafNode(new Assign(lhs, rhs, sideEffects)) } // `+=` code add(lhs: Code, rhs: SafeExpr): CodeGen { return this._leafNode(new AssignOp(lhs, operators.ADD, rhs)) } // appends passed SafeExpr to code or executes Block code(c: Block | SafeExpr): CodeGen { if (typeof c == "function") c() else if (c !== nil) this._leafNode(new AnyCode(c)) return this } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues: [Name | string, SafeExpr | string][]): _Code { const code: CodeItem[] = ["{"] for (const [key, value] of keyValues) { if (code.length > 1) code.push(",") code.push(key) if (key !== value || this.opts.es5) { code.push(":") addCodeArg(code, value) } } code.push("}") return new _Code(code) } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen { this._blockNode(new If(condition)) if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf() } else if (thenBody) { this.code(thenBody).endIf() } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body') } return this } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition: Code | boolean): CodeGen { return this._elseNode(new If(condition)) } // `else` clause - only valid after `if` or `else if` clauses else(): CodeGen { return this._elseNode(new Else()) } // end `if` statement (needed if gen.if was used only with condition) endIf(): CodeGen { return this._endBlockNode(If, Else) } private _for(node: For, forBody?: Block): CodeGen { this._blockNode(node) if (forBody) this.code(forBody).endFor() return this } // a generic `for` clause (or statement if `forBody` is passed) for(iteration: Code, forBody?: Block): CodeGen { return this._for(new ForLoop(iteration), forBody) } // `for` statement for a range of values forRange( nameOrPrefix: Name | string, from: SafeExpr, to: SafeExpr, forBody: (index: Name) => void, varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let ): CodeGen { const name = this._scope.toName(nameOrPrefix) return this._for(new ForRange(varKind, name, from, to), () => forBody(name)) } // `for-of` statement (in es5 mode replace with a normal for loop) forOf( nameOrPrefix: Name | string, iterable: Code, forBody: (item: Name) => void, varKind: Code = varKinds.const ): CodeGen { const name = this._scope.toName(nameOrPrefix) if (this.opts.es5) { const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable) return this.forRange("_i", 0, _`${arr}.length`, (i) => { this.var(name, _`${arr}[${i}]`) forBody(name) }) } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)) } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn( nameOrPrefix: Name | string, obj: Code, forBody: (item: Name) => void, varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const ): CodeGen { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody) } const name = this._scope.toName(nameOrPrefix) return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)) } // end `for` loop endFor(): CodeGen { return this._endBlockNode(For) } // `label` statement label(label: Name): CodeGen { return this._leafNode(new Label(label)) } // `break` statement break(label?: Code): CodeGen { return this._leafNode(new Break(label)) } // `return` statement return(value: Block | SafeExpr): CodeGen { const node = new Return() this._blockNode(node) this.code(value) if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node') return this._endBlockNode(Return) } // `try` statement try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"') const node = new Try() this._blockNode(node) this.code(tryBody) if (catchCode) { const error = this.name("e") this._currNode = node.catch = new Catch(error) catchCode(error) } if (finallyCode) { this._currNode = node.finally = new Finally() this.code(finallyCode) } return this._endBlockNode(Catch, Finally) } // `throw` statement throw(error: Code): CodeGen { return this._leafNode(new Throw(error)) } // start self-balancing block block(body?: Block, nodeCount?: number): CodeGen { this._blockStarts.push(this._nodes.length) if (body) this.code(body).endBlock(nodeCount) return this } // end the current self-balancing block endBlock(nodeCount?: number): CodeGen { const len = this._blockStarts.pop() if (len === undefined) throw new Error("CodeGen: not in self-balancing block") const toClose = this._nodes.length - len if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`) } this._nodes.length = len return this } // `function` heading (or definition if funcBody is passed) func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen { this._blockNode(new Func(name, args, async)) if (funcBody) this.code(funcBody).endFunc() return this } // end function definition endFunc(): CodeGen { return this._endBlockNode(Func) } optimize(n = 1): void { while (n-- > 0) { this._root.optimizeNodes() this._root.optimizeNames(this._root.names, this._constants) } } private _leafNode(node: LeafNode): CodeGen { this._currNode.nodes.push(node) return this } private _blockNode(node: StartBlockNode): void { this._currNode.nodes.push(node) this._nodes.push(node) } private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen { const n = this._currNode if (n instanceof N1 || (N2 && n instanceof N2)) { this._nodes.pop() return this } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`) } private _elseNode(node: If | Else): CodeGen { const n = this._currNode if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"') } this._currNode = n.else = node return this } private get _root(): Root { return this._nodes[0] as Root } private get _currNode(): ParentNode { const ns = this._nodes return ns[ns.length - 1] } private set _currNode(node: ParentNode) { const ns = this._nodes ns[ns.length - 1] = node } // get nodeCount(): number { // return this._root.count // } } function addNames(names: UsedNames, from: UsedNames): UsedNames { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0) return names } function addExprNames(names: UsedNames, from: SafeExpr): UsedNames { return from instanceof _CodeOrName ? addNames(names, from.names) : names } function optimizeExpr(expr: T, names: UsedNames, constants: Constants): T function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr { if (expr instanceof Name) return replaceName(expr) if (!canOptimize(expr)) return expr return new _Code( expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => { if (c instanceof Name) c = replaceName(c) if (c instanceof _Code) items.push(...c._items) else items.push(c) return items }, []) ) function replaceName(n: Name): SafeExpr { const c = constants[n.str] if (c === undefined || names[n.str] !== 1) return n delete names[n.str] return c } function canOptimize(e: SafeExpr): e is _Code { return ( e instanceof _Code && e._items.some( (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined ) ) } } function subtractNames(names: UsedNames, from: UsedNames): void { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0) } export function not(x: T): T export function not(x: Code | SafeExpr): Code | SafeExpr { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}` } const andCode = mappend(operators.AND) // boolean AND (&&) expression with the passed arguments export function and(...args: Code[]): Code { return args.reduce(andCode) } const orCode = mappend(operators.OR) // boolean OR (||) expression with the passed arguments export function or(...args: Code[]): Code { return args.reduce(orCode) } type MAppend = (x: Code, y: Code) => Code function mappend(op: Code): MAppend { return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`) } function par(x: Code): Code { return x instanceof Name ? x : _`(${x})` } import {_, nil, Code, Name} from "./code" interface NameGroup { prefix: string index: number } export interface NameValue { ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`) } export type ValueReference = unknown // possibly make CodeGen parameterized type on this type class ValueError extends Error { readonly value?: NameValue constructor(name: ValueScopeName) { super(`CodeGen: "code" for ${name} not defined`) this.value = name.value } } interface ScopeOptions { prefixes?: Set parent?: Scope } interface ValueScopeOptions extends ScopeOptions { scope: ScopeStore es5?: boolean lines?: boolean } export type ScopeStore = Record type ScopeValues = { [Prefix in string]?: Map } export type ScopeValueSets = { [Prefix in string]?: Set } export enum UsedValueState { Started, Completed, } export type UsedScopeValues = { [Prefix in string]?: Map } export const varKinds = { const: new Name("const"), let: new Name("let"), var: new Name("var"), } export class Scope { protected readonly _names: {[Prefix in string]?: NameGroup} = {} protected readonly _prefixes?: Set protected readonly _parent?: Scope constructor({prefixes, parent}: ScopeOptions = {}) { this._prefixes = prefixes this._parent = parent } toName(nameOrPrefix: Name | string): Name { return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix) } name(prefix: string): Name { return new Name(this._newName(prefix)) } protected _newName(prefix: string): string { const ng = this._names[prefix] || this._nameGroup(prefix) return `${prefix}${ng.index++}` } private _nameGroup(prefix: string): NameGroup { if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`) } return (this._names[prefix] = {prefix, index: 0}) } } interface ScopePath { property: string itemIndex: number } export class ValueScopeName extends Name { readonly prefix: string value?: NameValue scopePath?: Code constructor(prefix: string, nameStr: string) { super(nameStr) this.prefix = prefix } setValue(value: NameValue, {property, itemIndex}: ScopePath): void { this.value = value this.scopePath = _`.${new Name(property)}[${itemIndex}]` } } interface VSOptions extends ValueScopeOptions { _n: Code } const line = _`\n` export class ValueScope extends Scope { protected readonly _values: ScopeValues = {} protected readonly _scope: ScopeStore readonly opts: VSOptions constructor(opts: ValueScopeOptions) { super(opts) this._scope = opts.scope this.opts = {...opts, _n: opts.lines ? line : nil} } get(): ScopeStore { return this._scope } name(prefix: string): ValueScopeName { return new ValueScopeName(prefix, this._newName(prefix)) } value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName { if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value") const name = this.toName(nameOrPrefix) as ValueScopeName const {prefix} = name const valueKey = value.key ?? value.ref let vs = this._values[prefix] if (vs) { const _name = vs.get(valueKey) if (_name) return _name } else { vs = this._values[prefix] = new Map() } vs.set(valueKey, name) const s = this._scope[prefix] || (this._scope[prefix] = []) const itemIndex = s.length s[itemIndex] = value.ref name.setValue(value, {property: prefix, itemIndex}) return name } getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { const vs = this._values[prefix] if (!vs) return return vs.get(keyOrRef) } scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code { return this._reduceValues(values, (name: ValueScopeName) => { if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`) return _`${scopeName}${name.scopePath}` }) } scopeCode( values: ScopeValues | ScopeValueSets = this._values, usedValues?: UsedScopeValues, getCode?: (n: ValueScopeName) => Code | undefined ): Code { return this._reduceValues( values, (name: ValueScopeName) => { if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`) return name.value.code }, usedValues, getCode ) } private _reduceValues( values: ScopeValues | ScopeValueSets, valueCode: (n: ValueScopeName) => Code | undefined, usedValues: UsedScopeValues = {}, getCode?: (n: ValueScopeName) => Code | undefined ): Code { let code: Code = nil for (const prefix in values) { const vs = values[prefix] if (!vs) continue const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()) vs.forEach((name: ValueScopeName) => { if (nameSet.has(name)) return nameSet.set(name, UsedValueState.Started) let c = valueCode(name) if (c) { const def = this.opts.es5 ? varKinds.var : varKinds.const code = _`${code}${def} ${name} = ${c};${this.opts._n}` } else if ((c = getCode?.(name))) { code = _`${code}${c}${this.opts._n}` } else { throw new ValueError(name) } nameSet.set(name, UsedValueState.Completed) }) } return code } } import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types" import type {SchemaCxt} from "./index" import {CodeGen, _, str, strConcat, Code, Name} from "./codegen" import {SafeExpr} from "./codegen/code" import {getErrorPath, Type} from "./util" import N from "./names" export const keywordError: KeywordErrorDefinition = { message: ({keyword}) => str`must pass "${keyword}" keyword validation`, } export const keyword$DataError: KeywordErrorDefinition = { message: ({keyword, schemaType}) => schemaType ? str`"${keyword}" keyword must be ${schemaType} ($data)` : str`"${keyword}" keyword is invalid ($data)`, } export interface ErrorPaths { instancePath?: Code schemaPath?: string parentSchema?: boolean } export function reportError( cxt: KeywordErrorCxt, error: KeywordErrorDefinition = keywordError, errorPaths?: ErrorPaths, overrideAllErrors?: boolean ): void { const {it} = cxt const {gen, compositeRule, allErrors} = it const errObj = errorObjectCode(cxt, error, errorPaths) if (overrideAllErrors ?? (compositeRule || allErrors)) { addError(gen, errObj) } else { returnErrors(it, _`[${errObj}]`) } } export function reportExtraError( cxt: KeywordErrorCxt, error: KeywordErrorDefinition = keywordError, errorPaths?: ErrorPaths ): void { const {it} = cxt const {gen, compositeRule, allErrors} = it const errObj = errorObjectCode(cxt, error, errorPaths) addError(gen, errObj) if (!(compositeRule || allErrors)) { returnErrors(it, N.vErrors) } } export function resetErrorsCount(gen: CodeGen, errsCount: Name): void { gen.assign(N.errors, errsCount) gen.if(_`${N.vErrors} !== null`, () => gen.if( errsCount, () => gen.assign(_`${N.vErrors}.length`, errsCount), () => gen.assign(N.vErrors, null) ) ) } export function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }: KeywordErrorCxt): void { /* istanbul ignore if */ if (errsCount === undefined) throw new Error("ajv implementation error") const err = gen.name("err") gen.forRange("i", errsCount, N.errors, (i) => { gen.const(err, _`${N.vErrors}[${i}]`) gen.if(_`${err}.instancePath === undefined`, () => gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath)) ) gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`) if (it.opts.verbose) { gen.assign(_`${err}.schema`, schemaValue) gen.assign(_`${err}.data`, data) } }) } function addError(gen: CodeGen, errObj: Code): void { const err = gen.const("err", errObj) gen.if( _`${N.vErrors} === null`, () => gen.assign(N.vErrors, _`[${err}]`), _`${N.vErrors}.push(${err})` ) gen.code(_`${N.errors}++`) } function returnErrors(it: SchemaCxt, errs: Code): void { const {gen, validateName, schemaEnv} = it if (schemaEnv.$async) { gen.throw(_`new ${it.ValidationError as Name}(${errs})`) } else { gen.assign(_`${validateName}.errors`, errs) gen.return(false) } } const E = { keyword: new Name("keyword"), schemaPath: new Name("schemaPath"), // also used in JTD errors params: new Name("params"), propertyName: new Name("propertyName"), message: new Name("message"), schema: new Name("schema"), parentSchema: new Name("parentSchema"), } function errorObjectCode( cxt: KeywordErrorCxt, error: KeywordErrorDefinition, errorPaths?: ErrorPaths ): Code { const {createErrors} = cxt.it if (createErrors === false) return _`{}` return errorObject(cxt, error, errorPaths) } function errorObject( cxt: KeywordErrorCxt, error: KeywordErrorDefinition, errorPaths: ErrorPaths = {} ): Code { const {gen, it} = cxt const keyValues: [Name, SafeExpr | string][] = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths), ] extraErrorProps(cxt, error, keyValues) return gen.object(...keyValues) } function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] { const instPath = instancePath ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}` : errorPath return [N.instancePath, strConcat(N.instancePath, instPath)] } function errorSchemaPath( {keyword, it: {errSchemaPath}}: KeywordErrorCxt, {schemaPath, parentSchema}: ErrorPaths ): [Name, string | Code] { let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}` if (schemaPath) { schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}` } return [E.schemaPath, schPath] } function extraErrorProps( cxt: KeywordErrorCxt, {params, message}: KeywordErrorDefinition, keyValues: [Name, SafeExpr | string][] ): void { const {keyword, data, schemaValue, it} = cxt const {opts, propertyName, topSchemaRef, schemaPath} = it keyValues.push( [E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || _`{}`] ) if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]) } if (opts.verbose) { keyValues.push( [E.schema, schemaValue], [E.parentSchema, _`${topSchemaRef}${schemaPath}`], [N.data, data] ) } if (propertyName) keyValues.push([E.propertyName, propertyName]) } import type { AnySchema, AnySchemaObject, AnyValidateFunction, AsyncValidateFunction, EvaluatedProperties, EvaluatedItems, } from "../types" import type Ajv from "../core" import type {InstanceOptions} from "../core" import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen" import ValidationError from "../runtime/validation_error" import N from "./names" import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve" import {schemaHasRulesButRef, unescapeFragment} from "./util" import {validateFunctionCode} from "./validate" import {URIComponent} from "fast-uri" import {JSONType} from "./rules" export type SchemaRefs = { [Ref in string]?: SchemaEnv | AnySchema } export interface SchemaCxt { readonly gen: CodeGen readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error readonly data: Name // Name with reference to the current part of data instance readonly parentData: Name // should be used in keywords modifying data readonly parentDataProperty: Code | number // should be used in keywords modifying data readonly dataNames: Name[] readonly dataPathArr: (Code | number)[] readonly dataLevel: number // the level of the currently validated data, // it can be used to access both the property names and the data on all levels from the top. dataTypes: JSONType[] // data types applied to the current part of data instance definedProperties: Set // set of properties to keep track of for required checks readonly topSchemaRef: Code readonly validateName: Name evaluated?: Name readonly ValidationError?: Name readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt readonly schemaEnv: SchemaEnv readonly rootId: string baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref) readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema readonly errSchemaPath: string // this is actual string, should not be changed to Code readonly errorPath: Code readonly propertyName?: Name readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword, // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`). // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true. // You only need to use it if you have many steps in your keywords and potentially can define multiple errors. props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function jtdDiscriminator?: string jtdMetadata?: boolean readonly createErrors?: boolean readonly opts: InstanceOptions // Ajv instance option. readonly self: Ajv // current Ajv instance } export interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject } interface SchemaEnvArgs { readonly schema: AnySchema readonly schemaId?: "$id" | "id" readonly root?: SchemaEnv readonly baseId?: string readonly schemaPath?: string readonly localRefs?: LocalRefs readonly meta?: boolean } export class SchemaEnv implements SchemaEnvArgs { readonly schema: AnySchema readonly schemaId?: "$id" | "id" readonly root: SchemaEnv baseId: string // TODO possibly, it should be readonly schemaPath?: string localRefs?: LocalRefs readonly meta?: boolean readonly $async?: boolean // true if the current schema is asynchronous. readonly refs: SchemaRefs = {} readonly dynamicAnchors: {[Ref in string]?: true} = {} validate?: AnyValidateFunction validateName?: ValueScopeName serialize?: (data: unknown) => string serializeName?: ValueScopeName parse?: (data: string) => unknown parseName?: ValueScopeName constructor(env: SchemaEnvArgs) { let schema: AnySchemaObject | undefined if (typeof env.schema == "object") schema = env.schema this.schema = env.schema this.schemaId = env.schemaId this.root = env.root || this this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) this.schemaPath = env.schemaPath this.localRefs = env.localRefs this.meta = env.meta this.$async = schema?.$async this.refs = {} } } // let codeSize = 0 // let nodeCount = 0 // Compiles schema in SchemaEnv export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { // TODO refactor - remove compilations const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) let _ValidationError if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: ValidationError, code: _`require("ajv/dist/runtime/validation_error").default`, }) } const validateName = gen.scopeName("validate") sch.validateName = validateName const schemaCxt: SchemaCxt = { gen, allErrors: this.opts.allErrors, data: N.data, parentData: N.parentData, parentDataProperty: N.parentDataProperty, dataNames: [N.data], dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set(), topSchemaRef: gen.scopeValue( "schema", this.opts.code.source === true ? {ref: sch.schema, code: stringify(sch.schema)} : {ref: sch.schema} ), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: _`""`, opts: this.opts, self: this, } let sourceCode: string | undefined try { this._compilations.add(sch) validateFunctionCode(schemaCxt) gen.optimize(this.opts.code.optimize) // gen.optimize(1) const validateCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) // console.log("\n\n\n *** \n", sourceCode) const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) this.scope.value(validateName, {ref: validate}) validate.errors = null validate.schema = sch.schema validate.schemaEnv = sch if (sch.$async) (validate as AsyncValidateFunction).$async = true if (this.opts.code.source === true) { validate.source = {validateName, validateCode, scopeValues: gen._values} } if (this.opts.unevaluated) { const {props, items} = schemaCxt validate.evaluated = { props: props instanceof Name ? undefined : props, items: items instanceof Name ? undefined : items, dynamicProps: props instanceof Name, dynamicItems: items instanceof Name, } if (validate.source) validate.source.evaluated = stringify(validate.evaluated) } sch.validate = validate return sch } catch (e) { delete sch.validate delete sch.validateName if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) // console.log("\n\n\n *** \n", sourceCode, this.opts) throw e } finally { this._compilations.delete(sch) } } export function resolveRef( this: Ajv, root: SchemaEnv, baseId: string, ref: string ): AnySchema | SchemaEnv | undefined { ref = resolveUrl(this.opts.uriResolver, baseId, ref) const schOrFunc = root.refs[ref] if (schOrFunc) return schOrFunc let _sch = resolve.call(this, root, ref) if (_sch === undefined) { const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv const {schemaId} = this.opts if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) } if (_sch === undefined) return return (root.refs[ref] = inlineOrCompile.call(this, _sch)) } function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema return sch.validate ? sch : compileSchema.call(this, sch) } // Index of schema compilation in the currently compiled list export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch } } function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId } // resolve and compile the references ($ref) // TODO returns AnySchemaObject (if the schema can be inlined) or validation function function resolve( this: Ajv, root: SchemaEnv, // information about the root schema for the current schema ref: string // reference to resolve ): SchemaEnv | undefined { let sch while (typeof (sch = this.refs[ref]) == "string") ref = sch return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) } // Resolve schema, its root and baseId export function resolveSchema( this: Ajv, root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it ref: string // reference to resolve ): SchemaEnv | undefined { const p = this.opts.uriResolver.parse(ref) const refPath = _getFullPath(this.opts.uriResolver, p) let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined) // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root) } const id = normalizeId(refPath) const schOrRef = this.refs[id] || this.schemas[id] if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef) if (typeof sch?.schema !== "object") return return getJsonPointer.call(this, p, sch) } if (typeof schOrRef?.schema !== "object") return if (!schOrRef.validate) compileSchema.call(this, schOrRef) if (id === normalizeId(ref)) { const {schema} = schOrRef const {schemaId} = this.opts const schId = schema[schemaId] if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId) return new SchemaEnv({schema, schemaId, root, baseId}) } return getJsonPointer.call(this, p, schOrRef) } const PREVENT_SCOPE_CHANGE = new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions", ]) function getJsonPointer( this: Ajv, parsedRef: URIComponent, {baseId, schema, root}: SchemaEnv ): SchemaEnv | undefined { if (parsedRef.fragment?.[0] !== "/") return for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return const partSchema = schema[unescapeFragment(part)] if (partSchema === undefined) return schema = partSchema // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? const schId = typeof schema === "object" && schema[this.opts.schemaId] if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = resolveUrl(this.opts.uriResolver, baseId, schId) } } let env: SchemaEnv | undefined if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) { const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref) env = resolveSchema.call(this, root, $ref) } // even though resolution failed we need to return SchemaEnv to throw exception // so that compileAsync loads missing schema. const {schemaId} = this.opts env = env || new SchemaEnv({schema, schemaId, root, baseId}) if (env.schema !== env.root.schema) return env return undefined } import type Ajv from "../../core" import type {SchemaObject} from "../../types" import {jtdForms, JTDForm, SchemaObjectMap} from "./types" import {SchemaEnv, getCompilingSchema} from ".." import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen" import MissingRefError from "../ref_error" import N from "../names" import {hasPropFunc} from "../../vocabularies/code" import {hasRef} from "../../vocabularies/jtd/ref" import {intRange, IntType} from "../../vocabularies/jtd/type" import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson" import {useFunc} from "../util" import validTimestamp from "../../runtime/timestamp" type GenParse = (cxt: ParseCxt) => void const genParse: {[F in JTDForm]: GenParse} = { elements: parseElements, values: parseValues, discriminator: parseDiscriminator, properties: parseProperties, optionalProperties: parseProperties, enum: parseEnum, type: parseType, ref: parseRef, } interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name } export default function compileParser( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) const parseName = gen.scopeName("parse") const cxt: ParseCxt = { self: this, gen, schema: sch.schema as SchemaObject, schemaEnv: sch, definitions, data: N.data, parseName, char: gen.name("c"), } let sourceCode: string | undefined try { this._compilations.add(sch) sch.parseName = parseName parserFunction(cxt) gen.optimize(this.opts.code.optimize) const parseFuncCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}` const makeParse = new Function(`${N.scope}`, sourceCode) const parse: (json: string) => unknown = makeParse(this.scope.get()) this.scope.value(parseName, {ref: parse}) sch.parse = parse } catch (e) { if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode) delete sch.parse delete sch.parseName throw e } finally { this._compilations.delete(sch) } return sch } const undef = _`undefined` function parserFunction(cxt: ParseCxt): void { const {gen, parseName, char} = cxt gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => { gen.let(N.data) gen.let(char) gen.assign(_`${parseName}.message`, undef) gen.assign(_`${parseName}.position`, undef) gen.assign(N.jsonPos, _`${N.jsonPos} || 0`) gen.const(N.jsonLen, _`${N.json}.length`) parseCode(cxt) skipWhitespace(cxt) gen.if(N.jsonPart, () => { gen.assign(_`${parseName}.position`, N.jsonPos) gen.return(N.data) }) gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data)) jsonSyntaxError(cxt) }) } function parseCode(cxt: ParseCxt): void { let form: JTDForm | undefined for (const key of jtdForms) { if (key in cxt.schema) { form = key break } } if (form) parseNullable(cxt, genParse[form]) else parseEmpty(cxt) } const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)) function parseNullable(cxt: ParseCxt, parseForm: GenParse): void { const {gen, schema, data} = cxt if (!schema.nullable) return parseForm(cxt) tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)) } function parseElements(cxt: ParseCxt): void { const {gen, schema, data} = cxt parseToken(cxt, "[") const ix = gen.let("i", 0) gen.assign(data, _`[]`) parseItems(cxt, "]", () => { const el = gen.let("el") parseCode({...cxt, schema: schema.elements, data: el}) gen.assign(_`${data}[${ix}++]`, el) }) } function parseValues(cxt: ParseCxt): void { const {gen, schema, data} = cxt parseToken(cxt, "{") gen.assign(data, _`{}`) parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)) } function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void { tryParseItems(cxt, endToken, block) parseToken(cxt, endToken) } function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void { const {gen} = cxt gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { block() tryParseToken(cxt, ",", () => gen.break(), hasItem) }) function hasItem(): void { tryParseToken(cxt, endToken, () => {}, jsonSyntaxError) } } function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void { const {gen} = cxt const key = gen.let("key") parseString({...cxt, data: key}) parseToken(cxt, ":") parsePropertyValue(cxt, key, schema) } function parseDiscriminator(cxt: ParseCxt): void { const {gen, data, schema} = cxt const {discriminator, mapping} = schema parseToken(cxt, "{") gen.assign(data, _`{}`) const startPos = gen.const("pos", N.jsonPos) const value = gen.let("value") const tag = gen.let("tag") tryParseItems(cxt, "}", () => { const key = gen.let("key") parseString({...cxt, data: key}) parseToken(cxt, ":") gen.if( _`${key} === ${discriminator}`, () => { parseString({...cxt, data: tag}) gen.assign(_`${data}[${key}]`, tag) gen.break() }, () => parseEmpty({...cxt, data: value}) // can be discarded/skipped ) }) gen.assign(N.jsonPos, startPos) gen.if(_`${tag} === undefined`) parsingError(cxt, str`discriminator tag not found`) for (const tagValue in mapping) { gen.elseIf(_`${tag} === ${tagValue}`) parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator) } gen.else() parsingError(cxt, str`discriminator value not in schema`) gen.endIf() } function parseProperties(cxt: ParseCxt): void { const {gen, data} = cxt parseToken(cxt, "{") gen.assign(data, _`{}`) parseSchemaProperties(cxt) } function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void { const {gen, schema, data} = cxt const {properties, optionalProperties, additionalProperties} = schema parseItems(cxt, "}", () => { const key = gen.let("key") parseString({...cxt, data: key}) parseToken(cxt, ":") gen.if(false) parseDefinedProperty(cxt, key, properties) parseDefinedProperty(cxt, key, optionalProperties) if (discriminator) { gen.elseIf(_`${key} === ${discriminator}`) const tag = gen.let("tag") parseString({...cxt, data: tag}) // can be discarded, it is already assigned } gen.else() if (additionalProperties) { parseEmpty({...cxt, data: _`${data}[${key}]`}) } else { parsingError(cxt, str`property ${key} not allowed`) } gen.endIf() }) if (properties) { const hasProp = hasPropFunc(gen) const allProps: Code = and( ...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`) ) gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`)) } } function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { const {gen} = cxt for (const prop in schemas) { gen.elseIf(_`${key} === ${prop}`) parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) } } function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`}) } function parseType(cxt: ParseCxt): void { const {gen, schema, data, self} = cxt switch (schema.type) { case "boolean": parseBoolean(cxt) break case "string": parseString(cxt) break case "timestamp": { parseString(cxt) const vts = useFunc(gen, validTimestamp) const {allowDate, parseDate} = self.opts const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})` const fail: Code = parseDate ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`) : notValid gen.if(fail, () => parsingError(cxt, str`invalid timestamp`)) break } case "float32": case "float64": parseNumber(cxt) break default: { const t = schema.type as IntType if (!self.opts.int32range && (t === "int32" || t === "uint32")) { parseNumber(cxt, 16) // 2 ** 53 - max safe integer if (t === "uint32") { gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`)) } } else { const [min, max, maxDigits] = intRange[t] parseNumber(cxt, maxDigits) gen.if(_`${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, str`integer out of range`) ) } } } } function parseString(cxt: ParseCxt): void { parseToken(cxt, '"') parseWith(cxt, parseJsonString) } function parseEnum(cxt: ParseCxt): void { const {gen, data, schema} = cxt const enumSch = schema.enum parseToken(cxt, '"') // TODO loopEnum gen.if(false) for (const value of enumSch) { const valueStr = JSON.stringify(value).slice(1) // remove starting quote gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`) gen.assign(data, str`${value}`) gen.add(N.jsonPos, valueStr.length) } gen.else() jsonSyntaxError(cxt) gen.endIf() } function parseNumber(cxt: ParseCxt, maxDigits?: number): void { const {gen} = cxt skipWhitespace(cxt) gen.if( _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJsonNumber, maxDigits) ) } function parseBooleanToken(bool: boolean, fail: GenParse): GenParse { return (cxt) => { const {gen, data} = cxt tryParseToken( cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool) ) } } function parseRef(cxt: ParseCxt): void { const {gen, self, definitions, schema, schemaEnv} = cxt const {ref} = schema const refSchema = definitions[ref] if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema}) const {root} = schemaEnv const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions) partialParse(cxt, getParser(gen, sch), true) } function getParser(gen: CodeGen, sch: SchemaEnv): Code { return sch.parse ? gen.scopeValue("parse", {ref: sch.parse}) : _`${gen.scopeValue("wrapper", {ref: sch})}.parse` } function parseEmpty(cxt: ParseCxt): void { parseWith(cxt, parseJson) } function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { partialParse(cxt, useFunc(cxt.gen, parseFunc), args) } function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { const {gen, data} = cxt gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) gen.assign(N.jsonPos, _`${parseFunc}.position`) gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) } function parseToken(cxt: ParseCxt, tok: string): void { tryParseToken(cxt, tok, jsonSyntaxError) } function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void { const {gen} = cxt const n = tok.length skipWhitespace(cxt) gen.if( _`${jsonSlice(n)} === ${tok}`, () => { gen.add(N.jsonPos, n) success?.(cxt) }, () => fail(cxt) ) } function skipWhitespace({gen, char: c}: ParseCxt): void { gen.code( _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;` ) } function jsonSlice(len: number | Name): Code { return len === 1 ? _`${N.json}[${N.jsonPos}]` : _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})` } function jsonSyntaxError(cxt: ParseCxt): void { parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`) } function parsingError({gen, parseName}: ParseCxt, msg: Code): void { gen.assign(_`${parseName}.message`, msg) gen.assign(_`${parseName}.position`, N.jsonPos) gen.return(undef) } import type Ajv from "../../core" import type {SchemaObject} from "../../types" import {jtdForms, JTDForm, SchemaObjectMap} from "./types" import {SchemaEnv, getCompilingSchema} from ".." import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen" import MissingRefError from "../ref_error" import N from "../names" import {isOwnProperty} from "../../vocabularies/code" import {hasRef} from "../../vocabularies/jtd/ref" import {useFunc} from "../util" import quote from "../../runtime/quote" const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = { elements: serializeElements, values: serializeValues, discriminator: serializeDiscriminator, properties: serializeProperties, optionalProperties: serializeProperties, enum: serializeString, type: serializeType, ref: serializeRef, } interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code } export default function compileSerializer( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) const serializeName = gen.scopeName("serialize") const cxt: SerializeCxt = { self: this, gen, schema: sch.schema as SchemaObject, schemaEnv: sch, definitions, data: N.data, } let sourceCode: string | undefined try { this._compilations.add(sch) sch.serializeName = serializeName gen.func(serializeName, N.data, false, () => { gen.let(N.json, str``) serializeCode(cxt) gen.return(N.json) }) gen.optimize(this.opts.code.optimize) const serializeFuncCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` const makeSerialize = new Function(`${N.scope}`, sourceCode) const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) this.scope.value(serializeName, {ref: serialize}) sch.serialize = serialize } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) delete sch.serialize delete sch.serializeName throw e } finally { this._compilations.delete(sch) } return sch } function serializeCode(cxt: SerializeCxt): void { let form: JTDForm | undefined for (const key of jtdForms) { if (key in cxt.schema) { form = key break } } serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty) } function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void { const {gen, schema, data} = cxt if (!schema.nullable) return serializeForm(cxt) gen.if( _`${data} === undefined || ${data} === null`, () => gen.add(N.json, _`"null"`), () => serializeForm(cxt) ) } function serializeElements(cxt: SerializeCxt): void { const {gen, schema, data} = cxt gen.add(N.json, str`[`) const first = gen.let("first", true) gen.forOf("el", data, (el) => { addComma(cxt, first) serializeCode({...cxt, schema: schema.elements, data: el}) }) gen.add(N.json, str`]`) } function serializeValues(cxt: SerializeCxt): void { const {gen, schema, data} = cxt gen.add(N.json, str`{`) const first = gen.let("first", true) gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)) gen.add(N.json, str`}`) } function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { const {gen, data} = cxt addComma(cxt, first) serializeString({...cxt, data: key}) gen.add(N.json, str`:`) const value = gen.const("value", _`${data}${getProperty(key)}`) serializeCode({...cxt, schema, data: value}) } function serializeDiscriminator(cxt: SerializeCxt): void { const {gen, schema, data} = cxt const {discriminator} = schema gen.add(N.json, str`{${JSON.stringify(discriminator)}:`) const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`) serializeString({...cxt, data: tag}) gen.if(false) for (const tagValue in schema.mapping) { gen.elseIf(_`${tag} === ${tagValue}`) const sch = schema.mapping[tagValue] serializeSchemaProperties({...cxt, schema: sch}, discriminator) } gen.endIf() gen.add(N.json, str`}`) } function serializeProperties(cxt: SerializeCxt): void { const {gen} = cxt gen.add(N.json, str`{`) serializeSchemaProperties(cxt) gen.add(N.json, str`}`) } function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void { const {gen, schema, data} = cxt const {properties, optionalProperties} = schema const props = keys(properties) const optProps = keys(optionalProperties) const allProps = allProperties(props.concat(optProps)) let first = !discriminator let firstProp: Name | undefined for (const key of props) { if (first) first = false else gen.add(N.json, str`,`) serializeProperty(key, properties[key], keyValue(key)) } if (first) firstProp = gen.let("first", true) for (const key of optProps) { const value = keyValue(key) gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => { addComma(cxt, firstProp) serializeProperty(key, optionalProperties[key], value) }) } if (schema.additionalProperties) { gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)) ) } function keys(ps?: SchemaObjectMap): string[] { return ps ? Object.keys(ps) : [] } function allProperties(ps: string[]): string[] { if (discriminator) ps.push(discriminator) if (new Set(ps).size !== ps.length) { throw new Error("JTD: properties/optionalProperties/disciminator overlap") } return ps } function keyValue(key: string): Name { return gen.const("value", _`${data}${getProperty(key)}`) } function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void { gen.add(N.json, str`${JSON.stringify(key)}:`) serializeCode({...cxt, schema: propSchema, data: value}) } function isAdditional(key: Name, ps: string[]): Code | true { return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true } } function serializeType(cxt: SerializeCxt): void { const {gen, schema, data} = cxt switch (schema.type) { case "boolean": gen.add(N.json, _`${data} ? "true" : "false"`) break case "string": serializeString(cxt) break case "timestamp": gen.if( _`${data} instanceof Date`, () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt) ) break default: serializeNumber(cxt) } } function serializeString({gen, data}: SerializeCxt): void { gen.add(N.json, _`${useFunc(gen, quote)}(${data})`) } function serializeNumber({gen, data, self}: SerializeCxt): void { const condition = _`${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}` if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") { gen.add(N.json, _`"" + ${data}`) } else { // specialNumbers === "null" gen.if( condition, () => gen.add(N.json, _`null`), () => gen.add(N.json, _`"" + ${data}`) ) } } function serializeRef(cxt: SerializeCxt): void { const {gen, self, data, definitions, schema, schemaEnv} = cxt const {ref} = schema const refSchema = definitions[ref] if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema}) const {root} = schemaEnv const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions) gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`) } function getSerialize(gen: CodeGen, sch: SchemaEnv): Code { return sch.serialize ? gen.scopeValue("serialize", {ref: sch.serialize}) : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize` } function serializeEmpty({gen, data}: SerializeCxt): void { gen.add(N.json, _`JSON.stringify(${data})`) } function addComma({gen}: SerializeCxt, first?: Name): void { if (first) { gen.if( first, () => gen.assign(first, false), () => gen.add(N.json, str`,`) ) } else { gen.add(N.json, str`,`) } } import type {SchemaObject} from "../../types" export type SchemaObjectMap = {[Ref in string]?: SchemaObject} export const jtdForms = [ "elements", "values", "discriminator", "properties", "optionalProperties", "enum", "type", "ref", ] as const export type JTDForm = (typeof jtdForms)[number] import {Name} from "./codegen" const names = { // validation function arguments data: new Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new Name("instancePath"), parentData: new Name("parentData"), parentDataProperty: new Name("parentDataProperty"), rootData: new Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new Name("vErrors"), // null or array of validation errors errors: new Name("errors"), // counter of validation errors this: new Name("this"), // "globals" self: new Name("self"), scope: new Name("scope"), // JTD serialize/parse name for JSON string and position json: new Name("json"), jsonPos: new Name("jsonPos"), jsonLen: new Name("jsonLen"), jsonPart: new Name("jsonPart"), } export default names import {resolveUrl, normalizeId, getFullPath} from "./resolve" import type {UriResolver} from "../types" export default class MissingRefError extends Error { readonly missingRef: string readonly missingSchema: string constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) { super(msg || `can't resolve reference ${ref} from id ${baseId}`) this.missingRef = resolveUrl(resolver, baseId, ref) this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef)) } } import type {AnySchema, AnySchemaObject, UriResolver} from "../types" import type Ajv from "../ajv" import type {URIComponent} from "fast-uri" import {eachItem} from "./util" import * as equal from "fast-deep-equal" import * as traverse from "json-schema-traverse" // the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution export type LocalRefs = {[Ref in string]?: AnySchemaObject} // TODO refactor to use keyword definitions const SIMPLE_INLINED = new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const", ]) export function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean { if (typeof schema == "boolean") return true if (limit === true) return !hasRef(schema) if (!limit) return false return countKeys(schema) <= limit } const REF_KEYWORDS = new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor", ]) function hasRef(schema: AnySchemaObject): boolean { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true const sch = schema[key] if (Array.isArray(sch) && sch.some(hasRef)) return true if (typeof sch == "object" && hasRef(sch)) return true } return false } function countKeys(schema: AnySchemaObject): number { let count = 0 for (const key in schema) { if (key === "$ref") return Infinity count++ if (SIMPLE_INLINED.has(key)) continue if (typeof schema[key] == "object") { eachItem(schema[key], (sch) => (count += countKeys(sch))) } if (count === Infinity) return Infinity } return count } export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string { if (normalize !== false) id = normalizeId(id) const p = resolver.parse(id) return _getFullPath(resolver, p) } export function _getFullPath(resolver: UriResolver, p: URIComponent): string { const serialized = resolver.serialize(p) return serialized.split("#")[0] + "#" } const TRAILING_SLASH_HASH = /#\/?$/ export function normalizeId(id: string | undefined): string { return id ? id.replace(TRAILING_SLASH_HASH, "") : "" } export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string { id = normalizeId(id) return resolver.resolve(baseId, id) } const ANCHOR = /^[a-z_][-a-z0-9._]*$/i export function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs { if (typeof schema == "boolean") return {} const {schemaId, uriResolver} = this.opts const schId = normalizeId(schema[schemaId] || baseId) const baseIds: {[JsonPtr in string]?: string} = {"": schId} const pathPrefix = getFullPath(uriResolver, schId, false) const localRefs: LocalRefs = {} const schemaRefs: Set = new Set() traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === undefined) return const fullPath = pathPrefix + jsonPtr let innerBaseId = baseIds[parentJsonPtr] if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]) addAnchor.call(this, sch.$anchor) addAnchor.call(this, sch.$dynamicAnchor) baseIds[jsonPtr] = innerBaseId function addRef(this: Ajv, ref: string): string { // eslint-disable-next-line @typescript-eslint/unbound-method const _resolve = this.opts.uriResolver.resolve ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref) if (schemaRefs.has(ref)) throw ambiguos(ref) schemaRefs.add(ref) let schOrRef = this.refs[ref] if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef] if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref) } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref) localRefs[ref] = sch } else { this.refs[ref] = fullPath } } return ref } function addAnchor(this: Ajv, anchor: unknown): void { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`) addRef.call(this, `#${anchor}`) } } }) return localRefs function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void { if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref) } function ambiguos(ref: string): Error { return new Error(`reference "${ref}" resolves to more than one schema`) } } import type {AddedKeywordDefinition} from "../types" const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const export type JSONType = (typeof _jsonTypes)[number] const jsonTypes: Set = new Set(_jsonTypes) export function isJSONType(x: unknown): x is JSONType { return typeof x == "string" && jsonTypes.has(x) } type ValidationTypes = { [K in JSONType]: boolean | RuleGroup | undefined } export interface ValidationRules { rules: RuleGroup[] post: RuleGroup all: {[Key in string]?: boolean | Rule} // rules that have to be validated keywords: {[Key in string]?: boolean} // all known keywords (superset of "all") types: ValidationTypes } export interface RuleGroup { type?: JSONType rules: Rule[] } // This interface wraps KeywordDefinition because definition can have multiple keywords export interface Rule { keyword: string definition: AddedKeywordDefinition } export function getRules(): ValidationRules { const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = { number: {type: "number", rules: []}, string: {type: "string", rules: []}, array: {type: "array", rules: []}, object: {type: "object", rules: []}, } return { types: {...groups, integer: true, boolean: true, null: true}, rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object], post: {rules: []}, all: {}, keywords: {}, } } import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types" import type {SchemaCxt, SchemaObjCxt} from "." import {_, getProperty, Code, Name, CodeGen} from "./codegen" import {_Code} from "./codegen/code" import type {Rule, ValidationRules} from "./rules" // TODO refactor to use Set export function toHash(arr: T[]): {[K in T]?: true} { const hash: {[K in T]?: true} = {} for (const item of arr) hash[item] = true return hash } export function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void { if (typeof schema == "boolean") return schema if (Object.keys(schema).length === 0) return true checkUnknownRules(it, schema) return !schemaHasRules(schema, it.self.RULES.all) } export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void { const {opts, self} = it if (!opts.strictSchema) return if (typeof schema === "boolean") return const rules = self.RULES.keywords for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`) } } export function schemaHasRules( schema: AnySchema, rules: {[Key in string]?: boolean | Rule} ): boolean { if (typeof schema == "boolean") return !schema for (const key in schema) if (rules[key]) return true return false } export function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean { if (typeof schema == "boolean") return !schema for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true return false } export function schemaRefOrVal( {topSchemaRef, schemaPath}: SchemaObjCxt, schema: unknown, keyword: string, $data?: string | false ): Code | number | boolean { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema if (typeof schema == "string") return _`${schema}` } return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}` } export function unescapeFragment(str: string): string { return unescapeJsonPointer(decodeURIComponent(str)) } export function escapeFragment(str: string | number): string { return encodeURIComponent(escapeJsonPointer(str)) } export function escapeJsonPointer(str: string | number): string { if (typeof str == "number") return `${str}` return str.replace(/~/g, "~0").replace(/\//g, "~1") } export function unescapeJsonPointer(str: string): string { return str.replace(/~1/g, "/").replace(/~0/g, "~") } export function eachItem(xs: T | T[], f: (x: T) => void): void { if (Array.isArray(xs)) { for (const x of xs) f(x) } else { f(xs) } } type SomeEvaluated = EvaluatedProperties | EvaluatedItems type MergeEvaluatedFunc = ( gen: CodeGen, from: Name | T, to: Name | Exclude | undefined, toName?: typeof Name ) => Name | T interface MakeMergeFuncArgs { mergeNames: (gen: CodeGen, from: Name, to: Name) => void mergeToName: (gen: CodeGen, from: T, to: Name) => void mergeValues: (from: T, to: Exclude) => T resultToName: (gen: CodeGen, res?: T) => Name } function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }: MakeMergeFuncArgs): MergeEvaluatedFunc { return (gen, from, to, toName) => { const res = to === undefined ? from : to instanceof Name ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to) return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res } } interface MergeEvaluated { props: MergeEvaluatedFunc items: MergeEvaluatedFunc } export const mergeEvaluated: MergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if(_`${to} !== true && ${from} !== undefined`, () => { gen.if( _`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`) ) }), mergeToName: (gen, from, to) => gen.if(_`${to} !== true`, () => { if (from === true) { gen.assign(to, true) } else { gen.assign(to, _`${to} || {}`) setEvaluated(gen, to, from) } }), mergeValues: (from, to) => (from === true ? true : {...from, ...to}), resultToName: evaluatedPropsToName, }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if(_`${to} !== true && ${from} !== undefined`, () => gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`) ), mergeToName: (gen, from, to) => gen.if(_`${to} !== true`, () => gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`) ), mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), resultToName: (gen, items) => gen.var("items", items), }), } export function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name { if (ps === true) return gen.var("props", true) const props = gen.var("props", _`{}`) if (ps !== undefined) setEvaluated(gen, props, ps) return props } export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void { Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true)) } const snippets: {[S in string]?: _Code} = {} export function useFunc(gen: CodeGen, f: {code: string}): Name { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)), }) } export enum Type { Num, Str, } export function getErrorPath( dataProp: Name | string | number, dataPropType?: Type, jsPropertySyntax?: boolean ): Code | string { // let path if (dataProp instanceof Name) { const isNumber = dataPropType === Type.Num return jsPropertySyntax ? isNumber ? _`"[" + ${dataProp} + "]"` : _`"['" + ${dataProp} + "']"` : isNumber ? _`"/" + ${dataProp}` : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer } return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp) } export function checkStrictMode( it: SchemaCxt, msg: string, mode: boolean | "log" = it.opts.strictSchema ): void { if (!mode) return msg = `strict mode: ${msg}` if (mode === true) throw new Error(msg) it.self.logger.warn(msg) } import type {AnySchemaObject} from "../../types" import type {SchemaObjCxt} from ".." import type {JSONType, RuleGroup, Rule} from "../rules" export function schemaHasRulesForType( {schema, self}: SchemaObjCxt, type: JSONType ): boolean | undefined { const group = self.RULES.types[type] return group && group !== true && shouldUseGroup(schema, group) } export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean { return group.rules.some((rule) => shouldUseRule(schema, rule)) } export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined { return ( schema[rule.keyword] !== undefined || rule.definition.implements?.some((kwd) => schema[kwd] !== undefined) ) } import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types" import type {SchemaCxt} from ".." import {reportError} from "../errors" import {_, Name} from "../codegen" import N from "../names" const boolError: KeywordErrorDefinition = { message: "boolean schema is false", } export function topBoolOrEmptySchema(it: SchemaCxt): void { const {gen, schema, validateName} = it if (schema === false) { falseSchemaError(it, false) } else if (typeof schema == "object" && schema.$async === true) { gen.return(N.data) } else { gen.assign(_`${validateName}.errors`, null) gen.return(true) } } export function boolOrEmptySchema(it: SchemaCxt, valid: Name): void { const {gen, schema} = it if (schema === false) { gen.var(valid, false) // TODO var falseSchemaError(it) } else { gen.var(valid, true) // TODO var } } function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void { const {gen, data} = it // TODO maybe some other interface should be used for non-keyword validation errors... const cxt: KeywordErrorCxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it, } reportError(cxt, boolError, undefined, overrideAllErrors) } import type { KeywordErrorDefinition, KeywordErrorCxt, ErrorObject, AnySchemaObject, } from "../../types" import type {SchemaObjCxt} from ".." import {isJSONType, JSONType} from "../rules" import {schemaHasRulesForType} from "./applicability" import {reportError} from "../errors" import {_, nil, and, not, operators, Code, Name} from "../codegen" import {toHash, schemaRefOrVal} from "../util" export enum DataType { Correct, Wrong, } export function getSchemaTypes(schema: AnySchemaObject): JSONType[] { const types = getJSONTypes(schema.type) const hasNull = types.includes("null") if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false") } else { if (!types.length && schema.nullable !== undefined) { throw new Error('"nullable" cannot be used without "type"') } if (schema.nullable === true) types.push("null") } return types } // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents export function getJSONTypes(ts: unknown | unknown[]): JSONType[] { const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : [] if (types.every(isJSONType)) return types throw new Error("type must be JSONType or JSONType[]: " + types.join(",")) } export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean { const {gen, data, opts} = it const coerceTo = coerceToTypes(types, opts.coerceTypes) const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0])) if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong) gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo) else reportTypeError(it) }) } return checkTypes } const COERCIBLE: Set = new Set(["string", "number", "integer", "boolean", "null"]) function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) : [] } function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void { const {gen, data, opts} = it const dataType = gen.let("dataType", _`typeof ${data}`) const coerced = gen.let("coerced", _`undefined`) if (opts.coerceTypes === "array") { gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen .assign(data, _`${data}[0]`) .assign(dataType, _`typeof ${data}`) .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)) ) } gen.if(_`${coerced} !== undefined`) for (const t of coerceTo) { if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { coerceSpecificType(t) } } gen.else() reportTypeError(it) gen.endIf() gen.if(_`${coerced} !== undefined`, () => { gen.assign(data, coerced) assignParentData(it, coerced) }) function coerceSpecificType(t: string): void { switch (t) { case "string": gen .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`) .assign(coerced, _`"" + ${data}`) .elseIf(_`${data} === null`) .assign(coerced, _`""`) return case "number": gen .elseIf( _`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})` ) .assign(coerced, _`+${data}`) return case "integer": gen .elseIf( _`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))` ) .assign(coerced, _`+${data}`) return case "boolean": gen .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`) .assign(coerced, false) .elseIf(_`${data} === "true" || ${data} === 1`) .assign(coerced, true) return case "null": gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`) gen.assign(coerced, null) return case "array": gen .elseIf( _`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null` ) .assign(coerced, _`[${data}]`) } } } function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void { // TODO use gen.property gen.if(_`${parentData} !== undefined`, () => gen.assign(_`${parentData}[${parentDataProperty}]`, expr) ) } export function checkDataType( dataType: JSONType, data: Name, strictNums?: boolean | "log", correct = DataType.Correct ): Code { const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ let cond: Code switch (dataType) { case "null": return _`${data} ${EQ} null` case "array": cond = _`Array.isArray(${data})` break case "object": cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})` break case "integer": cond = numCond(_`!(${data} % 1) && !isNaN(${data})`) break case "number": cond = numCond() break default: return _`typeof ${data} ${EQ} ${dataType}` } return correct === DataType.Correct ? cond : not(cond) function numCond(_cond: Code = nil): Code { return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil) } } export function checkDataTypes( dataTypes: JSONType[], data: Name, strictNums?: boolean | "log", correct?: DataType ): Code { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct) } let cond: Code const types = toHash(dataTypes) if (types.array && types.object) { const notObj = _`typeof ${data} != "object"` cond = types.null ? notObj : _`!${data} || ${notObj}` delete types.null delete types.array delete types.object } else { cond = nil } if (types.number) delete types.integer for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct)) return cond } export type TypeError = ErrorObject<"type", {type: string}> const typeError: KeywordErrorDefinition = { message: ({schema}) => `must be ${schema}`, params: ({schema, schemaValue}) => typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`, } export function reportTypeError(it: SchemaObjCxt): void { const cxt = getTypeErrorContext(it) reportError(cxt, typeError) } function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt { const {gen, data, schema} = it const schemaCode = schemaRefOrVal(it, schema, "type") return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it, } } import type {SchemaObjCxt} from ".." import {_, getProperty, stringify} from "../codegen" import {checkStrictMode} from "../util" export function assignDefaults(it: SchemaObjCxt, ty?: string): void { const {properties, items} = it.schema if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default) } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i: number) => assignDefault(it, i, sch.default)) } } function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void { const {gen, compositeRule, data, opts} = it if (defaultValue === undefined) return const childData = _`${data}${getProperty(prop)}` if (compositeRule) { checkStrictMode(it, `default is ignored for: ${childData}`) return } let condition = _`${childData} === undefined` if (opts.useDefaults === "empty") { condition = _`${condition} || ${childData} === null || ${childData} === ""` } // `${childData} === undefined` + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") gen.if(condition, _`${childData} = ${stringify(defaultValue)}`) } import type { AddedKeywordDefinition, AnySchema, AnySchemaObject, KeywordErrorCxt, KeywordCxtParams, } from "../../types" import type {SchemaCxt, SchemaObjCxt} from ".." import type {InstanceOptions} from "../../core" import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema" import {coerceAndCheckDataType, getSchemaTypes} from "./dataType" import {shouldUseGroup, shouldUseRule} from "./applicability" import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType" import {assignDefaults} from "./defaults" import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword" import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema" import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen" import N from "../names" import {resolveUrl} from "../resolve" import { schemaRefOrVal, schemaHasRulesButRef, checkUnknownRules, checkStrictMode, unescapeJsonPointer, mergeEvaluated, } from "../util" import type {JSONType, Rule, RuleGroup} from "../rules" import { ErrorPaths, reportError, reportExtraError, resetErrorsCount, keyword$DataError, } from "../errors" // schema compilation - generates validation function, subschemaCode (below) is used for subschemas export function validateFunctionCode(it: SchemaCxt): void { if (isSchemaObj(it)) { checkKeywords(it) if (schemaCxtHasRules(it)) { topSchemaObjCode(it) return } } validateFunction(it, () => topBoolOrEmptySchema(it)) } function validateFunction( {gen, validateName, schema, schemaEnv, opts}: SchemaCxt, body: Block ): void { if (opts.code.es5) { gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => { gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`) destructureValCxtES5(gen, opts) gen.code(body) }) } else { gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body) ) } } function destructureValCxt(opts: InstanceOptions): Code { return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${ N.data }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}` } function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void { gen.if( N.valCxt, () => { gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`) gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`) gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`) gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`) if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`) }, () => { gen.var(N.instancePath, _`""`) gen.var(N.parentData, _`undefined`) gen.var(N.parentDataProperty, _`undefined`) gen.var(N.rootData, N.data) if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`) } ) } function topSchemaObjCode(it: SchemaObjCxt): void { const {schema, opts, gen} = it validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it) checkNoDefault(it) gen.let(N.vErrors, null) gen.let(N.errors, 0) if (opts.unevaluated) resetEvaluated(it) typeAndKeywords(it) returnResults(it) }) return } function resetEvaluated(it: SchemaObjCxt): void { // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated const {gen, validateName} = it it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`) gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`)) gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`)) } function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code { const schId = typeof schema == "object" && schema[opts.schemaId] return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil } // schema compilation - this function is used recursively to generate code for sub-schemas function subschemaCode(it: SchemaCxt, valid: Name): void { if (isSchemaObj(it)) { checkKeywords(it) if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid) return } } boolOrEmptySchema(it, valid) } function schemaCxtHasRules({schema, self}: SchemaCxt): boolean { if (typeof schema == "boolean") return !schema for (const key in schema) if (self.RULES.all[key]) return true return false } function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt { return typeof it.schema != "boolean" } function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void { const {schema, gen, opts} = it if (opts.$comment && schema.$comment) commentKeyword(it) updateContext(it) checkAsyncSchema(it) const errsCount = gen.const("_errs", N.errors) typeAndKeywords(it, errsCount) // TODO var gen.var(valid, _`${errsCount} === ${N.errors}`) } function checkKeywords(it: SchemaObjCxt): void { checkUnknownRules(it) checkRefsAndKeywords(it) } function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount) const types = getSchemaTypes(it.schema) const checkedTypes = coerceAndCheckDataType(it, types) schemaKeywords(it, types, !checkedTypes, errsCount) } function checkRefsAndKeywords(it: SchemaObjCxt): void { const {schema, errSchemaPath, opts, self} = it if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`) } } function checkNoDefault(it: SchemaObjCxt): void { const {schema, opts} = it if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { checkStrictMode(it, "default is ignored in the schema root") } } function updateContext(it: SchemaObjCxt): void { const schId = it.schema[it.opts.schemaId] if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId) } function checkAsyncSchema(it: SchemaObjCxt): void { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema") } function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void { const msg = schema.$comment if (opts.$comment === true) { gen.code(_`${N.self}.logger.log(${msg})`) } else if (typeof opts.$comment == "function") { const schemaPath = str`${errSchemaPath}/$comment` const rootName = gen.scopeValue("root", {ref: schemaEnv.root}) gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`) } } function returnResults(it: SchemaCxt): void { const {gen, schemaEnv, validateName, ValidationError, opts} = it if (schemaEnv.$async) { // TODO assign unevaluated gen.if( _`${N.errors} === 0`, () => gen.return(N.data), () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`) ) } else { gen.assign(_`${validateName}.errors`, N.vErrors) if (opts.unevaluated) assignEvaluated(it) gen.return(_`${N.errors} === 0`) } } function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void { if (props instanceof Name) gen.assign(_`${evaluated}.props`, props) if (items instanceof Name) gen.assign(_`${evaluated}.items`, items) } function schemaKeywords( it: SchemaObjCxt, types: JSONType[], typeErrors: boolean, errsCount?: Name ): void { const {gen, schema, data, allErrors, opts, self} = it const {RULES} = self if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast return } if (!opts.jtd) checkStrictTypes(it, types) gen.block(() => { for (const group of RULES.rules) groupKeywords(group) groupKeywords(RULES.post) }) function groupKeywords(group: RuleGroup): void { if (!shouldUseGroup(schema, group)) return if (group.type) { gen.if(checkDataType(group.type, data, opts.strictNumbers)) iterateKeywords(it, group) if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else() reportTypeError(it) } gen.endIf() } else { iterateKeywords(it, group) } // TODO make it "ok" call? if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`) } } function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { const { gen, schema, opts: {useDefaults}, } = it if (useDefaults) assignDefaults(it, group.type) gen.block(() => { for (const rule of group.rules) { if (shouldUseRule(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type) } } }) } function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void { if (it.schemaEnv.meta || !it.opts.strictTypes) return checkContextTypes(it, types) if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types) checkKeywordTypes(it, it.dataTypes) } function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void { if (!types.length) return if (!it.dataTypes.length) { it.dataTypes = types return } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`) } }) narrowSchemaTypes(it, types) } function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword") } } function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void { const rules = it.self.RULES.all for (const keyword in rules) { const rule = rules[keyword] if (typeof rule == "object" && shouldUseRule(it.schema, rule)) { const {type} = rule.definition if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`) } } } } function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean { return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")) } function includesType(ts: JSONType[], t: JSONType): boolean { return ts.includes(t) || (t === "integer" && ts.includes("number")) } function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void { const ts: JSONType[] = [] for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t) else if (withTypes.includes("integer") && t === "number") ts.push("integer") } it.dataTypes = ts } function strictTypesError(it: SchemaObjCxt, msg: string): void { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath msg += ` at "${schemaPath}" (strictTypes)` checkStrictMode(it, msg, it.opts.strictTypes) } export class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } } function keywordCode( it: SchemaObjCxt, keyword: string, def: AddedKeywordDefinition, ruleType?: JSONType ): void { const cxt = new KeywordCxt(it, def, keyword) if ("code" in def) { def.code(cxt, ruleType) } else if (cxt.$data && def.validate) { funcKeywordCode(cxt, def) } else if ("macro" in def) { macroKeywordCode(cxt, def) } else if (def.compile || def.validate) { funcKeywordCode(cxt, def) } } const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/ const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/ export function getData( $data: string, {dataLevel, dataNames, dataPathArr}: SchemaCxt ): Code | number { let jsonPointer let data: Code if ($data === "") return N.rootData if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`) jsonPointer = $data data = N.rootData } else { const matches = RELATIVE_JSON_POINTER.exec($data) if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`) const up: number = +matches[1] jsonPointer = matches[2] if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)) return dataPathArr[dataLevel - up] } if (up > dataLevel) throw new Error(errorMsg("data", up)) data = dataNames[dataLevel - up] if (!jsonPointer) return data } let expr = data const segments = jsonPointer.split("/") for (const segment of segments) { if (segment) { data = _`${data}${getProperty(unescapeJsonPointer(segment))}` expr = _`${expr} && ${data}` } } return expr function errorMsg(pointerType: string, up: number): string { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}` } } import type {KeywordCxt} from "." import type { AnySchema, SchemaValidateFunction, AnyValidateFunction, AddedKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, } from "../../types" import type {SchemaObjCxt} from ".." import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen" import N from "../names" import type {JSONType} from "../rules" import {callValidateCode} from "../../vocabularies/code" import {extendErrors} from "../errors" type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void { const {gen, keyword, schema, parentSchema, it} = cxt const macroSchema = def.macro.call(it.self, schema, parentSchema, it) const schemaRef = useKeyword(gen, keyword, macroSchema) if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true) const valid = gen.name("valid") cxt.subschema( { schema: macroSchema, schemaPath: nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true, }, valid ) cxt.pass(valid, () => cxt.error(true)) } export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void { const {gen, keyword, schema, parentSchema, $data, it} = cxt checkAsyncKeyword(it, def) const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate const validateRef = useKeyword(gen, keyword, validate) const valid = gen.let("valid") cxt.block$data(valid, validateKeyword) cxt.ok(def.valid ?? valid) function validateKeyword(): void { if (def.errors === false) { assignValid() if (def.modifying) modifyData(cxt) reportErrs(() => cxt.error()) } else { const ruleErrs = def.async ? validateAsync() : validateSync() if (def.modifying) modifyData(cxt) reportErrs(() => addErrs(cxt, ruleErrs)) } } function validateAsync(): Name { const ruleErrs = gen.let("ruleErrs", null) gen.try( () => assignValid(_`await `), (e) => gen.assign(valid, false).if( _`${e} instanceof ${it.ValidationError as Name}`, () => gen.assign(ruleErrs, _`${e}.errors`), () => gen.throw(e) ) ) return ruleErrs } function validateSync(): Code { const validateErrs = _`${validateRef}.errors` gen.assign(validateErrs, null) assignValid(nil) return validateErrs } function assignValid(_await: Code = def.async ? _`await ` : nil): void { const passCxt = it.opts.passContext ? N.this : N.self const passSchema = !(("compile" in def && !$data) || def.schema === false) gen.assign( valid, _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`, def.modifying ) } function reportErrs(errors: () => void): void { gen.if(not(def.valid ?? valid), errors) } } function modifyData(cxt: KeywordCxt): void { const {gen, data, it} = cxt gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`)) } function addErrs(cxt: KeywordCxt, errs: Code): void { const {gen} = cxt gen.if( _`Array.isArray(${errs})`, () => { gen .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) .assign(N.errors, _`${N.vErrors}.length`) extendErrors(cxt) }, () => cxt.error() ) } function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema") } function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name { if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`) return gen.scopeValue( "keyword", typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)} ) } export function validSchemaType( schema: unknown, schemaType: JSONType[], allowUndefined = false ): boolean { // TODO add tests return ( !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || (allowUndefined && typeof schema == "undefined") ) ) } export function validateKeywordUsage( {schema, opts, self, errSchemaPath}: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string ): void { /* istanbul ignore if */ if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error") } const deps = def.dependencies if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`) } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]) if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors) if (opts.validateSchema === "log") self.logger.error(msg) else throw new Error(msg) } } } import type {AnySchema} from "../../types" import type {SchemaObjCxt} from ".." import {_, str, getProperty, Code, Name} from "../codegen" import {escapeFragment, getErrorPath, Type} from "../util" import type {JSONType} from "../rules" export interface SubschemaContext { // TODO use Optional? align with SchemCxt property types schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef?: Code errorPath?: Code dataLevel?: number dataTypes?: JSONType[] data?: Name parentData?: Name parentDataProperty?: Code | number dataNames?: Name[] dataPathArr?: (Code | number)[] propertyName?: Name jtdDiscriminator?: string jtdMetadata?: boolean compositeRule?: true createErrors?: boolean allErrors?: boolean } export type SubschemaArgs = Partial<{ keyword: string schemaProp: string | number schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef: Code data: Name | Code dataProp: Code | string | number dataTypes: JSONType[] definedProperties: Set propertyName: Name dataPropType: Type jtdDiscriminator: string jtdMetadata: boolean compositeRule: true createErrors: boolean allErrors: boolean }> export function getSubschema( it: SchemaObjCxt, {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs ): SubschemaContext { if (keyword !== undefined && schema !== undefined) { throw new Error('both "keyword" and "schema" passed, only one allowed') } if (keyword !== undefined) { const sch = it.schema[keyword] return schemaProp === undefined ? { schema: sch, schemaPath: _`${it.schemaPath}${getProperty(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}`, } : { schema: sch[schemaProp], schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`, } } if (schema !== undefined) { if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"') } return { schema, schemaPath, topSchemaRef, errSchemaPath, } } throw new Error('either "keyword" or "schema" must be passed') } export function extendSubschemaData( subschema: SubschemaContext, it: SchemaObjCxt, {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs ): void { if (data !== undefined && dataProp !== undefined) { throw new Error('both "data" and "dataProp" passed, only one allowed') } const {gen} = it if (dataProp !== undefined) { const {errorPath, dataPathArr, opts} = it const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true) dataContextProps(nextData) subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}` subschema.parentDataProperty = _`${dataProp}` subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty] } if (data !== undefined) { const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once? dataContextProps(nextData) if (propertyName !== undefined) subschema.propertyName = propertyName // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr } if (dataTypes) subschema.dataTypes = dataTypes function dataContextProps(_nextData: Name): void { subschema.data = _nextData subschema.dataLevel = it.dataLevel + 1 subschema.dataTypes = [] it.definedProperties = new Set() subschema.parentData = it.data subschema.dataNames = [...it.dataNames, _nextData] } } export function extendSubschemaMode( subschema: SubschemaContext, {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs ): void { if (compositeRule !== undefined) subschema.compositeRule = compositeRule if (createErrors !== undefined) subschema.createErrors = createErrors if (allErrors !== undefined) subschema.allErrors = allErrors subschema.jtdDiscriminator = jtdDiscriminator // not inherited subschema.jtdMetadata = jtdMetadata // not inherited } export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, AnyValidateFunction, ErrorObject, ErrorNoParams, } from "./types" export {SchemaCxt, SchemaObjCxt} from "./compile" export interface Plugin { (ajv: Ajv, options?: Opts): Ajv [prop: string]: any } export {KeywordCxt} from "./compile/validate" export {DefinedError} from "./vocabularies/errors" export {JSONType} from "./compile/rules" export {JSONSchemaType} from "./types/json-schema" export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" import type { Schema, AnySchema, AnySchemaObject, SchemaObject, AsyncSchema, Vocabulary, KeywordDefinition, AddedKeywordDefinition, AnyValidateFunction, ValidateFunction, AsyncValidateFunction, ErrorObject, Format, AddedFormat, RegExpEngine, UriResolver, } from "./types" import type {JSONSchemaType} from "./types/json-schema" import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" import ValidationError from "./runtime/validation_error" import MissingRefError from "./compile/ref_error" import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules" import {SchemaEnv, compileSchema, resolveSchema} from "./compile" import {Code, ValueScope} from "./compile/codegen" import {normalizeId, getSchemaRefs} from "./compile/resolve" import {getJSONTypes} from "./compile/validate/dataType" import {eachItem} from "./compile/util" import * as $dataRefSchema from "./refs/data.json" import DefaultUriResolver from "./runtime/uri" const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags) defaultRegExp.code = "new RegExp" const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"] const EXT_SCOPE_NAMES = new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error", ]) export type Options = CurrentOptions & DeprecatedOptions export interface CurrentOptions { // strict mode options (NEW) strict?: boolean | "log" strictSchema?: boolean | "log" strictNumbers?: boolean | "log" strictTypes?: boolean | "log" strictTuples?: boolean | "log" strictRequired?: boolean | "log" allowMatchingProperties?: boolean // disables a strict mode restriction allowUnionTypes?: boolean validateFormats?: boolean // validation and reporting options: $data?: boolean allErrors?: boolean verbose?: boolean discriminator?: boolean unicodeRegExp?: boolean timestamp?: "string" | "date" // JTD only parseDate?: boolean // JTD only allowDate?: boolean // JTD only specialNumbers?: "fast" | "null" // JTD only $comment?: | true | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown) formats?: {[Name in string]?: Format} keywords?: Vocabulary schemas?: AnySchema[] | {[Key in string]?: AnySchema} logger?: Logger | false loadSchema?: (uri: string) => Promise // options to modify validated data: removeAdditional?: boolean | "all" | "failing" useDefaults?: boolean | "empty" coerceTypes?: boolean | "array" // advanced options: next?: boolean // NEW unevaluated?: boolean // NEW dynamicRef?: boolean // NEW schemaId?: "id" | "$id" jtd?: boolean // NEW meta?: SchemaObject | boolean defaultMeta?: string | AnySchemaObject validateSchema?: boolean | "log" addUsedSchema?: boolean inlineRefs?: boolean | number passContext?: boolean loopRequired?: number loopEnum?: number // NEW ownProperties?: boolean multipleOfPrecision?: number int32range?: boolean // JTD only messages?: boolean code?: CodeOptions // NEW uriResolver?: UriResolver } export interface CodeOptions { es5?: boolean esm?: boolean lines?: boolean optimize?: boolean | number formats?: Code // code to require (or construct) map of available formats - for standalone code source?: boolean process?: (code: string, schema?: SchemaEnv) => string regExp?: RegExpEngine } interface InstanceCodeOptions extends CodeOptions { regExp: RegExpEngine optimize: number } interface DeprecatedOptions { /** @deprecated */ ignoreKeywordsWithRef?: boolean /** @deprecated */ jsPropertySyntax?: boolean // added instead of jsonPointers /** @deprecated */ unicode?: boolean } interface RemovedOptions { format?: boolean errorDataPath?: "object" | "property" nullable?: boolean // "nullable" keyword is supported by default jsonPointers?: boolean extendRefs?: true | "ignore" | "fail" missingRefs?: true | "ignore" | "fail" processCode?: (code: string, schema?: SchemaEnv) => string sourceCode?: boolean strictDefaults?: boolean strictKeywords?: boolean uniqueItems?: boolean unknownFormats?: true | string[] | "ignore" cache?: any serialize?: (schema: AnySchema) => unknown ajvErrors?: boolean } type OptionsInfo = { [K in keyof T]-?: string | undefined } const removedOptions: OptionsInfo = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now.", } const deprecatedOptions: OptionsInfo = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.', } type RequiredInstanceOptions = { [K in | "strictSchema" | "strictNumbers" | "strictTypes" | "strictTuples" | "strictRequired" | "inlineRefs" | "loopRequired" | "loopEnum" | "meta" | "messages" | "schemaId" | "addUsedSchema" | "validateSchema" | "validateFormats" | "int32range" | "unicodeRegExp" | "uriResolver"]: NonNullable } & {code: InstanceCodeOptions} export type InstanceOptions = Options & RequiredInstanceOptions const MAX_EXPRESSION = 200 // eslint-disable-next-line complexity function requiredOptions(o: Options): RequiredInstanceOptions { const s = o.strict const _optz = o.code?.optimize const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0 const regExp = o.code?.regExp ?? defaultRegExp const uriResolver = o.uriResolver ?? DefaultUriResolver return { strictSchema: o.strictSchema ?? s ?? true, strictNumbers: o.strictNumbers ?? s ?? true, strictTypes: o.strictTypes ?? s ?? "log", strictTuples: o.strictTuples ?? s ?? "log", strictRequired: o.strictRequired ?? s ?? false, code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp}, loopRequired: o.loopRequired ?? MAX_EXPRESSION, loopEnum: o.loopEnum ?? MAX_EXPRESSION, meta: o.meta ?? true, messages: o.messages ?? true, inlineRefs: o.inlineRefs ?? true, schemaId: o.schemaId ?? "$id", addUsedSchema: o.addUsedSchema ?? true, validateSchema: o.validateSchema ?? true, validateFormats: o.validateFormats ?? true, unicodeRegExp: o.unicodeRegExp ?? true, int32range: o.int32range ?? true, uriResolver: uriResolver, } } export interface Logger { log(...args: unknown[]): unknown warn(...args: unknown[]): unknown error(...args: unknown[]): unknown } export default class Ajv { opts: InstanceOptions errors?: ErrorObject[] | null // errors from the last validation logger: Logger // shared external scope values for compiled functions readonly scope: ValueScope readonly schemas: {[Key in string]?: SchemaEnv} = {} readonly refs: {[Ref in string]?: SchemaEnv | string} = {} readonly formats: {[Name in string]?: AddedFormat} = Object.create(null) readonly RULES: ValidationRules readonly _compilations: Set = new Set() private readonly _loading: {[Ref in string]?: Promise} = {} private readonly _cache: Map = new Map() private readonly _metaOpts: InstanceOptions static ValidationError = ValidationError static MissingRefError = MissingRefError constructor(opts: Options = {}) { opts = this.opts = {...opts, ...requiredOptions(opts)} const {es5, lines} = this.opts.code this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines}) this.logger = getLogger(opts.logger) const formatOpt = opts.validateFormats opts.validateFormats = false this.RULES = getRules() checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED") checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn") this._metaOpts = getMetaSchemaOptions.call(this) if (opts.formats) addInitialFormats.call(this) this._addVocabularies() this._addDefaultMetaSchema() if (opts.keywords) addInitialKeywords.call(this, opts.keywords) if (typeof opts.meta == "object") this.addMetaSchema(opts.meta) addInitialSchemas.call(this) opts.validateFormats = formatOpt } _addVocabularies(): void { this.addKeyword("$async") } _addDefaultMetaSchema(): void { const {$data, meta, schemaId} = this.opts let _dataRefSchema: SchemaObject = $dataRefSchema if (schemaId === "id") { _dataRefSchema = {...$dataRefSchema} _dataRefSchema.id = _dataRefSchema.$id delete _dataRefSchema.$id } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false) } defaultMeta(): string | AnySchemaObject | undefined { const {meta, schemaId} = this.opts return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined) } // Validate data using schema // AnySchema will be compiled and cached using schema itself as a key for Map validate(schema: Schema | string, data: unknown): boolean validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise validate(schema: Schema | JSONSchemaType | string, data: unknown): data is T // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures validate(schema: JTDSchemaType, data: unknown): data is T // This overload is only intended for typescript inference, the first // argument prevents manual type annotation from matching this overload // eslint-disable-next-line @typescript-eslint/no-unused-vars validate( schema: T, data: unknown ): data is JTDDataType // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents validate(schema: AsyncSchema, data: unknown | T): Promise validate(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise validate( schemaKeyRef: AnySchema | string, // key, ref or schema object // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents data: unknown | T // to be validated ): boolean | Promise { let v: AnyValidateFunction | undefined if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef) if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`) } else { v = this.compile(schemaKeyRef) } const valid = v(data) if (!("$async" in v)) this.errors = v.errors return valid } // Create validation function for passed schema // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords. compile(schema: Schema | JSONSchemaType, _meta?: boolean): ValidateFunction // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compile(schema: JTDSchemaType, _meta?: boolean): ValidateFunction // This overload is only intended for typescript inference, the first // argument prevents manual type annotation from matching this overload // eslint-disable-next-line @typescript-eslint/no-unused-vars compile( schema: T, _meta?: boolean ): ValidateFunction> compile(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction { const sch = this._addSchema(schema, _meta) return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction } // Creates validating function for passed schema with asynchronous loading of missing schemas. // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. // TODO allow passing schema URI // meta - optional true to compile meta-schema compileAsync( schema: SchemaObject | JSONSchemaType, _meta?: boolean ): Promise> // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compileAsync(schema: JTDSchemaType, _meta?: boolean): Promise> compileAsync(schema: AsyncSchema, meta?: boolean): Promise> // eslint-disable-next-line @typescript-eslint/unified-signatures compileAsync( schema: AnySchemaObject, meta?: boolean ): Promise> compileAsync( schema: AnySchemaObject, meta?: boolean ): Promise> { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function") } const {loadSchema} = this.opts return runCompileAsync.call(this, schema, meta) async function runCompileAsync( this: Ajv, _schema: AnySchemaObject, _meta?: boolean ): Promise { await loadMetaSchema.call(this, _schema.$schema) const sch = this._addSchema(_schema, _meta) return sch.validate || _compileAsync.call(this, sch) } async function loadMetaSchema(this: Ajv, $ref?: string): Promise { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, {$ref}, true) } } async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise { try { return this._compileSchemaEnv(sch) } catch (e) { if (!(e instanceof MissingRefError)) throw e checkLoaded.call(this, e) await loadMissingSchema.call(this, e.missingSchema) return _compileAsync.call(this, sch) } } function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`) } } async function loadMissingSchema(this: Ajv, ref: string): Promise { const _schema = await _loadSchema.call(this, ref) if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema) if (!this.refs[ref]) this.addSchema(_schema, ref, meta) } async function _loadSchema(this: Ajv, ref: string): Promise { const p = this._loading[ref] if (p) return p try { return await (this._loading[ref] = loadSchema(ref)) } finally { delete this._loading[ref] } } } // Adds schema to the instance addSchema( schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. ): Ajv { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema) return this } let id: string | undefined if (typeof schema === "object") { const {schemaId} = this.opts id = schema[schemaId] if (id !== undefined && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`) } } key = normalizeId(key || id) this._checkUnique(key) this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true) return this } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema( schema: AnySchemaObject, key?: string, // schema key _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema ): Ajv { this.addSchema(schema, key, true, _validateSchema) return this } // Validate schema against its meta-schema validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise { if (typeof schema == "boolean") return true let $schema: string | AnySchemaObject | undefined $schema = schema.$schema if ($schema !== undefined && typeof $schema != "string") { throw new Error("$schema must be a string") } $schema = $schema || this.opts.defaultMeta || this.defaultMeta() if (!$schema) { this.logger.warn("meta-schema not available") this.errors = null return true } const valid = this.validate($schema, schema) if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText() if (this.opts.validateSchema === "log") this.logger.error(message) else throw new Error(message) } return valid } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef: string): AnyValidateFunction | undefined { let sch while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch if (sch === undefined) { const {schemaId} = this.opts const root = new SchemaEnv({schema: {}, schemaId}) sch = resolveSchema.call(this, root, keyRef) if (!sch) return this.refs[keyRef] = sch } return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction | undefined } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef) this._removeAllSchemas(this.refs, schemaKeyRef) return this } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas) this._removeAllSchemas(this.refs) this._cache.clear() return this case "string": { const sch = getSchEnv.call(this, schemaKeyRef) if (typeof sch == "object") this._cache.delete(sch.schema) delete this.schemas[schemaKeyRef] delete this.refs[schemaKeyRef] return this } case "object": { const cacheKey = schemaKeyRef this._cache.delete(cacheKey) let id = schemaKeyRef[this.opts.schemaId] if (id) { id = normalizeId(id) delete this.schemas[id] delete this.refs[id] } return this } default: throw new Error("ajv.removeSchema: invalid parameter") } } // add "vocabulary" - a collection of keywords addVocabulary(definitions: Vocabulary): Ajv { for (const def of definitions) this.addKeyword(def) return this } addKeyword( kwdOrDef: string | KeywordDefinition, def?: KeywordDefinition // deprecated ): Ajv { let keyword: string | string[] if (typeof kwdOrDef == "string") { keyword = kwdOrDef if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword") def.keyword = keyword } } else if (typeof kwdOrDef == "object" && def === undefined) { def = kwdOrDef keyword = def.keyword if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array") } } else { throw new Error("invalid addKeywords parameters") } checkKeyword.call(this, keyword, def) if (!def) { eachItem(keyword, (kwd) => addRule.call(this, kwd)) return this } keywordMetaschema.call(this, def) const definition: AddedKeywordDefinition = { ...def, type: getJSONTypes(def.type), schemaType: getJSONTypes(def.schemaType), } eachItem( keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)) ) return this } getKeyword(keyword: string): AddedKeywordDefinition | boolean { const rule = this.RULES.all[keyword] return typeof rule == "object" ? rule.definition : !!rule } // Remove keyword removeKeyword(keyword: string): Ajv { // TODO return type should be Ajv const {RULES} = this delete RULES.keywords[keyword] delete RULES.all[keyword] for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword) if (i >= 0) group.rules.splice(i, 1) } return this } // Add format addFormat(name: string, format: Format): Ajv { if (typeof format == "string") format = new RegExp(format) this.formats[name] = format return this } errorsText( errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar` ): string { if (!errors || errors.length === 0) return "No errors" return errors .map((e) => `${dataVar}${e.instancePath} ${e.message}`) .reduce((text, msg) => text + separator + msg) } $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject { const rules = this.RULES.all metaSchema = JSON.parse(JSON.stringify(metaSchema)) for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1) // first segment is an empty string let keywords = metaSchema for (const seg of segments) keywords = keywords[seg] as AnySchemaObject for (const key in rules) { const rule = rules[key] if (typeof rule != "object") continue const {$data} = rule.definition const schema = keywords[key] as AnySchemaObject | undefined if ($data && schema) keywords[key] = schemaOrData(schema) } } return metaSchema } private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void { for (const keyRef in schemas) { const sch = schemas[keyRef] if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef] } else if (sch && !sch.meta) { this._cache.delete(sch.schema) delete schemas[keyRef] } } } } _addSchema( schema: AnySchema, meta?: boolean, baseId?: string, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema ): SchemaEnv { let id: string | undefined const {schemaId} = this.opts if (typeof schema == "object") { id = schema[schemaId] } else { if (this.opts.jtd) throw new Error("schema must be object") else if (typeof schema != "boolean") throw new Error("schema must be object or boolean") } let sch = this._cache.get(schema) if (sch !== undefined) return sch baseId = normalizeId(id || baseId) const localRefs = getSchemaRefs.call(this, schema, baseId) sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs}) this._cache.set(sch.schema, sch) if (addSchema && !baseId.startsWith("#")) { // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) if (baseId) this._checkUnique(baseId) this.refs[baseId] = sch } if (validateSchema) this.validateSchema(schema, true) return sch } private _checkUnique(id: string): void { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`) } } private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction { if (sch.meta) this._compileMetaSchema(sch) else compileSchema.call(this, sch) /* istanbul ignore if */ if (!sch.validate) throw new Error("ajv implementation error") return sch.validate } private _compileMetaSchema(sch: SchemaEnv): void { const currentOpts = this.opts this.opts = this._metaOpts try { compileSchema.call(this, sch) } finally { this.opts = currentOpts } } } export interface ErrorsTextOptions { separator?: string dataVar?: string } function checkOptions( this: Ajv, checkOpts: OptionsInfo, options: Options & RemovedOptions, msg: string, log: "warn" | "error" = "error" ): void { for (const key in checkOpts) { const opt = key as keyof typeof checkOpts if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`) } } function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined { keyRef = normalizeId(keyRef) // TODO tests fail without this line return this.schemas[keyRef] || this.refs[keyRef] } function addInitialSchemas(this: Ajv): void { const optsSchemas = this.opts.schemas if (!optsSchemas) return if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas) else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key) } function addInitialFormats(this: Ajv): void { for (const name in this.opts.formats) { const format = this.opts.formats[name] if (format) this.addFormat(name, format) } } function addInitialKeywords( this: Ajv, defs: Vocabulary | {[K in string]?: KeywordDefinition} ): void { if (Array.isArray(defs)) { this.addVocabulary(defs) return } this.logger.warn("keywords option as map is deprecated, pass array") for (const keyword in defs) { const def = defs[keyword] as KeywordDefinition if (!def.keyword) def.keyword = keyword this.addKeyword(def) } } function getMetaSchemaOptions(this: Ajv): InstanceOptions { const metaOpts = {...this.opts} for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt] return metaOpts } const noLogs = {log() {}, warn() {}, error() {}} function getLogger(logger?: Partial | false): Logger { if (logger === false) return noLogs if (logger === undefined) return console if (logger.log && logger.warn && logger.error) return logger as Logger throw new Error("logger must implement log, warn and error methods") } const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void { const {RULES} = this eachItem(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`) if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`) }) if (!def) return if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function') } } function addRule( this: Ajv, keyword: string, definition?: AddedKeywordDefinition, dataType?: JSONType ): void { const post = definition?.post if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"') const {RULES} = this let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType) if (!ruleGroup) { ruleGroup = {type: dataType, rules: []} RULES.rules.push(ruleGroup) } RULES.keywords[keyword] = true if (!definition) return const rule: Rule = { keyword, definition: { ...definition, type: getJSONTypes(definition.type), schemaType: getJSONTypes(definition.schemaType), }, } if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before) else ruleGroup.rules.push(rule) RULES.all[keyword] = rule definition.implements?.forEach((kwd) => this.addKeyword(kwd)) } function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before) if (i >= 0) { ruleGroup.rules.splice(i, 0, rule) } else { ruleGroup.rules.push(rule) this.logger.warn(`rule ${before} is not defined`) } } function keywordMetaschema(this: Ajv, def: KeywordDefinition): void { let {metaSchema} = def if (metaSchema === undefined) return if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema) def.validateSchema = this.compile(metaSchema, true) } const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", } function schemaOrData(schema: AnySchema): AnySchemaObject { return {anyOf: [schema, $dataRef]} } import type {AnySchemaObject, SchemaObject, JTDParser} from "./types" import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" import AjvCore, {CurrentOptions} from "./core" import jtdVocabulary from "./vocabularies/jtd" import jtdMetaSchema from "./refs/jtd-schema" import compileSerializer from "./compile/jtd/serialize" import compileParser from "./compile/jtd/parse" import {SchemaEnv} from "./compile" const META_SCHEMA_ID = "JTD-meta-schema" type JTDOptions = CurrentOptions & { // strict mode options not supported with JTD: strict?: never allowMatchingProperties?: never allowUnionTypes?: never validateFormats?: never // validation and reporting options not supported with JTD: $data?: never verbose?: boolean $comment?: never formats?: never loadSchema?: never // options to modify validated data: useDefaults?: never coerceTypes?: never // advanced options: next?: never unevaluated?: never dynamicRef?: never meta?: boolean defaultMeta?: never inlineRefs?: boolean loopRequired?: never multipleOfPrecision?: never } export class Ajv extends AjvCore { constructor(opts: JTDOptions = {}) { super({ ...opts, jtd: true, }) } _addVocabularies(): void { super._addVocabularies() this.addVocabulary(jtdVocabulary) } _addDefaultMetaSchema(): void { super._addDefaultMetaSchema() if (!this.opts.meta) return this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false) } defaultMeta(): string | AnySchemaObject | undefined { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) } compileSerializer(schema: SchemaObject): (data: T) => string // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compileSerializer(schema: JTDSchemaType): (data: T) => string compileSerializer(schema: SchemaObject): (data: T) => string { const sch = this._addSchema(schema) return sch.serialize || this._compileSerializer(sch) } compileParser(schema: SchemaObject): JTDParser // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compileParser(schema: JTDSchemaType): JTDParser compileParser(schema: SchemaObject): JTDParser { const sch = this._addSchema(schema) return (sch.parse || this._compileParser(sch)) as JTDParser } private _compileSerializer(sch: SchemaEnv): (data: T) => string { compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) /* istanbul ignore if */ if (!sch.serialize) throw new Error("ajv implementation error") return sch.serialize } private _compileParser(sch: SchemaEnv): JTDParser { compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) /* istanbul ignore if */ if (!sch.parse) throw new Error("ajv implementation error") return sch.parse } } module.exports = exports = Ajv module.exports.Ajv = Ajv Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, JTDParser, } from "./types" export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" export {SchemaCxt, SchemaObjCxt} from "./compile" export {KeywordCxt} from "./compile/validate" export {JTDErrorObject} from "./vocabularies/jtd" export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} export {JTDOptions} export {default as ValidationError} from "./runtime/validation_error" export {default as MissingRefError} from "./compile/ref_error" { "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", "type": "object", "required": ["$data"], "properties": { "$data": { "type": "string", "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}] } }, "additionalProperties": false } import type Ajv from "../../core" import type {AnySchemaObject} from "../../types" import * as metaSchema from "./schema.json" import * as applicator from "./meta/applicator.json" import * as content from "./meta/content.json" import * as core from "./meta/core.json" import * as format from "./meta/format.json" import * as metadata from "./meta/meta-data.json" import * as validation from "./meta/validation.json" const META_SUPPORT_DATA = ["/properties"] export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/applicator", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, "$recursiveAnchor": true, "title": "Applicator vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "additionalItems": {"$recursiveRef": "#"}, "unevaluatedItems": {"$recursiveRef": "#"}, "items": { "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] }, "contains": {"$recursiveRef": "#"}, "additionalProperties": {"$recursiveRef": "#"}, "unevaluatedProperties": {"$recursiveRef": "#"}, "properties": { "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "propertyNames": {"format": "regex"}, "default": {} }, "dependentSchemas": { "type": "object", "additionalProperties": { "$recursiveRef": "#" } }, "propertyNames": {"$recursiveRef": "#"}, "if": {"$recursiveRef": "#"}, "then": {"$recursiveRef": "#"}, "else": {"$recursiveRef": "#"}, "allOf": {"$ref": "#/$defs/schemaArray"}, "anyOf": {"$ref": "#/$defs/schemaArray"}, "oneOf": {"$ref": "#/$defs/schemaArray"}, "not": {"$recursiveRef": "#"} }, "$defs": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$recursiveRef": "#"} } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/content", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, "$recursiveAnchor": true, "title": "Content vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "contentMediaType": {"type": "string"}, "contentEncoding": {"type": "string"}, "contentSchema": {"$recursiveRef": "#"} } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/core", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, "$recursiveAnchor": true, "title": "Core vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference", "$comment": "Non-empty fragments not allowed.", "pattern": "^[^#]*#?$" }, "$schema": { "type": "string", "format": "uri" }, "$anchor": { "type": "string", "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" }, "$ref": { "type": "string", "format": "uri-reference" }, "$recursiveRef": { "type": "string", "format": "uri-reference" }, "$recursiveAnchor": { "type": "boolean", "default": false }, "$vocabulary": { "type": "object", "propertyNames": { "type": "string", "format": "uri" }, "additionalProperties": { "type": "boolean" } }, "$comment": { "type": "string" }, "$defs": { "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "default": {} } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/format", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, "$recursiveAnchor": true, "title": "Format vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "format": {"type": "string"} } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, "$recursiveAnchor": true, "title": "Meta-data vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "deprecated": { "type": "boolean", "default": false }, "readOnly": { "type": "boolean", "default": false }, "writeOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/meta/validation", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, "$recursiveAnchor": true, "title": "Validation vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, "minContains": { "$ref": "#/$defs/nonNegativeInteger", "default": 1 }, "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/$defs/stringArray"}, "dependentRequired": { "type": "object", "additionalProperties": { "$ref": "#/$defs/stringArray" } }, "const": true, "enum": { "type": "array", "items": true }, "type": { "anyOf": [ {"$ref": "#/$defs/simpleTypes"}, { "type": "array", "items": {"$ref": "#/$defs/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] } }, "$defs": { "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "$ref": "#/$defs/nonNegativeInteger", "default": 0 }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } } } { "$schema": "https://json-schema.org/draft/2019-09/schema", "$id": "https://json-schema.org/draft/2019-09/schema", "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true, "https://json-schema.org/draft/2019-09/vocab/applicator": true, "https://json-schema.org/draft/2019-09/vocab/validation": true, "https://json-schema.org/draft/2019-09/vocab/meta-data": true, "https://json-schema.org/draft/2019-09/vocab/format": false, "https://json-schema.org/draft/2019-09/vocab/content": true }, "$recursiveAnchor": true, "title": "Core and Validation specifications meta-schema", "allOf": [ {"$ref": "meta/core"}, {"$ref": "meta/applicator"}, {"$ref": "meta/validation"}, {"$ref": "meta/meta-data"}, {"$ref": "meta/format"}, {"$ref": "meta/content"} ], "type": ["object", "boolean"], "properties": { "definitions": { "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", "type": "object", "additionalProperties": {"$recursiveRef": "#"}, "default": {} }, "dependencies": { "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", "type": "object", "additionalProperties": { "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] } } } } import type Ajv from "../../core" import type {AnySchemaObject} from "../../types" import * as metaSchema from "./schema.json" import * as applicator from "./meta/applicator.json" import * as unevaluated from "./meta/unevaluated.json" import * as content from "./meta/content.json" import * as core from "./meta/core.json" import * as format from "./meta/format-annotation.json" import * as metadata from "./meta/meta-data.json" import * as validation from "./meta/validation.json" const META_SUPPORT_DATA = ["/properties"] export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, unevaluated, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/applicator", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, "$dynamicAnchor": "meta", "title": "Applicator vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "prefixItems": {"$ref": "#/$defs/schemaArray"}, "items": {"$dynamicRef": "#meta"}, "contains": {"$dynamicRef": "#meta"}, "additionalProperties": {"$dynamicRef": "#meta"}, "properties": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "propertyNames": {"format": "regex"}, "default": {} }, "dependentSchemas": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "default": {} }, "propertyNames": {"$dynamicRef": "#meta"}, "if": {"$dynamicRef": "#meta"}, "then": {"$dynamicRef": "#meta"}, "else": {"$dynamicRef": "#meta"}, "allOf": {"$ref": "#/$defs/schemaArray"}, "anyOf": {"$ref": "#/$defs/schemaArray"}, "oneOf": {"$ref": "#/$defs/schemaArray"}, "not": {"$dynamicRef": "#meta"} }, "$defs": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$dynamicRef": "#meta"} } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/content", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, "$dynamicAnchor": "meta", "title": "Content vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "contentEncoding": {"type": "string"}, "contentMediaType": {"type": "string"}, "contentSchema": {"$dynamicRef": "#meta"} } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/core", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, "$dynamicAnchor": "meta", "title": "Core vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "$id": { "$ref": "#/$defs/uriReferenceString", "$comment": "Non-empty fragments not allowed.", "pattern": "^[^#]*#?$" }, "$schema": {"$ref": "#/$defs/uriString"}, "$ref": {"$ref": "#/$defs/uriReferenceString"}, "$anchor": {"$ref": "#/$defs/anchorString"}, "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, "$vocabulary": { "type": "object", "propertyNames": {"$ref": "#/$defs/uriString"}, "additionalProperties": { "type": "boolean" } }, "$comment": { "type": "string" }, "$defs": { "type": "object", "additionalProperties": {"$dynamicRef": "#meta"} } }, "$defs": { "anchorString": { "type": "string", "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" }, "uriString": { "type": "string", "format": "uri" }, "uriReferenceString": { "type": "string", "format": "uri-reference" } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, "$dynamicAnchor": "meta", "title": "Format vocabulary meta-schema for annotation results", "type": ["object", "boolean"], "properties": { "format": {"type": "string"} } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, "$dynamicAnchor": "meta", "title": "Meta-data vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "deprecated": { "type": "boolean", "default": false }, "readOnly": { "type": "boolean", "default": false }, "writeOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, "$dynamicAnchor": "meta", "title": "Unevaluated applicator vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "unevaluatedItems": {"$dynamicRef": "#meta"}, "unevaluatedProperties": {"$dynamicRef": "#meta"} } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/validation", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, "$dynamicAnchor": "meta", "title": "Validation vocabulary meta-schema", "type": ["object", "boolean"], "properties": { "type": { "anyOf": [ {"$ref": "#/$defs/simpleTypes"}, { "type": "array", "items": {"$ref": "#/$defs/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] }, "const": true, "enum": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, "minContains": { "$ref": "#/$defs/nonNegativeInteger", "default": 1 }, "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/$defs/stringArray"}, "dependentRequired": { "type": "object", "additionalProperties": { "$ref": "#/$defs/stringArray" } } }, "$defs": { "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "$ref": "#/$defs/nonNegativeInteger", "default": 0 }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } } } { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/schema", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true, "https://json-schema.org/draft/2020-12/vocab/applicator": true, "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, "https://json-schema.org/draft/2020-12/vocab/validation": true, "https://json-schema.org/draft/2020-12/vocab/meta-data": true, "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, "https://json-schema.org/draft/2020-12/vocab/content": true }, "$dynamicAnchor": "meta", "title": "Core and Validation specifications meta-schema", "allOf": [ {"$ref": "meta/core"}, {"$ref": "meta/applicator"}, {"$ref": "meta/unevaluated"}, {"$ref": "meta/validation"}, {"$ref": "meta/meta-data"}, {"$ref": "meta/format-annotation"}, {"$ref": "meta/content"} ], "type": ["object", "boolean"], "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", "properties": { "definitions": { "$comment": "\"definitions\" has been replaced by \"$defs\".", "type": "object", "additionalProperties": {"$dynamicRef": "#meta"}, "deprecated": true, "default": {} }, "dependencies": { "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", "type": "object", "additionalProperties": { "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] }, "deprecated": true, "default": {} }, "$recursiveAnchor": { "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", "$ref": "meta/core#/$defs/anchorString", "deprecated": true }, "$recursiveRef": { "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", "$ref": "meta/core#/$defs/uriReferenceString", "deprecated": true } } } { "$schema": "http://json-schema.org/draft-06/schema#", "$id": "http://json-schema.org/draft-06/schema#", "title": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$ref": "#"} }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } }, "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": {}, "examples": { "type": "array", "items": {} }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "additionalItems": {"$ref": "#"}, "items": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], "default": {} }, "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "contains": {"$ref": "#"}, "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/definitions/stringArray"}, "additionalProperties": {"$ref": "#"}, "definitions": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "properties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] } }, "propertyNames": {"$ref": "#"}, "const": {}, "enum": { "type": "array", "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [ {"$ref": "#/definitions/simpleTypes"}, { "type": "array", "items": {"$ref": "#/definitions/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] }, "format": {"type": "string"}, "allOf": {"$ref": "#/definitions/schemaArray"}, "anyOf": {"$ref": "#/definitions/schemaArray"}, "oneOf": {"$ref": "#/definitions/schemaArray"}, "not": {"$ref": "#"} }, "default": {} } { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "http://json-schema.org/draft-07/schema#", "title": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$ref": "#"} }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "uniqueItems": true, "default": [] } }, "type": ["object", "boolean"], "properties": { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "$comment": { "type": "string" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "readOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "additionalItems": {"$ref": "#"}, "items": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], "default": true }, "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "contains": {"$ref": "#"}, "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, "required": {"$ref": "#/definitions/stringArray"}, "additionalProperties": {"$ref": "#"}, "definitions": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "properties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$ref": "#"}, "propertyNames": {"format": "regex"}, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] } }, "propertyNames": {"$ref": "#"}, "const": true, "enum": { "type": "array", "items": true, "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [ {"$ref": "#/definitions/simpleTypes"}, { "type": "array", "items": {"$ref": "#/definitions/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] }, "format": {"type": "string"}, "contentMediaType": {"type": "string"}, "contentEncoding": {"type": "string"}, "if": {"$ref": "#"}, "then": {"$ref": "#"}, "else": {"$ref": "#"}, "allOf": {"$ref": "#/definitions/schemaArray"}, "anyOf": {"$ref": "#/definitions/schemaArray"}, "oneOf": {"$ref": "#/definitions/schemaArray"}, "not": {"$ref": "#"} }, "default": true } { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#", "title": "Meta-schema for the security assessment of JSON Schemas", "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$ref": "#"} } }, "dependencies": { "patternProperties": { "description": "prevent slow validation of large property names", "required": ["propertyNames"], "properties": { "propertyNames": { "required": ["maxLength"] } } }, "uniqueItems": { "description": "prevent slow validation of large non-scalar arrays", "if": { "properties": { "uniqueItems": {"const": true}, "items": { "properties": { "type": { "anyOf": [ { "enum": ["object", "array"] }, { "type": "array", "contains": {"enum": ["object", "array"]} } ] } } } } }, "then": { "required": ["maxItems"] } }, "pattern": { "description": "prevent slow pattern matching of large strings", "required": ["maxLength"] }, "format": { "description": "prevent slow format validation of large strings", "required": ["maxLength"] } }, "properties": { "additionalItems": {"$ref": "#"}, "additionalProperties": {"$ref": "#"}, "dependencies": { "additionalProperties": { "anyOf": [{"type": "array"}, {"$ref": "#"}] } }, "items": { "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}] }, "definitions": { "additionalProperties": {"$ref": "#"} }, "patternProperties": { "additionalProperties": {"$ref": "#"} }, "properties": { "additionalProperties": {"$ref": "#"} }, "if": {"$ref": "#"}, "then": {"$ref": "#"}, "else": {"$ref": "#"}, "allOf": {"$ref": "#/definitions/schemaArray"}, "anyOf": {"$ref": "#/definitions/schemaArray"}, "oneOf": {"$ref": "#/definitions/schemaArray"}, "not": {"$ref": "#"}, "contains": {"$ref": "#"}, "propertyNames": {"$ref": "#"} } } import {SchemaObject} from "../types" type MetaSchema = (root: boolean) => SchemaObject const shared: MetaSchema = (root) => { const sch: SchemaObject = { nullable: {type: "boolean"}, metadata: { optionalProperties: { union: {elements: {ref: "schema"}}, }, additionalProperties: true, }, } if (root) sch.definitions = {values: {ref: "schema"}} return sch } const emptyForm: MetaSchema = (root) => ({ optionalProperties: shared(root), }) const refForm: MetaSchema = (root) => ({ properties: { ref: {type: "string"}, }, optionalProperties: shared(root), }) const typeForm: MetaSchema = (root) => ({ properties: { type: { enum: [ "boolean", "timestamp", "string", "float32", "float64", "int8", "uint8", "int16", "uint16", "int32", "uint32", ], }, }, optionalProperties: shared(root), }) const enumForm: MetaSchema = (root) => ({ properties: { enum: {elements: {type: "string"}}, }, optionalProperties: shared(root), }) const elementsForm: MetaSchema = (root) => ({ properties: { elements: {ref: "schema"}, }, optionalProperties: shared(root), }) const propertiesForm: MetaSchema = (root) => ({ properties: { properties: {values: {ref: "schema"}}, }, optionalProperties: { optionalProperties: {values: {ref: "schema"}}, additionalProperties: {type: "boolean"}, ...shared(root), }, }) const optionalPropertiesForm: MetaSchema = (root) => ({ properties: { optionalProperties: {values: {ref: "schema"}}, }, optionalProperties: { additionalProperties: {type: "boolean"}, ...shared(root), }, }) const discriminatorForm: MetaSchema = (root) => ({ properties: { discriminator: {type: "string"}, mapping: { values: { metadata: { union: [propertiesForm(false), optionalPropertiesForm(false)], }, }, }, }, optionalProperties: shared(root), }) const valuesForm: MetaSchema = (root) => ({ properties: { values: {ref: "schema"}, }, optionalProperties: shared(root), }) const schema: MetaSchema = (root) => ({ metadata: { union: [ emptyForm, refForm, typeForm, enumForm, elementsForm, propertiesForm, optionalPropertiesForm, discriminatorForm, valuesForm, ].map((s) => s(root)), }, }) const jtdMetaSchema: SchemaObject = { definitions: { schema: schema(false), }, ...schema(true), } export default jtdMetaSchema // https://github.com/ajv-validator/ajv/issues/889 import * as equal from "fast-deep-equal" type Equal = typeof equal & {code: string} ;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default' export default equal as Equal const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/ export function parseJson(s: string, pos: number): unknown { let endPos: number | undefined parseJson.message = undefined let matches: RegExpExecArray | null if (pos) s = s.slice(pos) try { parseJson.position = pos + s.length return JSON.parse(s) } catch (e) { matches = rxParseJson.exec((e as Error).message) if (!matches) { parseJson.message = "unexpected end" return undefined } endPos = +matches[1] const c = s[endPos] s = s.slice(0, endPos) parseJson.position = pos + endPos try { return JSON.parse(s) } catch (e1) { parseJson.message = `unexpected token ${c}` return undefined } } } parseJson.message = undefined as string | undefined parseJson.position = 0 as number parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson' export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined { let numStr = "" let c: string parseJsonNumber.message = undefined if (s[pos] === "-") { numStr += "-" pos++ } if (s[pos] === "0") { numStr += "0" pos++ } else { if (!parseDigits(maxDigits)) { errorMessage() return undefined } } if (maxDigits) { parseJsonNumber.position = pos return +numStr } if (s[pos] === ".") { numStr += "." pos++ if (!parseDigits()) { errorMessage() return undefined } } if (((c = s[pos]), c === "e" || c === "E")) { numStr += "e" pos++ if (((c = s[pos]), c === "+" || c === "-")) { numStr += c pos++ } if (!parseDigits()) { errorMessage() return undefined } } parseJsonNumber.position = pos return +numStr function parseDigits(maxLen?: number): boolean { let digit = false while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) { digit = true numStr += c pos++ } return digit } function errorMessage(): void { parseJsonNumber.position = pos parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end" } } parseJsonNumber.message = undefined as string | undefined parseJsonNumber.position = 0 as number parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber' const escapedChars: {[X in string]?: string} = { b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", '"': '"', "/": "/", "\\": "\\", } const CODE_A: number = "a".charCodeAt(0) const CODE_0: number = "0".charCodeAt(0) export function parseJsonString(s: string, pos: number): string | undefined { let str = "" let c: string | undefined parseJsonString.message = undefined // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition while (true) { c = s[pos++] if (c === '"') break if (c === "\\") { c = s[pos] if (c in escapedChars) { str += escapedChars[c] pos++ } else if (c === "u") { pos++ let count = 4 let code = 0 while (count--) { code <<= 4 c = s[pos] // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (c === undefined) { errorMessage("unexpected end") return undefined } c = c.toLowerCase() if (c >= "a" && c <= "f") { code += c.charCodeAt(0) - CODE_A + 10 } else if (c >= "0" && c <= "9") { code += c.charCodeAt(0) - CODE_0 } else { errorMessage(`unexpected token ${c}`) return undefined } pos++ } str += String.fromCharCode(code) } else { errorMessage(`unexpected token ${c}`) return undefined } // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition } else if (c === undefined) { errorMessage("unexpected end") return undefined } else { if (c.charCodeAt(0) >= 0x20) { str += c } else { errorMessage(`unexpected token ${c}`) return undefined } } } parseJsonString.position = pos return str function errorMessage(msg: string): void { parseJsonString.position = pos parseJsonString.message = msg } } parseJsonString.message = undefined as string | undefined parseJsonString.position = 0 as number parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString' const rxEscapable = // eslint-disable-next-line no-control-regex, no-misleading-character-class /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g const escaped: {[K in string]?: string} = { "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\", } export default function quote(s: string): string { rxEscapable.lastIndex = 0 return ( '"' + (rxEscapable.test(s) ? s.replace(rxEscapable, (a) => { const c = escaped[a] return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4) }) : s) + '"' ) } quote.code = 'require("ajv/dist/runtime/quote").default' import * as re2 from "re2" type Re2 = typeof re2 & {code: string} ;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default' export default re2 as Re2 const DT_SEPARATOR = /t|\s/i const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] export default function validTimestamp(str: string, allowDate: boolean): boolean { // http://tools.ietf.org/html/rfc3339#section-5.6 const dt: string[] = str.split(DT_SEPARATOR) return ( (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) || (allowDate && dt.length === 1 && validDate(dt[0])) ) } function validDate(str: string): boolean { const matches: string[] | null = DATE.exec(str) if (!matches) return false const y: number = +matches[1] const m: number = +matches[2] const d: number = +matches[3] return ( m >= 1 && m <= 12 && d >= 1 && (d <= DAYS[m] || // leap year: https://tools.ietf.org/html/rfc3339#appendix-C (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))) ) } function validTime(str: string): boolean { const matches: string[] | null = TIME.exec(str) if (!matches) return false const hr: number = +matches[1] const min: number = +matches[2] const sec: number = +matches[3] const tzH: number = +(matches[4] || 0) const tzM: number = +(matches[5] || 0) return ( (hr <= 23 && min <= 59 && sec <= 59) || // leap second (hr - tzH === 23 && min - tzM === 59 && sec === 60) ) } validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default' // https://mathiasbynens.be/notes/javascript-encoding // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode export default function ucs2length(str: string): number { const len = str.length let length = 0 let pos = 0 let value: number while (pos < len) { length++ value = str.charCodeAt(pos++) if (value >= 0xd800 && value <= 0xdbff && pos < len) { // high surrogate, and there is a next character value = str.charCodeAt(pos) if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate } } return length } ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default' import * as uri from "fast-uri" type URI = typeof uri & {code: string} ;(uri as URI).code = 'require("ajv/dist/runtime/uri").default' export default uri as URI import type {ErrorObject} from "../types" export default class ValidationError extends Error { readonly errors: Partial[] readonly ajv: true readonly validation: true constructor(errors: Partial[]) { super("validation failed") this.errors = errors this.ajv = this.validation = true } } import type AjvCore from "../core" import type {AnyValidateFunction, SourceCode} from "../types" import type {SchemaEnv} from "../compile" import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope" import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code" function standaloneCode( ajv: AjvCore, refsOrFunc?: {[K in string]?: string} | AnyValidateFunction ): string { if (!ajv.opts.code.source) { throw new Error("moduleCode: ajv instance must have code.source option") } const {_n} = ajv.scope.opts return typeof refsOrFunc == "function" ? funcExportCode(refsOrFunc.source) : refsOrFunc !== undefined ? multiExportsCode(refsOrFunc, getValidate) : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema) ) function getValidate(id: string): AnyValidateFunction { const v = ajv.getSchema(id) if (!v) throw new Error(`moduleCode: no schema with id ${id}`) return v } function funcExportCode(source?: SourceCode): string { const usedValues: UsedScopeValues = {} const n = source?.validateName const vCode = validateCode(usedValues, source) if (ajv.opts.code.esm) { // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}` } return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}` } function multiExportsCode( schemas: {[K in string]?: T}, getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined ): string { const usedValues: UsedScopeValues = {} let code = _`"use strict";` for (const name in schemas) { const v = getValidateFunc(schemas[name] as T) if (v) { const vCode = validateCode(usedValues, v.source) const exportSyntax = ajv.opts.code.esm ? _`export const ${getEsmExportName(name)}` : _`exports${getProperty(name)}` code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}` } } return `${code}` } function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code { if (!s) throw new Error('moduleCode: function does not have "source" property') if (usedState(s.validateName) === UsedValueState.Completed) return nil setUsedState(s.validateName, UsedValueState.Started) const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode) const code = new _Code(`${scopeCode}${_n}${s.validateCode}`) return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code function refValidateCode(n: ValueScopeName): Code | undefined { const vRef = n.value?.ref if (n.prefix === "validate" && typeof vRef == "function") { const v = vRef as AnyValidateFunction return validateCode(usedValues, v.source) } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { const {validate, validateName} = vRef as SchemaEnv if (!validateName) throw new Error("ajv internal error") const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const const wrapper = _`${def} ${n} = {validate: ${validateName}};` if (usedState(validateName) === UsedValueState.Started) return wrapper const vCode = validateCode(usedValues, validate?.source) return _`${wrapper}${_n}${vCode}` } return undefined } function usedState(name: ValueScopeName): UsedValueState | undefined { return usedValues[name.prefix]?.get(name) } function setUsedState(name: ValueScopeName, state: UsedValueState): void { const {prefix} = name const names = (usedValues[prefix] = usedValues[prefix] || new Map()) names.set(name, state) } } } module.exports = exports = standaloneCode Object.defineProperty(exports, "__esModule", {value: true}) export default standaloneCode import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core" import standaloneCode from "." import * as requireFromString from "require-from-string" export default class AjvPack { errors?: ErrorObject[] | null // errors from the last validation constructor(readonly ajv: Ajv) {} validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise { return Ajv.prototype.validate.call(this, schemaKeyRef, data) } compile(schema: AnySchema, meta?: boolean): AnyValidateFunction { return this.getStandalone(this.ajv.compile(schema, meta)) } getSchema(keyRef: string): AnyValidateFunction | undefined { const v = this.ajv.getSchema(keyRef) if (!v) return undefined return this.getStandalone(v) } private getStandalone(v: AnyValidateFunction): AnyValidateFunction { return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction } addSchema(...args: Parameters): AjvPack { this.ajv.addSchema.call(this.ajv, ...args) return this } addKeyword(...args: Parameters): AjvPack { this.ajv.addKeyword.call(this.ajv, ...args) return this } } import {URIComponent} from "fast-uri" import type {CodeGen, Code, Name, ScopeValueSets, ValueScopeName} from "../compile/codegen" import type {SchemaEnv, SchemaCxt, SchemaObjCxt} from "../compile" import type {JSONType} from "../compile/rules" import type {KeywordCxt} from "../compile/validate" import type Ajv from "../core" interface _SchemaObject { id?: string $id?: string $schema?: string [x: string]: any // TODO } export interface SchemaObject extends _SchemaObject { id?: string $id?: string $schema?: string $async?: false [x: string]: any // TODO } export interface AsyncSchema extends _SchemaObject { $async: true } export type AnySchemaObject = SchemaObject | AsyncSchema export type Schema = SchemaObject | boolean export type AnySchema = Schema | AsyncSchema export type SchemaMap = {[Key in string]?: AnySchema} export interface SourceCode { validateName: ValueScopeName validateCode: string scopeValues: ScopeValueSets evaluated?: Code } export interface DataValidationCxt { instancePath: string parentData: {[K in T]: any} // object or array parentDataProperty: T // string or number rootData: Record | any[] dynamicAnchors: {[Ref in string]?: ValidateFunction} } export interface ValidateFunction { // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T errors?: null | ErrorObject[] evaluated?: Evaluated schema: AnySchema schemaEnv: SchemaEnv source?: SourceCode } export interface JTDParser { (json: string): T | undefined message?: string position?: number } export type EvaluatedProperties = {[K in string]?: true} | true export type EvaluatedItems = number | true export interface Evaluated { // determined at compile time if staticProps/Items is true props?: EvaluatedProperties items?: EvaluatedItems // whether props/items determined at compile time dynamicProps: boolean dynamicItems: boolean } export interface AsyncValidateFunction extends ValidateFunction { (...args: Parameters>): Promise $async: true } export type AnyValidateFunction = ValidateFunction | AsyncValidateFunction export interface ErrorObject, S = unknown> { keyword: K instancePath: string schemaPath: string params: P // Added to validation errors of "propertyNames" keyword schema propertyName?: string // Excluded if option `messages` set to false. message?: string // These are added with the `verbose` option. schema?: S parentSchema?: AnySchemaObject data?: unknown } export type ErrorNoParams = ErrorObject, S> interface _KeywordDef { keyword: string | string[] type?: JSONType | JSONType[] // data types that keyword applies to schemaType?: JSONType | JSONType[] // allowed type(s) of keyword value in the schema allowUndefined?: boolean // used for keywords that can be invoked by other keywords, not being present in the schema $data?: boolean // keyword supports [$data reference](../../docs/guide/combining-schemas.md#data-reference) implements?: string[] // other schema keywords that this keyword implements before?: string // keyword should be executed before this keyword (should be applicable to the same type) post?: boolean // keyword should be executed after other keywords without post flag metaSchema?: AnySchemaObject // meta-schema for keyword schema value - it is better to use schemaType where applicable validateSchema?: AnyValidateFunction // compiled keyword metaSchema - should not be passed dependencies?: string[] // keywords that must be present in the same schema error?: KeywordErrorDefinition $dataError?: KeywordErrorDefinition } export interface CodeKeywordDefinition extends _KeywordDef { code: (cxt: KeywordCxt, ruleType?: string) => void trackErrors?: boolean } export type MacroKeywordFunc = ( schema: any, parentSchema: AnySchemaObject, it: SchemaCxt ) => AnySchema export type CompileKeywordFunc = ( schema: any, parentSchema: AnySchemaObject, it: SchemaObjCxt ) => DataValidateFunction export interface DataValidateFunction { (...args: Parameters): boolean | Promise errors?: Partial[] } export interface SchemaValidateFunction { ( schema: any, data: any, parentSchema?: AnySchemaObject, dataCxt?: DataValidationCxt ): boolean | Promise errors?: Partial[] } export interface FuncKeywordDefinition extends _KeywordDef { validate?: SchemaValidateFunction | DataValidateFunction compile?: CompileKeywordFunc // schema: false makes validate not to expect schema (DataValidateFunction) schema?: boolean // requires "validate" modifying?: boolean async?: boolean valid?: boolean errors?: boolean | "full" } export interface MacroKeywordDefinition extends FuncKeywordDefinition { macro: MacroKeywordFunc } export type KeywordDefinition = | CodeKeywordDefinition | FuncKeywordDefinition | MacroKeywordDefinition export type AddedKeywordDefinition = KeywordDefinition & { type: JSONType[] schemaType: JSONType[] } export interface KeywordErrorDefinition { message: string | Code | ((cxt: KeywordErrorCxt) => string | Code) params?: Code | ((cxt: KeywordErrorCxt) => Code) } export type Vocabulary = (KeywordDefinition | string)[] export interface KeywordErrorCxt { gen: CodeGen keyword: string data: Name $data?: string | false schema: any // TODO parentSchema?: AnySchemaObject schemaCode: Code | number | boolean schemaValue: Code | number | boolean schemaType?: JSONType[] errsCount?: Name params: KeywordCxtParams it: SchemaCxt } export type KeywordCxtParams = {[P in string]?: Code | string | number} export type FormatValidator = (data: T) => boolean export type FormatCompare = (data1: T, data2: T) => number | undefined export type AsyncFormatValidator = (data: T) => Promise export interface FormatDefinition { type?: T extends string ? "string" | undefined : "number" validate: FormatValidator | (T extends string ? string | RegExp : never) async?: false | undefined compare?: FormatCompare } export interface AsyncFormatDefinition { type?: T extends string ? "string" | undefined : "number" validate: AsyncFormatValidator async: true compare?: FormatCompare } export type AddedFormat = | true | RegExp | FormatValidator | FormatDefinition | FormatDefinition | AsyncFormatDefinition | AsyncFormatDefinition export type Format = AddedFormat | string export interface RegExpEngine { (pattern: string, u: string): RegExpLike code: string } export interface RegExpLike { test: (s: string) => boolean } export interface UriResolver { parse(uri: string): URIComponent resolve(base: string, path: string): string serialize(component: URIComponent): string } /* eslint-disable @typescript-eslint/no-empty-interface */ type StrictNullChecksWrapper = undefined extends null ? `strictNullChecks must be true in tsconfig to use ${Name}` : Type type UnionToIntersection = (U extends any ? (_: U) => void : never) extends (_: infer I) => void ? I : never export type SomeJSONSchema = UncheckedJSONSchemaType type UncheckedPartialSchema = Partial> export type PartialSchema = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema> type JSONType = IsPartial extends true ? T | undefined : T interface NumberKeywords { minimum?: number maximum?: number exclusiveMinimum?: number exclusiveMaximum?: number multipleOf?: number format?: string } interface StringKeywords { minLength?: number maxLength?: number pattern?: string format?: string } type UncheckedJSONSchemaType = ( | // these two unions allow arbitrary unions of types { anyOf: readonly UncheckedJSONSchemaType[] } | { oneOf: readonly UncheckedJSONSchemaType[] } // this union allows for { type: (primitive)[] } style schemas | ({ type: readonly (T extends number ? JSONType<"number" | "integer", IsPartial> : T extends string ? JSONType<"string", IsPartial> : T extends boolean ? JSONType<"boolean", IsPartial> : never)[] } & UnionToIntersection< T extends number ? NumberKeywords : T extends string ? StringKeywords : T extends boolean ? // eslint-disable-next-line @typescript-eslint/ban-types {} : never >) // this covers "normal" types; it's last so typescript looks to it first for errors | ((T extends number ? { type: JSONType<"number" | "integer", IsPartial> } & NumberKeywords : T extends string ? { type: JSONType<"string", IsPartial> } & StringKeywords : T extends boolean ? { type: JSONType<"boolean", IsPartial> } : T extends readonly [any, ...any[]] ? { // JSON AnySchema for tuple type: JSONType<"array", IsPartial> items: { readonly [K in keyof T]-?: UncheckedJSONSchemaType & Nullable } & {length: T["length"]} minItems: T["length"] } & ({maxItems: T["length"]} | {additionalItems: false}) : T extends readonly any[] ? { type: JSONType<"array", IsPartial> items: UncheckedJSONSchemaType contains?: UncheckedPartialSchema minItems?: number maxItems?: number minContains?: number maxContains?: number uniqueItems?: true additionalItems?: never } : T extends Record ? { // JSON AnySchema for records and dictionaries // "required" is not optional because it is often forgotten // "properties" are optional for more concise dictionary schemas // "patternProperties" and can be only used with interfaces that have string index type: JSONType<"object", IsPartial> additionalProperties?: boolean | UncheckedJSONSchemaType unevaluatedProperties?: boolean | UncheckedJSONSchemaType properties?: IsPartial extends true ? Partial> : UncheckedPropertiesSchema patternProperties?: Record> propertyNames?: Omit, "type"> & {type?: "string"} dependencies?: {[K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema} dependentRequired?: {[K in keyof T]?: readonly (keyof T)[]} dependentSchemas?: {[K in keyof T]?: UncheckedPartialSchema} minProperties?: number maxProperties?: number } & (IsPartial extends true // "required" is not necessary if it's a non-partial type with no required keys // are listed it only asserts that optional cannot be listed. // "required" type does not guarantee that all required properties ? {required: readonly (keyof T)[]} : [UncheckedRequiredMembers] extends [never] ? {required?: readonly UncheckedRequiredMembers[]} : {required: readonly UncheckedRequiredMembers[]}) : T extends null ? { type: JSONType<"null", IsPartial> nullable: true } : never) & { allOf?: readonly UncheckedPartialSchema[] anyOf?: readonly UncheckedPartialSchema[] oneOf?: readonly UncheckedPartialSchema[] if?: UncheckedPartialSchema then?: UncheckedPartialSchema else?: UncheckedPartialSchema not?: UncheckedPartialSchema }) ) & { [keyword: string]: any $id?: string $ref?: string $defs?: Record> definitions?: Record> } export type JSONSchemaType = StrictNullChecksWrapper< "JSONSchemaType", UncheckedJSONSchemaType > type Known = | {[key: string]: Known} | [Known, ...Known[]] | Known[] | number | string | boolean | null type UncheckedPropertiesSchema = { [K in keyof T]-?: (UncheckedJSONSchemaType & Nullable) | {$ref: string} } export type PropertiesSchema = StrictNullChecksWrapper< "PropertiesSchema", UncheckedPropertiesSchema > type UncheckedRequiredMembers = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T] export type RequiredMembers = StrictNullChecksWrapper< "RequiredMembers", UncheckedRequiredMembers > type Nullable = undefined extends T ? { nullable: true const?: null // any non-null value would fail `const: null`, `null` would fail any other value in const enum?: readonly (T | null)[] // `null` must be explicitly included in "enum" for `null` to pass default?: T | null } : { nullable?: false const?: T enum?: readonly T[] default?: T } /** numeric strings */ type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" /** string strings */ type StringType = "string" | "timestamp" /** Generic JTD Schema without inference of the represented type */ export type SomeJTDSchemaType = ( | // ref {ref: string} // primitives | {type: NumberType | StringType | "boolean"} // enum | {enum: string[]} // elements | {elements: SomeJTDSchemaType} // values | {values: SomeJTDSchemaType} // properties | { properties: Record optionalProperties?: Record additionalProperties?: boolean } | { properties?: Record optionalProperties: Record additionalProperties?: boolean } // discriminator | {discriminator: string; mapping: Record} // empty // NOTE see the end of // https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492 // eslint-disable-next-line @typescript-eslint/ban-types | {} ) & { nullable?: boolean metadata?: Record definitions?: Record } /** required keys of an object, not undefined */ type RequiredKeys = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T] /** optional or undifined-able keys of an object */ type OptionalKeys = { [K in keyof T]-?: undefined extends T[K] ? K : never }[keyof T] /** type is true if T is a union type */ type IsUnion_ = false extends ( T extends unknown ? ([U] extends [T] ? false : true) : never ) ? false : true type IsUnion = IsUnion_ /** type is true if T is identically E */ type TypeEquality = [T] extends [E] ? ([E] extends [T] ? true : false) : false /** type is true if T or null is identically E or null*/ type NullTypeEquality = TypeEquality /** gets only the string literals of a type or null if a type isn't a string literal */ type EnumString = [T] extends [never] ? null : T extends string ? string extends T ? null : T : null /** true if type is a union of string literals */ type IsEnum = null extends EnumString ? false : true /** true only if all types are array types (not tuples) */ // NOTE relies on the fact that tuples don't have an index at 0.5, but arrays // have an index at every number type IsElements = false extends IsUnion ? [T] extends [readonly unknown[]] ? undefined extends T[0.5] ? false : true : false : false /** true if the the type is a values type */ type IsValues = false extends IsUnion ? TypeEquality : false /** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */ type IsRecord = Union extends IsUnion ? null extends EnumString ? false : true : false /** true if type represents an empty record */ type IsEmptyRecord = [T] extends [Record] ? [T] extends [never] ? false : true : false /** actual schema */ export type JTDSchemaType = Record> = ( | // refs - where null wasn't specified, must match exactly (null extends EnumString ? never : | ({[K in keyof D]: [T] extends [D[K]] ? {ref: K} : never}[keyof D] & {nullable?: false}) // nulled refs - if ref is nullable and nullable is specified, then it can // match either null or non-null definitions | (null extends T ? { [K in keyof D]: [Exclude] extends [Exclude] ? {ref: K} : never }[keyof D] & {nullable: true} : never)) // empty - empty schemas also treat nullable differently in that it's now fully ignored | (unknown extends T ? {nullable?: boolean} : never) // all other types // numbers - only accepts the type number | ((true extends NullTypeEquality ? {type: NumberType} : // booleans - accepts the type boolean true extends NullTypeEquality ? {type: "boolean"} : // strings - only accepts the type string true extends NullTypeEquality ? {type: StringType} : // strings - only accepts the type Date true extends NullTypeEquality ? {type: "timestamp"} : // enums - only accepts union of string literals // TODO we can't actually check that everything in the union was specified true extends IsEnum> ? {enum: EnumString>[]} : // arrays - only accepts arrays, could be array of unions to be resolved later true extends IsElements> ? T extends readonly (infer E)[] ? { elements: JTDSchemaType } : never : // empty properties true extends IsEmptyRecord> ? | {properties: Record; optionalProperties?: Record} | {optionalProperties: Record} : // values true extends IsValues> ? T extends Record ? { values: JTDSchemaType } : never : // properties true extends IsRecord, false> ? ([RequiredKeys>] extends [never] ? { properties?: Record } : { properties: {[K in RequiredKeys]: JTDSchemaType} }) & ([OptionalKeys>] extends [never] ? { optionalProperties?: Record } : { optionalProperties: { [K in OptionalKeys]: JTDSchemaType, D> } }) & { additionalProperties?: boolean } : // discriminator true extends IsRecord, true> ? { [K in keyof Exclude]-?: Exclude[K] extends string ? { discriminator: K mapping: { // TODO currently allows descriminator to be present in schema [M in Exclude[K]]: JTDSchemaType< Omit ? T : never, K>, D > } } : never }[keyof Exclude] : never) & (null extends T ? { nullable: true } : {nullable?: false})) ) & { // extra properties metadata?: Record // TODO these should only be allowed at the top level definitions?: {[K in keyof D]: JTDSchemaType} } type JTDDataDef> = | // ref (S extends {ref: string} ? D extends {[K in S["ref"]]: infer V} ? JTDDataDef : never : // type S extends {type: NumberType} ? number : S extends {type: "boolean"} ? boolean : S extends {type: "string"} ? string : S extends {type: "timestamp"} ? string | Date : // enum S extends {enum: readonly (infer E)[]} ? string extends E ? never : [E] extends [string] ? E : never : // elements S extends {elements: infer E} ? JTDDataDef[] : // properties S extends { properties: Record optionalProperties?: Record additionalProperties?: boolean } ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< S["optionalProperties"][K], D > } & ([S["additionalProperties"]] extends [true] ? Record : unknown) : S extends { properties?: Record optionalProperties: Record additionalProperties?: boolean } ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< S["optionalProperties"][K], D > } & ([S["additionalProperties"]] extends [true] ? Record : unknown) : // values S extends {values: infer V} ? Record> : // discriminator S extends {discriminator: infer M; mapping: Record} ? [M] extends [string] ? { [K in keyof S["mapping"]]: JTDDataDef & {[KM in M]: K} }[keyof S["mapping"]] : never : // empty unknown) | (S extends {nullable: true} ? null : never) export type JTDDataType = S extends {definitions: Record} ? JTDDataDef : JTDDataDef> import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, AnySchema, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, not, Name} from "../../compile/codegen" import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}, AnySchema> const error: KeywordErrorDefinition = { message: ({params: {len}}) => str`must NOT have more than ${len} items`, params: ({params: {len}}) => _`{limit: ${len}}`, } const def: CodeKeywordDefinition = { keyword: "additionalItems" as const, type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error, code(cxt: KeywordCxt) { const {parentSchema, it} = cxt const {items} = parentSchema if (!Array.isArray(items)) { checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas') return } validateAdditionalItems(cxt, items) }, } export function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void { const {gen, schema, data, keyword, it} = cxt it.items = true const len = gen.const("len", _`${data}.length`) if (schema === false) { cxt.setParams({len: items.length}) cxt.pass(_`${len} <= ${items.length}`) } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var gen.if(not(valid), () => validateItems(valid)) cxt.ok(valid) } function validateItems(valid: Name): void { gen.forRange("i", items.length, len, (i) => { cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid) if (!it.allErrors) gen.if(not(valid), () => gen.break()) }) } } export default def import type { CodeKeywordDefinition, AddedKeywordDefinition, ErrorObject, KeywordErrorDefinition, AnySchema, } from "../../types" import {allSchemaProperties, usePattern, isOwnProperty} from "../code" import {_, nil, or, not, Code, Name} from "../../compile/codegen" import N from "../../compile/names" import type {SubschemaArgs} from "../../compile/validate/subschema" import {alwaysValidSchema, schemaRefOrVal, Type} from "../../compile/util" export type AdditionalPropertiesError = ErrorObject< "additionalProperties", {additionalProperty: string}, AnySchema > const error: KeywordErrorDefinition = { message: "must NOT have additional properties", params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, } const def: CodeKeywordDefinition & AddedKeywordDefinition = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error, code(cxt) { const {gen, schema, parentSchema, data, errsCount, it} = cxt /* istanbul ignore if */ if (!errsCount) throw new Error("ajv implementation error") const {allErrors, opts} = it it.props = true if (opts.removeAdditional !== "all" && alwaysValidSchema(it, schema)) return const props = allSchemaProperties(parentSchema.properties) const patProps = allSchemaProperties(parentSchema.patternProperties) checkAdditionalProperties() cxt.ok(_`${errsCount} === ${N.errors}`) function checkAdditionalProperties(): void { gen.forIn("key", data, (key: Name) => { if (!props.length && !patProps.length) additionalPropertyCode(key) else gen.if(isAdditional(key), () => additionalPropertyCode(key)) }) } function isAdditional(key: Name): Code { let definedProp: Code if (props.length > 8) { // TODO maybe an option instead of hard-coded 8? const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties") definedProp = isOwnProperty(gen, propsSchema as Code, key) } else if (props.length) { definedProp = or(...props.map((p) => _`${key} === ${p}`)) } else { definedProp = nil } if (patProps.length) { definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`)) } return not(definedProp) } function deleteAdditional(key: Name): void { gen.code(_`delete ${data}[${key}]`) } function additionalPropertyCode(key: Name): void { if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { deleteAdditional(key) return } if (schema === false) { cxt.setParams({additionalProperty: key}) cxt.error() if (!allErrors) gen.break() return } if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { const valid = gen.name("valid") if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false) gen.if(not(valid), () => { cxt.reset() deleteAdditional(key) }) } else { applyAdditionalSchema(key, valid) if (!allErrors) gen.if(not(valid), () => gen.break()) } } } function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void { const subschema: SubschemaArgs = { keyword: "additionalProperties", dataProp: key, dataPropType: Type.Str, } if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false, }) } cxt.subschema(subschema, valid) } }, } export default def import type {CodeKeywordDefinition, AnySchema} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {alwaysValidSchema} from "../../compile/util" const def: CodeKeywordDefinition = { keyword: "allOf", schemaType: "array", code(cxt: KeywordCxt) { const {gen, schema, it} = cxt /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") const valid = gen.name("valid") schema.forEach((sch: AnySchema, i: number) => { if (alwaysValidSchema(it, sch)) return const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid) cxt.ok(valid) cxt.mergeEvaluated(schCxt) }) }, } export default def import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" import {validateUnion} from "../code" export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]> const def: CodeKeywordDefinition = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: validateUnion, error: {message: "must match a schema in anyOf"}, } export default def import type { CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject, AnySchema, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, Name} from "../../compile/codegen" import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" export type ContainsError = ErrorObject< "contains", {minContains: number; maxContains?: number}, AnySchema > const error: KeywordErrorDefinition = { message: ({params: {min, max}}) => max === undefined ? str`must contain at least ${min} valid item(s)` : str`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({params: {min, max}}) => max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`, } const def: CodeKeywordDefinition = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error, code(cxt: KeywordCxt) { const {gen, schema, parentSchema, data, it} = cxt let min: number let max: number | undefined const {minContains, maxContains} = parentSchema if (it.opts.next) { min = minContains === undefined ? 1 : minContains max = maxContains } else { min = 1 } const len = gen.const("len", _`${data}.length`) cxt.setParams({min, max}) if (max === undefined && min === 0) { checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`) return } if (max !== undefined && min > max) { checkStrictMode(it, `"minContains" > "maxContains" is always invalid`) cxt.fail() return } if (alwaysValidSchema(it, schema)) { let cond = _`${len} >= ${min}` if (max !== undefined) cond = _`${cond} && ${len} <= ${max}` cxt.pass(cond) return } it.items = true const valid = gen.name("valid") if (max === undefined && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())) } else if (min === 0) { gen.let(valid, true) if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount) } else { gen.let(valid, false) validateItemsWithCount() } cxt.result(valid, () => cxt.reset()) function validateItemsWithCount(): void { const schValid = gen.name("_valid") const count = gen.let("count", 0) validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))) } function validateItems(_valid: Name, block: () => void): void { gen.forRange("i", 0, len, (i) => { cxt.subschema( { keyword: "contains", dataProp: i, dataPropType: Type.Num, compositeRule: true, }, _valid ) block() }) } function checkLimits(count: Name): void { gen.code(_`${count}++`) if (max === undefined) { gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break()) } else { gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break()) if (min === 1) gen.assign(valid, true) else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true)) } } }, } export default def import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, SchemaMap, AnySchema, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str} from "../../compile/codegen" import {alwaysValidSchema} from "../../compile/util" import {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from "../code" export type PropertyDependencies = {[K in string]?: string[]} export interface DependenciesErrorParams { property: string missingProperty: string depsCount: number deps: string // TODO change to string[] } type SchemaDependencies = SchemaMap export type DependenciesError = ErrorObject< "dependencies", DependenciesErrorParams, {[K in string]?: string[] | AnySchema} > export const error: KeywordErrorDefinition = { message: ({params: {property, depsCount, deps}}) => { const property_ies = depsCount === 1 ? "property" : "properties" return str`must have ${property_ies} ${deps} when property ${property} is present` }, params: ({params: {property, depsCount, deps, missingProperty}}) => _`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}`, // TODO change to reference } const def: CodeKeywordDefinition = { keyword: "dependencies", type: "object", schemaType: "object", error, code(cxt: KeywordCxt) { const [propDeps, schDeps] = splitDependencies(cxt) validatePropertyDeps(cxt, propDeps) validateSchemaDeps(cxt, schDeps) }, } function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] { const propertyDeps: PropertyDependencies = {} const schemaDeps: SchemaDependencies = {} for (const key in schema) { if (key === "__proto__") continue const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps deps[key] = schema[key] } return [propertyDeps, schemaDeps] } export function validatePropertyDeps( cxt: KeywordCxt, propertyDeps: {[K in string]?: string[]} = cxt.schema ): void { const {gen, data, it} = cxt if (Object.keys(propertyDeps).length === 0) return const missing = gen.let("missing") for (const prop in propertyDeps) { const deps = propertyDeps[prop] as string[] if (deps.length === 0) continue const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties) cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", "), }) if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { checkReportMissingProp(cxt, depProp) } }) } else { gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`) reportMissingProp(cxt, missing) gen.else() } } } export function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void { const {gen, data, keyword, it} = cxt const valid = gen.name("valid") for (const prop in schemaDeps) { if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue gen.if( propertyInData(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid) cxt.mergeValidEvaluated(schCxt, valid) }, () => gen.var(valid, true) // TODO var ) cxt.ok(valid) } } export default def import type {CodeKeywordDefinition} from "../../types" import {validateSchemaDeps} from "./dependencies" const def: CodeKeywordDefinition = { keyword: "dependentSchemas", type: "object", schemaType: "object", code: (cxt) => validateSchemaDeps(cxt), } export default def import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, AnySchema, } from "../../types" import type {SchemaObjCxt} from "../../compile" import type {KeywordCxt} from "../../compile/validate" import {_, str, not, Name} from "../../compile/codegen" import {alwaysValidSchema, checkStrictMode} from "../../compile/util" export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema> const error: KeywordErrorDefinition = { message: ({params}) => str`must match "${params.ifClause}" schema`, params: ({params}) => _`{failingKeyword: ${params.ifClause}}`, } const def: CodeKeywordDefinition = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error, code(cxt: KeywordCxt) { const {gen, parentSchema, it} = cxt if (parentSchema.then === undefined && parentSchema.else === undefined) { checkStrictMode(it, '"if" without "then" and "else" is ignored') } const hasThen = hasSchema(it, "then") const hasElse = hasSchema(it, "else") if (!hasThen && !hasElse) return const valid = gen.let("valid", true) const schValid = gen.name("_valid") validateIf() cxt.reset() if (hasThen && hasElse) { const ifClause = gen.let("ifClause") cxt.setParams({ifClause}) gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)) } else if (hasThen) { gen.if(schValid, validateClause("then")) } else { gen.if(not(schValid), validateClause("else")) } cxt.pass(valid, () => cxt.error(true)) function validateIf(): void { const schCxt = cxt.subschema( { keyword: "if", compositeRule: true, createErrors: false, allErrors: false, }, schValid ) cxt.mergeEvaluated(schCxt) } function validateClause(keyword: string, ifClause?: Name): () => void { return () => { const schCxt = cxt.subschema({keyword}, schValid) gen.assign(valid, schValid) cxt.mergeValidEvaluated(schCxt, valid) if (ifClause) gen.assign(ifClause, _`${keyword}`) else cxt.setParams({ifClause: keyword}) } } }, } function hasSchema(it: SchemaObjCxt, keyword: string): boolean { const schema = it.schema[keyword] return schema !== undefined && !alwaysValidSchema(it, schema) } export default def import type {ErrorNoParams, Vocabulary} from "../../types" import additionalItems, {AdditionalItemsError} from "./additionalItems" import prefixItems from "./prefixItems" import items from "./items" import items2020, {ItemsError} from "./items2020" import contains, {ContainsError} from "./contains" import dependencies, {DependenciesError} from "./dependencies" import propertyNames, {PropertyNamesError} from "./propertyNames" import additionalProperties, {AdditionalPropertiesError} from "./additionalProperties" import properties from "./properties" import patternProperties from "./patternProperties" import notKeyword, {NotKeywordError} from "./not" import anyOf, {AnyOfError} from "./anyOf" import oneOf, {OneOfError} from "./oneOf" import allOf from "./allOf" import ifKeyword, {IfKeywordError} from "./if" import thenElse from "./thenElse" export default function getApplicator(draft2020 = false): Vocabulary { const applicator = [ // any notKeyword, anyOf, oneOf, allOf, ifKeyword, thenElse, // object propertyNames, additionalProperties, dependencies, properties, patternProperties, ] // array if (draft2020) applicator.push(prefixItems, items2020) else applicator.push(additionalItems, items) applicator.push(contains) return applicator } export type ApplicatorKeywordError = | ErrorNoParams<"false schema"> | AdditionalItemsError | ItemsError | ContainsError | AdditionalPropertiesError | DependenciesError | IfKeywordError | AnyOfError | OneOfError | NotKeywordError | PropertyNamesError import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_} from "../../compile/codegen" import {alwaysValidSchema, mergeEvaluated, checkStrictMode} from "../../compile/util" import {validateArray} from "../code" const def: CodeKeywordDefinition = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt: KeywordCxt) { const {schema, it} = cxt if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema) it.items = true if (alwaysValidSchema(it, schema)) return cxt.ok(validateArray(cxt)) }, } export function validateTuple( cxt: KeywordCxt, extraItems: string, schArr: AnySchema[] = cxt.schema ): void { const {gen, parentSchema, data, keyword, it} = cxt checkStrictTuple(parentSchema) if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = mergeEvaluated.items(gen, schArr.length, it.items) } const valid = gen.name("valid") const len = gen.const("len", _`${data}.length`) schArr.forEach((sch: AnySchema, i: number) => { if (alwaysValidSchema(it, sch)) return gen.if(_`${len} > ${i}`, () => cxt.subschema( { keyword, schemaProp: i, dataProp: i, }, valid ) ) cxt.ok(valid) }) function checkStrictTuple(sch: AnySchemaObject): void { const {opts, errSchemaPath} = it const l = schArr.length const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false) if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"` checkStrictMode(it, msg, opts.strictTuples) } } } export default def import type { CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject, AnySchema, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str} from "../../compile/codegen" import {alwaysValidSchema} from "../../compile/util" import {validateArray} from "../code" import {validateAdditionalItems} from "./additionalItems" export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema> const error: KeywordErrorDefinition = { message: ({params: {len}}) => str`must NOT have more than ${len} items`, params: ({params: {len}}) => _`{limit: ${len}}`, } const def: CodeKeywordDefinition = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error, code(cxt: KeywordCxt) { const {schema, parentSchema, it} = cxt const {prefixItems} = parentSchema it.items = true if (alwaysValidSchema(it, schema)) return if (prefixItems) validateAdditionalItems(cxt, prefixItems) else cxt.ok(validateArray(cxt)) }, } export default def import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {alwaysValidSchema} from "../../compile/util" export type NotKeywordError = ErrorNoParams<"not", AnySchema> const def: CodeKeywordDefinition = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt: KeywordCxt) { const {gen, schema, it} = cxt if (alwaysValidSchema(it, schema)) { cxt.fail() return } const valid = gen.name("valid") cxt.subschema( { keyword: "not", compositeRule: true, createErrors: false, allErrors: false, }, valid ) cxt.failResult( valid, () => cxt.reset(), () => cxt.error() ) }, error: {message: "must NOT be valid"}, } export default def import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, AnySchema, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, Name} from "../../compile/codegen" import {alwaysValidSchema} from "../../compile/util" import {SchemaCxt} from "../../compile" export type OneOfError = ErrorObject< "oneOf", {passingSchemas: [number, number] | null}, AnySchema[] > const error: KeywordErrorDefinition = { message: "must match exactly one schema in oneOf", params: ({params}) => _`{passingSchemas: ${params.passing}}`, } const def: CodeKeywordDefinition = { keyword: "oneOf", schemaType: "array", trackErrors: true, error, code(cxt: KeywordCxt) { const {gen, schema, parentSchema, it} = cxt /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") if (it.opts.discriminator && parentSchema.discriminator) return const schArr: AnySchema[] = schema const valid = gen.let("valid", false) const passing = gen.let("passing", null) const schValid = gen.name("_valid") cxt.setParams({passing}) // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas gen.block(validateOneOf) cxt.result( valid, () => cxt.reset(), () => cxt.error(true) ) function validateOneOf(): void { schArr.forEach((sch: AnySchema, i: number) => { let schCxt: SchemaCxt | undefined if (alwaysValidSchema(it, sch)) { gen.var(schValid, true) } else { schCxt = cxt.subschema( { keyword: "oneOf", schemaProp: i, compositeRule: true, }, schValid ) } if (i > 0) { gen .if(_`${schValid} && ${valid}`) .assign(valid, false) .assign(passing, _`[${passing}, ${i}]`) .else() } gen.if(schValid, () => { gen.assign(valid, true) gen.assign(passing, i) if (schCxt) cxt.mergeEvaluated(schCxt, Name) }) }) } }, } export default def import type {CodeKeywordDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {allSchemaProperties, usePattern} from "../code" import {_, not, Name} from "../../compile/codegen" import {alwaysValidSchema, checkStrictMode} from "../../compile/util" import {evaluatedPropsToName, Type} from "../../compile/util" import {AnySchema} from "../../types" const def: CodeKeywordDefinition = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt: KeywordCxt) { const {gen, schema, data, parentSchema, it} = cxt const {opts} = it const patterns = allSchemaProperties(schema) const alwaysValidPatterns = patterns.filter((p) => alwaysValidSchema(it, schema[p] as AnySchema) ) if ( patterns.length === 0 || (alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) ) { return } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties const valid = gen.name("valid") if (it.props !== true && !(it.props instanceof Name)) { it.props = evaluatedPropsToName(gen, it.props) } const {props} = it validatePatternProperties() function validatePatternProperties(): void { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat) if (it.allErrors) { validateProperties(pat) } else { gen.var(valid, true) // TODO var validateProperties(pat) gen.if(valid) } } } function checkMatchingProperties(pat: string): void { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { checkStrictMode( it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)` ) } } } function validateProperties(pat: string): void { gen.forIn("key", data, (key) => { gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat) if (!alwaysValid) { cxt.subschema( { keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: Type.Str, }, valid ) } if (it.opts.unevaluated && props !== true) { gen.assign(_`${props}[${key}]`, true) } else if (!alwaysValid && !it.allErrors) { // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) // or if all properties were evaluated (props === true) gen.if(not(valid), () => gen.break()) } }) }) } }, } export default def import type {CodeKeywordDefinition} from "../../types" import {validateTuple} from "./items" const def: CodeKeywordDefinition = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => validateTuple(cxt, "items"), } export default def import type {CodeKeywordDefinition} from "../../types" import {KeywordCxt} from "../../compile/validate" import {propertyInData, allSchemaProperties} from "../code" import {alwaysValidSchema, toHash, mergeEvaluated} from "../../compile/util" import apDef from "./additionalProperties" const def: CodeKeywordDefinition = { keyword: "properties", type: "object", schemaType: "object", code(cxt: KeywordCxt) { const {gen, schema, parentSchema, data, it} = cxt if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { apDef.code(new KeywordCxt(it, apDef, "additionalProperties")) } const allProps = allSchemaProperties(schema) for (const prop of allProps) { it.definedProperties.add(prop) } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = mergeEvaluated.props(gen, toHash(allProps), it.props) } const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p])) if (properties.length === 0) return const valid = gen.name("valid") for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop) } else { gen.if(propertyInData(gen, data, prop, it.opts.ownProperties)) applyPropertySchema(prop) if (!it.allErrors) gen.else().var(valid, true) gen.endIf() } cxt.it.definedProperties.add(prop) cxt.ok(valid) } function hasDefault(prop: string): boolean | undefined { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined } function applyPropertySchema(prop: string): void { cxt.subschema( { keyword: "properties", schemaProp: prop, dataProp: prop, }, valid ) } }, } export default def import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, AnySchema, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, not} from "../../compile/codegen" import {alwaysValidSchema} from "../../compile/util" export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema> const error: KeywordErrorDefinition = { message: "property name must be valid", params: ({params}) => _`{propertyName: ${params.propertyName}}`, } const def: CodeKeywordDefinition = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error, code(cxt: KeywordCxt) { const {gen, schema, data, it} = cxt if (alwaysValidSchema(it, schema)) return const valid = gen.name("valid") gen.forIn("key", data, (key) => { cxt.setParams({propertyName: key}) cxt.subschema( { keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true, }, valid ) gen.if(not(valid), () => { cxt.error(true) if (!it.allErrors) gen.break() }) }) cxt.ok(valid) }, } export default def import type {CodeKeywordDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {checkStrictMode} from "../../compile/util" const def: CodeKeywordDefinition = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({keyword, parentSchema, it}: KeywordCxt) { if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`) }, } export default def import type {AnySchema, SchemaMap} from "../types" import type {SchemaCxt} from "../compile" import type {KeywordCxt} from "../compile/validate" import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen" import {alwaysValidSchema, Type} from "../compile/util" import N from "../compile/names" import {useFunc} from "../compile/util" export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void { const {gen, data, it} = cxt gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({missingProperty: _`${prop}`}, true) cxt.error() }) } export function checkMissingProp( {gen, data, it: {opts}}: KeywordCxt, properties: string[], missing: Name ): Code { return or( ...properties.map((prop) => and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`) ) ) } export function reportMissingProp(cxt: KeywordCxt, missing: Name): void { cxt.setParams({missingProperty: missing}, true) cxt.error() } export function hasPropFunc(gen: CodeGen): Name { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: _`Object.prototype.hasOwnProperty`, }) } export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code { return _`${hasPropFunc(gen)}.call(${data}, ${property})` } export function propertyInData( gen: CodeGen, data: Name, property: Name | string, ownProperties?: boolean ): Code { const cond = _`${data}${getProperty(property)} !== undefined` return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond } export function noPropertyInData( gen: CodeGen, data: Name, property: Name | string, ownProperties?: boolean ): Code { const cond = _`${data}${getProperty(property)} === undefined` return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond } export function allSchemaProperties(schemaMap?: SchemaMap): string[] { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [] } export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] { return allSchemaProperties(schemaMap).filter( (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema) ) } export function callValidateCode( {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt, func: Code, context: Code, passSchema?: boolean ): Code { const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data const valCxt: [Name, Code | number][] = [ [N.instancePath, strConcat(N.instancePath, errorPath)], [N.parentData, it.parentData], [N.parentDataProperty, it.parentDataProperty], [N.rootData, N.rootData], ] if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors]) const args = _`${dataAndSchema}, ${gen.object(...valCxt)}` return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})` } const newRegExp = _`new RegExp` export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name { const u = opts.unicodeRegExp ? "u" : "" const {regExp} = opts.code const rx = regExp(pattern, u) return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`, }) } export function validateArray(cxt: KeywordCxt): Name { const {gen, data, keyword, it} = cxt const valid = gen.name("valid") if (it.allErrors) { const validArr = gen.let("valid", true) validateItems(() => gen.assign(validArr, false)) return validArr } gen.var(valid, true) validateItems(() => gen.break()) return valid function validateItems(notValid: () => void): void { const len = gen.const("len", _`${data}.length`) gen.forRange("i", 0, len, (i) => { cxt.subschema( { keyword, dataProp: i, dataPropType: Type.Num, }, valid ) gen.if(not(valid), notValid) }) } } export function validateUnion(cxt: KeywordCxt): void { const {gen, schema, keyword, it} = cxt /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch)) if (alwaysValid && !it.opts.unevaluated) return const valid = gen.let("valid", false) const schValid = gen.name("_valid") gen.block(() => schema.forEach((_sch: AnySchema, i: number) => { const schCxt = cxt.subschema( { keyword, schemaProp: i, compositeRule: true, }, schValid ) gen.assign(valid, _`${valid} || ${schValid}`) const merged = cxt.mergeValidEvaluated(schCxt, schValid) // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) // or if all properties and items were evaluated (it.props === true && it.items === true) if (!merged) gen.if(not(valid)) }) ) cxt.result( valid, () => cxt.reset(), () => cxt.error(true) ) } import type {CodeKeywordDefinition} from "../../types" const def: CodeKeywordDefinition = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID') }, } export default def import type {Vocabulary} from "../../types" import idKeyword from "./id" import refKeyword from "./ref" const core: Vocabulary = [ "$schema", "$id", "$defs", "$vocabulary", {keyword: "$comment"}, "definitions", idKeyword, refKeyword, ] export default core import type {CodeKeywordDefinition, AnySchema} from "../../types" import type {KeywordCxt} from "../../compile/validate" import MissingRefError from "../../compile/ref_error" import {callValidateCode} from "../code" import {_, nil, stringify, Code, Name} from "../../compile/codegen" import N from "../../compile/names" import {SchemaEnv, resolveRef} from "../../compile" import {mergeEvaluated} from "../../compile/util" const def: CodeKeywordDefinition = { keyword: "$ref", schemaType: "string", code(cxt: KeywordCxt): void { const {gen, schema: $ref, it} = cxt const {baseId, schemaEnv: env, validateName, opts, self} = it const {root} = env if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef() const schOrEnv = resolveRef.call(self, root, baseId, $ref) if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref) if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv) return inlineRefSchema(schOrEnv) function callRootRef(): void { if (env === root) return callRef(cxt, validateName, env, env.$async) const rootName = gen.scopeValue("root", {ref: root}) return callRef(cxt, _`${rootName}.validate`, root, root.$async) } function callValidate(sch: SchemaEnv): void { const v = getValidate(cxt, sch) callRef(cxt, v, sch, sch.$async) } function inlineRefSchema(sch: AnySchema): void { const schName = gen.scopeValue( "schema", opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch} ) const valid = gen.name("valid") const schCxt = cxt.subschema( { schema: sch, dataTypes: [], schemaPath: nil, topSchemaRef: schName, errSchemaPath: $ref, }, valid ) cxt.mergeEvaluated(schCxt) cxt.ok(valid) } }, } export function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code { const {gen} = cxt return sch.validate ? gen.scopeValue("validate", {ref: sch.validate}) : _`${gen.scopeValue("wrapper", {ref: sch})}.validate` } export function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { const {gen, it} = cxt const {allErrors, schemaEnv: env, opts} = it const passCxt = opts.passContext ? N.this : nil if ($async) callAsyncRef() else callSyncRef() function callAsyncRef(): void { if (!env.$async) throw new Error("async schema referenced by sync schema") const valid = gen.let("valid") gen.try( () => { gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result if (!allErrors) gen.assign(valid, true) }, (e) => { gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) addErrorsFrom(e) if (!allErrors) gen.assign(valid, false) } ) cxt.ok(valid) } function callSyncRef(): void { cxt.result( callValidateCode(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v) ) } function addErrorsFrom(source: Code): void { const errs = _`${source}.errors` gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged gen.assign(N.errors, _`${N.vErrors}.length`) } function addEvaluatedFrom(source: Code): void { if (!it.opts.unevaluated) return const schEvaluated = sch?.validate?.evaluated // TODO refactor if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== undefined) { it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) } } else { const props = gen.var("props", _`${source}.evaluated.props`) it.props = mergeEvaluated.props(gen, props, it.props, Name) } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== undefined) { it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) } } else { const items = gen.var("items", _`${source}.evaluated.items`) it.items = mergeEvaluated.items(gen, items, it.items, Name) } } } } export default def import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, getProperty, Name} from "../../compile/codegen" import {DiscrError, DiscrErrorObj} from "../discriminator/types" import {resolveRef, SchemaEnv} from "../../compile" import MissingRefError from "../../compile/ref_error" import {schemaHasRulesButRef} from "../../compile/util" export type DiscriminatorError = DiscrErrorObj | DiscrErrorObj const error: KeywordErrorDefinition = { message: ({params: {discrError, tagName}}) => discrError === DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({params: {discrError, tag, tagName}}) => _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, } const def: CodeKeywordDefinition = { keyword: "discriminator", type: "object", schemaType: "object", error, code(cxt: KeywordCxt) { const {gen, data, schema, parentSchema, it} = cxt const {oneOf} = parentSchema if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option") } const tagName = schema.propertyName if (typeof tagName != "string") throw new Error("discriminator: requires propertyName") if (schema.mapping) throw new Error("discriminator: mapping is not supported") if (!oneOf) throw new Error("discriminator: requires oneOf keyword") const valid = gen.let("valid", false) const tag = gen.const("tag", _`${data}${getProperty(tagName)}`) gen.if( _`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName}) ) cxt.ok(valid) function validateMapping(): void { const mapping = getMapping() gen.if(false) for (const tagValue in mapping) { gen.elseIf(_`${tag} === ${tagValue}`) gen.assign(valid, applyTagSchema(mapping[tagValue])) } gen.else() cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName}) gen.endIf() } function applyTagSchema(schemaProp?: number): Name { const _valid = gen.name("valid") const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid) cxt.mergeEvaluated(schCxt, Name) return _valid } function getMapping(): {[T in string]?: number} { const oneOfMapping: {[T in string]?: number} = {} const topRequired = hasRequired(parentSchema) let tagRequired = true for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i] if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) { const ref = sch.$ref sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref) if (sch instanceof SchemaEnv) sch = sch.schema if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref) } const propSch = sch?.properties?.[tagName] if (typeof propSch != "object") { throw new Error( `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"` ) } tagRequired = tagRequired && (topRequired || hasRequired(sch)) addMappings(propSch, i) } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`) return oneOfMapping function hasRequired({required}: AnySchemaObject): boolean { return Array.isArray(required) && required.includes(tagName) } function addMappings(sch: AnySchemaObject, i: number): void { if (sch.const) { addMapping(sch.const, i) } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i) } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`) } } function addMapping(tagValue: unknown, i: number): void { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`) } oneOfMapping[tagValue] = i } } }, } export default def import type {ErrorObject} from "../../types" export enum DiscrError { Tag = "tag", Mapping = "mapping", } export type DiscrErrorObj = ErrorObject< "discriminator", {error: E; tag: string; tagValue: unknown}, string > import type {Vocabulary} from "../types" import coreVocabulary from "./core" import validationVocabulary from "./validation" import getApplicatorVocabulary from "./applicator" import dynamicVocabulary from "./dynamic" import nextVocabulary from "./next" import unevaluatedVocabulary from "./unevaluated" import formatVocabulary from "./format" import {metadataVocabulary, contentVocabulary} from "./metadata" const draft2020Vocabularies: Vocabulary[] = [ dynamicVocabulary, coreVocabulary, validationVocabulary, getApplicatorVocabulary(true), formatVocabulary, metadataVocabulary, contentVocabulary, nextVocabulary, unevaluatedVocabulary, ] export default draft2020Vocabularies import type {Vocabulary} from "../types" import coreVocabulary from "./core" import validationVocabulary from "./validation" import getApplicatorVocabulary from "./applicator" import formatVocabulary from "./format" import {metadataVocabulary, contentVocabulary} from "./metadata" const draft7Vocabularies: Vocabulary[] = [ coreVocabulary, validationVocabulary, getApplicatorVocabulary(), formatVocabulary, metadataVocabulary, contentVocabulary, ] export default draft7Vocabularies import type {CodeKeywordDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, getProperty, Code} from "../../compile/codegen" import N from "../../compile/names" import {SchemaEnv, compileSchema} from "../../compile" import {getValidate} from "../core/ref" const def: CodeKeywordDefinition = { keyword: "$dynamicAnchor", schemaType: "string", code: (cxt) => dynamicAnchor(cxt, cxt.schema), } export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void { const {gen, it} = cxt it.schemaEnv.root.dynamicAnchors[anchor] = true const v = _`${N.dynamicAnchors}${getProperty(anchor)}` const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt) gen.if(_`!${v}`, () => gen.assign(v, validate)) } function _getValidate(cxt: KeywordCxt): Code { const {schemaEnv, schema, self} = cxt.it const {root, baseId, localRefs, meta} = schemaEnv.root const {schemaId} = self.opts const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta}) compileSchema.call(self, sch) return getValidate(cxt, sch) } export default def import type {CodeKeywordDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, getProperty, Code, Name} from "../../compile/codegen" import N from "../../compile/names" import {callRef} from "../core/ref" const def: CodeKeywordDefinition = { keyword: "$dynamicRef", schemaType: "string", code: (cxt) => dynamicRef(cxt, cxt.schema), } export function dynamicRef(cxt: KeywordCxt, ref: string): void { const {gen, keyword, it} = cxt if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`) const anchor = ref.slice(1) if (it.allErrors) { _dynamicRef() } else { const valid = gen.let("valid", false) _dynamicRef(valid) cxt.ok(valid) } function _dynamicRef(valid?: Name): void { // TODO the assumption here is that `recursiveRef: #` always points to the root // of the schema object, which is not correct, because there may be $id that // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. // Because of that 2 tests in recursiveRef.json fail. // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). // (This problem is not tested in JSON-Schema-Test-Suite) if (it.schemaEnv.root.dynamicAnchors[anchor]) { const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`) gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)) } else { _callRef(it.validateName, valid)() } } function _callRef(validate: Code, valid?: Name): () => void { return valid ? () => gen.block(() => { callRef(cxt, validate) gen.let(valid, true) }) : () => callRef(cxt, validate) } } export default def import type {Vocabulary} from "../../types" import dynamicAnchor from "./dynamicAnchor" import dynamicRef from "./dynamicRef" import recursiveAnchor from "./recursiveAnchor" import recursiveRef from "./recursiveRef" const dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef] export default dynamic import type {CodeKeywordDefinition} from "../../types" import {dynamicAnchor} from "./dynamicAnchor" import {checkStrictMode} from "../../compile/util" const def: CodeKeywordDefinition = { keyword: "$recursiveAnchor", schemaType: "boolean", code(cxt) { if (cxt.schema) dynamicAnchor(cxt, "") else checkStrictMode(cxt.it, "$recursiveAnchor: false is ignored") }, } export default def import type {CodeKeywordDefinition} from "../../types" import {dynamicRef} from "./dynamicRef" const def: CodeKeywordDefinition = { keyword: "$recursiveRef", schemaType: "string", code: (cxt) => dynamicRef(cxt, cxt.schema), } export default def import type {TypeError} from "../compile/validate/dataType" import type {ApplicatorKeywordError} from "./applicator" import type {ValidationKeywordError} from "./validation" import type {FormatError} from "./format/format" import type {UnevaluatedPropertiesError} from "./unevaluated/unevaluatedProperties" import type {UnevaluatedItemsError} from "./unevaluated/unevaluatedItems" import type {DependentRequiredError} from "./validation/dependentRequired" import type {DiscriminatorError} from "./discriminator" export type DefinedError = | TypeError | ApplicatorKeywordError | ValidationKeywordError | FormatError | UnevaluatedPropertiesError | UnevaluatedItemsError | DependentRequiredError | DiscriminatorError import type { AddedFormat, FormatValidator, AsyncFormatValidator, CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, nil, or, Code, getProperty, regexpCode} from "../../compile/codegen" type FormatValidate = | FormatValidator | FormatValidator | AsyncFormatValidator | AsyncFormatValidator | RegExp | string | true export type FormatError = ErrorObject<"format", {format: string}, string | {$data: string}> const error: KeywordErrorDefinition = { message: ({schemaCode}) => str`must match format "${schemaCode}"`, params: ({schemaCode}) => _`{format: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error, code(cxt: KeywordCxt, ruleType?: string) { const {gen, data, $data, schema, schemaCode, it} = cxt const {opts, errSchemaPath, schemaEnv, self} = it if (!opts.validateFormats) return if ($data) validate$DataFormat() else validateFormat() function validate$DataFormat(): void { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats, }) const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`) const fType = gen.let("fType") const format = gen.let("format") // TODO simplify gen.if( _`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`), () => gen.assign(fType, _`"string"`).assign(format, fDef) ) cxt.fail$data(or(unknownFmt(), invalidFmt())) function unknownFmt(): Code { if (opts.strictSchema === false) return nil return _`${schemaCode} && !${format}` } function invalidFmt(): Code { const callFormat = schemaEnv.$async ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : _`${format}(${data})` const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))` return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}` } } function validateFormat(): void { const formatDef: AddedFormat | undefined = self.formats[schema] if (!formatDef) { unknownFormat() return } if (formatDef === true) return const [fmtType, format, fmtRef] = getFormat(formatDef) if (fmtType === ruleType) cxt.pass(validCondition()) function unknownFormat(): void { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()) return } throw new Error(unknownMsg()) function unknownMsg(): string { return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"` } } function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] { const code = fmtDef instanceof RegExp ? regexpCode(fmtDef) : opts.code.formats ? _`${opts.code.formats}${getProperty(schema)}` : undefined const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code}) if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`] } return ["string", fmtDef, fmt] } function validCondition(): Code { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema") return _`await ${fmtRef}(${data})` } return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})` } } }, } export default def import type {Vocabulary} from "../../types" import formatKeyword from "./format" const format: Vocabulary = [formatKeyword] export default format import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, not, getProperty, Name} from "../../compile/codegen" import {checkMetadata} from "./metadata" import {checkNullableObject} from "./nullable" import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" import {DiscrError, DiscrErrorObj} from "../discriminator/types" export type JTDDiscriminatorError = | _JTDTypeError<"discriminator", "object", string> | DiscrErrorObj | DiscrErrorObj const error: KeywordErrorDefinition = { message: (cxt) => { const {schema, params} = cxt return params.discrError ? params.discrError === DiscrError.Tag ? `tag "${schema}" must be string` : `value of tag "${schema}" must be in mapping` : typeErrorMessage(cxt, "object") }, params: (cxt) => { const {schema, params} = cxt return params.discrError ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` : typeErrorParams(cxt, "object") }, } const def: CodeKeywordDefinition = { keyword: "discriminator", schemaType: "string", implements: ["mapping"], error, code(cxt: KeywordCxt) { checkMetadata(cxt) const {gen, data, schema, parentSchema} = cxt const [valid, cond] = checkNullableObject(cxt, data) gen.if(cond) validateDiscriminator() gen.elseIf(not(valid)) cxt.error() gen.endIf() cxt.ok(valid) function validateDiscriminator(): void { const tag = gen.const("tag", _`${data}${getProperty(schema)}`) gen.if(_`${tag} === undefined`) cxt.error(false, {discrError: DiscrError.Tag, tag}) gen.elseIf(_`typeof ${tag} == "string"`) validateMapping(tag) gen.else() cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema}) gen.endIf() } function validateMapping(tag: Name): void { gen.if(false) for (const tagValue in parentSchema.mapping) { gen.elseIf(_`${tag} === ${tagValue}`) gen.assign(valid, applyTagSchema(tagValue)) } gen.else() cxt.error( false, {discrError: DiscrError.Mapping, tag}, {instancePath: schema, schemaPath: "mapping", parentSchema: true} ) gen.endIf() } function applyTagSchema(schemaProp: string): Name { const _valid = gen.name("valid") cxt.subschema( { keyword: "mapping", schemaProp, jtdDiscriminator: schema, }, _valid ) return _valid } }, } export default def import type {CodeKeywordDefinition, SchemaObject} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {alwaysValidSchema} from "../../compile/util" import {validateArray} from "../code" import {_, not} from "../../compile/codegen" import {checkMetadata} from "./metadata" import {checkNullable} from "./nullable" import {typeError, _JTDTypeError} from "./error" export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject> const def: CodeKeywordDefinition = { keyword: "elements", schemaType: "object", error: typeError("array"), code(cxt: KeywordCxt) { checkMetadata(cxt) const {gen, data, schema, it} = cxt if (alwaysValidSchema(it, schema)) return const [valid] = checkNullable(cxt) gen.if(not(valid), () => gen.if( _`Array.isArray(${data})`, () => gen.assign(valid, validateArray(cxt)), () => cxt.error() ) ) cxt.ok(valid) }, } export default def import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, or, and, Code} from "../../compile/codegen" import {checkMetadata} from "./metadata" import {checkNullable} from "./nullable" export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]> const error: KeywordErrorDefinition = { message: "must be equal to one of the allowed values", params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: "enum", schemaType: "array", error, code(cxt: KeywordCxt) { checkMetadata(cxt) const {gen, data, schema, schemaValue, parentSchema, it} = cxt if (schema.length === 0) throw new Error("enum must have non-empty array") if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique") let valid: Code const isString = _`typeof ${data} == "string"` if (schema.length >= it.opts.loopEnum) { let cond: Code ;[valid, cond] = checkNullable(cxt, isString) gen.if(cond, loopEnum) } else { /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`))) if (parentSchema.nullable) valid = or(_`${data} === null`, valid) } cxt.pass(valid) function loopEnum(): void { gen.forOf("v", schemaValue as Code, (v) => gen.if(_`${valid} = ${data} === ${v}`, () => gen.break()) ) } }, } export default def import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types" import {_, Code} from "../../compile/codegen" export type _JTDTypeError = ErrorObject< K, {type: T; nullable: boolean}, S > export function typeError(t: string): KeywordErrorDefinition { return { message: (cxt) => typeErrorMessage(cxt, t), params: (cxt) => typeErrorParams(cxt, t), } } export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string { return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}` } export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code { return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}` } import type {Vocabulary} from "../../types" import refKeyword from "./ref" import typeKeyword, {JTDTypeError} from "./type" import enumKeyword, {JTDEnumError} from "./enum" import elements, {JTDElementsError} from "./elements" import properties, {JTDPropertiesError} from "./properties" import optionalProperties from "./optionalProperties" import discriminator, {JTDDiscriminatorError} from "./discriminator" import values, {JTDValuesError} from "./values" import union from "./union" import metadata from "./metadata" const jtdVocabulary: Vocabulary = [ "definitions", refKeyword, typeKeyword, enumKeyword, elements, properties, optionalProperties, discriminator, values, union, metadata, {keyword: "additionalProperties", schemaType: "boolean"}, {keyword: "nullable", schemaType: "boolean"}, ] export default jtdVocabulary export type JTDErrorObject = | JTDTypeError | JTDEnumError | JTDElementsError | JTDPropertiesError | JTDDiscriminatorError | JTDValuesError import {KeywordCxt} from "../../ajv" import type {CodeKeywordDefinition} from "../../types" import {alwaysValidSchema} from "../../compile/util" const def: CodeKeywordDefinition = { keyword: "metadata", schemaType: "object", code(cxt: KeywordCxt) { checkMetadata(cxt) const {gen, schema, it} = cxt if (alwaysValidSchema(it, schema)) return const valid = gen.name("valid") cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid) cxt.ok(valid) }, } export function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void { if (it.jtdMetadata !== metadata) { throw new Error(`JTD: "${keyword}" cannot be used in this schema location`) } } export default def import type {KeywordCxt} from "../../compile/validate" import {_, not, nil, Code, Name} from "../../compile/codegen" export function checkNullable( {gen, data, parentSchema}: KeywordCxt, cond: Code = nil ): [Name, Code] { const valid = gen.name("valid") if (parentSchema.nullable) { gen.let(valid, _`${data} === null`) cond = not(valid) } else { gen.let(valid, false) } return [valid, cond] } export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] { const [valid, cond_] = checkNullable(cxt, cond) return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`] } import type {CodeKeywordDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {validateProperties, error} from "./properties" const def: CodeKeywordDefinition = { keyword: "optionalProperties", schemaType: "object", error, code(cxt: KeywordCxt) { if (cxt.parentSchema.properties) return validateProperties(cxt) }, } export default def import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, SchemaObject, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {propertyInData, allSchemaProperties, isOwnProperty} from "../code" import {alwaysValidSchema, schemaRefOrVal} from "../../compile/util" import {_, and, not, Code, Name} from "../../compile/codegen" import {checkMetadata} from "./metadata" import {checkNullableObject} from "./nullable" import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" enum PropError { Additional = "additional", Missing = "missing", } type PropKeyword = "properties" | "optionalProperties" type PropSchema = {[P in string]?: SchemaObject} export type JTDPropertiesError = | _JTDTypeError | ErrorObject | ErrorObject export const error: KeywordErrorDefinition = { message: (cxt) => { const {params} = cxt return params.propError ? params.propError === PropError.Additional ? "must NOT have additional properties" : `must have property '${params.missingProperty}'` : typeErrorMessage(cxt, "object") }, params: (cxt) => { const {params} = cxt return params.propError ? params.propError === PropError.Additional ? _`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` : _`{error: ${params.propError}, missingProperty: ${params.missingProperty}}` : typeErrorParams(cxt, "object") }, } const def: CodeKeywordDefinition = { keyword: "properties", schemaType: "object", error, code: validateProperties, } // const error: KeywordErrorDefinition = { // message: "should NOT have additional properties", // params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, // } export function validateProperties(cxt: KeywordCxt): void { checkMetadata(cxt) const {gen, data, parentSchema, it} = cxt const {additionalProperties, nullable} = parentSchema if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping") if (commonProperties()) { throw new Error("JTD: properties and optionalProperties have common members") } const [allProps, properties] = schemaProperties("properties") const [allOptProps, optProperties] = schemaProperties("optionalProperties") if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { return } const [valid, cond] = it.jtdDiscriminator === undefined ? checkNullableObject(cxt, data) : [gen.let("valid", false), true] gen.if(cond, () => gen.assign(valid, true).block(() => { validateProps(properties, "properties", true) validateProps(optProperties, "optionalProperties") if (!additionalProperties) validateAdditional() }) ) cxt.pass(valid) function commonProperties(): boolean { const props = parentSchema.properties as Record | undefined const optProps = parentSchema.optionalProperties as Record | undefined if (!(props && optProps)) return false for (const p in props) { if (Object.prototype.hasOwnProperty.call(optProps, p)) return true } return false } function schemaProperties(keyword: string): [string[], string[]] { const schema = parentSchema[keyword] const allPs = schema ? allSchemaProperties(schema) : [] if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { throw new Error(`JTD: discriminator tag used in ${keyword}`) } const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p])) return [allPs, ps] } function validateProps(props: string[], keyword: string, required?: boolean): void { const _valid = gen.var("valid") for (const prop of props) { gen.if( propertyInData(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop) ) cxt.ok(_valid) } function missingProperty(prop: string): void { if (required) { gen.assign(_valid, false) cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop}) } else { gen.assign(_valid, true) } } } function applyPropertySchema(prop: string, keyword: string, _valid: Name): void { cxt.subschema( { keyword, schemaProp: prop, dataProp: prop, }, _valid ) } function validateAdditional(): void { gen.forIn("key", data, (key: Name) => { const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator) const addOptProp = isAdditional(key, allOptProps, "optionalProperties") const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp) gen.if(extra, () => { if (it.opts.removeAdditional) { gen.code(_`delete ${data}[${key}]`) } else { cxt.error( false, {propError: PropError.Additional, additionalProperty: key}, {instancePath: key, parentSchema: true} ) if (!it.opts.allErrors) gen.break() } }) }) } function isAdditional( key: Name, props: string[], keyword: string, jtdDiscriminator?: string ): Code | true { let additional: Code | boolean if (props.length > 8) { // TODO maybe an option instead of hard-coded 8? const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword) additional = not(isOwnProperty(gen, propsSchema as Code, key)) if (jtdDiscriminator !== undefined) { additional = and(additional, _`${key} !== ${jtdDiscriminator}`) } } else if (props.length || jtdDiscriminator !== undefined) { const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props) additional = and(...ps.map((p) => _`${key} !== ${p}`)) } else { additional = true } return additional } } export default def import type {CodeKeywordDefinition, AnySchemaObject} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {compileSchema, SchemaEnv} from "../../compile" import {_, not, nil, stringify} from "../../compile/codegen" import MissingRefError from "../../compile/ref_error" import N from "../../compile/names" import {getValidate, callRef} from "../core/ref" import {checkMetadata} from "./metadata" const def: CodeKeywordDefinition = { keyword: "ref", schemaType: "string", code(cxt: KeywordCxt) { checkMetadata(cxt) const {gen, data, schema: ref, parentSchema, it} = cxt const { schemaEnv: {root}, } = it const valid = gen.name("valid") if (parentSchema.nullable) { gen.var(valid, _`${data} === null`) gen.if(not(valid), validateJtdRef) } else { gen.var(valid, false) validateJtdRef() } cxt.ok(valid) function validateJtdRef(): void { const refSchema = (root.schema as AnySchemaObject).definitions?.[ref] if (!refSchema) { throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`) } if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema) else inlineRefSchema(refSchema) } function callValidate(schema: AnySchemaObject): void { const sch = compileSchema.call( it.self, new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`}) ) const v = getValidate(cxt, sch) const errsCount = gen.const("_errs", N.errors) callRef(cxt, v, sch, sch.$async) gen.assign(valid, _`${errsCount} === ${N.errors}`) } function inlineRefSchema(schema: AnySchemaObject): void { const schName = gen.scopeValue( "schema", it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema} ) cxt.subschema( { schema, dataTypes: [], schemaPath: nil, topSchemaRef: schName, errSchemaPath: `/definitions/${ref}`, }, valid ) } }, } export function hasRef(schema: AnySchemaObject): boolean { for (const key in schema) { let sch: AnySchemaObject if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true } return false } export default def import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, nil, or, Code} from "../../compile/codegen" import validTimestamp from "../../runtime/timestamp" import {useFunc} from "../../compile/util" import {checkMetadata} from "./metadata" import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType> export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" export const intRange: {[T in IntType]: [number, number, number]} = { int8: [-128, 127, 3], uint8: [0, 255, 3], int16: [-32768, 32767, 5], uint16: [0, 65535, 5], int32: [-2147483648, 2147483647, 10], uint32: [0, 4294967295, 10], } export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType const error: KeywordErrorDefinition = { message: (cxt) => typeErrorMessage(cxt, cxt.schema), params: (cxt) => typeErrorParams(cxt, cxt.schema), } function timestampCode(cxt: KeywordCxt): Code { const {gen, data, it} = cxt const {timestamp, allowDate} = it.opts if (timestamp === "date") return _`${data} instanceof Date ` const vts = useFunc(gen, validTimestamp) const allowDateArg = allowDate ? _`, true` : nil const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})` return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString) } const def: CodeKeywordDefinition = { keyword: "type", schemaType: "string", error, code(cxt: KeywordCxt) { checkMetadata(cxt) const {data, schema, parentSchema, it} = cxt let cond: Code switch (schema) { case "boolean": case "string": cond = _`typeof ${data} == ${schema}` break case "timestamp": { cond = timestampCode(cxt) break } case "float32": case "float64": cond = _`typeof ${data} == "number"` break default: { const sch = schema as IntType cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)` if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { if (sch === "uint32") cond = _`${cond} && ${data} >= 0` } else { const [min, max] = intRange[sch] cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}` } } } cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond) }, } export default def import type {CodeKeywordDefinition} from "../../types" import {validateUnion} from "../code" const def: CodeKeywordDefinition = { keyword: "union", schemaType: "array", trackErrors: true, code: validateUnion, error: {message: "must match a schema in union"}, } export default def import type {CodeKeywordDefinition, SchemaObject} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {alwaysValidSchema, Type} from "../../compile/util" import {not, or, Name} from "../../compile/codegen" import {checkMetadata} from "./metadata" import {checkNullableObject} from "./nullable" import {typeError, _JTDTypeError} from "./error" export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject> const def: CodeKeywordDefinition = { keyword: "values", schemaType: "object", error: typeError("object"), code(cxt: KeywordCxt) { checkMetadata(cxt) const {gen, data, schema, it} = cxt const [valid, cond] = checkNullableObject(cxt, data) if (alwaysValidSchema(it, schema)) { gen.if(not(or(cond, valid)), () => cxt.error()) } else { gen.if(cond) gen.assign(valid, validateMap()) gen.elseIf(not(valid)) cxt.error() gen.endIf() } cxt.ok(valid) function validateMap(): Name | boolean { const _valid = gen.name("valid") if (it.allErrors) { const validMap = gen.let("valid", true) validateValues(() => gen.assign(validMap, false)) return validMap } gen.var(_valid, true) validateValues(() => gen.break()) return _valid function validateValues(notValid: () => void): void { gen.forIn("key", data, (key) => { cxt.subschema( { keyword: "values", dataProp: key, dataPropType: Type.Str, }, _valid ) gen.if(not(_valid), notValid) }) } } }, } export default def import type {Vocabulary} from "../types" export const metadataVocabulary: Vocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples", ] export const contentVocabulary: Vocabulary = [ "contentMediaType", "contentEncoding", "contentSchema", ] import type {Vocabulary} from "../types" import dependentRequired from "./validation/dependentRequired" import dependentSchemas from "./applicator/dependentSchemas" import limitContains from "./validation/limitContains" const next: Vocabulary = [dependentRequired, dependentSchemas, limitContains] export default next import type {Vocabulary} from "../../types" import unevaluatedProperties from "./unevaluatedProperties" import unevaluatedItems from "./unevaluatedItems" const unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems] export default unevaluated import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, AnySchema, } from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, not, Name} from "../../compile/codegen" import {alwaysValidSchema, Type} from "../../compile/util" export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema> const error: KeywordErrorDefinition = { message: ({params: {len}}) => str`must NOT have more than ${len} items`, params: ({params: {len}}) => _`{limit: ${len}}`, } const def: CodeKeywordDefinition = { keyword: "unevaluatedItems", type: "array", schemaType: ["boolean", "object"], error, code(cxt: KeywordCxt) { const {gen, schema, data, it} = cxt const items = it.items || 0 if (items === true) return const len = gen.const("len", _`${data}.length`) if (schema === false) { cxt.setParams({len: items}) cxt.fail(_`${len} > ${items}`) } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { const valid = gen.var("valid", _`${len} <= ${items}`) gen.if(not(valid), () => validateItems(valid, items)) cxt.ok(valid) } it.items = true function validateItems(valid: Name, from: Name | number): void { gen.forRange("i", from, len, (i) => { cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid) if (!it.allErrors) gen.if(not(valid), () => gen.break()) }) } }, } export default def import type { CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject, AnySchema, } from "../../types" import {_, not, and, Name, Code} from "../../compile/codegen" import {alwaysValidSchema, Type} from "../../compile/util" import N from "../../compile/names" export type UnevaluatedPropertiesError = ErrorObject< "unevaluatedProperties", {unevaluatedProperty: string}, AnySchema > const error: KeywordErrorDefinition = { message: "must NOT have unevaluated properties", params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`, } const def: CodeKeywordDefinition = { keyword: "unevaluatedProperties", type: "object", schemaType: ["boolean", "object"], trackErrors: true, error, code(cxt) { const {gen, schema, data, errsCount, it} = cxt /* istanbul ignore if */ if (!errsCount) throw new Error("ajv implementation error") const {allErrors, props} = it if (props instanceof Name) { gen.if(_`${props} !== true`, () => gen.forIn("key", data, (key: Name) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)) ) ) } else if (props !== true) { gen.forIn("key", data, (key: Name) => props === undefined ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)) ) } it.props = true cxt.ok(_`${errsCount} === ${N.errors}`) function unevaluatedPropCode(key: Name): void { if (schema === false) { cxt.setParams({unevaluatedProperty: key}) cxt.error() if (!allErrors) gen.break() return } if (!alwaysValidSchema(it, schema)) { const valid = gen.name("valid") cxt.subschema( { keyword: "unevaluatedProperties", dataProp: key, dataPropType: Type.Str, }, valid ) if (!allErrors) gen.if(not(valid), () => gen.break()) } } function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code { return _`!${evaluatedProps} || !${evaluatedProps}[${key}]` } function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code { const ps: Code[] = [] for (const p in evaluatedProps) { if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`) } return and(...ps) } }, } export default def import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_} from "../../compile/codegen" import {useFunc} from "../../compile/util" import equal from "../../runtime/equal" export type ConstError = ErrorObject<"const", {allowedValue: any}> const error: KeywordErrorDefinition = { message: "must be equal to constant", params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: "const", $data: true, error, code(cxt: KeywordCxt) { const {gen, data, $data, schemaCode, schema} = cxt if ($data || (schema && typeof schema == "object")) { cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`) } else { cxt.fail(_`${schema} !== ${data}`) } }, } export default def import type {CodeKeywordDefinition, ErrorObject} from "../../types" import { validatePropertyDeps, error, DependenciesErrorParams, PropertyDependencies, } from "../applicator/dependencies" export type DependentRequiredError = ErrorObject< "dependentRequired", DependenciesErrorParams, PropertyDependencies > const def: CodeKeywordDefinition = { keyword: "dependentRequired", type: "object", schemaType: "object", error, code: (cxt) => validatePropertyDeps(cxt), } export default def import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, or, Name, Code} from "../../compile/codegen" import {useFunc} from "../../compile/util" import equal from "../../runtime/equal" export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: string}> const error: KeywordErrorDefinition = { message: "must be equal to one of the allowed values", params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: "enum", schemaType: "array", $data: true, error, code(cxt: KeywordCxt) { const {gen, data, $data, schema, schemaCode, it} = cxt if (!$data && schema.length === 0) throw new Error("enum must have non-empty array") const useLoop = schema.length >= it.opts.loopEnum let eql: Name | undefined const getEql = (): Name => (eql ??= useFunc(gen, equal)) let valid: Code if (useLoop || $data) { valid = gen.let("valid") cxt.block$data(valid, loopEnum) } else { /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") const vSchema = gen.const("vSchema", schemaCode) valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i))) } cxt.pass(valid) function loopEnum(): void { gen.assign(valid, false) gen.forOf("v", schemaCode as Code, (v) => gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()) ) } function equalCode(vSchema: Name, i: number): Code { const sch = schema[i] return typeof sch === "object" && sch !== null ? _`${getEql()}(${data}, ${vSchema}[${i}])` : _`${data} === ${sch}` } }, } export default def import type {ErrorObject, Vocabulary} from "../../types" import limitNumber, {LimitNumberError} from "./limitNumber" import multipleOf, {MultipleOfError} from "./multipleOf" import limitLength from "./limitLength" import pattern, {PatternError} from "./pattern" import limitProperties from "./limitProperties" import required, {RequiredError} from "./required" import limitItems from "./limitItems" import uniqueItems, {UniqueItemsError} from "./uniqueItems" import constKeyword, {ConstError} from "./const" import enumKeyword, {EnumError} from "./enum" const validation: Vocabulary = [ // number limitNumber, multipleOf, // string limitLength, pattern, // object limitProperties, required, // array limitItems, uniqueItems, // any {keyword: "type", schemaType: ["string", "array"]}, {keyword: "nullable", schemaType: "boolean"}, constKeyword, enumKeyword, ] export default validation type LimitError = ErrorObject< "maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength", {limit: number}, number | {$data: string} > export type ValidationKeywordError = | LimitError | LimitNumberError | MultipleOfError | PatternError | RequiredError | UniqueItemsError | ConstError | EnumError import type {CodeKeywordDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {checkStrictMode} from "../../compile/util" const def: CodeKeywordDefinition = { keyword: ["maxContains", "minContains"], type: "array", schemaType: "number", code({keyword, parentSchema, it}: KeywordCxt) { if (parentSchema.contains === undefined) { checkStrictMode(it, `"${keyword}" without "contains" is ignored`) } }, } export default def import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, operators} from "../../compile/codegen" const error: KeywordErrorDefinition = { message({keyword, schemaCode}) { const comp = keyword === "maxItems" ? "more" : "fewer" return str`must NOT have ${comp} than ${schemaCode} items` }, params: ({schemaCode}) => _`{limit: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error, code(cxt: KeywordCxt) { const {keyword, data, schemaCode} = cxt const op = keyword === "maxItems" ? operators.GT : operators.LT cxt.fail$data(_`${data}.length ${op} ${schemaCode}`) }, } export default def import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, operators} from "../../compile/codegen" import {useFunc} from "../../compile/util" import ucs2length from "../../runtime/ucs2length" const error: KeywordErrorDefinition = { message({keyword, schemaCode}) { const comp = keyword === "maxLength" ? "more" : "fewer" return str`must NOT have ${comp} than ${schemaCode} characters` }, params: ({schemaCode}) => _`{limit: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error, code(cxt: KeywordCxt) { const {keyword, data, schemaCode, it} = cxt const op = keyword === "maxLength" ? operators.GT : operators.LT const len = it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})` cxt.fail$data(_`${len} ${op} ${schemaCode}`) }, } export default def import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, operators, Code} from "../../compile/codegen" const ops = operators type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum" type Comparison = "<=" | ">=" | "<" | ">" const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, } export type LimitNumberError = ErrorObject< Kwd, {limit: number; comparison: Comparison}, number | {$data: string} > const error: KeywordErrorDefinition = { message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, params: ({keyword, schemaCode}) => _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error, code(cxt: KeywordCxt) { const {keyword, data, schemaCode} = cxt cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`) }, } export default def import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str, operators} from "../../compile/codegen" const error: KeywordErrorDefinition = { message({keyword, schemaCode}) { const comp = keyword === "maxProperties" ? "more" : "fewer" return str`must NOT have ${comp} than ${schemaCode} properties` }, params: ({schemaCode}) => _`{limit: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error, code(cxt: KeywordCxt) { const {keyword, data, schemaCode} = cxt const op = keyword === "maxProperties" ? operators.GT : operators.LT cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`) }, } export default def import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {_, str} from "../../compile/codegen" export type MultipleOfError = ErrorObject< "multipleOf", {multipleOf: number}, number | {$data: string} > const error: KeywordErrorDefinition = { message: ({schemaCode}) => str`must be multiple of ${schemaCode}`, params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error, code(cxt: KeywordCxt) { const {gen, data, schemaCode, it} = cxt // const bdt = bad$DataType(schemaCode, def.schemaType, $data) const prec = it.opts.multipleOfPrecision const res = gen.let("res") const invalid = prec ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : _`${res} !== parseInt(${res})` cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`) }, } export default def import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {usePattern} from "../code" import {useFunc} from "../../compile/util" import {_, str} from "../../compile/codegen" export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}> const error: KeywordErrorDefinition = { message: ({schemaCode}) => str`must match pattern "${schemaCode}"`, params: ({schemaCode}) => _`{pattern: ${schemaCode}}`, } const def: CodeKeywordDefinition = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error, code(cxt: KeywordCxt) { const {gen, data, $data, schema, schemaCode, it} = cxt const u = it.opts.unicodeRegExp ? "u" : "" if ($data) { const {regExp} = it.opts.code const regExpCode = regExp.code === "new RegExp" ? _`new RegExp` : useFunc(gen, regExp) const valid = gen.let("valid") gen.try( () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false) ) cxt.fail$data(_`!${valid}`) } else { const regExp = usePattern(cxt, schema) cxt.fail$data(_`!${regExp}.test(${data})`) } }, } export default def import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import { checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData, noPropertyInData, } from "../code" import {_, str, nil, not, Name, Code} from "../../compile/codegen" import {checkStrictMode} from "../../compile/util" export type RequiredError = ErrorObject< "required", {missingProperty: string}, string[] | {$data: string} > const error: KeywordErrorDefinition = { message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`, params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`, } const def: CodeKeywordDefinition = { keyword: "required", type: "object", schemaType: "array", $data: true, error, code(cxt: KeywordCxt) { const {gen, schema, schemaCode, data, $data, it} = cxt const {opts} = it if (!$data && schema.length === 0) return const useLoop = schema.length >= opts.loopRequired if (it.allErrors) allErrorsMode() else exitOnErrorMode() if (opts.strictRequired) { const props = cxt.parentSchema.properties const {definedProperties} = cxt.it for (const requiredKey of schema) { if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)` checkStrictMode(it, msg, it.opts.strictRequired) } } } function allErrorsMode(): void { if (useLoop || $data) { cxt.block$data(nil, loopAllRequired) } else { for (const prop of schema) { checkReportMissingProp(cxt, prop) } } } function exitOnErrorMode(): void { const missing = gen.let("missing") if (useLoop || $data) { const valid = gen.let("valid", true) cxt.block$data(valid, () => loopUntilMissing(missing, valid)) cxt.ok(valid) } else { gen.if(checkMissingProp(cxt, schema, missing)) reportMissingProp(cxt, missing) gen.else() } } function loopAllRequired(): void { gen.forOf("prop", schemaCode as Code, (prop) => { cxt.setParams({missingProperty: prop}) gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error()) }) } function loopUntilMissing(missing: Name, valid: Name): void { cxt.setParams({missingProperty: missing}) gen.forOf( missing, schemaCode as Code, () => { gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties)) gen.if(not(valid), () => { cxt.error() gen.break() }) }, nil ) } }, } export default def import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" import type {KeywordCxt} from "../../compile/validate" import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType" import {_, str, Name} from "../../compile/codegen" import {useFunc} from "../../compile/util" import equal from "../../runtime/equal" export type UniqueItemsError = ErrorObject< "uniqueItems", {i: number; j: number}, boolean | {$data: string} > const error: KeywordErrorDefinition = { message: ({params: {i, j}}) => str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`, } const def: CodeKeywordDefinition = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error, code(cxt: KeywordCxt) { const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt if (!$data && !schema) return const valid = gen.let("valid") const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : [] cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`) cxt.ok(valid) function validateUniqueItems(): void { const i = gen.let("i", _`${data}.length`) const j = gen.let("j") cxt.setParams({i, j}) gen.assign(valid, true) gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)) } function canOptimize(): boolean { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array") } function loopN(i: Name, j: Name): void { const item = gen.name("item") const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong) const indices = gen.const("indices", _`{}`) gen.for(_`;${i}--;`, () => { gen.let(item, _`${data}[${i}]`) gen.if(wrongType, _`continue`) if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`) gen .if(_`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, _`${indices}[${item}]`) cxt.error() gen.assign(valid, false).break() }) .code(_`${indices}[${item}] = ${i}`) }) } function loopN2(i: Name, j: Name): void { const eql = useFunc(gen, equal) const outer = gen.name("outer") gen.label(outer).for(_`;${i}--;`, () => gen.for(_`${j} = ${i}; ${j}--;`, () => gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error() gen.assign(valid, false).break(outer) }) ) ) } }, } export default def { "name": "ajv", "version": "8.20.0", "description": "Another JSON Schema Validator", "main": "dist/ajv.js", "types": "dist/ajv.d.ts", "files": [ "lib/", "dist/", ".runkit_example.js" ], "sideEffects": false, "repository": "ajv-validator/ajv", "author": "Evgeny Poberezkin", "license": "MIT", "homepage": "https://ajv.js.org", "runkitExampleFilename": ".runkit_example.js", "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" }, "devDependencies": { "@ajv-validator/config": "^0.5.0", "@rollup/plugin-commonjs": "^25.0.7", "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-typescript": "^11.1.6", "@types/chai": "^4.3.11", "@types/mocha": "^10.0.6", "@types/node": "^20.11.30", "@types/require-from-string": "^1.2.3", "@typescript-eslint/eslint-plugin": "^7.3.1", "@typescript-eslint/parser": "^7.3.1", "ajv-formats": "^3.0.1", "browserify": "^17.0.0", "chai": "^4.4.1", "cross-env": "^7.0.3", "dayjs": "^1.11.10", "dayjs-plugin-utc": "^0.1.2", "eslint": "^8.57.0", "eslint-config-prettier": "^9.1.0", "glob": "^10.3.10", "husky": "^9.0.11", "jimp": "^0.22.10", "js-beautify": "^1.15.1", "json-schema-test": "^2.0.0", "karma": "^6.4.2", "karma-chrome-launcher": "^3.2.0", "karma-mocha": "^2.0.1", "lint-staged": "^15.2.2", "mocha": "^10.3.0", "module-from-string": "^3.3.0", "node-fetch": "^3.3.2", "nyc": "^15.1.0", "prettier": "3.0.3", "re2": "^1.20.9", "rollup": "^2.79.1", "rollup-plugin-terser": "^7.0.2", "ts-node": "^10.9.2", "tsify": "^5.0.4", "typescript": "5.3.3", "uri-js": "^4.4.1" }, "collective": { "type": "opencollective", "url": "https://opencollective.com/ajv" }, "funding": { "type": "github", "url": "https://github.com/sponsors/epoberezkin" }, "prettier": "@ajv-validator/config/prettierrc.json", "husky": { "hooks": { "pre-commit": "lint-staged && npm test" } }, "lint-staged": { "*.{json,yaml,js,ts}": "prettier --write" } }MIT License Copyright (c) 2020 Evgeny Poberezkin 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; function fmtDef(validate, compare) { return { validate, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(getTime(true), compareTime), "date-time": fmtDef(getDateTime(true), compareDateTime), "iso-time": fmtDef(getTime(), compareIsoTime), "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: { type: "number", validate: validateInt32 }, // signed 64 bit integer int64: { type: "number", validate: validateInt64 }, // C-type float float: { type: "number", validate: validateNumber }, // C-type double double: { type: "number", validate: validateNumber }, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true, }; exports.fastFormats = { ...exports.fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, }; exports.formatNames = Object.keys(exports.fullFormats); function isLeapYear(year) { // https://tools.ietf.org/html/rfc3339#appendix-C return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function date(str) { // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 const matches = DATE.exec(str); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return (month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])); } function compareDate(d1, d2) { if (!(d1 && d2)) return undefined; if (d1 > d2) return 1; if (d1 < d2) return -1; return 0; } const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; function getTime(strictTimeZone) { return function time(str) { const matches = TIME.exec(str); if (!matches) return false; const hr = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tz = matches[4]; const tzSign = matches[5] === "-" ? -1 : 1; const tzH = +(matches[6] || 0); const tzM = +(matches[7] || 0); if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false; if (hr <= 23 && min <= 59 && sec < 60) return true; // leap second const utcMin = min - tzM * tzSign; const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; }; } function compareTime(s1, s2) { if (!(s1 && s2)) return undefined; const t1 = new Date("2020-01-01T" + s1).valueOf(); const t2 = new Date("2020-01-01T" + s2).valueOf(); if (!(t1 && t2)) return undefined; return t1 - t2; } function compareIsoTime(t1, t2) { if (!(t1 && t2)) return undefined; const a1 = TIME.exec(t1); const a2 = TIME.exec(t2); if (!(a1 && a2)) return undefined; t1 = a1[1] + a1[2] + a1[3]; t2 = a2[1] + a2[2] + a2[3]; if (t1 > t2) return 1; if (t1 < t2) return -1; return 0; } const DATE_TIME_SEPARATOR = /t|\s/i; function getDateTime(strictTimeZone) { const time = getTime(strictTimeZone); return function date_time(str) { // http://tools.ietf.org/html/rfc3339#section-5.6 const dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); }; } function compareDateTime(dt1, dt2) { if (!(dt1 && dt2)) return undefined; const d1 = new Date(dt1).valueOf(); const d2 = new Date(dt2).valueOf(); if (!(d1 && d2)) return undefined; return d1 - d2; } function compareIsoDateTime(dt1, dt2) { if (!(dt1 && dt2)) return undefined; const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); const res = compareDate(d1, d2); if (res === undefined) return undefined; return res || compareTime(t1, t2); } const NOT_URI_FRAGMENT = /\/|:/; const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; function uri(str) { // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." return NOT_URI_FRAGMENT.test(str) && URI.test(str); } const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; function byte(str) { BYTE.lastIndex = 0; return BYTE.test(str); } const MIN_INT32 = -(2 ** 31); const MAX_INT32 = 2 ** 31 - 1; function validateInt32(value) { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; } function validateInt64(value) { // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64 return Number.isInteger(value); } function validateNumber() { return true; } const Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch (e) { return false; } } //# sourceMappingURL=formats.js.map{"version":3,"file":"formats.js","sourceRoot":"","sources":["../src/formats.ts"],"names":[],"mappings":";;;AAqCA,SAAS,MAAM,CACb,QAA0C,EAC1C,OAA8B;IAE9B,OAAO,EAAC,QAAQ,EAAE,OAAO,EAAC,CAAA;AAC5B,CAAC;AAEY,QAAA,WAAW,GAAmB;IACzC,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,WAAW,CAAC;IAC/B,4DAA4D;IAC5D,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,WAAW,CAAC;IACxC,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,eAAe,CAAC;IACvD,UAAU,EAAE,MAAM,CAAC,OAAO,EAAE,EAAE,cAAc,CAAC;IAC7C,eAAe,EAAE,MAAM,CAAC,WAAW,EAAE,EAAE,kBAAkB,CAAC;IAC1D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ED,SAAS,cAAc;IACrB,OAAO,IAAI,CAAA;AACb,CAAC;AAED,MAAM,QAAQ,GAAG,UAAU,CAAA;AAC3B,SAAS,KAAK,CAAC,GAAW;IACxB,IAAI,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAA;IACpC,IAAI;QACF,IAAI,MAAM,CAAC,GAAG,CAAC,CAAA;QACf,OAAO,IAAI,CAAA;KACZ;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAA;KACb;AACH,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const formats_1 = require("./formats"); const limit_1 = require("./limit"); const codegen_1 = require("ajv/dist/compile/codegen"); const fullName = new codegen_1.Name("fullFormats"); const fastName = new codegen_1.Name("fastFormats"); const formatsPlugin = (ajv, opts = { keywords: true }) => { if (Array.isArray(opts)) { addFormats(ajv, opts, formats_1.fullFormats, fullName); return ajv; } const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; const list = opts.formats || formats_1.formatNames; addFormats(ajv, list, formats, exportName); if (opts.keywords) (0, limit_1.default)(ajv); return ajv; }; formatsPlugin.get = (name, mode = "full") => { const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; const f = formats[name]; if (!f) throw new Error(`Unknown format "${name}"`); return f; }; function addFormats(ajv, list, fs, exportName) { var _a; var _b; (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require("ajv-formats/dist/formats").${exportName}`); for (const f of list) ajv.addFormat(f, fs[f]); } module.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = formatsPlugin; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA,uCAOkB;AAClB,mCAAiC;AAGjC,sDAAgD;AAgBhD,MAAM,QAAQ,GAAG,IAAI,cAAI,CAAC,aAAa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EAAC,OAAO,uCAAP,OAAO,GAAK,IAAA,WAAC,EAAA,uCAAuC,UAAU,EAAE,EAAA;IAC9E,KAAK,MAAM,CAAC,IAAI,IAAI;QAAE,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;AAC/C,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,aAAa,CAAA;AACxC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,aAAa,CAAA"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatLimitDefinition = void 0; const ajv_1 = require("ajv"); const codegen_1 = require("ajv/dist/compile/codegen"); const ops = codegen_1.operators; const KWDs = { formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, }; const error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, }; exports.formatLimitDefinition = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self } = it; if (!opts.validateFormats) return; const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); if (fCxt.$data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats, }); const fmt = gen.const("fmt", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`); cxt.fail$data((0, codegen_1.or)((0, codegen_1._) `typeof ${fmt} != "object"`, (0, codegen_1._) `${fmt} instanceof RegExp`, (0, codegen_1._) `typeof ${fmt}.compare != "function"`, compareCode(fmt))); } function validateFormat() { const format = fCxt.schema; const fmtDef = self.formats[format]; if (!fmtDef || fmtDef === true) return; if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); } const fmt = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined, }); cxt.fail$data(compareCode(fmt)); } function compareCode(fmt) { return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; } }, dependencies: ["format"], }; const formatLimitPlugin = (ajv) => { ajv.addKeyword(exports.formatLimitDefinition); return ajv; }; exports.default = formatLimitPlugin; //# sourceMappingURL=limit.js.map{"version":3,"file":"limit.js","sourceRoot":"","sources":["../src/limit.ts"],"names":[],"mappings":";;;AAWA,6BAA8B;AAC9B,sDAA2E;AAM3E,MAAM,GAAG,GAAG,mBAAS,CAAA;AAErB,MAAM,IAAI,GAA4D;IACpE,aAAa,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACvD,aAAa,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACvD,sBAAsB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;IAC/D,sBAAsB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;CAChE,CAAA;AAID,MAAM,KAAK,GAA2B;IACpC,OA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,CAAA;AAED,MAAM,iBAAiB,GAAsB,CAAC,GAAQ,EAAO,EAAE;IAC7D,GAAG,CAAC,UAAU,CAAC,6BAAqB,CAAC,CAAA;IACrC,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,kBAAe,iBAAiB,CAAA"}{ "name": "ajv-formats", "version": "3.0.1", "description": "Format validation for Ajv v7+", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ "src/", "dist/" ], "repository": { "type": "git", "url": "git+https://github.com/ajv-validator/ajv-formats.git" }, "author": "Evgeny Poberezkin", "license": "MIT", "homepage": "https://github.com/ajv-validator/ajv-formats#readme", "dependencies": { "ajv": "^8.0.0" }, "peerDependencies": { "ajv": "^8.0.0" }, "peerDependenciesMeta": { "ajv": { "optional": true } }, "devDependencies": { "@ajv-validator/config": "^0.3.0", "@types/jest": "^26.0.5", "@types/node": "^14.10.1", "@typescript-eslint/eslint-plugin": "^3.7.0", "@typescript-eslint/parser": "^3.7.0", "ajv": "^8.0.0", "eslint": "^7.5.0", "eslint-config-prettier": "^6.11.0", "husky": "^4.2.5", "jest": "^26.1.0", "json-schema-test": "^2.0.0", "lint-staged": "^10.2.11", "prettier": "^2.3.2", "ts-jest": "^26.1.3", "typescript": "^4.0.0" }, "prettier": "@ajv-validator/config/prettierrc.json", "husky": { "hooks": { "pre-commit": "lint-staged && npm test" } }, "lint-staged": { "*.{md,json,yaml,js,ts}": "prettier --write" } }import type {Format, FormatDefinition} from "ajv" import type {FormatValidator, FormatCompare} from "ajv/dist/types" export type FormatMode = "fast" | "full" export type FormatName = | "date" | "time" | "date-time" | "iso-time" | "iso-date-time" | "duration" | "uri" | "uri-reference" | "uri-template" | "url" | "email" | "hostname" | "ipv4" | "ipv6" | "regex" | "uuid" | "json-pointer" | "json-pointer-uri-fragment" | "relative-json-pointer" | "byte" | "int32" | "int64" | "float" | "double" | "password" | "binary" export type DefinedFormats = { [key in FormatName]: Format } function fmtDef( validate: RegExp | FormatValidator, compare: FormatCompare ): FormatDefinition { return {validate, compare} } export const fullFormats: DefinedFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(getTime(true), compareTime), "date-time": fmtDef(getDateTime(true), compareDateTime), "iso-time": fmtDef(getTime(), compareIsoTime), "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: {type: "number", validate: validateInt32}, // signed 64 bit integer int64: {type: "number", validate: validateInt64}, // C-type float float: {type: "number", validate: validateNumber}, // C-type double double: {type: "number", validate: validateNumber}, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true, } export const fastFormats: DefinedFormats = { ...fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef( /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime ), "date-time": fmtDef( /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime ), "iso-time": fmtDef( /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime ), "iso-date-time": fmtDef( /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime ), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, } export const formatNames = Object.keys(fullFormats) as FormatName[] function isLeapYear(year: number): boolean { // https://tools.ietf.org/html/rfc3339#appendix-C return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) } const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] function date(str: string): boolean { // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 const matches: string[] | null = DATE.exec(str) if (!matches) return false const year: number = +matches[1] const month: number = +matches[2] const day: number = +matches[3] return ( month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]) ) } function compareDate(d1: string, d2: string): number | undefined { if (!(d1 && d2)) return undefined if (d1 > d2) return 1 if (d1 < d2) return -1 return 0 } const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i function getTime(strictTimeZone?: boolean): (str: string) => boolean { return function time(str: string): boolean { const matches: string[] | null = TIME.exec(str) if (!matches) return false const hr: number = +matches[1] const min: number = +matches[2] const sec: number = +matches[3] const tz: string | undefined = matches[4] const tzSign: number = matches[5] === "-" ? -1 : 1 const tzH: number = +(matches[6] || 0) const tzM: number = +(matches[7] || 0) if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false if (hr <= 23 && min <= 59 && sec < 60) return true // leap second const utcMin = min - tzM * tzSign const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0) return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61 } } function compareTime(s1: string, s2: string): number | undefined { if (!(s1 && s2)) return undefined const t1 = new Date("2020-01-01T" + s1).valueOf() const t2 = new Date("2020-01-01T" + s2).valueOf() if (!(t1 && t2)) return undefined return t1 - t2 } function compareIsoTime(t1: string, t2: string): number | undefined { if (!(t1 && t2)) return undefined const a1 = TIME.exec(t1) const a2 = TIME.exec(t2) if (!(a1 && a2)) return undefined t1 = a1[1] + a1[2] + a1[3] t2 = a2[1] + a2[2] + a2[3] if (t1 > t2) return 1 if (t1 < t2) return -1 return 0 } const DATE_TIME_SEPARATOR = /t|\s/i function getDateTime(strictTimeZone?: boolean): (str: string) => boolean { const time = getTime(strictTimeZone) return function date_time(str: string): boolean { // http://tools.ietf.org/html/rfc3339#section-5.6 const dateTime: string[] = str.split(DATE_TIME_SEPARATOR) return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]) } } function compareDateTime(dt1: string, dt2: string): number | undefined { if (!(dt1 && dt2)) return undefined const d1 = new Date(dt1).valueOf() const d2 = new Date(dt2).valueOf() if (!(d1 && d2)) return undefined return d1 - d2 } function compareIsoDateTime(dt1: string, dt2: string): number | undefined { if (!(dt1 && dt2)) return undefined const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR) const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR) const res = compareDate(d1, d2) if (res === undefined) return undefined return res || compareTime(t1, t2) } const NOT_URI_FRAGMENT = /\/|:/ const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i function uri(str: string): boolean { // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." return NOT_URI_FRAGMENT.test(str) && URI.test(str) } const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm function byte(str: string): boolean { BYTE.lastIndex = 0 return BYTE.test(str) } const MIN_INT32 = -(2 ** 31) const MAX_INT32 = 2 ** 31 - 1 function validateInt32(value: number): boolean { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32 } function validateInt64(value: number): boolean { // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64 return Number.isInteger(value) } function validateNumber(): boolean { return true } const Z_ANCHOR = /[^\\]\\Z/ function regex(str: string): boolean { if (Z_ANCHOR.test(str)) return false try { new RegExp(str) return true } catch (e) { return false } } import { DefinedFormats, FormatMode, FormatName, formatNames, fastFormats, fullFormats, } from "./formats" import formatLimit from "./limit" import type Ajv from "ajv" import type {Plugin, Format} from "ajv" import {_, Name} from "ajv/dist/compile/codegen" export {FormatMode, FormatName} from "./formats" export {LimitFormatError} from "./limit" export interface FormatOptions { mode?: FormatMode formats?: FormatName[] keywords?: boolean } export type FormatsPluginOptions = FormatName[] | FormatOptions export interface FormatsPlugin extends Plugin { get: (format: FormatName, mode?: FormatMode) => Format } const fullName = new Name("fullFormats") const fastName = new Name("fastFormats") const formatsPlugin: FormatsPlugin = ( ajv: Ajv, opts: FormatsPluginOptions = {keywords: true} ): Ajv => { if (Array.isArray(opts)) { addFormats(ajv, opts, fullFormats, fullName) return ajv } const [formats, exportName] = opts.mode === "fast" ? [fastFormats, fastName] : [fullFormats, fullName] const list = opts.formats || formatNames addFormats(ajv, list, formats, exportName) if (opts.keywords) formatLimit(ajv) return ajv } formatsPlugin.get = (name: FormatName, mode: FormatMode = "full"): Format => { const formats = mode === "fast" ? fastFormats : fullFormats const f = formats[name] if (!f) throw new Error(`Unknown format "${name}"`) return f } function addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void { ajv.opts.code.formats ??= _`require("ajv-formats/dist/formats").${exportName}` for (const f of list) ajv.addFormat(f, fs[f]) } module.exports = exports = formatsPlugin Object.defineProperty(exports, "__esModule", {value: true}) export default formatsPlugin import type Ajv from "ajv" import type { Plugin, CodeKeywordDefinition, KeywordErrorDefinition, Code, Name, ErrorObject, } from "ajv" import type {AddedFormat} from "ajv/dist/types" import type {Rule} from "ajv/dist/compile/rules" import {KeywordCxt} from "ajv" import {_, str, or, getProperty, operators} from "ajv/dist/compile/codegen" type Kwd = "formatMaximum" | "formatMinimum" | "formatExclusiveMaximum" | "formatExclusiveMinimum" type Comparison = "<=" | ">=" | "<" | ">" const ops = operators const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { formatMaximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, formatMinimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, formatExclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, formatExclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, } export type LimitFormatError = ErrorObject const error: KeywordErrorDefinition = { message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, params: ({keyword, schemaCode}) => _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, } export const formatLimitDefinition: CodeKeywordDefinition = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error, code(cxt) { const {gen, data, schemaCode, keyword, it} = cxt const {opts, self} = it if (!opts.validateFormats) return const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, "format") if (fCxt.$data) validate$DataFormat() else validateFormat() function validate$DataFormat(): void { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats, }) const fmt = gen.const("fmt", _`${fmts}[${fCxt.schemaCode}]`) cxt.fail$data( or( _`typeof ${fmt} != "object"`, _`${fmt} instanceof RegExp`, _`typeof ${fmt}.compare != "function"`, compareCode(fmt) ) ) } function validateFormat(): void { const format = fCxt.schema as string const fmtDef: AddedFormat | undefined = self.formats[format] if (!fmtDef || fmtDef === true) return if ( typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function" ) { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`) } const fmt = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined, }) cxt.fail$data(compareCode(fmt)) } function compareCode(fmt: Name): Code { return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0` } }, dependencies: ["format"], } const formatLimitPlugin: Plugin = (ajv: Ajv): Ajv => { ajv.addKeyword(formatLimitDefinition) return ajv } export default formatLimitPlugin 1.0.0 / 2015-01-27 ================== * README: use single quotes for `require()` call * package: remove "lib" and "engines" fields * Merge pull request #9 from linclark/fix-arg-order * fix arg order * Merge pull request #6 from Resseguie/no-callback * allow for no callback * Merge pull request #1 from cnandreu/patch-1 * Fixed example in README.md 0.2.1 / 2010-09-03 ================== * If an error is returned from the AppleScript, then the offending code is attached to the Error object as `err.appleScript` 0.2.0 / 2010-07-27 ================== * Exposed the underlying parser Functions via the exported `Parsers` property * Add MIT license 0.1.0 / 2010-07-21 ================== * Adding a "package.json" file for "npm". Preparing for v0.1.0 tag * Added a simple script to easily execute *.applescript test script * Added a new test case to ensure the 'fail' case issue is (and remains) fixed * Fixed the case where a zero-length response would cause an infinite loop in the result parser * Now converting `«data »` results into native Buffer instances. Horray! * Fixed StringParser with escaping control characters * Rewrote parsing logic to use Strings and substring * Replaced the RegExp based result parsing logic to actual char-by-char based parsing logic * Write to stdin when 'execString' is called, instead of passing the String as an argument (potentially dangerous) * Rename 'node-applescript.js' to 'applescript.js' * Initial commit Copyright (c) 2010 Nathan Rajlich 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. // 'parse' accepts a string that is expected to be the stdout stream of an // osascript invocation. It reads the fist char of the string to determine // the data-type of the result, and creates the appropriate type parser. exports.parse = function(str) { if (str.length == 0) { return; } var rtn = parseFromFirstRemaining.call({ value: str, index: 0 }); return rtn; } // Attemps to determine the data type of the next part of the String to // parse. The 'this' value has a Object with 'value' as the AppleScript // string to parse, and 'index' as the pointer to the current position // of parsing in the String. This Function does not need to be exported??? function parseFromFirstRemaining() { var cur = this.value[this.index]; switch(cur) { case '{': return exports.ArrayParser.call(this); break; case '"': return exports.StringParser.call(this); break; case 'a': if (this.value.substring(this.index, this.index+5) == 'alias') { return exports.AliasParser.call(this); } break; case '«': if (this.value.substring(this.index, this.index+5) == '«data') { return exports.DataParser.call(this); } break; } if (!isNaN(cur)) { return exports.NumberParser.call(this); } return exports.UndefinedParser.call(this); } // Parses an AppleScript "alias", which is really just a reference to a // location on the filesystem, but formatted kinda weirdly. exports.AliasParser = function() { this.index += 6; return "/Volumes/" + exports.StringParser.call(this).replace(/:/g, "/"); } // Parses an AppleScript Array. Which looks like {}, instead of JavaScript's []. exports.ArrayParser = function() { var rtn = [], cur = this.value[++this.index]; while (cur != '}') { rtn.push(parseFromFirstRemaining.call(this)); if (this.value[this.index] == ',') this.index += 2; cur = this.value[this.index]; } this.index++; return rtn; } // Parses «data » results into native Buffer instances. exports.DataParser = function() { var body = exports.UndefinedParser.call(this); body = body.substring(6, body.length-1); var type = body.substring(0,4); body = body.substring(4, body.length); var buf = new Buffer(body.length/2); var count = 0; for (var i=0, l=body.length; i", "main": "./lib/applescript" }var fs = require("fs"); var path = require("path"); var applescript = require("../lib/applescript"); if (process.argv.length <= 2) { console.error("USAGE: " + path.basename(process.execPath) + " " + path.basename(__filename) + " something.applescript"); console.error(" Try one of:"); fs.readdirSync(__dirname).filter(function(file) { return path.extname(file) == '.applescript'; }).forEach(function(file) { console.error(" " + file); }); } else { console.error('Executing "' + process.argv[2] + '"'); applescript.execFile(process.argv[2], process.argv.slice(3), function(err, rtn) { console.error(' DONE!\n'); if (err) { // Something went wrong! console.error("EXIT CODE: " + err.exitCode); console.error(err); } else { // If we got here, then there's probably some worthy content. console.error(rtn); } }); } var applescript = require("../lib/applescript"); // Very basic AppleScript command. Returns the song name of each // currently selected track in iTunes as an 'Array' of 'String's. var script = 'tell application "iTunes" to get name of selection'; applescript.execString(script, function(err, rtn) { if (err) { // Something went wrong! throw err; } if (Array.isArray(rtn) && rtn.length > 0) { console.log("Currently selected tracks in \"iTunes\":"); rtn.forEach(function(songName) { console.log("\t" + songName); }); } else { console.log("No tracks are selected in \"iTunes\"...") } }); tell application "iTunes" return source 100 end tell tell application "iTunes" return location of current track end tell A. HISTORY OF THE SOFTWARE ========================== Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations, which became Zope Corporation. In 2001, the Python Software Foundation (PSF, see https://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation was a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. Release Derived Year Owner GPL- from compatible? (1) 0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2 and above 2.1.1 2001-now PSF yes Footnotes: (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't. (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause. According to CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 ------------------------------------------- BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 --------------------------------------- 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013". 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ACCEPT CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 -------------------------------------------------- Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, 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. // Port of python's argparse module, version 3.9.0: // https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py 'use strict' // Copyright (C) 2010-2020 Python Software Foundation. // Copyright (C) 2020 argparse.js authors /* * Command-line parsing library * * This module is an optparse-inspired command-line parsing library that: * * - handles both optional and positional arguments * - produces highly informative usage messages * - supports parsers that dispatch to sub-parsers * * The following is a simple usage example that sums integers from the * command-line and writes the result to a file:: * * parser = argparse.ArgumentParser( * description='sum the integers at the command line') * parser.add_argument( * 'integers', metavar='int', nargs='+', type=int, * help='an integer to be summed') * parser.add_argument( * '--log', default=sys.stdout, type=argparse.FileType('w'), * help='the file where the sum should be written') * args = parser.parse_args() * args.log.write('%s' % sum(args.integers)) * args.log.close() * * The module contains the following public classes: * * - ArgumentParser -- The main entry point for command-line parsing. As the * example above shows, the add_argument() method is used to populate * the parser with actions for optional and positional arguments. Then * the parse_args() method is invoked to convert the args at the * command-line into an object with attributes. * * - ArgumentError -- The exception raised by ArgumentParser objects when * there are errors with the parser's actions. Errors raised while * parsing the command-line are caught by ArgumentParser and emitted * as command-line messages. * * - FileType -- A factory for defining types of files to be created. As the * example above shows, instances of FileType are typically passed as * the type= argument of add_argument() calls. * * - Action -- The base class for parser actions. Typically actions are * selected by passing strings like 'store_true' or 'append_const' to * the action= argument of add_argument(). However, for greater * customization of ArgumentParser actions, subclasses of Action may * be defined and passed as the action= argument. * * - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, * ArgumentDefaultsHelpFormatter -- Formatter classes which * may be passed as the formatter_class= argument to the * ArgumentParser constructor. HelpFormatter is the default, * RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser * not to change the formatting for help text, and * ArgumentDefaultsHelpFormatter adds information about argument defaults * to the help. * * All other classes in this module are considered implementation details. * (Also note that HelpFormatter and RawDescriptionHelpFormatter are only * considered public as object names -- the API of the formatter objects is * still considered an implementation detail.) */ const SUPPRESS = '==SUPPRESS==' const OPTIONAL = '?' const ZERO_OR_MORE = '*' const ONE_OR_MORE = '+' const PARSER = 'A...' const REMAINDER = '...' const _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' // ================================== // Utility functions used for porting // ================================== const assert = require('assert') const util = require('util') const fs = require('fs') const sub = require('./lib/sub') const path = require('path') const repr = util.inspect function get_argv() { // omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.) return process.argv.slice(1) } function get_terminal_size() { return { columns: +process.env.COLUMNS || process.stdout.columns || 80 } } function hasattr(object, name) { return Object.prototype.hasOwnProperty.call(object, name) } function getattr(object, name, value) { return hasattr(object, name) ? object[name] : value } function setattr(object, name, value) { object[name] = value } function setdefault(object, name, value) { if (!hasattr(object, name)) object[name] = value return object[name] } function delattr(object, name) { delete object[name] } function range(from, to, step=1) { // range(10) is equivalent to range(0, 10) if (arguments.length === 1) [ to, from ] = [ from, 0 ] if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') { throw new TypeError('argument cannot be interpreted as an integer') } if (step === 0) throw new TypeError('range() arg 3 must not be zero') let result = [] if (step > 0) { for (let i = from; i < to; i += step) result.push(i) } else { for (let i = from; i > to; i += step) result.push(i) } return result } function splitlines(str, keepends = false) { let result if (!keepends) { result = str.split(/\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/) } else { result = [] let parts = str.split(/(\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029])/) for (let i = 0; i < parts.length; i += 2) { result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : '')) } } if (!result[result.length - 1]) result.pop() return result } function _string_lstrip(string, prefix_chars) { let idx = 0 while (idx < string.length && prefix_chars.includes(string[idx])) idx++ return idx ? string.slice(idx) : string } function _string_split(string, sep, maxsplit) { let result = string.split(sep) if (result.length > maxsplit) { result = result.slice(0, maxsplit).concat([ result.slice(maxsplit).join(sep) ]) } return result } function _array_equal(array1, array2) { if (array1.length !== array2.length) return false for (let i = 0; i < array1.length; i++) { if (array1[i] !== array2[i]) return false } return true } function _array_remove(array, item) { let idx = array.indexOf(item) if (idx === -1) throw new TypeError(sub('%r not in list', item)) array.splice(idx, 1) } // normalize choices to array; // this isn't required in python because `in` and `map` operators work with anything, // but in js dealing with multiple types here is too clunky function _choices_to_array(choices) { if (choices === undefined) { return [] } else if (Array.isArray(choices)) { return choices } else if (choices !== null && typeof choices[Symbol.iterator] === 'function') { return Array.from(choices) } else if (typeof choices === 'object' && choices !== null) { return Object.keys(choices) } else { throw new Error(sub('invalid choices value: %r', choices)) } } // decorator that allows a class to be called without new function _callable(cls) { let result = { // object is needed for inferred class name [cls.name]: function (...args) { let this_class = new.target === result || !new.target return Reflect.construct(cls, args, this_class ? cls : new.target) } } result[cls.name].prototype = cls.prototype // fix default tag for toString, e.g. [object Action] instead of [object Object] cls.prototype[Symbol.toStringTag] = cls.name return result[cls.name] } function _alias(object, from, to) { try { let name = object.constructor.name Object.defineProperty(object, from, { value: util.deprecate(object[to], sub('%s.%s() is renamed to %s.%s()', name, from, name, to)), enumerable: false }) } catch {} } // decorator that allows snake_case class methods to be called with camelCase and vice versa function _camelcase_alias(_class) { for (let name of Object.getOwnPropertyNames(_class.prototype)) { let camelcase = name.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) if (camelcase !== name) _alias(_class.prototype, camelcase, name) } return _class } function _to_legacy_name(key) { key = key.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) if (key === 'default') key = 'defaultValue' if (key === 'const') key = 'constant' return key } function _to_new_name(key) { if (key === 'defaultValue') key = 'default' if (key === 'constant') key = 'const' key = key.replace(/[A-Z]/g, c => '_' + c.toLowerCase()) return key } // parse options let no_default = Symbol('no_default_value') function _parse_opts(args, descriptor) { function get_name() { let stack = new Error().stack.split('\n') .map(x => x.match(/^ at (.*) \(.*\)$/)) .filter(Boolean) .map(m => m[1]) .map(fn => fn.match(/[^ .]*$/)[0]) if (stack.length && stack[0] === get_name.name) stack.shift() if (stack.length && stack[0] === _parse_opts.name) stack.shift() return stack.length ? stack[0] : '' } args = Array.from(args) let kwargs = {} let result = [] let last_opt = args.length && args[args.length - 1] if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) && (!last_opt.constructor || last_opt.constructor.name === 'Object')) { kwargs = Object.assign({}, args.pop()) } // LEGACY (v1 compatibility): camelcase let renames = [] for (let key of Object.keys(descriptor)) { let old_name = _to_legacy_name(key) if (old_name !== key && (old_name in kwargs)) { if (key in kwargs) { // default and defaultValue specified at the same time, happens often in old tests //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) } else { kwargs[key] = kwargs[old_name] } renames.push([ old_name, key ]) delete kwargs[old_name] } } if (renames.length) { let name = get_name() deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) } // end let missing_positionals = [] let positional_count = args.length for (let [ key, def ] of Object.entries(descriptor)) { if (key[0] === '*') { if (key.length > 0 && key[1] === '*') { // LEGACY (v1 compatibility): camelcase let renames = [] for (let key of Object.keys(kwargs)) { let new_name = _to_new_name(key) if (new_name !== key && (key in kwargs)) { if (new_name in kwargs) { // default and defaultValue specified at the same time, happens often in old tests //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), new_name)) } else { kwargs[new_name] = kwargs[key] } renames.push([ key, new_name ]) delete kwargs[key] } } if (renames.length) { let name = get_name() deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) } // end result.push(kwargs) kwargs = {} } else { result.push(args) args = [] } } else if (key in kwargs && args.length > 0) { throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) } else if (key in kwargs) { result.push(kwargs[key]) delete kwargs[key] } else if (args.length > 0) { result.push(args.shift()) } else if (def !== no_default) { result.push(def) } else { missing_positionals.push(key) } } if (Object.keys(kwargs).length) { throw new TypeError(sub('%s() got an unexpected keyword argument %r', get_name(), Object.keys(kwargs)[0])) } if (args.length) { let from = Object.entries(descriptor).filter(([ k, v ]) => k[0] !== '*' && v !== no_default).length let to = Object.entries(descriptor).filter(([ k ]) => k[0] !== '*').length throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given', get_name(), from === to ? sub('from %s to %s', from, to) : to, from === to && to === 1 ? '' : 's', positional_count, positional_count === 1 ? 'was' : 'were')) } if (missing_positionals.length) { let strs = missing_positionals.map(repr) if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1] let str_joined = strs.join(strs.length === 2 ? '' : ', ') throw new TypeError(sub('%s() missing %i required positional argument%s: %s', get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined)) } return result } let _deprecations = {} function deprecate(id, string) { _deprecations[id] = _deprecations[id] || util.deprecate(() => {}, string) _deprecations[id]() } // ============================= // Utility functions and classes // ============================= function _AttributeHolder(cls = Object) { /* * Abstract base class that provides __repr__. * * The __repr__ method returns a string in the format:: * ClassName(attr=name, attr=name, ...) * The attributes are determined either by a class-level attribute, * '_kwarg_names', or by inspecting the instance __dict__. */ return class _AttributeHolder extends cls { [util.inspect.custom]() { let type_name = this.constructor.name let arg_strings = [] let star_args = {} for (let arg of this._get_args()) { arg_strings.push(repr(arg)) } for (let [ name, value ] of this._get_kwargs()) { if (/^[a-z_][a-z0-9_$]*$/i.test(name)) { arg_strings.push(sub('%s=%r', name, value)) } else { star_args[name] = value } } if (Object.keys(star_args).length) { arg_strings.push(sub('**%s', repr(star_args))) } return sub('%s(%s)', type_name, arg_strings.join(', ')) } toString() { return this[util.inspect.custom]() } _get_kwargs() { return Object.entries(this) } _get_args() { return [] } } } function _copy_items(items) { if (items === undefined) { return [] } return items.slice(0) } // =============== // Formatting Help // =============== const HelpFormatter = _camelcase_alias(_callable(class HelpFormatter { /* * Formatter for generating usage messages and argument help strings. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ constructor() { let [ prog, indent_increment, max_help_position, width ] = _parse_opts(arguments, { prog: no_default, indent_increment: 2, max_help_position: 24, width: undefined }) // default setting for width if (width === undefined) { width = get_terminal_size().columns width -= 2 } this._prog = prog this._indent_increment = indent_increment this._max_help_position = Math.min(max_help_position, Math.max(width - 20, indent_increment * 2)) this._width = width this._current_indent = 0 this._level = 0 this._action_max_length = 0 this._root_section = this._Section(this, undefined) this._current_section = this._root_section this._whitespace_matcher = /[ \t\n\r\f\v]+/g // equivalent to python /\s+/ with ASCII flag this._long_break_matcher = /\n\n\n+/g } // =============================== // Section and indentation methods // =============================== _indent() { this._current_indent += this._indent_increment this._level += 1 } _dedent() { this._current_indent -= this._indent_increment assert(this._current_indent >= 0, 'Indent decreased below 0.') this._level -= 1 } _add_item(func, args) { this._current_section.items.push([ func, args ]) } // ======================== // Message building methods // ======================== start_section(heading) { this._indent() let section = this._Section(this, this._current_section, heading) this._add_item(section.format_help.bind(section), []) this._current_section = section } end_section() { this._current_section = this._current_section.parent this._dedent() } add_text(text) { if (text !== SUPPRESS && text !== undefined) { this._add_item(this._format_text.bind(this), [text]) } } add_usage(usage, actions, groups, prefix = undefined) { if (usage !== SUPPRESS) { let args = [ usage, actions, groups, prefix ] this._add_item(this._format_usage.bind(this), args) } } add_argument(action) { if (action.help !== SUPPRESS) { // find all invocations let invocations = [this._format_action_invocation(action)] for (let subaction of this._iter_indented_subactions(action)) { invocations.push(this._format_action_invocation(subaction)) } // update the maximum item length let invocation_length = Math.max(...invocations.map(invocation => invocation.length)) let action_length = invocation_length + this._current_indent this._action_max_length = Math.max(this._action_max_length, action_length) // add the item to the list this._add_item(this._format_action.bind(this), [action]) } } add_arguments(actions) { for (let action of actions) { this.add_argument(action) } } // ======================= // Help-formatting methods // ======================= format_help() { let help = this._root_section.format_help() if (help) { help = help.replace(this._long_break_matcher, '\n\n') help = help.replace(/^\n+|\n+$/g, '') + '\n' } return help } _join_parts(part_strings) { return part_strings.filter(part => part && part !== SUPPRESS).join('') } _format_usage(usage, actions, groups, prefix) { if (prefix === undefined) { prefix = 'usage: ' } // if usage is specified, use that if (usage !== undefined) { usage = sub(usage, { prog: this._prog }) // if no optionals or positionals are available, usage is just prog } else if (usage === undefined && !actions.length) { usage = sub('%(prog)s', { prog: this._prog }) // if optionals and positionals are available, calculate usage } else if (usage === undefined) { let prog = sub('%(prog)s', { prog: this._prog }) // split optionals from positionals let optionals = [] let positionals = [] for (let action of actions) { if (action.option_strings.length) { optionals.push(action) } else { positionals.push(action) } } // build full usage string let action_usage = this._format_actions_usage([].concat(optionals).concat(positionals), groups) usage = [ prog, action_usage ].map(String).join(' ') // wrap the usage parts if it's too long let text_width = this._width - this._current_indent if (prefix.length + usage.length > text_width) { // break usage into wrappable parts let part_regexp = /\(.*?\)+(?=\s|$)|\[.*?\]+(?=\s|$)|\S+/g let opt_usage = this._format_actions_usage(optionals, groups) let pos_usage = this._format_actions_usage(positionals, groups) let opt_parts = opt_usage.match(part_regexp) || [] let pos_parts = pos_usage.match(part_regexp) || [] assert(opt_parts.join(' ') === opt_usage) assert(pos_parts.join(' ') === pos_usage) // helper for wrapping lines let get_lines = (parts, indent, prefix = undefined) => { let lines = [] let line = [] let line_len if (prefix !== undefined) { line_len = prefix.length - 1 } else { line_len = indent.length - 1 } for (let part of parts) { if (line_len + 1 + part.length > text_width && line) { lines.push(indent + line.join(' ')) line = [] line_len = indent.length - 1 } line.push(part) line_len += part.length + 1 } if (line.length) { lines.push(indent + line.join(' ')) } if (prefix !== undefined) { lines[0] = lines[0].slice(indent.length) } return lines } let lines // if prog is short, follow it with optionals or positionals if (prefix.length + prog.length <= 0.75 * text_width) { let indent = ' '.repeat(prefix.length + prog.length + 1) if (opt_parts.length) { lines = get_lines([prog].concat(opt_parts), indent, prefix) lines = lines.concat(get_lines(pos_parts, indent)) } else if (pos_parts.length) { lines = get_lines([prog].concat(pos_parts), indent, prefix) } else { lines = [prog] } // if prog is long, put it on its own line } else { let indent = ' '.repeat(prefix.length) let parts = [].concat(opt_parts).concat(pos_parts) lines = get_lines(parts, indent) if (lines.length > 1) { lines = [] lines = lines.concat(get_lines(opt_parts, indent)) lines = lines.concat(get_lines(pos_parts, indent)) } lines = [prog].concat(lines) } // join lines into usage usage = lines.join('\n') } } // prefix with 'usage:' return sub('%s%s\n\n', prefix, usage) } _format_actions_usage(actions, groups) { // find group indices and identify actions in groups let group_actions = new Set() let inserts = {} for (let group of groups) { let start = actions.indexOf(group._group_actions[0]) if (start === -1) { continue } else { let end = start + group._group_actions.length if (_array_equal(actions.slice(start, end), group._group_actions)) { for (let action of group._group_actions) { group_actions.add(action) } if (!group.required) { if (start in inserts) { inserts[start] += ' [' } else { inserts[start] = '[' } if (end in inserts) { inserts[end] += ']' } else { inserts[end] = ']' } } else { if (start in inserts) { inserts[start] += ' (' } else { inserts[start] = '(' } if (end in inserts) { inserts[end] += ')' } else { inserts[end] = ')' } } for (let i of range(start + 1, end)) { inserts[i] = '|' } } } } // collect all actions format strings let parts = [] for (let [ i, action ] of Object.entries(actions)) { // suppressed arguments are marked with None // remove | separators for suppressed arguments if (action.help === SUPPRESS) { parts.push(undefined) if (inserts[+i] === '|') { delete inserts[+i] } else if (inserts[+i + 1] === '|') { delete inserts[+i + 1] } // produce all arg strings } else if (!action.option_strings.length) { let default_value = this._get_default_metavar_for_positional(action) let part = this._format_args(action, default_value) // if it's in a group, strip the outer [] if (group_actions.has(action)) { if (part[0] === '[' && part[part.length - 1] === ']') { part = part.slice(1, -1) } } // add the action string to the list parts.push(part) // produce the first way to invoke the option in brackets } else { let option_string = action.option_strings[0] let part // if the Optional doesn't take a value, format is: // -s or --long if (action.nargs === 0) { part = action.format_usage() // if the Optional takes a value, format is: // -s ARGS or --long ARGS } else { let default_value = this._get_default_metavar_for_optional(action) let args_string = this._format_args(action, default_value) part = sub('%s %s', option_string, args_string) } // make it look optional if it's not required or in a group if (!action.required && !group_actions.has(action)) { part = sub('[%s]', part) } // add the action string to the list parts.push(part) } } // insert things at the necessary indices for (let i of Object.keys(inserts).map(Number).sort((a, b) => b - a)) { parts.splice(+i, 0, inserts[+i]) } // join all the action items with spaces let text = parts.filter(Boolean).join(' ') // clean up separators for mutually exclusive groups text = text.replace(/([\[(]) /g, '$1') text = text.replace(/ ([\])])/g, '$1') text = text.replace(/[\[(] *[\])]/g, '') text = text.replace(/\(([^|]*)\)/g, '$1', text) text = text.trim() // return the text return text } _format_text(text) { if (text.includes('%(prog)')) { text = sub(text, { prog: this._prog }) } let text_width = Math.max(this._width - this._current_indent, 11) let indent = ' '.repeat(this._current_indent) return this._fill_text(text, text_width, indent) + '\n\n' } _format_action(action) { // determine the required width and the entry label let help_position = Math.min(this._action_max_length + 2, this._max_help_position) let help_width = Math.max(this._width - help_position, 11) let action_width = help_position - this._current_indent - 2 let action_header = this._format_action_invocation(action) let indent_first // no help; start on same line and add a final newline if (!action.help) { let tup = [ this._current_indent, '', action_header ] action_header = sub('%*s%s\n', ...tup) // short action name; start on the same line and pad two spaces } else if (action_header.length <= action_width) { let tup = [ this._current_indent, '', action_width, action_header ] action_header = sub('%*s%-*s ', ...tup) indent_first = 0 // long action name; start on the next line } else { let tup = [ this._current_indent, '', action_header ] action_header = sub('%*s%s\n', ...tup) indent_first = help_position } // collect the pieces of the action help let parts = [action_header] // if there was help for the action, add lines of help text if (action.help) { let help_text = this._expand_help(action) let help_lines = this._split_lines(help_text, help_width) parts.push(sub('%*s%s\n', indent_first, '', help_lines[0])) for (let line of help_lines.slice(1)) { parts.push(sub('%*s%s\n', help_position, '', line)) } // or add a newline if the description doesn't end with one } else if (!action_header.endsWith('\n')) { parts.push('\n') } // if there are any sub-actions, add their help as well for (let subaction of this._iter_indented_subactions(action)) { parts.push(this._format_action(subaction)) } // return a single string return this._join_parts(parts) } _format_action_invocation(action) { if (!action.option_strings.length) { let default_value = this._get_default_metavar_for_positional(action) let metavar = this._metavar_formatter(action, default_value)(1)[0] return metavar } else { let parts = [] // if the Optional doesn't take a value, format is: // -s, --long if (action.nargs === 0) { parts = parts.concat(action.option_strings) // if the Optional takes a value, format is: // -s ARGS, --long ARGS } else { let default_value = this._get_default_metavar_for_optional(action) let args_string = this._format_args(action, default_value) for (let option_string of action.option_strings) { parts.push(sub('%s %s', option_string, args_string)) } } return parts.join(', ') } } _metavar_formatter(action, default_metavar) { let result if (action.metavar !== undefined) { result = action.metavar } else if (action.choices !== undefined) { let choice_strs = _choices_to_array(action.choices).map(String) result = sub('{%s}', choice_strs.join(',')) } else { result = default_metavar } function format(tuple_size) { if (Array.isArray(result)) { return result } else { return Array(tuple_size).fill(result) } } return format } _format_args(action, default_metavar) { let get_metavar = this._metavar_formatter(action, default_metavar) let result if (action.nargs === undefined) { result = sub('%s', ...get_metavar(1)) } else if (action.nargs === OPTIONAL) { result = sub('[%s]', ...get_metavar(1)) } else if (action.nargs === ZERO_OR_MORE) { let metavar = get_metavar(1) if (metavar.length === 2) { result = sub('[%s [%s ...]]', ...metavar) } else { result = sub('[%s ...]', ...metavar) } } else if (action.nargs === ONE_OR_MORE) { result = sub('%s [%s ...]', ...get_metavar(2)) } else if (action.nargs === REMAINDER) { result = '...' } else if (action.nargs === PARSER) { result = sub('%s ...', ...get_metavar(1)) } else if (action.nargs === SUPPRESS) { result = '' } else { let formats try { formats = range(action.nargs).map(() => '%s') } catch (err) { throw new TypeError('invalid nargs value') } result = sub(formats.join(' '), ...get_metavar(action.nargs)) } return result } _expand_help(action) { let params = Object.assign({ prog: this._prog }, action) for (let name of Object.keys(params)) { if (params[name] === SUPPRESS) { delete params[name] } } for (let name of Object.keys(params)) { if (params[name] && params[name].name) { params[name] = params[name].name } } if (params.choices !== undefined) { let choices_str = _choices_to_array(params.choices).map(String).join(', ') params.choices = choices_str } // LEGACY (v1 compatibility): camelcase for (let key of Object.keys(params)) { let old_name = _to_legacy_name(key) if (old_name !== key) { params[old_name] = params[key] } } // end return sub(this._get_help_string(action), params) } * _iter_indented_subactions(action) { if (typeof action._get_subactions === 'function') { this._indent() yield* action._get_subactions() this._dedent() } } _split_lines(text, width) { text = text.replace(this._whitespace_matcher, ' ').trim() // The textwrap module is used only for formatting help. // Delay its import for speeding up the common usage of argparse. let textwrap = require('./lib/textwrap') return textwrap.wrap(text, { width }) } _fill_text(text, width, indent) { text = text.replace(this._whitespace_matcher, ' ').trim() let textwrap = require('./lib/textwrap') return textwrap.fill(text, { width, initial_indent: indent, subsequent_indent: indent }) } _get_help_string(action) { return action.help } _get_default_metavar_for_optional(action) { return action.dest.toUpperCase() } _get_default_metavar_for_positional(action) { return action.dest } })) HelpFormatter.prototype._Section = _callable(class _Section { constructor(formatter, parent, heading = undefined) { this.formatter = formatter this.parent = parent this.heading = heading this.items = [] } format_help() { // format the indented section if (this.parent !== undefined) { this.formatter._indent() } let item_help = this.formatter._join_parts(this.items.map(([ func, args ]) => func.apply(null, args))) if (this.parent !== undefined) { this.formatter._dedent() } // return nothing if the section was empty if (!item_help) { return '' } // add the heading if the section was non-empty let heading if (this.heading !== SUPPRESS && this.heading !== undefined) { let current_indent = this.formatter._current_indent heading = sub('%*s%s:\n', current_indent, '', this.heading) } else { heading = '' } // join the section-initial newline, the heading and the help return this.formatter._join_parts(['\n', heading, item_help, '\n']) } }) const RawDescriptionHelpFormatter = _camelcase_alias(_callable(class RawDescriptionHelpFormatter extends HelpFormatter { /* * Help message formatter which retains any formatting in descriptions. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _fill_text(text, width, indent) { return splitlines(text, true).map(line => indent + line).join('') } })) const RawTextHelpFormatter = _camelcase_alias(_callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter { /* * Help message formatter which retains formatting of all help text. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _split_lines(text/*, width*/) { return splitlines(text) } })) const ArgumentDefaultsHelpFormatter = _camelcase_alias(_callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter { /* * Help message formatter which adds default values to argument help. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _get_help_string(action) { let help = action.help // LEGACY (v1 compatibility): additional check for defaultValue needed if (!action.help.includes('%(default)') && !action.help.includes('%(defaultValue)')) { if (action.default !== SUPPRESS) { let defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) { help += ' (default: %(default)s)' } } } return help } })) const MetavarTypeHelpFormatter = _camelcase_alias(_callable(class MetavarTypeHelpFormatter extends HelpFormatter { /* * Help message formatter which uses the argument 'type' as the default * metavar value (instead of the argument 'dest') * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _get_default_metavar_for_optional(action) { return typeof action.type === 'function' ? action.type.name : action.type } _get_default_metavar_for_positional(action) { return typeof action.type === 'function' ? action.type.name : action.type } })) // ===================== // Options and Arguments // ===================== function _get_action_name(argument) { if (argument === undefined) { return undefined } else if (argument.option_strings.length) { return argument.option_strings.join('/') } else if (![ undefined, SUPPRESS ].includes(argument.metavar)) { return argument.metavar } else if (![ undefined, SUPPRESS ].includes(argument.dest)) { return argument.dest } else { return undefined } } const ArgumentError = _callable(class ArgumentError extends Error { /* * An error from creating or using an argument (optional or positional). * * The string value of this exception is the message, augmented with * information about the argument that caused it. */ constructor(argument, message) { super() this.name = 'ArgumentError' this._argument_name = _get_action_name(argument) this._message = message this.message = this.str() } str() { let format if (this._argument_name === undefined) { format = '%(message)s' } else { format = 'argument %(argument_name)s: %(message)s' } return sub(format, { message: this._message, argument_name: this._argument_name }) } }) const ArgumentTypeError = _callable(class ArgumentTypeError extends Error { /* * An error from trying to convert a command line string to a type. */ constructor(message) { super(message) this.name = 'ArgumentTypeError' } }) // ============== // Action classes // ============== const Action = _camelcase_alias(_callable(class Action extends _AttributeHolder(Function) { /* * Information about how to convert command line strings to Python objects. * * Action objects are used by an ArgumentParser to represent the information * needed to parse a single argument from one or more strings from the * command line. The keyword arguments to the Action constructor are also * all attributes of Action instances. * * Keyword Arguments: * * - option_strings -- A list of command-line option strings which * should be associated with this action. * * - dest -- The name of the attribute to hold the created object(s) * * - nargs -- The number of command-line arguments that should be * consumed. By default, one argument will be consumed and a single * value will be produced. Other values include: * - N (an integer) consumes N arguments (and produces a list) * - '?' consumes zero or one arguments * - '*' consumes zero or more arguments (and produces a list) * - '+' consumes one or more arguments (and produces a list) * Note that the difference between the default and nargs=1 is that * with the default, a single value will be produced, while with * nargs=1, a list containing a single value will be produced. * * - const -- The value to be produced if the option is specified and the * option uses an action that takes no values. * * - default -- The value to be produced if the option is not specified. * * - type -- A callable that accepts a single string argument, and * returns the converted value. The standard Python types str, int, * float, and complex are useful examples of such callables. If None, * str is used. * * - choices -- A container of values that should be allowed. If not None, * after a command-line argument has been converted to the appropriate * type, an exception will be raised if it is not a member of this * collection. * * - required -- True if the action must always be specified at the * command line. This is only meaningful for optional command-line * arguments. * * - help -- The help string describing the argument. * * - metavar -- The name to be used for the option's argument with the * help string. If None, the 'dest' value will be used as the name. */ constructor() { let [ option_strings, dest, nargs, const_value, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, nargs: undefined, const: undefined, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) // when this class is called as a function, redirect it to .call() method of itself super('return arguments.callee.call.apply(arguments.callee, arguments)') this.option_strings = option_strings this.dest = dest this.nargs = nargs this.const = const_value this.default = default_value this.type = type this.choices = choices this.required = required this.help = help this.metavar = metavar } _get_kwargs() { let names = [ 'option_strings', 'dest', 'nargs', 'const', 'default', 'type', 'choices', 'help', 'metavar' ] return names.map(name => [ name, getattr(this, name) ]) } format_usage() { return this.option_strings[0] } call(/*parser, namespace, values, option_string = undefined*/) { throw new Error('.call() not defined') } })) const BooleanOptionalAction = _camelcase_alias(_callable(class BooleanOptionalAction extends Action { constructor() { let [ option_strings, dest, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) let _option_strings = [] for (let option_string of option_strings) { _option_strings.push(option_string) if (option_string.startsWith('--')) { option_string = '--no-' + option_string.slice(2) _option_strings.push(option_string) } } if (help !== undefined && default_value !== undefined) { help += ` (default: ${default_value})` } super({ option_strings: _option_strings, dest, nargs: 0, default: default_value, type, choices, required, help, metavar }) } call(parser, namespace, values, option_string = undefined) { if (this.option_strings.includes(option_string)) { setattr(namespace, this.dest, !option_string.startsWith('--no-')) } } format_usage() { return this.option_strings.join(' | ') } })) const _StoreAction = _callable(class _StoreAction extends Action { constructor() { let [ option_strings, dest, nargs, const_value, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, nargs: undefined, const: undefined, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) if (nargs === 0) { throw new TypeError('nargs for store actions must be != 0; if you ' + 'have nothing to store, actions such as store ' + 'true or store const may be more appropriate') } if (const_value !== undefined && nargs !== OPTIONAL) { throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) } super({ option_strings, dest, nargs, const: const_value, default: default_value, type, choices, required, help, metavar }) } call(parser, namespace, values/*, option_string = undefined*/) { setattr(namespace, this.dest, values) } }) const _StoreConstAction = _callable(class _StoreConstAction extends Action { constructor() { let [ option_strings, dest, const_value, default_value, required, help //, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, const: no_default, default: undefined, required: false, help: undefined, metavar: undefined }) super({ option_strings, dest, nargs: 0, const: const_value, default: default_value, required, help }) } call(parser, namespace/*, values, option_string = undefined*/) { setattr(namespace, this.dest, this.const) } }) const _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction { constructor() { let [ option_strings, dest, default_value, required, help ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: false, required: false, help: undefined }) super({ option_strings, dest, const: true, default: default_value, required, help }) } }) const _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction { constructor() { let [ option_strings, dest, default_value, required, help ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: true, required: false, help: undefined }) super({ option_strings, dest, const: false, default: default_value, required, help }) } }) const _AppendAction = _callable(class _AppendAction extends Action { constructor() { let [ option_strings, dest, nargs, const_value, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, nargs: undefined, const: undefined, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) if (nargs === 0) { throw new TypeError('nargs for append actions must be != 0; if arg ' + 'strings are not supplying the value to append, ' + 'the append const action may be more appropriate') } if (const_value !== undefined && nargs !== OPTIONAL) { throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) } super({ option_strings, dest, nargs, const: const_value, default: default_value, type, choices, required, help, metavar }) } call(parser, namespace, values/*, option_string = undefined*/) { let items = getattr(namespace, this.dest, undefined) items = _copy_items(items) items.push(values) setattr(namespace, this.dest, items) } }) const _AppendConstAction = _callable(class _AppendConstAction extends Action { constructor() { let [ option_strings, dest, const_value, default_value, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, const: no_default, default: undefined, required: false, help: undefined, metavar: undefined }) super({ option_strings, dest, nargs: 0, const: const_value, default: default_value, required, help, metavar }) } call(parser, namespace/*, values, option_string = undefined*/) { let items = getattr(namespace, this.dest, undefined) items = _copy_items(items) items.push(this.const) setattr(namespace, this.dest, items) } }) const _CountAction = _callable(class _CountAction extends Action { constructor() { let [ option_strings, dest, default_value, required, help ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: undefined, required: false, help: undefined }) super({ option_strings, dest, nargs: 0, default: default_value, required, help }) } call(parser, namespace/*, values, option_string = undefined*/) { let count = getattr(namespace, this.dest, undefined) if (count === undefined) { count = 0 } setattr(namespace, this.dest, count + 1) } }) const _HelpAction = _callable(class _HelpAction extends Action { constructor() { let [ option_strings, dest, default_value, help ] = _parse_opts(arguments, { option_strings: no_default, dest: SUPPRESS, default: SUPPRESS, help: undefined }) super({ option_strings, dest, default: default_value, nargs: 0, help }) } call(parser/*, namespace, values, option_string = undefined*/) { parser.print_help() parser.exit() } }) const _VersionAction = _callable(class _VersionAction extends Action { constructor() { let [ option_strings, version, dest, default_value, help ] = _parse_opts(arguments, { option_strings: no_default, version: undefined, dest: SUPPRESS, default: SUPPRESS, help: "show program's version number and exit" }) super({ option_strings, dest, default: default_value, nargs: 0, help }) this.version = version } call(parser/*, namespace, values, option_string = undefined*/) { let version = this.version if (version === undefined) { version = parser.version } let formatter = parser._get_formatter() formatter.add_text(version) parser._print_message(formatter.format_help(), process.stdout) parser.exit() } }) const _SubParsersAction = _camelcase_alias(_callable(class _SubParsersAction extends Action { constructor() { let [ option_strings, prog, parser_class, dest, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, prog: no_default, parser_class: no_default, dest: SUPPRESS, required: false, help: undefined, metavar: undefined }) let name_parser_map = {} super({ option_strings, dest, nargs: PARSER, choices: name_parser_map, required, help, metavar }) this._prog_prefix = prog this._parser_class = parser_class this._name_parser_map = name_parser_map this._choices_actions = [] } add_parser() { let [ name, kwargs ] = _parse_opts(arguments, { name: no_default, '**kwargs': no_default }) // set prog from the existing prefix if (kwargs.prog === undefined) { kwargs.prog = sub('%s %s', this._prog_prefix, name) } let aliases = getattr(kwargs, 'aliases', []) delete kwargs.aliases // create a pseudo-action to hold the choice help if ('help' in kwargs) { let help = kwargs.help delete kwargs.help let choice_action = this._ChoicesPseudoAction(name, aliases, help) this._choices_actions.push(choice_action) } // create the parser and add it to the map let parser = new this._parser_class(kwargs) this._name_parser_map[name] = parser // make parser available under aliases also for (let alias of aliases) { this._name_parser_map[alias] = parser } return parser } _get_subactions() { return this._choices_actions } call(parser, namespace, values/*, option_string = undefined*/) { let parser_name = values[0] let arg_strings = values.slice(1) // set the parser name if requested if (this.dest !== SUPPRESS) { setattr(namespace, this.dest, parser_name) } // select the parser if (hasattr(this._name_parser_map, parser_name)) { parser = this._name_parser_map[parser_name] } else { let args = {parser_name, choices: this._name_parser_map.join(', ')} let msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args) throw new ArgumentError(this, msg) } // parse all the remaining options into the namespace // store any unrecognized options on the object, so that the top // level parser can decide what to do with them // In case this subparser defines new defaults, we parse them // in a new namespace object and then update the original // namespace for the relevant parts. let subnamespace [ subnamespace, arg_strings ] = parser.parse_known_args(arg_strings, undefined) for (let [ key, value ] of Object.entries(subnamespace)) { setattr(namespace, key, value) } if (arg_strings.length) { setdefault(namespace, _UNRECOGNIZED_ARGS_ATTR, []) getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings) } } })) _SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action { constructor(name, aliases, help) { let metavar = name, dest = name if (aliases.length) { metavar += sub(' (%s)', aliases.join(', ')) } super({ option_strings: [], dest, help, metavar }) } }) const _ExtendAction = _callable(class _ExtendAction extends _AppendAction { call(parser, namespace, values/*, option_string = undefined*/) { let items = getattr(namespace, this.dest, undefined) items = _copy_items(items) items = items.concat(values) setattr(namespace, this.dest, items) } }) // ============== // Type classes // ============== const FileType = _callable(class FileType extends Function { /* * Factory for creating file object types * * Instances of FileType are typically passed as type= arguments to the * ArgumentParser add_argument() method. * * Keyword Arguments: * - mode -- A string indicating how the file is to be opened. Accepts the * same values as the builtin open() function. * - bufsize -- The file's desired buffer size. Accepts the same values as * the builtin open() function. * - encoding -- The file's encoding. Accepts the same values as the * builtin open() function. * - errors -- A string indicating how encoding and decoding errors are to * be handled. Accepts the same value as the builtin open() function. */ constructor() { let [ flags, encoding, mode, autoClose, emitClose, start, end, highWaterMark, fs ] = _parse_opts(arguments, { flags: 'r', encoding: undefined, mode: undefined, // 0o666 autoClose: undefined, // true emitClose: undefined, // false start: undefined, // 0 end: undefined, // Infinity highWaterMark: undefined, // 64 * 1024 fs: undefined }) // when this class is called as a function, redirect it to .call() method of itself super('return arguments.callee.call.apply(arguments.callee, arguments)') Object.defineProperty(this, 'name', { get() { return sub('FileType(%r)', flags) } }) this._flags = flags this._options = {} if (encoding !== undefined) this._options.encoding = encoding if (mode !== undefined) this._options.mode = mode if (autoClose !== undefined) this._options.autoClose = autoClose if (emitClose !== undefined) this._options.emitClose = emitClose if (start !== undefined) this._options.start = start if (end !== undefined) this._options.end = end if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark if (fs !== undefined) this._options.fs = fs } call(string) { // the special argument "-" means sys.std{in,out} if (string === '-') { if (this._flags.includes('r')) { return process.stdin } else if (this._flags.includes('w')) { return process.stdout } else { let msg = sub('argument "-" with mode %r', this._flags) throw new TypeError(msg) } } // all other arguments are used as file names let fd try { fd = fs.openSync(string, this._flags, this._options.mode) } catch (e) { let args = { filename: string, error: e.message } let message = "can't open '%(filename)s': %(error)s" throw new ArgumentTypeError(sub(message, args)) } let options = Object.assign({ fd, flags: this._flags }, this._options) if (this._flags.includes('r')) { return fs.createReadStream(undefined, options) } else if (this._flags.includes('w')) { return fs.createWriteStream(undefined, options) } else { let msg = sub('argument "%s" with mode %r', string, this._flags) throw new TypeError(msg) } } [util.inspect.custom]() { let args = [ this._flags ] let kwargs = Object.entries(this._options).map(([ k, v ]) => { if (k === 'mode') v = { value: v, [util.inspect.custom]() { return '0o' + this.value.toString(8) } } return [ k, v ] }) let args_str = [] .concat(args.filter(arg => arg !== -1).map(repr)) .concat(kwargs.filter(([/*kw*/, arg]) => arg !== undefined) .map(([kw, arg]) => sub('%s=%r', kw, arg))) .join(', ') return sub('%s(%s)', this.constructor.name, args_str) } toString() { return this[util.inspect.custom]() } }) // =========================== // Optional and Positional Parsing // =========================== const Namespace = _callable(class Namespace extends _AttributeHolder() { /* * Simple object for storing attributes. * * Implements equality by attribute names and values, and provides a simple * string representation. */ constructor(options = {}) { super() Object.assign(this, options) } }) // unset string tag to mimic plain object Namespace.prototype[Symbol.toStringTag] = undefined const _ActionsContainer = _camelcase_alias(_callable(class _ActionsContainer { constructor() { let [ description, prefix_chars, argument_default, conflict_handler ] = _parse_opts(arguments, { description: no_default, prefix_chars: no_default, argument_default: no_default, conflict_handler: no_default }) this.description = description this.argument_default = argument_default this.prefix_chars = prefix_chars this.conflict_handler = conflict_handler // set up registries this._registries = {} // register actions this.register('action', undefined, _StoreAction) this.register('action', 'store', _StoreAction) this.register('action', 'store_const', _StoreConstAction) this.register('action', 'store_true', _StoreTrueAction) this.register('action', 'store_false', _StoreFalseAction) this.register('action', 'append', _AppendAction) this.register('action', 'append_const', _AppendConstAction) this.register('action', 'count', _CountAction) this.register('action', 'help', _HelpAction) this.register('action', 'version', _VersionAction) this.register('action', 'parsers', _SubParsersAction) this.register('action', 'extend', _ExtendAction) // LEGACY (v1 compatibility): camelcase variants ;[ 'storeConst', 'storeTrue', 'storeFalse', 'appendConst' ].forEach(old_name => { let new_name = _to_new_name(old_name) this.register('action', old_name, util.deprecate(this._registry_get('action', new_name), sub('{action: "%s"} is renamed to {action: "%s"}', old_name, new_name))) }) // end // raise an exception if the conflict handler is invalid this._get_handler() // action storage this._actions = [] this._option_string_actions = {} // groups this._action_groups = [] this._mutually_exclusive_groups = [] // defaults storage this._defaults = {} // determines whether an "option" looks like a negative number this._negative_number_matcher = /^-\d+$|^-\d*\.\d+$/ // whether or not there are any optionals that look like negative // numbers -- uses a list so it can be shared and edited this._has_negative_number_optionals = [] } // ==================== // Registration methods // ==================== register(registry_name, value, object) { let registry = setdefault(this._registries, registry_name, {}) registry[value] = object } _registry_get(registry_name, value, default_value = undefined) { return getattr(this._registries[registry_name], value, default_value) } // ================================== // Namespace default accessor methods // ================================== set_defaults(kwargs) { Object.assign(this._defaults, kwargs) // if these defaults match any existing arguments, replace // the previous default on the object with the new one for (let action of this._actions) { if (action.dest in kwargs) { action.default = kwargs[action.dest] } } } get_default(dest) { for (let action of this._actions) { if (action.dest === dest && action.default !== undefined) { return action.default } } return this._defaults[dest] } // ======================= // Adding argument actions // ======================= add_argument() { /* * add_argument(dest, ..., name=value, ...) * add_argument(option_string, option_string, ..., name=value, ...) */ let [ args, kwargs ] = _parse_opts(arguments, { '*args': no_default, '**kwargs': no_default }) // LEGACY (v1 compatibility), old-style add_argument([ args ], { options }) if (args.length === 1 && Array.isArray(args[0])) { args = args[0] deprecate('argument-array', sub('use add_argument(%(args)s, {...}) instead of add_argument([ %(args)s ], { ... })', { args: args.map(repr).join(', ') })) } // end // if no positional args are supplied or only one is supplied and // it doesn't look like an option string, parse a positional // argument let chars = this.prefix_chars if (!args.length || args.length === 1 && !chars.includes(args[0][0])) { if (args.length && 'dest' in kwargs) { throw new TypeError('dest supplied twice for positional argument') } kwargs = this._get_positional_kwargs(...args, kwargs) // otherwise, we're adding an optional argument } else { kwargs = this._get_optional_kwargs(...args, kwargs) } // if no default was supplied, use the parser-level default if (!('default' in kwargs)) { let dest = kwargs.dest if (dest in this._defaults) { kwargs.default = this._defaults[dest] } else if (this.argument_default !== undefined) { kwargs.default = this.argument_default } } // create the action object, and add it to the parser let action_class = this._pop_action_class(kwargs) if (typeof action_class !== 'function') { throw new TypeError(sub('unknown action "%s"', action_class)) } // eslint-disable-next-line new-cap let action = new action_class(kwargs) // raise an error if the action type is not callable let type_func = this._registry_get('type', action.type, action.type) if (typeof type_func !== 'function') { throw new TypeError(sub('%r is not callable', type_func)) } if (type_func === FileType) { throw new TypeError(sub('%r is a FileType class object, instance of it' + ' must be passed', type_func)) } // raise an error if the metavar does not match the type if ('_get_formatter' in this) { try { this._get_formatter()._format_args(action, undefined) } catch (err) { // check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same if (err instanceof TypeError && err.message !== 'invalid nargs value') { throw new TypeError('length of metavar tuple does not match nargs') } else { throw err } } } return this._add_action(action) } add_argument_group() { let group = _ArgumentGroup(this, ...arguments) this._action_groups.push(group) return group } add_mutually_exclusive_group() { // eslint-disable-next-line no-use-before-define let group = _MutuallyExclusiveGroup(this, ...arguments) this._mutually_exclusive_groups.push(group) return group } _add_action(action) { // resolve any conflicts this._check_conflict(action) // add to actions list this._actions.push(action) action.container = this // index the action by any option strings it has for (let option_string of action.option_strings) { this._option_string_actions[option_string] = action } // set the flag if any option strings look like negative numbers for (let option_string of action.option_strings) { if (this._negative_number_matcher.test(option_string)) { if (!this._has_negative_number_optionals.length) { this._has_negative_number_optionals.push(true) } } } // return the created action return action } _remove_action(action) { _array_remove(this._actions, action) } _add_container_actions(container) { // collect groups by titles let title_group_map = {} for (let group of this._action_groups) { if (group.title in title_group_map) { let msg = 'cannot merge actions - two groups are named %r' throw new TypeError(sub(msg, group.title)) } title_group_map[group.title] = group } // map each action to its group let group_map = new Map() for (let group of container._action_groups) { // if a group with the title exists, use that, otherwise // create a new group matching the container's group if (!(group.title in title_group_map)) { title_group_map[group.title] = this.add_argument_group({ title: group.title, description: group.description, conflict_handler: group.conflict_handler }) } // map the actions to their new group for (let action of group._group_actions) { group_map.set(action, title_group_map[group.title]) } } // add container's mutually exclusive groups // NOTE: if add_mutually_exclusive_group ever gains title= and // description= then this code will need to be expanded as above for (let group of container._mutually_exclusive_groups) { let mutex_group = this.add_mutually_exclusive_group({ required: group.required }) // map the actions to their new mutex group for (let action of group._group_actions) { group_map.set(action, mutex_group) } } // add all actions to this container or their group for (let action of container._actions) { group_map.get(action)._add_action(action) } } _get_positional_kwargs() { let [ dest, kwargs ] = _parse_opts(arguments, { dest: no_default, '**kwargs': no_default }) // make sure required is not specified if ('required' in kwargs) { let msg = "'required' is an invalid argument for positionals" throw new TypeError(msg) } // mark positional arguments as required if at least one is // always required if (![OPTIONAL, ZERO_OR_MORE].includes(kwargs.nargs)) { kwargs.required = true } if (kwargs.nargs === ZERO_OR_MORE && !('default' in kwargs)) { kwargs.required = true } // return the keyword arguments with no option strings return Object.assign(kwargs, { dest, option_strings: [] }) } _get_optional_kwargs() { let [ args, kwargs ] = _parse_opts(arguments, { '*args': no_default, '**kwargs': no_default }) // determine short and long option strings let option_strings = [] let long_option_strings = [] let option_string for (option_string of args) { // error on strings that don't start with an appropriate prefix if (!this.prefix_chars.includes(option_string[0])) { let args = {option: option_string, prefix_chars: this.prefix_chars} let msg = 'invalid option string %(option)r: ' + 'must start with a character %(prefix_chars)r' throw new TypeError(sub(msg, args)) } // strings starting with two prefix characters are long options option_strings.push(option_string) if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) { long_option_strings.push(option_string) } } // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' let dest = kwargs.dest delete kwargs.dest if (dest === undefined) { let dest_option_string if (long_option_strings.length) { dest_option_string = long_option_strings[0] } else { dest_option_string = option_strings[0] } dest = _string_lstrip(dest_option_string, this.prefix_chars) if (!dest) { let msg = 'dest= is required for options like %r' throw new TypeError(sub(msg, option_string)) } dest = dest.replace(/-/g, '_') } // return the updated keyword arguments return Object.assign(kwargs, { dest, option_strings }) } _pop_action_class(kwargs, default_value = undefined) { let action = getattr(kwargs, 'action', default_value) delete kwargs.action return this._registry_get('action', action, action) } _get_handler() { // determine function from conflict handler string let handler_func_name = sub('_handle_conflict_%s', this.conflict_handler) if (typeof this[handler_func_name] === 'function') { return this[handler_func_name] } else { let msg = 'invalid conflict_resolution value: %r' throw new TypeError(sub(msg, this.conflict_handler)) } } _check_conflict(action) { // find all options that conflict with this option let confl_optionals = [] for (let option_string of action.option_strings) { if (hasattr(this._option_string_actions, option_string)) { let confl_optional = this._option_string_actions[option_string] confl_optionals.push([ option_string, confl_optional ]) } } // resolve any conflicts if (confl_optionals.length) { let conflict_handler = this._get_handler() conflict_handler.call(this, action, confl_optionals) } } _handle_conflict_error(action, conflicting_actions) { let message = conflicting_actions.length === 1 ? 'conflicting option string: %s' : 'conflicting option strings: %s' let conflict_string = conflicting_actions.map(([ option_string/*, action*/ ]) => option_string).join(', ') throw new ArgumentError(action, sub(message, conflict_string)) } _handle_conflict_resolve(action, conflicting_actions) { // remove all conflicting options for (let [ option_string, action ] of conflicting_actions) { // remove the conflicting option _array_remove(action.option_strings, option_string) delete this._option_string_actions[option_string] // if the option now has no option string, remove it from the // container holding it if (!action.option_strings.length) { action.container._remove_action(action) } } } })) const _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer { constructor() { let [ container, title, description, kwargs ] = _parse_opts(arguments, { container: no_default, title: undefined, description: undefined, '**kwargs': no_default }) // add any missing keyword arguments by checking the container setdefault(kwargs, 'conflict_handler', container.conflict_handler) setdefault(kwargs, 'prefix_chars', container.prefix_chars) setdefault(kwargs, 'argument_default', container.argument_default) super(Object.assign({ description }, kwargs)) // group attributes this.title = title this._group_actions = [] // share most attributes with the container this._registries = container._registries this._actions = container._actions this._option_string_actions = container._option_string_actions this._defaults = container._defaults this._has_negative_number_optionals = container._has_negative_number_optionals this._mutually_exclusive_groups = container._mutually_exclusive_groups } _add_action(action) { action = super._add_action(action) this._group_actions.push(action) return action } _remove_action(action) { super._remove_action(action) _array_remove(this._group_actions, action) } }) const _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup { constructor() { let [ container, required ] = _parse_opts(arguments, { container: no_default, required: false }) super(container) this.required = required this._container = container } _add_action(action) { if (action.required) { let msg = 'mutually exclusive arguments must be optional' throw new TypeError(msg) } action = this._container._add_action(action) this._group_actions.push(action) return action } _remove_action(action) { this._container._remove_action(action) _array_remove(this._group_actions, action) } }) const ArgumentParser = _camelcase_alias(_callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) { /* * Object for parsing command line strings into Python objects. * * Keyword Arguments: * - prog -- The name of the program (default: sys.argv[0]) * - usage -- A usage message (default: auto-generated from arguments) * - description -- A description of what the program does * - epilog -- Text following the argument descriptions * - parents -- Parsers whose arguments should be copied into this one * - formatter_class -- HelpFormatter class for printing help messages * - prefix_chars -- Characters that prefix optional arguments * - fromfile_prefix_chars -- Characters that prefix files containing * additional arguments * - argument_default -- The default value for all arguments * - conflict_handler -- String indicating how to handle conflicts * - add_help -- Add a -h/-help option * - allow_abbrev -- Allow long options to be abbreviated unambiguously * - exit_on_error -- Determines whether or not ArgumentParser exits with * error info when an error occurs */ constructor() { let [ prog, usage, description, epilog, parents, formatter_class, prefix_chars, fromfile_prefix_chars, argument_default, conflict_handler, add_help, allow_abbrev, exit_on_error, debug, // LEGACY (v1 compatibility), debug mode version // LEGACY (v1 compatibility), version ] = _parse_opts(arguments, { prog: undefined, usage: undefined, description: undefined, epilog: undefined, parents: [], formatter_class: HelpFormatter, prefix_chars: '-', fromfile_prefix_chars: undefined, argument_default: undefined, conflict_handler: 'error', add_help: true, allow_abbrev: true, exit_on_error: true, debug: undefined, // LEGACY (v1 compatibility), debug mode version: undefined // LEGACY (v1 compatibility), version }) // LEGACY (v1 compatibility) if (debug !== undefined) { deprecate('debug', 'The "debug" argument to ArgumentParser is deprecated. Please ' + 'override ArgumentParser.exit function instead.' ) } if (version !== undefined) { deprecate('version', 'The "version" argument to ArgumentParser is deprecated. Please use ' + "add_argument(..., { action: 'version', version: 'N', ... }) instead." ) } // end super({ description, prefix_chars, argument_default, conflict_handler }) // default setting for prog if (prog === undefined) { prog = path.basename(get_argv()[0] || '') } this.prog = prog this.usage = usage this.epilog = epilog this.formatter_class = formatter_class this.fromfile_prefix_chars = fromfile_prefix_chars this.add_help = add_help this.allow_abbrev = allow_abbrev this.exit_on_error = exit_on_error // LEGACY (v1 compatibility), debug mode this.debug = debug // end this._positionals = this.add_argument_group('positional arguments') this._optionals = this.add_argument_group('optional arguments') this._subparsers = undefined // register types function identity(string) { return string } this.register('type', undefined, identity) this.register('type', null, identity) this.register('type', 'auto', identity) this.register('type', 'int', function (x) { let result = Number(x) if (!Number.isInteger(result)) { throw new TypeError(sub('could not convert string to int: %r', x)) } return result }) this.register('type', 'float', function (x) { let result = Number(x) if (isNaN(result)) { throw new TypeError(sub('could not convert string to float: %r', x)) } return result }) this.register('type', 'str', String) // LEGACY (v1 compatibility): custom types this.register('type', 'string', util.deprecate(String, 'use {type:"str"} or {type:String} instead of {type:"string"}')) // end // add help argument if necessary // (using explicit default to override global argument_default) let default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0] if (this.add_help) { this.add_argument( default_prefix + 'h', default_prefix.repeat(2) + 'help', { action: 'help', default: SUPPRESS, help: 'show this help message and exit' } ) } // LEGACY (v1 compatibility), version if (version) { this.add_argument( default_prefix + 'v', default_prefix.repeat(2) + 'version', { action: 'version', default: SUPPRESS, version: this.version, help: "show program's version number and exit" } ) } // end // add parent arguments and defaults for (let parent of parents) { this._add_container_actions(parent) Object.assign(this._defaults, parent._defaults) } } // ======================= // Pretty __repr__ methods // ======================= _get_kwargs() { let names = [ 'prog', 'usage', 'description', 'formatter_class', 'conflict_handler', 'add_help' ] return names.map(name => [ name, getattr(this, name) ]) } // ================================== // Optional/Positional adding methods // ================================== add_subparsers() { let [ kwargs ] = _parse_opts(arguments, { '**kwargs': no_default }) if (this._subparsers !== undefined) { this.error('cannot have multiple subparser arguments') } // add the parser class to the arguments if it's not present setdefault(kwargs, 'parser_class', this.constructor) if ('title' in kwargs || 'description' in kwargs) { let title = getattr(kwargs, 'title', 'subcommands') let description = getattr(kwargs, 'description', undefined) delete kwargs.title delete kwargs.description this._subparsers = this.add_argument_group(title, description) } else { this._subparsers = this._positionals } // prog defaults to the usage message of this parser, skipping // optional arguments and with no "usage:" prefix if (kwargs.prog === undefined) { let formatter = this._get_formatter() let positionals = this._get_positional_actions() let groups = this._mutually_exclusive_groups formatter.add_usage(this.usage, positionals, groups, '') kwargs.prog = formatter.format_help().trim() } // create the parsers action and add it to the positionals list let parsers_class = this._pop_action_class(kwargs, 'parsers') // eslint-disable-next-line new-cap let action = new parsers_class(Object.assign({ option_strings: [] }, kwargs)) this._subparsers._add_action(action) // return the created parsers action return action } _add_action(action) { if (action.option_strings.length) { this._optionals._add_action(action) } else { this._positionals._add_action(action) } return action } _get_optional_actions() { return this._actions.filter(action => action.option_strings.length) } _get_positional_actions() { return this._actions.filter(action => !action.option_strings.length) } // ===================================== // Command line argument parsing methods // ===================================== parse_args(args = undefined, namespace = undefined) { let argv [ args, argv ] = this.parse_known_args(args, namespace) if (argv && argv.length > 0) { let msg = 'unrecognized arguments: %s' this.error(sub(msg, argv.join(' '))) } return args } parse_known_args(args = undefined, namespace = undefined) { if (args === undefined) { args = get_argv().slice(1) } // default Namespace built from parser defaults if (namespace === undefined) { namespace = new Namespace() } // add any action defaults that aren't present for (let action of this._actions) { if (action.dest !== SUPPRESS) { if (!hasattr(namespace, action.dest)) { if (action.default !== SUPPRESS) { setattr(namespace, action.dest, action.default) } } } } // add any parser defaults that aren't present for (let dest of Object.keys(this._defaults)) { if (!hasattr(namespace, dest)) { setattr(namespace, dest, this._defaults[dest]) } } // parse the arguments and exit if there are any errors if (this.exit_on_error) { try { [ namespace, args ] = this._parse_known_args(args, namespace) } catch (err) { if (err instanceof ArgumentError) { this.error(err.message) } else { throw err } } } else { [ namespace, args ] = this._parse_known_args(args, namespace) } if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) { args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) } return [ namespace, args ] } _parse_known_args(arg_strings, namespace) { // replace arg strings that are file references if (this.fromfile_prefix_chars !== undefined) { arg_strings = this._read_args_from_files(arg_strings) } // map all mutually exclusive arguments to the other arguments // they can't occur with let action_conflicts = new Map() for (let mutex_group of this._mutually_exclusive_groups) { let group_actions = mutex_group._group_actions for (let [ i, mutex_action ] of Object.entries(mutex_group._group_actions)) { let conflicts = action_conflicts.get(mutex_action) || [] conflicts = conflicts.concat(group_actions.slice(0, +i)) conflicts = conflicts.concat(group_actions.slice(+i + 1)) action_conflicts.set(mutex_action, conflicts) } } // find all option indices, and determine the arg_string_pattern // which has an 'O' if there is an option at an index, // an 'A' if there is an argument, or a '-' if there is a '--' let option_string_indices = {} let arg_string_pattern_parts = [] let arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]() for (let [ i, arg_string ] of arg_strings_iter) { // all args after -- are non-options if (arg_string === '--') { arg_string_pattern_parts.push('-') for ([ i, arg_string ] of arg_strings_iter) { arg_string_pattern_parts.push('A') } // otherwise, add the arg to the arg strings // and note the index if it was an option } else { let option_tuple = this._parse_optional(arg_string) let pattern if (option_tuple === undefined) { pattern = 'A' } else { option_string_indices[i] = option_tuple pattern = 'O' } arg_string_pattern_parts.push(pattern) } } // join the pieces together to form the pattern let arg_strings_pattern = arg_string_pattern_parts.join('') // converts arg strings to the appropriate and then takes the action let seen_actions = new Set() let seen_non_default_actions = new Set() let extras let take_action = (action, argument_strings, option_string = undefined) => { seen_actions.add(action) let argument_values = this._get_values(action, argument_strings) // error if this argument is not allowed with other previously // seen arguments, assuming that actions that use the default // value don't really count as "present" if (argument_values !== action.default) { seen_non_default_actions.add(action) for (let conflict_action of action_conflicts.get(action) || []) { if (seen_non_default_actions.has(conflict_action)) { let msg = 'not allowed with argument %s' let action_name = _get_action_name(conflict_action) throw new ArgumentError(action, sub(msg, action_name)) } } } // take the action if we didn't receive a SUPPRESS value // (e.g. from a default) if (argument_values !== SUPPRESS) { action(this, namespace, argument_values, option_string) } } // function to convert arg_strings into an optional action let consume_optional = start_index => { // get the optional identified at this index let option_tuple = option_string_indices[start_index] let [ action, option_string, explicit_arg ] = option_tuple // identify additional optionals in the same arg string // (e.g. -xyz is the same as -x -y -z if no args are required) let action_tuples = [] let stop for (;;) { // if we found no optional action, skip it if (action === undefined) { extras.push(arg_strings[start_index]) return start_index + 1 } // if there is an explicit argument, try to match the // optional's string arguments to only this if (explicit_arg !== undefined) { let arg_count = this._match_argument(action, 'A') // if the action is a single-dash option and takes no // arguments, try to parse more single-dash options out // of the tail of the option string let chars = this.prefix_chars if (arg_count === 0 && !chars.includes(option_string[1])) { action_tuples.push([ action, [], option_string ]) let char = option_string[0] option_string = char + explicit_arg[0] let new_explicit_arg = explicit_arg.slice(1) || undefined let optionals_map = this._option_string_actions if (hasattr(optionals_map, option_string)) { action = optionals_map[option_string] explicit_arg = new_explicit_arg } else { let msg = 'ignored explicit argument %r' throw new ArgumentError(action, sub(msg, explicit_arg)) } // if the action expect exactly one argument, we've // successfully matched the option; exit the loop } else if (arg_count === 1) { stop = start_index + 1 let args = [ explicit_arg ] action_tuples.push([ action, args, option_string ]) break // error if a double-dash option did not use the // explicit argument } else { let msg = 'ignored explicit argument %r' throw new ArgumentError(action, sub(msg, explicit_arg)) } // if there is no explicit argument, try to match the // optional's string arguments with the following strings // if successful, exit the loop } else { let start = start_index + 1 let selected_patterns = arg_strings_pattern.slice(start) let arg_count = this._match_argument(action, selected_patterns) stop = start + arg_count let args = arg_strings.slice(start, stop) action_tuples.push([ action, args, option_string ]) break } } // add the Optional to the list and return the index at which // the Optional's string args stopped assert(action_tuples.length) for (let [ action, args, option_string ] of action_tuples) { take_action(action, args, option_string) } return stop } // the list of Positionals left to be parsed; this is modified // by consume_positionals() let positionals = this._get_positional_actions() // function to convert arg_strings into positional actions let consume_positionals = start_index => { // match as many Positionals as possible let selected_pattern = arg_strings_pattern.slice(start_index) let arg_counts = this._match_arguments_partial(positionals, selected_pattern) // slice off the appropriate arg strings for each Positional // and add the Positional and its args to the list for (let i = 0; i < positionals.length && i < arg_counts.length; i++) { let action = positionals[i] let arg_count = arg_counts[i] let args = arg_strings.slice(start_index, start_index + arg_count) start_index += arg_count take_action(action, args) } // slice off the Positionals that we just parsed and return the // index at which the Positionals' string args stopped positionals = positionals.slice(arg_counts.length) return start_index } // consume Positionals and Optionals alternately, until we have // passed the last option string extras = [] let start_index = 0 let max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number)) while (start_index <= max_option_string_index) { // consume any Positionals preceding the next option let next_option_string_index = Math.min( // eslint-disable-next-line no-loop-func ...Object.keys(option_string_indices).map(Number).filter(index => index >= start_index) ) if (start_index !== next_option_string_index) { let positionals_end_index = consume_positionals(start_index) // only try to parse the next optional if we didn't consume // the option string during the positionals parsing if (positionals_end_index > start_index) { start_index = positionals_end_index continue } else { start_index = positionals_end_index } } // if we consumed all the positionals we could and we're not // at the index of an option string, there were extra arguments if (!(start_index in option_string_indices)) { let strings = arg_strings.slice(start_index, next_option_string_index) extras = extras.concat(strings) start_index = next_option_string_index } // consume the next optional and any arguments for it start_index = consume_optional(start_index) } // consume any positionals following the last Optional let stop_index = consume_positionals(start_index) // if we didn't consume all the argument strings, there were extras extras = extras.concat(arg_strings.slice(stop_index)) // make sure all required actions were present and also convert // action defaults which were not given as arguments let required_actions = [] for (let action of this._actions) { if (!seen_actions.has(action)) { if (action.required) { required_actions.push(_get_action_name(action)) } else { // Convert action default now instead of doing it before // parsing arguments to avoid calling convert functions // twice (which may fail) if the argument was given, but // only if it was defined already in the namespace if (action.default !== undefined && typeof action.default === 'string' && hasattr(namespace, action.dest) && action.default === getattr(namespace, action.dest)) { setattr(namespace, action.dest, this._get_value(action, action.default)) } } } } if (required_actions.length) { this.error(sub('the following arguments are required: %s', required_actions.join(', '))) } // make sure all required groups had one option present for (let group of this._mutually_exclusive_groups) { if (group.required) { let no_actions_used = true for (let action of group._group_actions) { if (seen_non_default_actions.has(action)) { no_actions_used = false break } } // if no actions were used, report the error if (no_actions_used) { let names = group._group_actions .filter(action => action.help !== SUPPRESS) .map(action => _get_action_name(action)) let msg = 'one of the arguments %s is required' this.error(sub(msg, names.join(' '))) } } } // return the updated namespace and the extra arguments return [ namespace, extras ] } _read_args_from_files(arg_strings) { // expand arguments referencing files let new_arg_strings = [] for (let arg_string of arg_strings) { // for regular arguments, just add them back into the list if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) { new_arg_strings.push(arg_string) // replace arguments referencing files with the file content } else { try { let args_file = fs.readFileSync(arg_string.slice(1), 'utf8') let arg_strings = [] for (let arg_line of splitlines(args_file)) { for (let arg of this.convert_arg_line_to_args(arg_line)) { arg_strings.push(arg) } } arg_strings = this._read_args_from_files(arg_strings) new_arg_strings = new_arg_strings.concat(arg_strings) } catch (err) { this.error(err.message) } } } // return the modified argument list return new_arg_strings } convert_arg_line_to_args(arg_line) { return [arg_line] } _match_argument(action, arg_strings_pattern) { // match the pattern for this action to the arg strings let nargs_pattern = this._get_nargs_pattern(action) let match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern)) // raise an exception if we weren't able to find a match if (match === null) { let nargs_errors = { undefined: 'expected one argument', [OPTIONAL]: 'expected at most one argument', [ONE_OR_MORE]: 'expected at least one argument' } let msg = nargs_errors[action.nargs] if (msg === undefined) { msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs) } throw new ArgumentError(action, msg) } // return the number of arguments matched return match[1].length } _match_arguments_partial(actions, arg_strings_pattern) { // progressively shorten the actions list by slicing off the // final actions until we find a match let result = [] for (let i of range(actions.length, 0, -1)) { let actions_slice = actions.slice(0, i) let pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('') let match = arg_strings_pattern.match(new RegExp('^' + pattern)) if (match !== null) { result = result.concat(match.slice(1).map(string => string.length)) break } } // return the list of arg string counts return result } _parse_optional(arg_string) { // if it's an empty string, it was meant to be a positional if (!arg_string) { return undefined } // if it doesn't start with a prefix, it was meant to be positional if (!this.prefix_chars.includes(arg_string[0])) { return undefined } // if the option string is present in the parser, return the action if (arg_string in this._option_string_actions) { let action = this._option_string_actions[arg_string] return [ action, arg_string, undefined ] } // if it's just a single character, it was meant to be positional if (arg_string.length === 1) { return undefined } // if the option string before the "=" is present, return the action if (arg_string.includes('=')) { let [ option_string, explicit_arg ] = _string_split(arg_string, '=', 1) if (option_string in this._option_string_actions) { let action = this._option_string_actions[option_string] return [ action, option_string, explicit_arg ] } } // search through all possible prefixes of the option string // and all actions in the parser for possible interpretations let option_tuples = this._get_option_tuples(arg_string) // if multiple actions match, the option string was ambiguous if (option_tuples.length > 1) { let options = option_tuples.map(([ /*action*/, option_string/*, explicit_arg*/ ]) => option_string).join(', ') let args = {option: arg_string, matches: options} let msg = 'ambiguous option: %(option)s could match %(matches)s' this.error(sub(msg, args)) // if exactly one action matched, this segmentation is good, // so return the parsed action } else if (option_tuples.length === 1) { let [ option_tuple ] = option_tuples return option_tuple } // if it was not found as an option, but it looks like a negative // number, it was meant to be positional // unless there are negative-number-like options if (this._negative_number_matcher.test(arg_string)) { if (!this._has_negative_number_optionals.length) { return undefined } } // if it contains a space, it was meant to be a positional if (arg_string.includes(' ')) { return undefined } // it was meant to be an optional but there is no such option // in this parser (though it might be a valid option in a subparser) return [ undefined, arg_string, undefined ] } _get_option_tuples(option_string) { let result = [] // option strings starting with two prefix characters are only // split at the '=' let chars = this.prefix_chars if (chars.includes(option_string[0]) && chars.includes(option_string[1])) { if (this.allow_abbrev) { let option_prefix, explicit_arg if (option_string.includes('=')) { [ option_prefix, explicit_arg ] = _string_split(option_string, '=', 1) } else { option_prefix = option_string explicit_arg = undefined } for (let option_string of Object.keys(this._option_string_actions)) { if (option_string.startsWith(option_prefix)) { let action = this._option_string_actions[option_string] let tup = [ action, option_string, explicit_arg ] result.push(tup) } } } // single character options can be concatenated with their arguments // but multiple character options always have to have their argument // separate } else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) { let option_prefix = option_string let explicit_arg = undefined let short_option_prefix = option_string.slice(0, 2) let short_explicit_arg = option_string.slice(2) for (let option_string of Object.keys(this._option_string_actions)) { if (option_string === short_option_prefix) { let action = this._option_string_actions[option_string] let tup = [ action, option_string, short_explicit_arg ] result.push(tup) } else if (option_string.startsWith(option_prefix)) { let action = this._option_string_actions[option_string] let tup = [ action, option_string, explicit_arg ] result.push(tup) } } // shouldn't ever get here } else { this.error(sub('unexpected option string: %s', option_string)) } // return the collected option tuples return result } _get_nargs_pattern(action) { // in all examples below, we have to allow for '--' args // which are represented as '-' in the pattern let nargs = action.nargs let nargs_pattern // the default (None) is assumed to be a single argument if (nargs === undefined) { nargs_pattern = '(-*A-*)' // allow zero or one arguments } else if (nargs === OPTIONAL) { nargs_pattern = '(-*A?-*)' // allow zero or more arguments } else if (nargs === ZERO_OR_MORE) { nargs_pattern = '(-*[A-]*)' // allow one or more arguments } else if (nargs === ONE_OR_MORE) { nargs_pattern = '(-*A[A-]*)' // allow any number of options or arguments } else if (nargs === REMAINDER) { nargs_pattern = '([-AO]*)' // allow one argument followed by any number of options or arguments } else if (nargs === PARSER) { nargs_pattern = '(-*A[-AO]*)' // suppress action, like nargs=0 } else if (nargs === SUPPRESS) { nargs_pattern = '(-*-*)' // all others should be integers } else { nargs_pattern = sub('(-*%s-*)', 'A'.repeat(nargs).split('').join('-*')) } // if this is an optional action, -- is not allowed if (action.option_strings.length) { nargs_pattern = nargs_pattern.replace(/-\*/g, '') nargs_pattern = nargs_pattern.replace(/-/g, '') } // return the pattern return nargs_pattern } // ======================== // Alt command line argument parsing, allowing free intermix // ======================== parse_intermixed_args(args = undefined, namespace = undefined) { let argv [ args, argv ] = this.parse_known_intermixed_args(args, namespace) if (argv.length) { let msg = 'unrecognized arguments: %s' this.error(sub(msg, argv.join(' '))) } return args } parse_known_intermixed_args(args = undefined, namespace = undefined) { // returns a namespace and list of extras // // positional can be freely intermixed with optionals. optionals are // first parsed with all positional arguments deactivated. The 'extras' // are then parsed. If the parser definition is incompatible with the // intermixed assumptions (e.g. use of REMAINDER, subparsers) a // TypeError is raised. // // positionals are 'deactivated' by setting nargs and default to // SUPPRESS. This blocks the addition of that positional to the // namespace let extras let positionals = this._get_positional_actions() let a = positionals.filter(action => [ PARSER, REMAINDER ].includes(action.nargs)) if (a.length) { throw new TypeError(sub('parse_intermixed_args: positional arg' + ' with nargs=%s', a[0].nargs)) } for (let group of this._mutually_exclusive_groups) { for (let action of group._group_actions) { if (positionals.includes(action)) { throw new TypeError('parse_intermixed_args: positional in' + ' mutuallyExclusiveGroup') } } } let save_usage try { save_usage = this.usage let remaining_args try { if (this.usage === undefined) { // capture the full usage for use in error messages this.usage = this.format_usage().slice(7) } for (let action of positionals) { // deactivate positionals action.save_nargs = action.nargs // action.nargs = 0 action.nargs = SUPPRESS action.save_default = action.default action.default = SUPPRESS } [ namespace, remaining_args ] = this.parse_known_args(args, namespace) for (let action of positionals) { // remove the empty positional values from namespace let attr = getattr(namespace, action.dest) if (Array.isArray(attr) && attr.length === 0) { // eslint-disable-next-line no-console console.warn(sub('Do not expect %s in %s', action.dest, namespace)) delattr(namespace, action.dest) } } } finally { // restore nargs and usage before exiting for (let action of positionals) { action.nargs = action.save_nargs action.default = action.save_default } } let optionals = this._get_optional_actions() try { // parse positionals. optionals aren't normally required, but // they could be, so make sure they aren't. for (let action of optionals) { action.save_required = action.required action.required = false } for (let group of this._mutually_exclusive_groups) { group.save_required = group.required group.required = false } [ namespace, extras ] = this.parse_known_args(remaining_args, namespace) } finally { // restore parser values before exiting for (let action of optionals) { action.required = action.save_required } for (let group of this._mutually_exclusive_groups) { group.required = group.save_required } } } finally { this.usage = save_usage } return [ namespace, extras ] } // ======================== // Value conversion methods // ======================== _get_values(action, arg_strings) { // for everything but PARSER, REMAINDER args, strip out first '--' if (![PARSER, REMAINDER].includes(action.nargs)) { try { _array_remove(arg_strings, '--') } catch (err) {} } let value // optional argument produces a default when not present if (!arg_strings.length && action.nargs === OPTIONAL) { if (action.option_strings.length) { value = action.const } else { value = action.default } if (typeof value === 'string') { value = this._get_value(action, value) this._check_value(action, value) } // when nargs='*' on a positional, if there were no command-line // args, use the default if it is anything other than None } else if (!arg_strings.length && action.nargs === ZERO_OR_MORE && !action.option_strings.length) { if (action.default !== undefined) { value = action.default } else { value = arg_strings } this._check_value(action, value) // single argument or optional argument produces a single value } else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) { let arg_string = arg_strings[0] value = this._get_value(action, arg_string) this._check_value(action, value) // REMAINDER arguments convert all values, checking none } else if (action.nargs === REMAINDER) { value = arg_strings.map(v => this._get_value(action, v)) // PARSER arguments convert all values, but check only the first } else if (action.nargs === PARSER) { value = arg_strings.map(v => this._get_value(action, v)) this._check_value(action, value[0]) // SUPPRESS argument does not put anything in the namespace } else if (action.nargs === SUPPRESS) { value = SUPPRESS // all other types of nargs produce a list } else { value = arg_strings.map(v => this._get_value(action, v)) for (let v of value) { this._check_value(action, v) } } // return the converted value return value } _get_value(action, arg_string) { let type_func = this._registry_get('type', action.type, action.type) if (typeof type_func !== 'function') { let msg = '%r is not callable' throw new ArgumentError(action, sub(msg, type_func)) } // convert the value to the appropriate type let result try { try { result = type_func(arg_string) } catch (err) { // Dear TC39, why would you ever consider making es6 classes not callable? // We had one universal interface, [[Call]], which worked for anything // (with familiar this-instanceof guard for classes). Now we have two. if (err instanceof TypeError && /Class constructor .* cannot be invoked without 'new'/.test(err.message)) { // eslint-disable-next-line new-cap result = new type_func(arg_string) } else { throw err } } } catch (err) { // ArgumentTypeErrors indicate errors if (err instanceof ArgumentTypeError) { //let name = getattr(action.type, 'name', repr(action.type)) let msg = err.message throw new ArgumentError(action, msg) // TypeErrors or ValueErrors also indicate errors } else if (err instanceof TypeError) { let name = getattr(action.type, 'name', repr(action.type)) let args = {type: name, value: arg_string} let msg = 'invalid %(type)s value: %(value)r' throw new ArgumentError(action, sub(msg, args)) } else { throw err } } // return the converted value return result } _check_value(action, value) { // converted value must be one of the choices (if specified) if (action.choices !== undefined && !_choices_to_array(action.choices).includes(value)) { let args = {value, choices: _choices_to_array(action.choices).map(repr).join(', ')} let msg = 'invalid choice: %(value)r (choose from %(choices)s)' throw new ArgumentError(action, sub(msg, args)) } } // ======================= // Help-formatting methods // ======================= format_usage() { let formatter = this._get_formatter() formatter.add_usage(this.usage, this._actions, this._mutually_exclusive_groups) return formatter.format_help() } format_help() { let formatter = this._get_formatter() // usage formatter.add_usage(this.usage, this._actions, this._mutually_exclusive_groups) // description formatter.add_text(this.description) // positionals, optionals and user-defined groups for (let action_group of this._action_groups) { formatter.start_section(action_group.title) formatter.add_text(action_group.description) formatter.add_arguments(action_group._group_actions) formatter.end_section() } // epilog formatter.add_text(this.epilog) // determine help from format above return formatter.format_help() } _get_formatter() { // eslint-disable-next-line new-cap return new this.formatter_class({ prog: this.prog }) } // ===================== // Help-printing methods // ===================== print_usage(file = undefined) { if (file === undefined) file = process.stdout this._print_message(this.format_usage(), file) } print_help(file = undefined) { if (file === undefined) file = process.stdout this._print_message(this.format_help(), file) } _print_message(message, file = undefined) { if (message) { if (file === undefined) file = process.stderr file.write(message) } } // =============== // Exiting methods // =============== exit(status = 0, message = undefined) { if (message) { this._print_message(message, process.stderr) } process.exit(status) } error(message) { /* * error(message: string) * * Prints a usage message incorporating the message to stderr and * exits. * * If you override this in a subclass, it should not return -- it * should either exit or raise an exception. */ // LEGACY (v1 compatibility), debug mode if (this.debug === true) throw new Error(message) // end this.print_usage(process.stderr) let args = {prog: this.prog, message: message} this.exit(2, sub('%(prog)s: error: %(message)s\n', args)) } })) module.exports = { ArgumentParser, ArgumentError, ArgumentTypeError, BooleanOptionalAction, FileType, HelpFormatter, ArgumentDefaultsHelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, MetavarTypeHelpFormatter, Namespace, Action, ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE } // LEGACY (v1 compatibility), Const alias Object.defineProperty(module.exports, 'Const', { get() { let result = {} Object.entries({ ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE }).forEach(([ n, v ]) => { Object.defineProperty(result, n, { get() { deprecate(n, sub('use argparse.%s instead of argparse.Const.%s', n, n)) return v } }) }) Object.entries({ _UNRECOGNIZED_ARGS_ATTR }).forEach(([ n, v ]) => { Object.defineProperty(result, n, { get() { deprecate(n, sub('argparse.Const.%s is an internal symbol and will no longer be available', n)) return v } }) }) return result }, enumerable: false }) // end // Limited implementation of python % string operator, supports only %s and %r for now // (other formats are not used here, but may appear in custom templates) 'use strict' const { inspect } = require('util') module.exports = function sub(pattern, ...values) { let regex = /%(?:(%)|(-)?(\*)?(?:\((\w+)\))?([A-Za-z]))/g let result = pattern.replace(regex, function (_, is_literal, is_left_align, is_padded, name, format) { if (is_literal) return '%' let padded_count = 0 if (is_padded) { if (values.length === 0) throw new TypeError('not enough arguments for format string') padded_count = values.shift() if (!Number.isInteger(padded_count)) throw new TypeError('* wants int') } let str if (name !== undefined) { let dict = values[0] if (typeof dict !== 'object' || dict === null) throw new TypeError('format requires a mapping') if (!(name in dict)) throw new TypeError(`no such key: '${name}'`) str = dict[name] } else { if (values.length === 0) throw new TypeError('not enough arguments for format string') str = values.shift() } switch (format) { case 's': str = String(str) break case 'r': str = inspect(str) break case 'd': case 'i': if (typeof str !== 'number') { throw new TypeError(`%${format} format: a number is required, not ${typeof str}`) } str = String(str.toFixed(0)) break default: throw new TypeError(`unsupported format character '${format}'`) } if (padded_count > 0) { return is_left_align ? str.padEnd(padded_count) : str.padStart(padded_count) } else { return str } }) if (values.length) { if (values.length === 1 && typeof values[0] === 'object' && values[0] !== null) { // mapping } else { throw new TypeError('not all arguments converted during string formatting') } } return result } // Partial port of python's argparse module, version 3.9.0 (only wrap and fill functions): // https://github.com/python/cpython/blob/v3.9.0b4/Lib/textwrap.py 'use strict' /* * Text wrapping and filling. */ // Copyright (C) 1999-2001 Gregory P. Ward. // Copyright (C) 2002, 2003 Python Software Foundation. // Copyright (C) 2020 argparse.js authors // Originally written by Greg Ward // Hardcode the recognized whitespace characters to the US-ASCII // whitespace characters. The main reason for doing this is that // some Unicode spaces (like \u00a0) are non-breaking whitespaces. // // This less funky little regex just split on recognized spaces. E.g. // "Hello there -- you goof-ball, use the -b option!" // splits into // Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ const wordsep_simple_re = /([\t\n\x0b\x0c\r ]+)/ class TextWrapper { /* * Object for wrapping/filling text. The public interface consists of * the wrap() and fill() methods; the other methods are just there for * subclasses to override in order to tweak the default behaviour. * If you want to completely replace the main wrapping algorithm, * you'll probably have to override _wrap_chunks(). * * Several instance attributes control various aspects of wrapping: * width (default: 70) * the maximum width of wrapped lines (unless break_long_words * is false) * initial_indent (default: "") * string that will be prepended to the first line of wrapped * output. Counts towards the line's width. * subsequent_indent (default: "") * string that will be prepended to all lines save the first * of wrapped output; also counts towards each line's width. * expand_tabs (default: true) * Expand tabs in input text to spaces before further processing. * Each tab will become 0 .. 'tabsize' spaces, depending on its position * in its line. If false, each tab is treated as a single character. * tabsize (default: 8) * Expand tabs in input text to 0 .. 'tabsize' spaces, unless * 'expand_tabs' is false. * replace_whitespace (default: true) * Replace all whitespace characters in the input text by spaces * after tab expansion. Note that if expand_tabs is false and * replace_whitespace is true, every tab will be converted to a * single space! * fix_sentence_endings (default: false) * Ensure that sentence-ending punctuation is always followed * by two spaces. Off by default because the algorithm is * (unavoidably) imperfect. * break_long_words (default: true) * Break words longer than 'width'. If false, those words will not * be broken, and some lines might be longer than 'width'. * break_on_hyphens (default: true) * Allow breaking hyphenated words. If true, wrapping will occur * preferably on whitespaces and right after hyphens part of * compound words. * drop_whitespace (default: true) * Drop leading and trailing whitespace from lines. * max_lines (default: None) * Truncate wrapped lines. * placeholder (default: ' [...]') * Append to the last line of truncated text. */ constructor(options = {}) { let { width = 70, initial_indent = '', subsequent_indent = '', expand_tabs = true, replace_whitespace = true, fix_sentence_endings = false, break_long_words = true, drop_whitespace = true, break_on_hyphens = true, tabsize = 8, max_lines = undefined, placeholder=' [...]' } = options this.width = width this.initial_indent = initial_indent this.subsequent_indent = subsequent_indent this.expand_tabs = expand_tabs this.replace_whitespace = replace_whitespace this.fix_sentence_endings = fix_sentence_endings this.break_long_words = break_long_words this.drop_whitespace = drop_whitespace this.break_on_hyphens = break_on_hyphens this.tabsize = tabsize this.max_lines = max_lines this.placeholder = placeholder } // -- Private methods ----------------------------------------------- // (possibly useful for subclasses to override) _munge_whitespace(text) { /* * _munge_whitespace(text : string) -> string * * Munge whitespace in text: expand tabs and convert all other * whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" * becomes " foo bar baz". */ if (this.expand_tabs) { text = text.replace(/\t/g, ' '.repeat(this.tabsize)) // not strictly correct in js } if (this.replace_whitespace) { text = text.replace(/[\t\n\x0b\x0c\r]/g, ' ') } return text } _split(text) { /* * _split(text : string) -> [string] * * Split the text to wrap into indivisible chunks. Chunks are * not quite the same as words; see _wrap_chunks() for full * details. As an example, the text * Look, goof-ball -- use the -b option! * breaks into the following chunks: * 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', * 'use', ' ', 'the', ' ', '-b', ' ', 'option!' * if break_on_hyphens is True, or in: * 'Look,', ' ', 'goof-ball', ' ', '--', ' ', * 'use', ' ', 'the', ' ', '-b', ' ', option!' * otherwise. */ let chunks = text.split(wordsep_simple_re) chunks = chunks.filter(Boolean) return chunks } _handle_long_word(reversed_chunks, cur_line, cur_len, width) { /* * _handle_long_word(chunks : [string], * cur_line : [string], * cur_len : int, width : int) * * Handle a chunk of text (most likely a word, not whitespace) that * is too long to fit in any line. */ // Figure out when indent is larger than the specified width, and make // sure at least one character is stripped off on every pass let space_left if (width < 1) { space_left = 1 } else { space_left = width - cur_len } // If we're allowed to break long words, then do so: put as much // of the next chunk onto the current line as will fit. if (this.break_long_words) { cur_line.push(reversed_chunks[reversed_chunks.length - 1].slice(0, space_left)) reversed_chunks[reversed_chunks.length - 1] = reversed_chunks[reversed_chunks.length - 1].slice(space_left) // Otherwise, we have to preserve the long word intact. Only add // it to the current line if there's nothing already there -- // that minimizes how much we violate the width constraint. } else if (!cur_line) { cur_line.push(...reversed_chunks.pop()) } // If we're not allowed to break long words, and there's already // text on the current line, do nothing. Next time through the // main loop of _wrap_chunks(), we'll wind up here again, but // cur_len will be zero, so the next line will be entirely // devoted to the long word that we can't handle right now. } _wrap_chunks(chunks) { /* * _wrap_chunks(chunks : [string]) -> [string] * * Wrap a sequence of text chunks and return a list of lines of * length 'self.width' or less. (If 'break_long_words' is false, * some lines may be longer than this.) Chunks correspond roughly * to words and the whitespace between them: each chunk is * indivisible (modulo 'break_long_words'), but a line break can * come between any two chunks. Chunks should not have internal * whitespace; ie. a chunk is either all whitespace or a "word". * Whitespace chunks will be removed from the beginning and end of * lines, but apart from that whitespace is preserved. */ let lines = [] let indent if (this.width <= 0) { throw Error(`invalid width ${this.width} (must be > 0)`) } if (this.max_lines !== undefined) { if (this.max_lines > 1) { indent = this.subsequent_indent } else { indent = this.initial_indent } if (indent.length + this.placeholder.trimStart().length > this.width) { throw Error('placeholder too large for max width') } } // Arrange in reverse order so items can be efficiently popped // from a stack of chucks. chunks = chunks.reverse() while (chunks.length > 0) { // Start the list of chunks that will make up the current line. // cur_len is just the length of all the chunks in cur_line. let cur_line = [] let cur_len = 0 // Figure out which static string will prefix this line. let indent if (lines) { indent = this.subsequent_indent } else { indent = this.initial_indent } // Maximum width for this line. let width = this.width - indent.length // First chunk on line is whitespace -- drop it, unless this // is the very beginning of the text (ie. no lines started yet). if (this.drop_whitespace && chunks[chunks.length - 1].trim() === '' && lines.length > 0) { chunks.pop() } while (chunks.length > 0) { let l = chunks[chunks.length - 1].length // Can at least squeeze this chunk onto the current line. if (cur_len + l <= width) { cur_line.push(chunks.pop()) cur_len += l // Nope, this line is full. } else { break } } // The current line is full, and the next chunk is too big to // fit on *any* line (not just this one). if (chunks.length && chunks[chunks.length - 1].length > width) { this._handle_long_word(chunks, cur_line, cur_len, width) cur_len = cur_line.map(l => l.length).reduce((a, b) => a + b, 0) } // If the last chunk on this line is all whitespace, drop it. if (this.drop_whitespace && cur_line.length > 0 && cur_line[cur_line.length - 1].trim() === '') { cur_len -= cur_line[cur_line.length - 1].length cur_line.pop() } if (cur_line) { if (this.max_lines === undefined || lines.length + 1 < this.max_lines || (chunks.length === 0 || this.drop_whitespace && chunks.length === 1 && !chunks[0].trim()) && cur_len <= width) { // Convert current line back to a string and store it in // list of all lines (return value). lines.push(indent + cur_line.join('')) } else { let had_break = false while (cur_line) { if (cur_line[cur_line.length - 1].trim() && cur_len + this.placeholder.length <= width) { cur_line.push(this.placeholder) lines.push(indent + cur_line.join('')) had_break = true break } cur_len -= cur_line[-1].length cur_line.pop() } if (!had_break) { if (lines) { let prev_line = lines[lines.length - 1].trimEnd() if (prev_line.length + this.placeholder.length <= this.width) { lines[lines.length - 1] = prev_line + this.placeholder break } } lines.push(indent + this.placeholder.lstrip()) } break } } } return lines } _split_chunks(text) { text = this._munge_whitespace(text) return this._split(text) } // -- Public interface ---------------------------------------------- wrap(text) { /* * wrap(text : string) -> [string] * * Reformat the single paragraph in 'text' so it fits in lines of * no more than 'self.width' columns, and return a list of wrapped * lines. Tabs in 'text' are expanded with string.expandtabs(), * and all other whitespace characters (including newline) are * converted to space. */ let chunks = this._split_chunks(text) // not implemented in js //if (this.fix_sentence_endings) { // this._fix_sentence_endings(chunks) //} return this._wrap_chunks(chunks) } fill(text) { /* * fill(text : string) -> string * * Reformat the single paragraph in 'text' to fit in lines of no * more than 'self.width' columns, and return a new string * containing the entire wrapped paragraph. */ return this.wrap(text).join('\n') } } // -- Convenience interface --------------------------------------------- function wrap(text, options = {}) { /* * Wrap a single paragraph of text, returning a list of wrapped lines. * * Reformat the single paragraph in 'text' so it fits in lines of no * more than 'width' columns, and return a list of wrapped lines. By * default, tabs in 'text' are expanded with string.expandtabs(), and * all other whitespace characters (including newline) are converted to * space. See TextWrapper class for available keyword args to customize * wrapping behaviour. */ let { width = 70, ...kwargs } = options let w = new TextWrapper(Object.assign({ width }, kwargs)) return w.wrap(text) } function fill(text, options = {}) { /* * Fill a single paragraph of text, returning a new string. * * Reformat the single paragraph in 'text' to fit in lines of no more * than 'width' columns, and return a new string containing the entire * wrapped paragraph. As with wrap(), tabs are expanded and other * whitespace characters converted to space. See TextWrapper class for * available keyword args to customize wrapping behaviour. */ let { width = 70, ...kwargs } = options let w = new TextWrapper(Object.assign({ width }, kwargs)) return w.fill(text) } // -- Loosely related functionality ------------------------------------- let _whitespace_only_re = /^[ \t]+$/mg let _leading_whitespace_re = /(^[ \t]*)(?:[^ \t\n])/mg function dedent(text) { /* * Remove any common leading whitespace from every line in `text`. * * This can be used to make triple-quoted strings line up with the left * edge of the display, while still presenting them in the source code * in indented form. * * Note that tabs and spaces are both treated as whitespace, but they * are not equal: the lines " hello" and "\\thello" are * considered to have no common leading whitespace. * * Entirely blank lines are normalized to a newline character. */ // Look for the longest leading string of spaces and tabs common to // all lines. let margin = undefined text = text.replace(_whitespace_only_re, '') let indents = text.match(_leading_whitespace_re) || [] for (let indent of indents) { indent = indent.slice(0, -1) if (margin === undefined) { margin = indent // Current line more deeply indented than previous winner: // no change (previous winner is still on top). } else if (indent.startsWith(margin)) { // pass // Current line consistent with and no deeper than previous winner: // it's the new winner. } else if (margin.startsWith(indent)) { margin = indent // Find the largest common whitespace between current line and previous // winner. } else { for (let i = 0; i < margin.length && i < indent.length; i++) { if (margin[i] !== indent[i]) { margin = margin.slice(0, i) break } } } } if (margin) { text = text.replace(new RegExp('^' + margin, 'mg'), '') } return text } module.exports = { wrap, fill, dedent } { "name": "argparse", "description": "CLI arguments parser. Native port of python's argparse.", "version": "2.0.1", "main": "argparse.js", "files": [ "argparse.js", "lib/" ], "license": "Python-2.0", "repository": "nodeca/argparse", "devDependencies": { "@babel/eslint-parser": "^7.11.0", "@babel/plugin-syntax-class-properties": "^7.10.4", "eslint": "^7.5.0", "mocha": "^8.0.1", "nyc": "^15.1.0" } }/* IMPORT */ import process from 'node:process'; /* MAIN */ const DEFAULT_ENCODING = 'utf8'; const DEFAULT_FILE_MODE = 0o666; const DEFAULT_FOLDER_MODE = 0o777; const DEFAULT_READ_OPTIONS = {}; const DEFAULT_WRITE_OPTIONS = {}; const DEFAULT_USER_UID = process.geteuid ? process.geteuid() : -1; const DEFAULT_USER_GID = process.getegid ? process.getegid() : -1; const DEFAULT_INTERVAL_ASYNC = 200; const DEFAULT_TIMEOUT_ASYNC = 7500; const DEFAULT_TIMEOUT_SYNC = 1000; const IS_POSIX = !!process.getuid; const IS_USER_ROOT = process.getuid ? !process.getuid() : false; const LIMIT_BASENAME_LENGTH = 128; //TODO: Fetch the real limit from the filesystem //TODO: Fetch the whole-path length limit too const NOOP = () => { }; /* EXPORT */ export { DEFAULT_ENCODING, DEFAULT_FILE_MODE, DEFAULT_FOLDER_MODE, DEFAULT_READ_OPTIONS, DEFAULT_WRITE_OPTIONS, DEFAULT_USER_UID, DEFAULT_USER_GID, DEFAULT_INTERVAL_ASYNC, DEFAULT_TIMEOUT_ASYNC, DEFAULT_TIMEOUT_SYNC, IS_POSIX, IS_USER_ROOT, LIMIT_BASENAME_LENGTH, NOOP }; /* IMPORT */ import { once } from 'node:events'; import { createWriteStream } from 'node:fs'; import path from 'node:path'; import { Readable } from 'node:stream'; import fs from 'stubborn-fs'; import { DEFAULT_ENCODING, DEFAULT_FILE_MODE, DEFAULT_FOLDER_MODE, DEFAULT_READ_OPTIONS, DEFAULT_WRITE_OPTIONS, DEFAULT_USER_UID, DEFAULT_USER_GID, DEFAULT_INTERVAL_ASYNC, DEFAULT_TIMEOUT_ASYNC, DEFAULT_TIMEOUT_SYNC, IS_POSIX } from './constants.js'; import { isException, isFunction, isString, isUndefined } from './utils/lang.js'; import Scheduler from './utils/scheduler.js'; import Temp from './utils/temp.js'; function readFile(filePath, options = DEFAULT_READ_OPTIONS) { if (isString(options)) return readFile(filePath, { encoding: options }); const timeout = options.timeout ?? DEFAULT_TIMEOUT_ASYNC; const retryOptions = { timeout, interval: DEFAULT_INTERVAL_ASYNC }; return fs.retry.readFile(retryOptions)(filePath, options); } function readFileSync(filePath, options = DEFAULT_READ_OPTIONS) { if (isString(options)) return readFileSync(filePath, { encoding: options }); const timeout = options.timeout ?? DEFAULT_TIMEOUT_SYNC; const retryOptions = { timeout }; return fs.retry.readFileSync(retryOptions)(filePath, options); } function writeFile(filePath, data, options, callback) { if (isFunction(options)) return writeFile(filePath, data, DEFAULT_WRITE_OPTIONS, options); const promise = writeFileAsync(filePath, data, options); if (callback) promise.then(callback, callback); return promise; } async function writeFileAsync(filePath, data, options = DEFAULT_WRITE_OPTIONS) { if (isString(options)) return writeFileAsync(filePath, data, { encoding: options }); const timeout = options.timeout ?? DEFAULT_TIMEOUT_ASYNC; const retryOptions = { timeout, interval: DEFAULT_INTERVAL_ASYNC }; let schedulerCustomDisposer = null; let schedulerDisposer = null; let tempDisposer = null; let tempPath = null; let fd = null; try { if (options.schedule) schedulerCustomDisposer = await options.schedule(filePath); schedulerDisposer = await Scheduler.schedule(filePath); const filePathReal = await fs.attempt.realpath(filePath); const filePathExists = !!filePathReal; filePath = filePathReal || filePath; [tempPath, tempDisposer] = Temp.get(filePath, options.tmpCreate || Temp.create, !(options.tmpPurge === false)); const useStatChown = IS_POSIX && isUndefined(options.chown); const useStatMode = isUndefined(options.mode); if (filePathExists && (useStatChown || useStatMode)) { const stats = await fs.attempt.stat(filePath); if (stats) { options = { ...options }; if (useStatChown) { options.chown = { uid: stats.uid, gid: stats.gid }; } if (useStatMode) { options.mode = stats.mode; } } } if (!filePathExists) { const parentPath = path.dirname(filePath); await fs.attempt.mkdir(parentPath, { mode: DEFAULT_FOLDER_MODE, recursive: true }); } fd = await fs.retry.open(retryOptions)(tempPath, 'w', options.mode || DEFAULT_FILE_MODE); if (options.tmpCreated) { options.tmpCreated(tempPath); } if (isString(data)) { await fs.retry.write(retryOptions)(fd, data, 0, options.encoding || DEFAULT_ENCODING); } else if (data instanceof Readable) { const writeStream = createWriteStream(tempPath, { fd, autoClose: false }); const finishPromise = once(writeStream, 'finish'); data.pipe(writeStream); await finishPromise; } else if (!isUndefined(data)) { await fs.retry.write(retryOptions)(fd, data, 0, data.length, 0); } if (options.fsync !== false) { if (options.fsyncWait !== false) { await fs.retry.fsync(retryOptions)(fd); } else { fs.attempt.fsync(fd); } } await fs.retry.close(retryOptions)(fd); fd = null; if (options.chown && (options.chown.uid !== DEFAULT_USER_UID || options.chown.gid !== DEFAULT_USER_GID)) { await fs.attempt.chown(tempPath, options.chown.uid, options.chown.gid); } if (options.mode && options.mode !== DEFAULT_FILE_MODE) { await fs.attempt.chmod(tempPath, options.mode); } try { await fs.retry.rename(retryOptions)(tempPath, filePath); } catch (error) { if (!isException(error)) throw error; if (error.code !== 'ENAMETOOLONG') throw error; await fs.retry.rename(retryOptions)(tempPath, Temp.truncate(filePath)); } tempDisposer(); tempPath = null; } finally { if (fd) await fs.attempt.close(fd); if (tempPath) Temp.purge(tempPath); if (schedulerCustomDisposer) schedulerCustomDisposer(); if (schedulerDisposer) schedulerDisposer(); } } function writeFileSync(filePath, data, options = DEFAULT_WRITE_OPTIONS) { if (isString(options)) return writeFileSync(filePath, data, { encoding: options }); const timeout = options.timeout ?? DEFAULT_TIMEOUT_SYNC; const retryOptions = { timeout }; let tempDisposer = null; let tempPath = null; let fd = null; try { const filePathReal = fs.attempt.realpathSync(filePath); const filePathExists = !!filePathReal; filePath = filePathReal || filePath; [tempPath, tempDisposer] = Temp.get(filePath, options.tmpCreate || Temp.create, !(options.tmpPurge === false)); const useStatChown = IS_POSIX && isUndefined(options.chown); const useStatMode = isUndefined(options.mode); if (filePathExists && (useStatChown || useStatMode)) { const stats = fs.attempt.statSync(filePath); if (stats) { options = { ...options }; if (useStatChown) { options.chown = { uid: stats.uid, gid: stats.gid }; } if (useStatMode) { options.mode = stats.mode; } } } if (!filePathExists) { const parentPath = path.dirname(filePath); fs.attempt.mkdirSync(parentPath, { mode: DEFAULT_FOLDER_MODE, recursive: true }); } fd = fs.retry.openSync(retryOptions)(tempPath, 'w', options.mode || DEFAULT_FILE_MODE); if (options.tmpCreated) { options.tmpCreated(tempPath); } if (isString(data)) { fs.retry.writeSync(retryOptions)(fd, data, 0, options.encoding || DEFAULT_ENCODING); } else if (!isUndefined(data)) { fs.retry.writeSync(retryOptions)(fd, data, 0, data.length, 0); } if (options.fsync !== false) { if (options.fsyncWait !== false) { fs.retry.fsyncSync(retryOptions)(fd); } else { fs.attempt.fsync(fd); } } fs.retry.closeSync(retryOptions)(fd); fd = null; if (options.chown && (options.chown.uid !== DEFAULT_USER_UID || options.chown.gid !== DEFAULT_USER_GID)) { fs.attempt.chownSync(tempPath, options.chown.uid, options.chown.gid); } if (options.mode && options.mode !== DEFAULT_FILE_MODE) { fs.attempt.chmodSync(tempPath, options.mode); } try { fs.retry.renameSync(retryOptions)(tempPath, filePath); } catch (error) { if (!isException(error)) throw error; if (error.code !== 'ENAMETOOLONG') throw error; fs.retry.renameSync(retryOptions)(tempPath, Temp.truncate(filePath)); } tempDisposer(); tempPath = null; } finally { if (fd) fs.attempt.closeSync(fd); if (tempPath) Temp.purge(tempPath); } } /* EXPORT */ export { readFile, readFileSync, writeFile, writeFileSync }; /* MAIN */ export {}; /* IMPORT */ /* MAIN */ const isException = (value) => { return (value instanceof Error) && ('code' in value); }; const isFunction = (value) => { return (typeof value === 'function'); }; const isString = (value) => { return (typeof value === 'string'); }; const isUndefined = (value) => { return (value === undefined); }; /* EXPORT */ export { isException, isFunction, isString, isUndefined }; /* IMPORT */ /* HELPERS */ const Queues = {}; /* MAIN */ //TODO: Maybe publish this as a standalone package const Scheduler = { /* API */ next: (id) => { const queue = Queues[id]; if (!queue) return; queue.shift(); const job = queue[0]; if (job) { job(() => Scheduler.next(id)); } else { delete Queues[id]; } }, schedule: (id) => { return new Promise(resolve => { let queue = Queues[id]; if (!queue) queue = Queues[id] = []; queue.push(resolve); if (queue.length > 1) return; resolve(() => Scheduler.next(id)); }); } }; /* EXPORT */ export default Scheduler; /* IMPORT */ import path from 'node:path'; import fs from 'stubborn-fs'; import whenExit from 'when-exit'; import { LIMIT_BASENAME_LENGTH } from '../constants.js'; /* MAIN */ //TODO: Maybe publish this as a standalone package const Temp = { /* VARIABLES */ store: {}, // filePath => purge /* API */ create: (filePath) => { const randomness = `000000${Math.floor(Math.random() * 16777215).toString(16)}`.slice(-6); // 6 random-enough hex characters const timestamp = Date.now().toString().slice(-10); // 10 precise timestamp digits const prefix = 'tmp-'; const suffix = `.${prefix}${timestamp}${randomness}`; const tempPath = `${filePath}${suffix}`; return tempPath; }, get: (filePath, creator, purge = true) => { const tempPath = Temp.truncate(creator(filePath)); if (tempPath in Temp.store) return Temp.get(filePath, creator, purge); // Collision found, try again Temp.store[tempPath] = purge; const disposer = () => delete Temp.store[tempPath]; return [tempPath, disposer]; }, purge: (filePath) => { if (!Temp.store[filePath]) return; delete Temp.store[filePath]; fs.attempt.unlink(filePath); }, purgeSync: (filePath) => { if (!Temp.store[filePath]) return; delete Temp.store[filePath]; fs.attempt.unlinkSync(filePath); }, purgeSyncAll: () => { for (const filePath in Temp.store) { Temp.purgeSync(filePath); } }, truncate: (filePath) => { const basename = path.basename(filePath); if (basename.length <= LIMIT_BASENAME_LENGTH) return filePath; //FIXME: Rough and quick attempt at detecting ok lengths const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename); if (!truncable) return filePath; //FIXME: No truncable part detected, can't really do much without also changing the parent path, which is unsafe, hoping for the best here const truncationLength = basename.length - LIMIT_BASENAME_LENGTH; return `${filePath.slice(0, -basename.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`; //FIXME: The truncable part might be shorter than needed here } }; /* INIT */ whenExit(Temp.purgeSyncAll); // Ensuring purgeable temp files are purged on exit /* EXPORT */ export default Temp; The MIT License (MIT) Copyright (c) 2020-present Fabio Spampinato 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. { "name": "atomically", "repository": "github:fabiospampinato/atomically", "description": "Read and write files atomically and reliably.", "license": "MIT", "version": "2.1.1", "type": "module", "main": "dist/index.js", "exports": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { "stubborn-fs": "^2.0.0", "when-exit": "^2.1.4" }, "devDependencies": { "@types/node": "^18.19.130", "esbuild": "^0.18.20", "require-inject": "^1.4.4", "tap": "^21.1.1", "tsex": "^4.0.2", "typescript": "^5.9.3", "write-file-atomic": "^7.0.0" } }MIT License Copyright (c) 2016 Teamwork.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. var fileBasedUtilities, untildify; untildify = require('untildify'); fileBasedUtilities = require('./fileBasedUtilities'); module.exports = { /* Public */ enable: function(arg) { var appName, appPath, data, hiddenArg, isHiddenOnLaunch; appName = arg.appName, appPath = arg.appPath, isHiddenOnLaunch = arg.isHiddenOnLaunch; hiddenArg = isHiddenOnLaunch ? ' --hidden' : ''; data = "[Desktop Entry]\nType=Application\nVersion=1.0\nName=" + appName + "\nComment=" + appName + "startup script\nExec=" + appPath + hiddenArg + "\nStartupNotify=false\nTerminal=false"; return fileBasedUtilities.createFile({ data: data, directory: this.getDirectory(), filePath: this.getFilePath(appName) }); }, disable: function(appName) { return fileBasedUtilities.removeFile(this.getFilePath(appName)); }, isEnabled: function(appName) { return fileBasedUtilities.isEnabled(this.getFilePath(appName)); }, /* Private */ getDirectory: function() { return untildify('~/.config/autostart/'); }, getFilePath: function(appName) { return "" + (this.getDirectory()) + appName + ".desktop"; } }; var applescript, fileBasedUtilities, untildify, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; applescript = require('applescript'); untildify = require('untildify'); fileBasedUtilities = require('./fileBasedUtilities'); module.exports = { /* Public */ enable: function(arg) { var appName, appPath, data, isHiddenOnLaunch, isHiddenValue, mac, programArguments, programArgumentsSection, properties; appName = arg.appName, appPath = arg.appPath, isHiddenOnLaunch = arg.isHiddenOnLaunch, mac = arg.mac; if (mac.useLaunchAgent) { programArguments = [appPath]; if (isHiddenOnLaunch) { programArguments.push('--hidden'); } programArgumentsSection = programArguments.map(function(argument) { return " " + argument + ""; }).join('\n'); data = "\n\n\n\n Label\n " + appName + "\n ProgramArguments\n \n " + programArgumentsSection + "\n \n RunAtLoad\n \n\n"; return fileBasedUtilities.createFile({ data: data, directory: this.getDirectory(), filePath: this.getFilePath(appName) }); } isHiddenValue = isHiddenOnLaunch ? 'true' : 'false'; properties = "{path:\"" + appPath + "\", hidden:" + isHiddenValue + ", name:\"" + appName + "\"}"; return this.execApplescriptCommand("make login item at end with properties " + properties); }, disable: function(appName, mac) { if (mac.useLaunchAgent) { return fileBasedUtilities.removeFile(this.getFilePath(appName)); } return this.execApplescriptCommand("delete login item \"" + appName + "\""); }, isEnabled: function(appName, mac) { if (mac.useLaunchAgent) { return fileBasedUtilities.isEnabled(this.getFilePath(appName)); } return this.execApplescriptCommand('get the name of every login item').then(function(loginItems) { return (loginItems != null) && indexOf.call(loginItems, appName) >= 0; }); }, /* Private */ execApplescriptCommand: function(commandSuffix) { return new Promise(function(resolve, reject) { return applescript.execString("tell application \"System Events\" to " + commandSuffix, function(err, result) { if (err != null) { return reject(err); } return resolve(result); }); }); }, getDirectory: function() { return untildify('~/Library/LaunchAgents/'); }, getFilePath: function(appName) { return "" + (this.getDirectory()) + appName + ".plist"; } }; var Winreg, fs, path, regKey; fs = require('fs'); path = require('path'); Winreg = require('winreg'); regKey = new Winreg({ hive: Winreg.HKCU, key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' }); module.exports = { /* Public */ enable: function(arg) { var appName, appPath, isHiddenOnLaunch; appName = arg.appName, appPath = arg.appPath, isHiddenOnLaunch = arg.isHiddenOnLaunch; return new Promise(function(resolve, reject) { var args, pathToAutoLaunchedApp, ref, updateDotExe; pathToAutoLaunchedApp = appPath; args = ''; updateDotExe = path.join(path.dirname(process.execPath), '..', 'update.exe'); if ((((ref = process.versions) != null ? ref.electron : void 0) != null) && fs.existsSync(updateDotExe)) { pathToAutoLaunchedApp = updateDotExe; args = " --processStart \"" + (path.basename(process.execPath)) + "\""; if (isHiddenOnLaunch) { args += ' --process-start-args "--hidden"'; } } else { if (isHiddenOnLaunch) { args += ' --hidden'; } } return regKey.set(appName, Winreg.REG_SZ, "\"" + pathToAutoLaunchedApp + "\"" + args, function(err) { if (err != null) { return reject(err); } return resolve(); }); }); }, disable: function(appName) { return new Promise(function(resolve, reject) { return regKey.remove(appName, function(err) { if (err != null) { if (err.message.indexOf('The system was unable to find the specified registry key or value') !== -1) { return resolve(false); } return reject(err); } return resolve(); }); }); }, isEnabled: function(appName) { return new Promise(function(resolve, reject) { return regKey.get(appName, function(err, item) { if (err != null) { return resolve(false); } return resolve(item != null); }); }); } }; var fs, mkdirp; fs = require('fs'); mkdirp = require('mkdirp'); module.exports = { /* Public */ createFile: function(arg) { var data, directory, filePath; directory = arg.directory, filePath = arg.filePath, data = arg.data; return new Promise(function(resolve, reject) { return mkdirp(directory, function(mkdirErr) { if (mkdirErr != null) { return reject(mkdirErr); } return fs.writeFile(filePath, data, function(writeErr) { if (writeErr != null) { return reject(writeErr); } return resolve(); }); }); }); }, isEnabled: function(filePath) { return new Promise((function(_this) { return function(resolve, reject) { return fs.stat(filePath, function(err, stat) { if (err != null) { return resolve(false); } return resolve(stat != null); }); }; })(this)); }, removeFile: function(filePath) { return new Promise((function(_this) { return function(resolve, reject) { return fs.stat(filePath, function(statErr) { if (statErr != null) { return resolve(); } return fs.unlink(filePath, function(unlinkErr) { if (unlinkErr != null) { return reject(unlinkErr); } return resolve(); }); }); }; })(this)); } }; var AutoLaunch, isPathAbsolute, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; isPathAbsolute = require('path-is-absolute'); module.exports = AutoLaunch = (function() { /* Public */ function AutoLaunch(arg) { var isHidden, mac, name, path, versions; name = arg.name, isHidden = arg.isHidden, mac = arg.mac, path = arg.path; this.fixOpts = bind(this.fixOpts, this); this.isEnabled = bind(this.isEnabled, this); this.disable = bind(this.disable, this); this.enable = bind(this.enable, this); if (name == null) { throw new Error('You must specify a name'); } this.opts = { appName: name, isHiddenOnLaunch: isHidden != null ? isHidden : false, mac: mac != null ? mac : {} }; versions = typeof process !== "undefined" && process !== null ? process.versions : void 0; if (path != null) { if (!isPathAbsolute(path)) { throw new Error('path must be absolute'); } this.opts.appPath = path; } else if ((versions != null) && ((versions.nw != null) || (versions['node-webkit'] != null) || (versions.electron != null))) { this.opts.appPath = process.execPath; } else { throw new Error('You must give a path (this is only auto-detected for NW.js and Electron apps)'); } this.fixOpts(); this.api = null; if (/^win/.test(process.platform)) { this.api = require('./AutoLaunchWindows'); } else if (/darwin/.test(process.platform)) { this.api = require('./AutoLaunchMac'); } else if ((/linux/.test(process.platform)) || (/freebsd/.test(process.platform))) { this.api = require('./AutoLaunchLinux'); } else { throw new Error('Unsupported platform'); } } AutoLaunch.prototype.enable = function() { return this.api.enable(this.opts); }; AutoLaunch.prototype.disable = function() { return this.api.disable(this.opts.appName, this.opts.mac); }; AutoLaunch.prototype.isEnabled = function() { return this.api.isEnabled(this.opts.appName, this.opts.mac); }; /* Private */ AutoLaunch.prototype.fixMacExecPath = function(path, macOptions) { path = path.replace(/(^.+?[^\/]+?\.app)\/Contents\/(Frameworks\/((\1|[^\/]+?) Helper)\.app\/Contents\/MacOS\/\3|MacOS\/Electron)/, '$1'); if (!macOptions.useLaunchAgent) { path = path.replace(/\.app\/Contents\/MacOS\/[^\/]*$/, '.app'); } return path; }; AutoLaunch.prototype.fixOpts = function() { var tempPath; this.opts.appPath = this.opts.appPath.replace(/\/$/, ''); if (/darwin/.test(process.platform)) { this.opts.appPath = this.fixMacExecPath(this.opts.appPath, this.opts.mac); } if (this.opts.appPath.indexOf('/') !== -1) { tempPath = this.opts.appPath.split('/'); this.opts.appName = tempPath[tempPath.length - 1]; } else if (this.opts.appPath.indexOf('\\') !== -1) { tempPath = this.opts.appPath.split('\\'); this.opts.appName = tempPath[tempPath.length - 1]; this.opts.appName = this.opts.appName.substr(0, this.opts.appName.length - '.exe'.length); } if (/darwin/.test(process.platform)) { if (this.opts.appName.indexOf('.app', this.opts.appName.length - '.app'.length) !== -1) { return this.opts.appName = this.opts.appName.substr(0, this.opts.appName.length - '.app'.length); } } }; return AutoLaunch; })(); { "name": "auto-launch", "version": "5.0.6", "description": "Launch node applications or executables at login (Mac, Windows, and Linux)", "main": "dist/index.js", "engines": { "node": ">=4.0.0" }, "repository": { "type": "git", "url": "https://github.com/4ver/node-auto-launch" }, "author": "Donal Linehan", "license": "MIT", "devDependencies": { "chai": "^3.5.0", "coffee-script": "^1.10.0", "gulp": "^3.9.1", "gulp-coffee": "^2.3.2", "gulp-coffeelint": "^0.6.0", "gulp-coffeelint-threshold": "^1.0.0", "gulp-load-plugins": "^1.2.0", "gulp-mocha": "^3.0.1", "gulp-util": "^3.0.7", "teamwork-coffeelint-rules": "0.0.1" }, "homepage": "https://github.com/4ver/node-auto-launch", "dependencies": { "applescript": "^1.0.0", "mkdirp": "^0.5.1", "path-is-absolute": "^1.0.0", "untildify": "^3.0.2", "winreg": "1.2.4" } }The MIT License (MIT) Copyright (c) 2015 Loopline Systems 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CancellationError = exports.CancellationToken = void 0; const events_1 = require("events"); class CancellationToken extends events_1.EventEmitter { get cancelled() { return this._cancelled || (this._parent != null && this._parent.cancelled); } set parent(value) { this.removeParentCancelHandler(); this._parent = value; this.parentCancelHandler = () => this.cancel(); this._parent.onCancel(this.parentCancelHandler); } // babel cannot compile ... correctly for super calls constructor(parent) { super(); this.parentCancelHandler = null; this._parent = null; this._cancelled = false; if (parent != null) { this.parent = parent; } } cancel() { this._cancelled = true; this.emit("cancel"); } onCancel(handler) { if (this.cancelled) { handler(); } else { this.once("cancel", handler); } } createPromise(callback) { if (this.cancelled) { return Promise.reject(new CancellationError()); } const finallyHandler = () => { if (cancelHandler != null) { try { this.removeListener("cancel", cancelHandler); cancelHandler = null; } catch (_ignore) { // ignore } } }; let cancelHandler = null; return new Promise((resolve, reject) => { let addedCancelHandler = null; cancelHandler = () => { try { if (addedCancelHandler != null) { addedCancelHandler(); addedCancelHandler = null; } } finally { reject(new CancellationError()); } }; if (this.cancelled) { cancelHandler(); return; } this.onCancel(cancelHandler); callback(resolve, reject, (callback) => { addedCancelHandler = callback; }); }) .then(it => { finallyHandler(); return it; }) .catch((e) => { finallyHandler(); throw e; }); } removeParentCancelHandler() { const parent = this._parent; if (parent != null && this.parentCancelHandler != null) { parent.removeListener("cancel", this.parentCancelHandler); this.parentCancelHandler = null; } } dispose() { try { this.removeParentCancelHandler(); } finally { this.removeAllListeners(); this._parent = null; } } } exports.CancellationToken = CancellationToken; class CancellationError extends Error { constructor() { super("cancelled"); } } exports.CancellationError = CancellationError; //# sourceMappingURL=CancellationToken.js.map{"version":3,"file":"CancellationToken.js","sourceRoot":"","sources":["../src/CancellationToken.ts"],"names":[],"mappings":";;;AAAA,mCAAqC;AAErC,MAAa,iBAAkB,SAAQ,qBAAY;IAIjD,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IAC5E,CAAC;IAGD,IAAI,MAAM,CAAC,KAAwB;QACjC,IAAI,CAAC,yBAAyB,EAAE,CAAA;QAEhC,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;QACpB,IAAI,CAAC,mBAAmB,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAA;QAC9C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;IACjD,CAAC;IAED,qDAAqD;IACrD,YAAY,MAA0B;QACpC,KAAK,EAAE,CAAA;QAlBD,wBAAmB,GAAuB,IAAI,CAAA;QAO9C,YAAO,GAA6B,IAAI,CAAA;QAa9C,IAAI,CAAC,UAAU,GAAG,KAAK,CAAA;QACvB,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;YACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACtB,CAAC;IACH,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;QACtB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;IACrB,CAAC;IAEO,QAAQ,CAAC,OAAkB;QACjC,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO,EAAE,CAAA;QACX,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAA;QAC9B,CAAC;IACH,CAAC;IAED,aAAa,CACX,QAAqJ;QAErJ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC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E,CAAA;YAChB,MAAM,CAAC,CAAA;QACT,CAAC,CAAC,CAAA;IACN,CAAC;IAEO,yBAAyB;QAC/B,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAA;QAC3B,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,mBAAmB,IAAI,IAAI,EAAE,CAAC;YACvD,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,mBAAmB,CAAC,CAAA;YACzD,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAA;QACjC,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC;YACH,IAAI,CAAC,yBAAyB,EAAE,CAAA;QAClC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,kBAAkB,EAAE,CAAA;YACzB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;QACrB,CAAC;IACH,CAAC;CACF;AA9GD,8CA8GC;AAED,MAAa,iBAAkB,SAAQ,KAAK;IAC1C;QACE,KAAK,CAAC,WAAW,CAAC,CAAA;IACpB,CAAC;CACF;AAJD,8CAIC","sourcesContent":["import { EventEmitter } from \"events\"\n\nexport class CancellationToken extends EventEmitter {\n private parentCancelHandler: (() => any) | null = null\n\n private _cancelled: boolean\n get cancelled(): boolean {\n return this._cancelled || (this._parent != null && this._parent.cancelled)\n }\n\n private _parent: CancellationToken | null = null\n set parent(value: CancellationToken) {\n this.removeParentCancelHandler()\n\n this._parent = value\n this.parentCancelHandler = () => this.cancel()\n this._parent.onCancel(this.parentCancelHandler)\n }\n\n // babel cannot compile ... correctly for super calls\n constructor(parent?: CancellationToken) {\n super()\n\n this._cancelled = false\n if (parent != null) {\n this.parent = parent\n }\n }\n\n cancel() {\n this._cancelled = true\n this.emit(\"cancel\")\n }\n\n private onCancel(handler: () => any) {\n if (this.cancelled) {\n handler()\n } else {\n this.once(\"cancel\", handler)\n }\n }\n\n createPromise(\n callback: (resolve: (thenableOrResult: R | PromiseLike) => void, reject: (error: Error) => void, onCancel: (callback: () => void) => void) => void\n ): Promise {\n if (this.cancelled) {\n return Promise.reject(new CancellationError())\n }\n\n const finallyHandler = () => {\n if (cancelHandler != null) {\n try {\n this.removeListener(\"cancel\", cancelHandler)\n cancelHandler = null\n } catch (_ignore) {\n // ignore\n }\n }\n }\n\n let cancelHandler: (() => void) | null = null\n return new Promise((resolve, reject) => {\n let addedCancelHandler: (() => void) | null = null\n\n cancelHandler = () => {\n try {\n if (addedCancelHandler != null) {\n addedCancelHandler()\n addedCancelHandler = null\n }\n } finally {\n reject(new CancellationError())\n }\n }\n\n if (this.cancelled) {\n cancelHandler()\n return\n }\n\n this.onCancel(cancelHandler)\n\n callback(resolve, reject, (callback: () => void) => {\n addedCancelHandler = callback\n })\n })\n .then(it => {\n finallyHandler()\n return it\n })\n .catch((e: any) => {\n finallyHandler()\n throw e\n })\n }\n\n private removeParentCancelHandler() {\n const parent = this._parent\n if (parent != null && this.parentCancelHandler != null) {\n parent.removeListener(\"cancel\", this.parentCancelHandler)\n this.parentCancelHandler = null\n }\n }\n\n dispose() {\n try {\n this.removeParentCancelHandler()\n } finally {\n this.removeAllListeners()\n this._parent = null\n }\n }\n}\n\nexport class CancellationError extends Error {\n constructor() {\n super(\"cancelled\")\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MemoLazy = void 0; class MemoLazy { constructor(selector, creator) { this.selector = selector; this.creator = creator; this.selected = undefined; this._value = undefined; } get hasValue() { return this._value !== undefined; } get value() { const selected = this.selector(); if (this._value !== undefined && equals(this.selected, selected)) { // value exists and selected hasn't changed, so return the cached value return this._value; } this.selected = selected; const result = this.creator(selected); this.value = result; return result; } set value(value) { this._value = value; } } exports.MemoLazy = MemoLazy; function equals(firstValue, secondValue) { const isFirstObject = typeof firstValue === "object" && firstValue !== null; const isSecondObject = typeof secondValue === "object" && secondValue !== null; // do a shallow comparison of objects, arrays etc. if (isFirstObject && isSecondObject) { const keys1 = Object.keys(firstValue); const keys2 = Object.keys(secondValue); return keys1.length === keys2.length && keys1.every((key) => equals(firstValue[key], secondValue[key])); } // otherwise just compare the values directly return firstValue === secondValue; } //# sourceMappingURL=MemoLazy.js.map{"version":3,"file":"MemoLazy.js","sourceRoot":"","sources":["../src/MemoLazy.ts"],"names":[],"mappings":";;;AAAA,MAAa,QAAQ;IAInB,YACU,QAAiB,EACjB,OAAoC;QADpC,aAAQ,GAAR,QAAQ,CAAS;QACjB,YAAO,GAAP,OAAO,CAA6B;QALtC,aAAQ,GAAkB,SAAS,CAAA;QACnC,WAAM,GAA2B,SAAS,CAAA;IAK/C,CAAC;IAEJ,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,MAAM,KAAK,SAAS,CAAA;IAClC,CAAC;IAED,IAAI,KAAK;QACP,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAA;QAChC,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC;YACjE,uEAAuE;YACvE,OAAO,IAAI,CAAC,MAAM,CAAA;QACpB,CAAC;QAED,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;QACrC,IAAI,CAAC,KAAK,GAAG,MAAM,CAAA;QAEnB,OAAO,MAAM,CAAA;IACf,CAAC;IAED,IAAI,KAAK,CAAC,KAAiB;QACzB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;CACF;AA9BD,4BA8BC;AAED,SAAS,MAAM,CAAC,UAAe,EAAE,WAAgB;IAC/C,MAAM,aAAa,GAAG,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,KAAK,IAAI,CAAA;IAC3E,MAAM,cAAc,GAAG,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,CAAA;IAE9E,kDAAkD;IAClD,IAAI,aAAa,IAAI,cAAc,EAAE,CAAC;QACpC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;QACrC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;QAEtC,OAAO,KAAK,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IAC9G,CAAC;IAED,6CAA6C;IAC7C,OAAO,UAAU,KAAK,WAAW,CAAA;AACnC,CAAC","sourcesContent":["export class MemoLazy {\n private selected: S | undefined = undefined\n private _value: Promise | undefined = undefined\n\n constructor(\n private selector: () => S,\n private creator: (selected: S) => Promise\n ) {}\n\n get hasValue() {\n return this._value !== undefined\n }\n\n get value(): Promise {\n const selected = this.selector()\n if (this._value !== undefined && equals(this.selected, selected)) {\n // value exists and selected hasn't changed, so return the cached value\n return this._value\n }\n\n this.selected = selected\n const result = this.creator(selected)\n this.value = result\n\n return result\n }\n\n set value(value: Promise) {\n this._value = value\n }\n}\n\nfunction equals(firstValue: any, secondValue: any): boolean {\n const isFirstObject = typeof firstValue === \"object\" && firstValue !== null\n const isSecondObject = typeof secondValue === \"object\" && secondValue !== null\n\n // do a shallow comparison of objects, arrays etc.\n if (isFirstObject && isSecondObject) {\n const keys1 = Object.keys(firstValue)\n const keys2 = Object.keys(secondValue)\n\n return keys1.length === keys2.length && keys1.every((key: any) => equals(firstValue[key], secondValue[key]))\n }\n\n // otherwise just compare the values directly\n return firstValue === secondValue\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProgressCallbackTransform = void 0; const stream_1 = require("stream"); class ProgressCallbackTransform extends stream_1.Transform { constructor(total, cancellationToken, onProgress) { super(); this.total = total; this.cancellationToken = cancellationToken; this.onProgress = onProgress; this.start = Date.now(); this.transferred = 0; this.delta = 0; this.nextUpdate = this.start + 1000; } _transform(chunk, encoding, callback) { if (this.cancellationToken.cancelled) { callback(new Error("cancelled"), null); return; } this.transferred += chunk.length; this.delta += chunk.length; const now = Date.now(); if (now >= this.nextUpdate && this.transferred !== this.total /* will be emitted on _flush */) { this.nextUpdate = now + 1000; this.onProgress({ total: this.total, delta: this.delta, transferred: this.transferred, percent: (this.transferred / this.total) * 100, bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)), }); this.delta = 0; } callback(null, chunk); } _flush(callback) { if (this.cancellationToken.cancelled) { callback(new Error("cancelled")); return; } this.onProgress({ total: this.total, delta: this.delta, transferred: this.total, percent: 100, bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)), }); this.delta = 0; callback(null); } } exports.ProgressCallbackTransform = ProgressCallbackTransform; //# sourceMappingURL=ProgressCallbackTransform.js.map{"version":3,"file":"ProgressCallbackTransform.js","sourceRoot":"","sources":["../src/ProgressCallbackTransform.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAWlC,MAAa,yBAA0B,SAAQ,kBAAS;IAOtD,YACmB,KAAa,EACb,iBAAoC,EACpC,UAAuC;QAExD,KAAK,EAAE,CAAA;QAJU,UAAK,GAAL,KAAK,CAAQ;QACb,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,eAAU,GAAV,UAAU,CAA6B;QATlD,UAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QAClB,gBAAW,GAAG,CAAC,CAAA;QACf,UAAK,GAAG,CAAC,CAAA;QAET,eAAU,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAA;IAQtC,CAAC;IAED,UAAU,CAAC,KAAU,EAAE,QAAgB,EAAE,QAAa;QACpD,IAAI,IAAI,CAAC,iBAAiB,CAAC,SAAS,EAAE,CAAC;YACrC,QAAQ,CAAC,IAAI,KAAK,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC,CAAA;YACtC,OAAM;QACR,CAAC;QAED,IA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AAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;SAClF,CAAC,CAAA;QACF,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;QAEd,QAAQ,CAAC,IAAI,CAAC,CAAA;IAChB,CAAC;CACF;AA1DD,8DA0DC","sourcesContent":["import { Transform } from \"stream\"\nimport { CancellationToken } from \"./CancellationToken\"\n\nexport interface ProgressInfo {\n total: number\n delta: number\n transferred: number\n percent: number\n bytesPerSecond: number\n}\n\nexport class ProgressCallbackTransform extends Transform {\n private start = Date.now()\n private transferred = 0\n private delta = 0\n\n private nextUpdate = this.start + 1000\n\n constructor(\n private readonly total: number,\n private readonly cancellationToken: CancellationToken,\n private readonly onProgress: (info: ProgressInfo) => any\n ) {\n super()\n }\n\n _transform(chunk: any, encoding: string, callback: any) {\n if (this.cancellationToken.cancelled) {\n callback(new Error(\"cancelled\"), null)\n return\n }\n\n this.transferred += chunk.length\n this.delta += chunk.length\n\n const now = Date.now()\n if (now >= this.nextUpdate && this.transferred !== this.total /* will be emitted on _flush */) {\n this.nextUpdate = now + 1000\n\n this.onProgress({\n total: this.total,\n delta: this.delta,\n transferred: this.transferred,\n percent: (this.transferred / this.total) * 100,\n bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)),\n })\n this.delta = 0\n }\n\n callback(null, chunk)\n }\n\n _flush(callback: any): void {\n if (this.cancellationToken.cancelled) {\n callback(new Error(\"cancelled\"))\n return\n }\n\n this.onProgress({\n total: this.total,\n delta: this.delta,\n transferred: this.total,\n percent: 100,\n bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)),\n })\n this.delta = 0\n\n callback(null)\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=blockMapApi.js.map{"version":3,"file":"blockMapApi.js","sourceRoot":"","sources":["../src/blockMapApi.ts"],"names":[],"mappings":"","sourcesContent":["export interface FileChunks {\n checksums: Array\n sizes: Array\n}\n\nexport interface BlockMap {\n version: \"1\" | \"2\"\n files: Array\n}\n\nexport interface BlockMapFile extends FileChunks {\n name: string\n offset: number\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.newError = newError; function newError(message, code) { const error = new Error(message); error.code = code; return error; } //# sourceMappingURL=error.js.map{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;AAAA,4BAIC;AAJD,SAAgB,QAAQ,CAAC,OAAe,EAAE,IAAY;IACpD,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,CAC/B;IAAC,KAA+B,CAAC,IAAI,GAAG,IAAI,CAAA;IAC7C,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["export function newError(message: string, code: string) {\n const error = new Error(message)\n ;(error as NodeJS.ErrnoException).code = code\n return error\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DigestTransform = exports.HttpExecutor = exports.HttpError = void 0; exports.createHttpError = createHttpError; exports.parseJson = parseJson; exports.configureRequestOptionsFromUrl = configureRequestOptionsFromUrl; exports.configureRequestUrl = configureRequestUrl; exports.safeGetHeader = safeGetHeader; exports.configureRequestOptions = configureRequestOptions; exports.safeStringifyJson = safeStringifyJson; const crypto_1 = require("crypto"); const debug_1 = require("debug"); const fs_1 = require("fs"); const stream_1 = require("stream"); const url_1 = require("url"); const CancellationToken_1 = require("./CancellationToken"); const error_1 = require("./error"); const ProgressCallbackTransform_1 = require("./ProgressCallbackTransform"); const debug = (0, debug_1.default)("electron-builder"); function createHttpError(response, description = null) { return new HttpError(response.statusCode || -1, `${response.statusCode} ${response.statusMessage}` + (description == null ? "" : "\n" + JSON.stringify(description, null, " ")) + "\nHeaders: " + safeStringifyJson(response.headers), description); } const HTTP_STATUS_CODES = new Map([ [429, "Too many requests"], [400, "Bad request"], [403, "Forbidden"], [404, "Not found"], [405, "Method not allowed"], [406, "Not acceptable"], [408, "Request timeout"], [413, "Request entity too large"], [500, "Internal server error"], [502, "Bad gateway"], [503, "Service unavailable"], [504, "Gateway timeout"], [505, "HTTP version not supported"], ]); class HttpError extends Error { constructor(statusCode, message = `HTTP error: ${HTTP_STATUS_CODES.get(statusCode) || statusCode}`, description = null) { super(message); this.statusCode = statusCode; this.description = description; this.name = "HttpError"; this.code = `HTTP_ERROR_${statusCode}`; } isServerError() { return this.statusCode >= 500 && this.statusCode <= 599; } } exports.HttpError = HttpError; function parseJson(result) { return result.then(it => (it == null || it.length === 0 ? null : JSON.parse(it))); } class HttpExecutor { constructor() { this.maxRedirects = 10; } request(options, cancellationToken = new CancellationToken_1.CancellationToken(), data) { configureRequestOptions(options); const json = data == null ? undefined : JSON.stringify(data); const encodedData = json ? Buffer.from(json) : undefined; if (encodedData != null) { debug(json); const { headers, ...opts } = options; options = { method: "post", headers: { "Content-Type": "application/json", "Content-Length": encodedData.length, ...headers, }, ...opts, }; } return this.doApiRequest(options, cancellationToken, it => it.end(encodedData)); } doApiRequest(options, cancellationToken, requestProcessor, redirectCount = 0) { if (debug.enabled) { const { headers: _headers, auth: _auth, ...safeOptions } = options; debug(`Request: ${safeStringifyJson(safeOptions)}`); } return cancellationToken.createPromise((resolve, reject, onCancel) => { const request = this.createRequest(options, (response) => { try { this.handleResponse(response, options, cancellationToken, resolve, reject, redirectCount, requestProcessor); } catch (e) { reject(e); } }); this.addErrorAndTimeoutHandlers(request, reject, options.timeout); this.addRedirectHandlers(request, options, reject, redirectCount, options => { this.doApiRequest(options, cancellationToken, requestProcessor, redirectCount).then(resolve).catch(reject); }); requestProcessor(request, reject); onCancel(() => request.abort()); }); } // noinspection JSUnusedLocalSymbols // eslint-disable-next-line addRedirectHandlers(request, options, reject, redirectCount, handler) { // not required for NodeJS } addErrorAndTimeoutHandlers(request, reject, timeout = 60 * 1000) { this.addTimeOutHandler(request, reject, timeout); request.on("error", reject); request.on("aborted", () => { reject(new Error("Request has been aborted by the server")); }); } handleResponse(response, options, cancellationToken, resolve, reject, redirectCount, requestProcessor) { var _a; if (debug.enabled) { const { headers: _headers, auth: _auth, ...safeOptions } = options; debug(`Response: ${response.statusCode} ${response.statusMessage}, request options: ${safeStringifyJson(safeOptions)}`); } // we handle any other >= 400 error on request end (read detailed message in the response body) if (response.statusCode === 404) { // error is clear, we don't need to read detailed error description reject(createHttpError(response, `method: ${options.method || "GET"} url: ${options.protocol || "https:"}//${options.hostname}${options.port ? `:${options.port}` : ""}${options.path} Please double check that your authentication token is correct. Due to security reasons, actual status maybe not reported, but 404. `)); return; } else if (response.statusCode === 204) { // on DELETE request resolve(); return; } const code = (_a = response.statusCode) !== null && _a !== void 0 ? _a : 0; const shouldRedirect = code >= 300 && code < 400; const redirectUrl = safeGetHeader(response, "location"); if (shouldRedirect && redirectUrl != null) { if (redirectCount > this.maxRedirects) { reject(this.createMaxRedirectError()); return; } this.doApiRequest(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options), cancellationToken, requestProcessor, redirectCount).then(resolve).catch(reject); return; } response.setEncoding("utf8"); let data = ""; response.on("error", reject); response.on("data", (chunk) => (data += chunk)); response.on("end", () => { try { if (response.statusCode != null && response.statusCode >= 400) { const contentType = safeGetHeader(response, "content-type"); const isJson = contentType != null && (Array.isArray(contentType) ? contentType.find(it => it.includes("json")) != null : contentType.includes("json")); reject(createHttpError(response, `method: ${options.method || "GET"} url: ${options.protocol || "https:"}//${options.hostname}${options.port ? `:${options.port}` : ""}${options.path} Data: ${isJson ? JSON.stringify(JSON.parse(data)) : data} `)); } else { resolve(data.length === 0 ? null : data); } } catch (e) { reject(e); } }); } async downloadToBuffer(url, options) { return await options.cancellationToken.createPromise((resolve, reject, onCancel) => { const responseChunks = []; const requestOptions = { headers: options.headers || undefined, // because PrivateGitHubProvider requires HttpExecutor.prepareRedirectUrlOptions logic, so, we need to redirect manually redirect: "manual", }; configureRequestUrl(url, requestOptions); configureRequestOptions(requestOptions); this.doDownload(requestOptions, { destination: null, options, onCancel, callback: error => { if (error == null) { resolve(Buffer.concat(responseChunks)); } else { reject(error); } }, responseHandler: (response, callback) => { let receivedLength = 0; response.on("data", (chunk) => { receivedLength += chunk.length; if (receivedLength > 524288000) { callback(new Error("Maximum allowed size is 500 MB")); return; } responseChunks.push(chunk); }); response.on("end", () => { callback(null); }); }, }, 0); }); } doDownload(requestOptions, options, redirectCount) { const request = this.createRequest(requestOptions, (response) => { if (response.statusCode >= 400) { options.callback(new Error(`Cannot download "${requestOptions.protocol || "https:"}//${requestOptions.hostname}${requestOptions.path}", status ${response.statusCode}: ${response.statusMessage}`)); return; } // It is possible for the response stream to fail, e.g. when a network is lost while // response stream is in progress. Stop waiting and reject so consumer can catch the error. response.on("error", options.callback); // this code not relevant for Electron (redirect event instead handled) const redirectUrl = safeGetHeader(response, "location"); if (redirectUrl != null) { if (redirectCount < this.maxRedirects) { this.doDownload(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, requestOptions), options, redirectCount++); } else { options.callback(this.createMaxRedirectError()); } return; } if (options.responseHandler == null) { configurePipes(options, response); } else { options.responseHandler(response, options.callback); } }); this.addErrorAndTimeoutHandlers(request, options.callback, requestOptions.timeout); this.addRedirectHandlers(request, requestOptions, options.callback, redirectCount, requestOptions => { this.doDownload(requestOptions, options, redirectCount++); }); request.end(); } createMaxRedirectError() { return new Error(`Too many redirects (> ${this.maxRedirects})`); } addTimeOutHandler(request, callback, timeout) { request.on("socket", (socket) => { socket.setTimeout(timeout, () => { request.abort(); callback(new Error("Request timed out")); }); }); } static prepareRedirectUrlOptions(redirectUrl, options) { const newOptions = configureRequestOptionsFromUrl(redirectUrl, { ...options }); const headers = newOptions.headers; if (headers === null || headers === void 0 ? void 0 : headers.authorization) { // Parse original and redirect URLs to compare origins const originalUrl = HttpExecutor.reconstructOriginalUrl(options); const parsedRedirectUrl = parseUrl(redirectUrl, options); // Strip authorization header on cross-origin redirects (different protocol, hostname, or port) if (HttpExecutor.isCrossOriginRedirect(originalUrl, parsedRedirectUrl)) { if (debug.enabled) { debug(`Given the cross-origin redirect (from ${originalUrl.host} to ${parsedRedirectUrl.host}), the Authorization header will be stripped out.`); } delete headers.authorization; } } return newOptions; } static reconstructOriginalUrl(options) { const protocol = options.protocol || "https:"; if (!options.hostname) { throw new Error("Missing hostname in request options"); } const hostname = options.hostname; const port = options.port ? `:${options.port}` : ""; const path = options.path || "/"; return new url_1.URL(`${protocol}//${hostname}${port}${path}`); } static isCrossOriginRedirect(originalUrl, redirectUrl) { // Case-insensitive hostname comparison if (originalUrl.hostname.toLowerCase() !== redirectUrl.hostname.toLowerCase()) { return true; } // Special case: allow http -> https redirect on same host with standard ports // This matches the behavior of Python requests library for backward compatibility // url.port returns an empty string if the port is omitted // or explicitly set to the default port for a given protocol. if (originalUrl.protocol === "http:" && // This can be replaced with `!originalUrl.port`, but for the sake of clarity. ["80", ""].includes(originalUrl.port) && redirectUrl.protocol === "https:" && // This can be replaced with `!redirectUrl.port`, but for the sake of clarity. ["443", ""].includes(redirectUrl.port)) { return false; } // According to RFC 7235, a change in protocol or port constitutes a cross-origin request. // Forwarding authentication headers to a different origin can be a security risk. // For example, https://example.com:443 and http://example.com:80 are different origins. // We only make an exception for HTTP -> HTTPS upgrades on standard ports for backward compatibility. // Strip auth on any other protocol change if (originalUrl.protocol !== redirectUrl.protocol) { return true; } // Strip auth on port change (accounting for default ports) const originalPort = originalUrl.port; const redirectPort = redirectUrl.port; return originalPort !== redirectPort; } static async retryOnServerError(task, maxRetries = 3) { for (let attemptNumber = 0;; attemptNumber++) { try { return await task(); } catch (e) { if (attemptNumber < maxRetries && ((e instanceof HttpError && e.isServerError()) || e.code === "EPIPE")) { await new Promise(r => setTimeout(r, 1000 * (attemptNumber + 1))); continue; } throw e; } } } } exports.HttpExecutor = HttpExecutor; function parseUrl(url, options) { try { // Would throw exception if url is not absolute return new url_1.URL(url); } catch { // Relative URL - construct base URL from original options const hostname = options.hostname; const protocol = options.protocol || "https:"; const port = options.port ? `:${options.port}` : ""; const baseUrl = `${protocol}//${hostname}${port}`; return new url_1.URL(url, baseUrl); } } function configureRequestOptionsFromUrl(url, options) { const result = configureRequestOptions(options); const parsedUrl = parseUrl(url, options); configureRequestUrl(parsedUrl, result); return result; } function configureRequestUrl(url, options) { options.protocol = url.protocol; options.hostname = url.hostname; if (url.port) { options.port = url.port; } else if (options.port) { delete options.port; } options.path = url.pathname + url.search; } class DigestTransform extends stream_1.Transform { // noinspection JSUnusedGlobalSymbols get actual() { return this._actual; } constructor(expected, algorithm = "sha512", encoding = "base64") { super(); this.expected = expected; this.algorithm = algorithm; this.encoding = encoding; this._actual = null; this.isValidateOnEnd = true; this.digester = (0, crypto_1.createHash)(algorithm); } // noinspection JSUnusedGlobalSymbols _transform(chunk, encoding, callback) { this.digester.update(chunk); callback(null, chunk); } // noinspection JSUnusedGlobalSymbols _flush(callback) { this._actual = this.digester.digest(this.encoding); if (this.isValidateOnEnd) { try { this.validate(); } catch (e) { callback(e); return; } } callback(null); } validate() { if (this._actual == null) { throw (0, error_1.newError)("Not finished yet", "ERR_STREAM_NOT_FINISHED"); } if (this._actual !== this.expected) { throw (0, error_1.newError)(`${this.algorithm} checksum mismatch, expected ${this.expected}, got ${this._actual}`, "ERR_CHECKSUM_MISMATCH"); } return null; } } exports.DigestTransform = DigestTransform; function checkSha2(sha2Header, sha2, callback) { if (sha2Header != null && sha2 != null && sha2Header !== sha2) { callback(new Error(`checksum mismatch: expected ${sha2} but got ${sha2Header} (X-Checksum-Sha2 header)`)); return false; } return true; } function safeGetHeader(response, headerKey) { const value = response.headers[headerKey]; if (value == null) { return null; } else if (Array.isArray(value)) { // electron API return value.length === 0 ? null : value[value.length - 1]; } else { return value; } } function configurePipes(options, response) { if (!checkSha2(safeGetHeader(response, "X-Checksum-Sha2"), options.options.sha2, options.callback)) { return; } const streams = []; if (options.options.onProgress != null) { const contentLength = safeGetHeader(response, "content-length"); if (contentLength != null) { streams.push(new ProgressCallbackTransform_1.ProgressCallbackTransform(parseInt(contentLength, 10), options.options.cancellationToken, options.options.onProgress)); } } const sha512 = options.options.sha512; if (sha512 != null) { streams.push(new DigestTransform(sha512, "sha512", sha512.length === 128 && !sha512.includes("+") && !sha512.includes("Z") && !sha512.includes("=") ? "hex" : "base64")); } else if (options.options.sha2 != null) { streams.push(new DigestTransform(options.options.sha2, "sha256", "hex")); } const fileOut = (0, fs_1.createWriteStream)(options.destination); streams.push(fileOut); let lastStream = response; for (const stream of streams) { stream.on("error", (error) => { fileOut.close(); if (!options.options.cancellationToken.cancelled) { options.callback(error); } }); lastStream = lastStream.pipe(stream); } fileOut.on("finish", () => { ; fileOut.close(options.callback); }); } function configureRequestOptions(options, token, method) { if (method != null) { options.method = method; } options.headers = { ...options.headers }; const headers = options.headers; if (token != null) { ; headers.authorization = token.startsWith("Basic") || token.startsWith("Bearer") ? token : `token ${token}`; } if (headers["User-Agent"] == null) { headers["User-Agent"] = "electron-builder"; } if (method == null || method === "GET" || headers["Cache-Control"] == null) { headers["Cache-Control"] = "no-cache"; } // do not specify for node (in any case we use https module) if (options.protocol == null && process.versions.electron != null) { options.protocol = "https:"; } return options; } function safeStringifyJson(data, skippedNames) { return JSON.stringify(data, (name, value) => { if (name.endsWith("Authorization") || name.endsWith("authorization") || name.endsWith("Password") || name.endsWith("PASSWORD") || name.endsWith("Token") || name.includes("password") || name.includes("token") || (skippedNames != null && skippedNames.has(name))) { return ""; } return value; }, 2); } //# sourceMappingURL=httpExecutor.js.map{"version":3,"file":"httpExecutor.js","sourceRoot":"","sources":["../src/httpExecutor.ts"],"names":[],"mappings":";;;AA6BA,0CASC;AAmCD,8BAEC;AA8VD,wEAKC;AAED,kDASC;AAmED,sCAUC;AAyCD,0DAwBC;AAED,8CAoBC;AA7lBD,mCAA+D;AAC/D,iCAA0B;AAC1B,2BAAsC;AAGtC,mCAAkC;AAClC,6BAAyB;AAEzB,2DAAuD;AACvD,mCAAkC;AAClC,2EAAqF;AAErF,MAAM,KAAK,GAAG,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;AAiBxC,SAAgB,eAAe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,MAAM,KAAK,KAAK,IAAI,OAAO,CAAC,eAAe,CAAC,IAAI,IAAI,EAAE,CAAC;QAC3E,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,CAAA;IACvC,CAAC;IAED,4DAA4D;IAC5D,IAAI,OAAO,CAAC,QAAQ,IAAI,IAAI,IAAK,OAAO,CAAC,QAAgB,CAAC,QAAQ,IAAI,IAAI,EAAE,CAAC;QAC3E,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC7B,CAAC;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED,SAAgB,iBAAiB,CAAC,IAAS,EAAE,YAA0B;IACrE,OAAO,IAAI,CAAC,SAAS,CACnB,IAAI,EACJ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QACd,IACE,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC;YAC9B,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC;YAC9B,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;YACzB,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;YACzB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;YACtB,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;YACzB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;YACtB,CAAC,YAAY,IAAI,IAAI,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,EAChD,CAAC;YACD,OAAO,2BAA2B,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC,EACD,CAAC,CACF,CAAA;AACH,CAAC","sourcesContent":["import { BinaryToTextEncoding, createHash, Hash } from \"crypto\"\nimport _debug from \"debug\"\nimport { createWriteStream } from \"fs\"\nimport { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { Socket } from \"net\"\nimport { Transform } from \"stream\"\nimport { URL } from \"url\"\nimport { Nullish } from \".\"\nimport { CancellationToken } from \"./CancellationToken\"\nimport { newError } from \"./error\"\nimport { ProgressCallbackTransform, ProgressInfo } from \"./ProgressCallbackTransform\"\n\nconst debug = _debug(\"electron-builder\")\n\nexport interface RequestHeaders extends OutgoingHttpHeaders {\n [key: string]: OutgoingHttpHeader | undefined\n}\n\nexport interface DownloadOptions {\n readonly headers?: OutgoingHttpHeaders | null\n readonly sha2?: string | null\n readonly sha512?: string | null\n\n readonly cancellationToken: CancellationToken\n\n // noinspection JSUnusedLocalSymbols\n onProgress?: (progress: ProgressInfo) => void\n}\n\nexport function createHttpError(response: IncomingMessage, description: any | null = null) {\n return new HttpError(\n response.statusCode || -1,\n `${response.statusCode} ${response.statusMessage}` +\n (description == null ? \"\" : \"\\n\" + JSON.stringify(description, null, \" \")) +\n \"\\nHeaders: \" +\n safeStringifyJson(response.headers),\n description\n )\n}\n\nconst HTTP_STATUS_CODES = new Map([\n [429, \"Too many requests\"],\n [400, \"Bad request\"],\n [403, \"Forbidden\"],\n [404, \"Not found\"],\n [405, \"Method not allowed\"],\n [406, \"Not acceptable\"],\n [408, \"Request timeout\"],\n [413, \"Request entity too large\"],\n [500, \"Internal server error\"],\n [502, \"Bad gateway\"],\n [503, \"Service unavailable\"],\n [504, \"Gateway timeout\"],\n [505, \"HTTP version not supported\"],\n])\n\nexport class HttpError extends Error {\n constructor(\n readonly statusCode: number,\n message = `HTTP error: ${HTTP_STATUS_CODES.get(statusCode) || statusCode}`,\n readonly description: any | null = null\n ) {\n super(message)\n\n this.name = \"HttpError\"\n ;(this as NodeJS.ErrnoException).code = `HTTP_ERROR_${statusCode}`\n }\n\n isServerError() {\n return this.statusCode >= 500 && this.statusCode <= 599\n }\n}\n\nexport function parseJson(result: Promise) {\n return result.then(it => (it == null || it.length === 0 ? null : JSON.parse(it)))\n}\n\ninterface Request {\n abort: () => void\n end: (data?: Buffer) => void\n}\nexport abstract class HttpExecutor {\n protected readonly maxRedirects = 10\n\n request(options: RequestOptions, cancellationToken: CancellationToken = new CancellationToken(), data?: { [name: string]: any } | null): Promise {\n configureRequestOptions(options)\n const json = data == null ? undefined : JSON.stringify(data)\n const encodedData = json ? Buffer.from(json) : undefined\n if (encodedData != null) {\n debug(json!)\n const { headers, ...opts } = options\n options = {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": encodedData.length,\n ...headers,\n },\n ...opts,\n }\n }\n return this.doApiRequest(options, cancellationToken, it => it.end(encodedData))\n }\n\n doApiRequest(\n options: RequestOptions,\n cancellationToken: CancellationToken,\n requestProcessor: (request: T, reject: (error: Error) => void) => void,\n redirectCount = 0\n ): Promise {\n if (debug.enabled) {\n const { headers: _headers, auth: _auth, ...safeOptions } = options as any\n debug(`Request: ${safeStringifyJson(safeOptions)}`)\n }\n\n return cancellationToken.createPromise((resolve, reject, onCancel) => {\n const request = this.createRequest(options, (response: any) => {\n try {\n this.handleResponse(response, options, cancellationToken, resolve, reject, redirectCount, requestProcessor)\n } catch (e: any) {\n reject(e)\n }\n })\n this.addErrorAndTimeoutHandlers(request, reject, options.timeout)\n this.addRedirectHandlers(request, options, reject, redirectCount, options => {\n this.doApiRequest(options, cancellationToken, requestProcessor, redirectCount).then(resolve).catch(reject)\n })\n requestProcessor(request, reject)\n onCancel(() => request.abort())\n })\n }\n\n // noinspection JSUnusedLocalSymbols\n // eslint-disable-next-line\n protected addRedirectHandlers(request: any, options: RequestOptions, reject: (error: Error) => void, redirectCount: number, handler: (options: RequestOptions) => void) {\n // not required for NodeJS\n }\n\n addErrorAndTimeoutHandlers(request: any, reject: (error: Error) => void, timeout = 60 * 1000) {\n this.addTimeOutHandler(request, reject, timeout)\n request.on(\"error\", reject)\n request.on(\"aborted\", () => {\n reject(new Error(\"Request has been aborted by the server\"))\n })\n }\n\n private handleResponse(\n response: IncomingMessage,\n options: RequestOptions,\n cancellationToken: CancellationToken,\n resolve: (data?: any) => void,\n reject: (error: Error) => void,\n redirectCount: number,\n requestProcessor: (request: T, reject: (error: Error) => void) => void\n ) {\n if (debug.enabled) {\n const { headers: _headers, auth: _auth, ...safeOptions } = options as any\n debug(`Response: ${response.statusCode} ${response.statusMessage}, request options: ${safeStringifyJson(safeOptions)}`)\n }\n\n // we handle any other >= 400 error on request end (read detailed message in the response body)\n if (response.statusCode === 404) {\n // error is clear, we don't need to read detailed error description\n reject(\n createHttpError(\n response,\n `method: ${options.method || \"GET\"} url: ${options.protocol || \"https:\"}//${options.hostname}${options.port ? `:${options.port}` : \"\"}${options.path}\n\nPlease double check that your authentication token is correct. Due to security reasons, actual status maybe not reported, but 404.\n`\n )\n )\n return\n } else if (response.statusCode === 204) {\n // on DELETE request\n resolve()\n return\n }\n\n const code = response.statusCode ?? 0\n const shouldRedirect = code >= 300 && code < 400\n const redirectUrl = safeGetHeader(response, \"location\")\n if (shouldRedirect && redirectUrl != null) {\n if (redirectCount > this.maxRedirects) {\n reject(this.createMaxRedirectError())\n return\n }\n\n this.doApiRequest(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options), cancellationToken, requestProcessor, redirectCount).then(resolve).catch(reject)\n return\n }\n\n response.setEncoding(\"utf8\")\n\n let data = \"\"\n response.on(\"error\", reject)\n response.on(\"data\", (chunk: string) => (data += chunk))\n response.on(\"end\", () => {\n try {\n if (response.statusCode != null && response.statusCode >= 400) {\n const contentType = safeGetHeader(response, \"content-type\")\n const isJson = contentType != null && (Array.isArray(contentType) ? contentType.find(it => it.includes(\"json\")) != null : contentType.includes(\"json\"))\n reject(\n createHttpError(\n response,\n `method: ${options.method || \"GET\"} url: ${options.protocol || \"https:\"}//${options.hostname}${options.port ? `:${options.port}` : \"\"}${options.path}\n\n Data:\n ${isJson ? JSON.stringify(JSON.parse(data)) : data}\n `\n )\n )\n } else {\n resolve(data.length === 0 ? null : data)\n }\n } catch (e: any) {\n reject(e)\n }\n })\n }\n\n // noinspection JSUnusedLocalSymbols\n abstract createRequest(options: RequestOptions, callback: (response: any) => void): T\n\n async downloadToBuffer(url: URL, options: DownloadOptions): Promise {\n return await options.cancellationToken.createPromise((resolve, reject, onCancel) => {\n const responseChunks: Buffer[] = []\n const requestOptions = {\n headers: options.headers || undefined,\n // because PrivateGitHubProvider requires HttpExecutor.prepareRedirectUrlOptions logic, so, we need to redirect manually\n redirect: \"manual\",\n }\n configureRequestUrl(url, requestOptions)\n configureRequestOptions(requestOptions)\n this.doDownload(\n requestOptions,\n {\n destination: null,\n options,\n onCancel,\n callback: error => {\n if (error == null) {\n resolve(Buffer.concat(responseChunks))\n } else {\n reject(error)\n }\n },\n responseHandler: (response, callback) => {\n let receivedLength = 0\n response.on(\"data\", (chunk: Buffer) => {\n receivedLength += chunk.length\n if (receivedLength > 524288000) {\n callback(new Error(\"Maximum allowed size is 500 MB\"))\n return\n }\n responseChunks.push(chunk)\n })\n response.on(\"end\", () => {\n callback(null)\n })\n },\n },\n 0\n )\n })\n }\n\n protected doDownload(requestOptions: RequestOptions, options: DownloadCallOptions, redirectCount: number) {\n const request = this.createRequest(requestOptions, (response: IncomingMessage) => {\n if (response.statusCode! >= 400) {\n options.callback(\n new Error(\n `Cannot download \"${requestOptions.protocol || \"https:\"}//${requestOptions.hostname}${requestOptions.path}\", status ${response.statusCode}: ${response.statusMessage}`\n )\n )\n return\n }\n\n // It is possible for the response stream to fail, e.g. when a network is lost while\n // response stream is in progress. Stop waiting and reject so consumer can catch the error.\n response.on(\"error\", options.callback)\n\n // this code not relevant for Electron (redirect event instead handled)\n const redirectUrl = safeGetHeader(response, \"location\")\n if (redirectUrl != null) {\n if (redirectCount < this.maxRedirects) {\n this.doDownload(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, requestOptions), options, redirectCount++)\n } else {\n options.callback(this.createMaxRedirectError())\n }\n return\n }\n\n if (options.responseHandler == null) {\n configurePipes(options, response)\n } else {\n options.responseHandler(response, options.callback)\n }\n })\n this.addErrorAndTimeoutHandlers(request, options.callback, requestOptions.timeout)\n this.addRedirectHandlers(request, requestOptions, options.callback, redirectCount, requestOptions => {\n this.doDownload(requestOptions, options, redirectCount++)\n })\n request.end()\n }\n\n protected createMaxRedirectError() {\n return new Error(`Too many redirects (> ${this.maxRedirects})`)\n }\n\n private addTimeOutHandler(request: any, callback: (error: Error) => void, timeout: number) {\n request.on(\"socket\", (socket: Socket) => {\n socket.setTimeout(timeout, () => {\n request.abort()\n callback(new Error(\"Request timed out\"))\n })\n })\n }\n\n static prepareRedirectUrlOptions(redirectUrl: string, options: RequestOptions): RequestOptions {\n const newOptions = configureRequestOptionsFromUrl(redirectUrl, { ...options })\n const headers = newOptions.headers\n if (headers?.authorization) {\n // Parse original and redirect URLs to compare origins\n const originalUrl = HttpExecutor.reconstructOriginalUrl(options)\n const parsedRedirectUrl = parseUrl(redirectUrl, options)\n\n // Strip authorization header on cross-origin redirects (different protocol, hostname, or port)\n if (HttpExecutor.isCrossOriginRedirect(originalUrl, parsedRedirectUrl)) {\n if (debug.enabled) {\n debug(`Given the cross-origin redirect (from ${originalUrl.host} to ${parsedRedirectUrl.host}), the Authorization header will be stripped out.`)\n }\n delete headers.authorization\n }\n }\n return newOptions\n }\n\n private static reconstructOriginalUrl(options: RequestOptions): URL {\n const protocol = options.protocol || \"https:\"\n if (!options.hostname) {\n throw new Error(\"Missing hostname in request options\")\n }\n const hostname = options.hostname\n const port = options.port ? `:${options.port}` : \"\"\n const path = options.path || \"/\"\n return new URL(`${protocol}//${hostname}${port}${path}`)\n }\n\n private static isCrossOriginRedirect(originalUrl: URL, redirectUrl: URL): boolean {\n // Case-insensitive hostname comparison\n if (originalUrl.hostname.toLowerCase() !== redirectUrl.hostname.toLowerCase()) {\n return true\n }\n\n // Special case: allow http -> https redirect on same host with standard ports\n // This matches the behavior of Python requests library for backward compatibility\n // url.port returns an empty string if the port is omitted\n // or explicitly set to the default port for a given protocol.\n if (\n originalUrl.protocol === \"http:\" &&\n // This can be replaced with `!originalUrl.port`, but for the sake of clarity.\n [\"80\", \"\"].includes(originalUrl.port) &&\n redirectUrl.protocol === \"https:\" &&\n // This can be replaced with `!redirectUrl.port`, but for the sake of clarity.\n [\"443\", \"\"].includes(redirectUrl.port)\n ) {\n return false\n }\n\n // According to RFC 7235, a change in protocol or port constitutes a cross-origin request.\n // Forwarding authentication headers to a different origin can be a security risk.\n // For example, https://example.com:443 and http://example.com:80 are different origins.\n // We only make an exception for HTTP -> HTTPS upgrades on standard ports for backward compatibility.\n\n // Strip auth on any other protocol change\n if (originalUrl.protocol !== redirectUrl.protocol) {\n return true\n }\n\n // Strip auth on port change (accounting for default ports)\n const originalPort = originalUrl.port\n const redirectPort = redirectUrl.port\n return originalPort !== redirectPort\n }\n\n static async retryOnServerError(task: () => Promise, maxRetries = 3): Promise {\n for (let attemptNumber = 0; ; attemptNumber++) {\n try {\n return await task()\n } catch (e: any) {\n if (attemptNumber < maxRetries && ((e instanceof HttpError && e.isServerError()) || e.code === \"EPIPE\")) {\n await new Promise(r => setTimeout(r, 1000 * (attemptNumber + 1)))\n continue\n }\n throw e\n }\n }\n }\n}\n\nexport interface DownloadCallOptions {\n responseHandler: ((response: IncomingMessage, callback: (error: Error | null) => void) => void) | null\n onCancel: (callback: () => void) => void\n callback: (error: Error | null) => void\n\n options: DownloadOptions\n\n destination: string | null\n}\n\nfunction parseUrl(url: string, options: RequestOptions): URL {\n try {\n // Would throw exception if url is not absolute\n return new URL(url)\n } catch {\n // Relative URL - construct base URL from original options\n const hostname = options.hostname\n const protocol = options.protocol || \"https:\"\n const port = options.port ? `:${options.port}` : \"\"\n const baseUrl = `${protocol}//${hostname}${port}`\n return new URL(url, baseUrl)\n }\n}\n\nexport function configureRequestOptionsFromUrl(url: string, options: RequestOptions) {\n const result = configureRequestOptions(options)\n const parsedUrl = parseUrl(url, options)\n configureRequestUrl(parsedUrl, result)\n return result\n}\n\nexport function configureRequestUrl(url: URL, options: RequestOptions): void {\n options.protocol = url.protocol\n options.hostname = url.hostname\n if (url.port) {\n options.port = url.port\n } else if (options.port) {\n delete options.port\n }\n options.path = url.pathname + url.search\n}\n\nexport class DigestTransform extends Transform {\n private readonly digester: Hash\n\n private _actual: string | null = null\n\n // noinspection JSUnusedGlobalSymbols\n get actual() {\n return this._actual\n }\n\n isValidateOnEnd = true\n\n constructor(\n readonly expected: string,\n private readonly algorithm: string = \"sha512\",\n private readonly encoding: BinaryToTextEncoding = \"base64\"\n ) {\n super()\n\n this.digester = createHash(algorithm)\n }\n\n // noinspection JSUnusedGlobalSymbols\n _transform(chunk: Buffer, encoding: string, callback: any) {\n this.digester.update(chunk)\n callback(null, chunk)\n }\n\n // noinspection JSUnusedGlobalSymbols\n _flush(callback: any): void {\n this._actual = this.digester.digest(this.encoding)\n\n if (this.isValidateOnEnd) {\n try {\n this.validate()\n } catch (e: any) {\n callback(e)\n return\n }\n }\n\n callback(null)\n }\n\n validate() {\n if (this._actual == null) {\n throw newError(\"Not finished yet\", \"ERR_STREAM_NOT_FINISHED\")\n }\n\n if (this._actual !== this.expected) {\n throw newError(`${this.algorithm} checksum mismatch, expected ${this.expected}, got ${this._actual}`, \"ERR_CHECKSUM_MISMATCH\")\n }\n\n return null\n }\n}\n\nfunction checkSha2(sha2Header: string | Nullish, sha2: string | Nullish, callback: (error: Error | null) => void): boolean {\n if (sha2Header != null && sha2 != null && sha2Header !== sha2) {\n callback(new Error(`checksum mismatch: expected ${sha2} but got ${sha2Header} (X-Checksum-Sha2 header)`))\n return false\n }\n return true\n}\n\nexport function safeGetHeader(response: any, headerKey: string) {\n const value = response.headers[headerKey]\n if (value == null) {\n return null\n } else if (Array.isArray(value)) {\n // electron API\n return value.length === 0 ? null : value[value.length - 1]\n } else {\n return value\n }\n}\n\nfunction configurePipes(options: DownloadCallOptions, response: IncomingMessage) {\n if (!checkSha2(safeGetHeader(response, \"X-Checksum-Sha2\"), options.options.sha2, options.callback)) {\n return\n }\n\n const streams: Array = []\n if (options.options.onProgress != null) {\n const contentLength = safeGetHeader(response, \"content-length\")\n if (contentLength != null) {\n streams.push(new ProgressCallbackTransform(parseInt(contentLength, 10), options.options.cancellationToken, options.options.onProgress))\n }\n }\n\n const sha512 = options.options.sha512\n if (sha512 != null) {\n streams.push(new DigestTransform(sha512, \"sha512\", sha512.length === 128 && !sha512.includes(\"+\") && !sha512.includes(\"Z\") && !sha512.includes(\"=\") ? \"hex\" : \"base64\"))\n } else if (options.options.sha2 != null) {\n streams.push(new DigestTransform(options.options.sha2, \"sha256\", \"hex\"))\n }\n\n const fileOut = createWriteStream(options.destination!)\n streams.push(fileOut)\n\n let lastStream = response\n for (const stream of streams) {\n stream.on(\"error\", (error: Error) => {\n fileOut.close()\n if (!options.options.cancellationToken.cancelled) {\n options.callback(error)\n }\n })\n lastStream = lastStream.pipe(stream)\n }\n\n fileOut.on(\"finish\", () => {\n ;(fileOut.close as any)(options.callback)\n })\n}\n\nexport function configureRequestOptions(options: RequestOptions, token?: string | null, method?: \"GET\" | \"DELETE\" | \"PUT\" | \"POST\"): RequestOptions {\n if (method != null) {\n options.method = method\n }\n\n options.headers = { ...options.headers }\n const headers = options.headers\n\n if (token != null) {\n ;(headers as any).authorization = token.startsWith(\"Basic\") || token.startsWith(\"Bearer\") ? token : `token ${token}`\n }\n if (headers[\"User-Agent\"] == null) {\n headers[\"User-Agent\"] = \"electron-builder\"\n }\n\n if (method == null || method === \"GET\" || headers[\"Cache-Control\"] == null) {\n headers[\"Cache-Control\"] = \"no-cache\"\n }\n\n // do not specify for node (in any case we use https module)\n if (options.protocol == null && (process.versions as any).electron != null) {\n options.protocol = \"https:\"\n }\n return options\n}\n\nexport function safeStringifyJson(data: any, skippedNames?: Set) {\n return JSON.stringify(\n data,\n (name, value) => {\n if (\n name.endsWith(\"Authorization\") ||\n name.endsWith(\"authorization\") ||\n name.endsWith(\"Password\") ||\n name.endsWith(\"PASSWORD\") ||\n name.endsWith(\"Token\") ||\n name.includes(\"password\") ||\n name.includes(\"token\") ||\n (skippedNames != null && skippedNames.has(name))\n ) {\n return \"\"\n }\n return value\n },\n 2\n )\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CURRENT_APP_PACKAGE_FILE_NAME = exports.CURRENT_APP_INSTALLER_FILE_NAME = exports.deepAssign = exports.asArray = exports.mapToObject = exports.isValidKey = exports.XElement = exports.parseXml = exports.UUID = exports.parseDn = exports.retry = exports.githubTagPrefix = exports.githubUrl = exports.getS3LikeProviderBaseUrl = exports.ProgressCallbackTransform = exports.MemoLazy = exports.safeStringifyJson = exports.safeGetHeader = exports.parseJson = exports.HttpExecutor = exports.HttpError = exports.DigestTransform = exports.createHttpError = exports.configureRequestUrl = exports.configureRequestOptionsFromUrl = exports.configureRequestOptions = exports.newError = exports.CancellationToken = exports.CancellationError = void 0; var CancellationToken_1 = require("./CancellationToken"); Object.defineProperty(exports, "CancellationError", { enumerable: true, get: function () { return CancellationToken_1.CancellationError; } }); Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return CancellationToken_1.CancellationToken; } }); var error_1 = require("./error"); Object.defineProperty(exports, "newError", { enumerable: true, get: function () { return error_1.newError; } }); var httpExecutor_1 = require("./httpExecutor"); Object.defineProperty(exports, "configureRequestOptions", { enumerable: true, get: function () { return httpExecutor_1.configureRequestOptions; } }); Object.defineProperty(exports, "configureRequestOptionsFromUrl", { enumerable: true, get: function () { return httpExecutor_1.configureRequestOptionsFromUrl; } }); Object.defineProperty(exports, "configureRequestUrl", { enumerable: true, get: function () { return httpExecutor_1.configureRequestUrl; } }); Object.defineProperty(exports, "createHttpError", { enumerable: true, get: function () { return httpExecutor_1.createHttpError; } }); Object.defineProperty(exports, "DigestTransform", { enumerable: true, get: function () { return httpExecutor_1.DigestTransform; } }); Object.defineProperty(exports, "HttpError", { enumerable: true, get: function () { return httpExecutor_1.HttpError; } }); Object.defineProperty(exports, "HttpExecutor", { enumerable: true, get: function () { return httpExecutor_1.HttpExecutor; } }); Object.defineProperty(exports, "parseJson", { enumerable: true, get: function () { return httpExecutor_1.parseJson; } }); Object.defineProperty(exports, "safeGetHeader", { enumerable: true, get: function () { return httpExecutor_1.safeGetHeader; } }); Object.defineProperty(exports, "safeStringifyJson", { enumerable: true, get: function () { return httpExecutor_1.safeStringifyJson; } }); var MemoLazy_1 = require("./MemoLazy"); Object.defineProperty(exports, "MemoLazy", { enumerable: true, get: function () { return MemoLazy_1.MemoLazy; } }); var ProgressCallbackTransform_1 = require("./ProgressCallbackTransform"); Object.defineProperty(exports, "ProgressCallbackTransform", { enumerable: true, get: function () { return ProgressCallbackTransform_1.ProgressCallbackTransform; } }); var publishOptions_1 = require("./publishOptions"); Object.defineProperty(exports, "getS3LikeProviderBaseUrl", { enumerable: true, get: function () { return publishOptions_1.getS3LikeProviderBaseUrl; } }); Object.defineProperty(exports, "githubUrl", { enumerable: true, get: function () { return publishOptions_1.githubUrl; } }); Object.defineProperty(exports, "githubTagPrefix", { enumerable: true, get: function () { return publishOptions_1.githubTagPrefix; } }); var retry_1 = require("./retry"); Object.defineProperty(exports, "retry", { enumerable: true, get: function () { return retry_1.retry; } }); var rfc2253Parser_1 = require("./rfc2253Parser"); Object.defineProperty(exports, "parseDn", { enumerable: true, get: function () { return rfc2253Parser_1.parseDn; } }); var uuid_1 = require("./uuid"); Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return uuid_1.UUID; } }); var xml_1 = require("./xml"); Object.defineProperty(exports, "parseXml", { enumerable: true, get: function () { return xml_1.parseXml; } }); Object.defineProperty(exports, "XElement", { enumerable: true, get: function () { return xml_1.XElement; } }); var objects_1 = require("./objects"); Object.defineProperty(exports, "isValidKey", { enumerable: true, get: function () { return objects_1.isValidKey; } }); Object.defineProperty(exports, "mapToObject", { enumerable: true, get: function () { return objects_1.mapToObject; } }); Object.defineProperty(exports, "asArray", { enumerable: true, get: function () { return objects_1.asArray; } }); Object.defineProperty(exports, "deepAssign", { enumerable: true, get: function () { return objects_1.deepAssign; } }); // nsis exports.CURRENT_APP_INSTALLER_FILE_NAME = "installer.exe"; // nsis-web exports.CURRENT_APP_PACKAGE_FILE_NAME = "package.7z"; //# sourceMappingURL=index.js.map{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AACA,yDAA0E;AAAjE,sHAAA,iBAAiB,OAAA;AAAE,sHAAA,iBAAiB,OAAA;AAC7C,iCAAkC;AAAzB,iGAAA,QAAQ,OAAA;AACjB,+CAauB;AAZrB,uHAAA,uBAAuB,OAAA;AACvB,8HAAA,8BAA8B,OAAA;AAC9B,mHAAA,mBAAmB,OAAA;AACnB,+GAAA,eAAe,OAAA;AACf,+GAAA,eAAe,OAAA;AAEf,yGAAA,SAAS,OAAA;AACT,4GAAA,YAAY,OAAA;AACZ,yGAAA,SAAS,OAAA;AAET,6GAAA,aAAa,OAAA;AACb,iHAAA,iBAAiB,OAAA;AAEnB,uCAAqC;AAA5B,oGAAA,QAAQ,OAAA;AACjB,yEAAqF;AAA5E,sIAAA,yBAAyB,OAAA;AAClC,mDAmByB;AAbvB,0HAAA,wBAAwB,OAAA;AAExB,2GAAA,SAAS,OAAA;AACT,iHAAA,eAAe,OAAA;AAWjB,iCAA+B;AAAtB,8FAAA,KAAK,OAAA;AACd,iDAAyC;AAAhC,wGAAA,OAAO,OAAA;AAEhB,+BAA6B;AAApB,4FAAA,IAAI,OAAA;AACb,6BAA0C;AAAjC,+FAAA,QAAQ,OAAA;AAAE,+FAAA,QAAQ,OAAA;AAC3B,qCAAiF;AAAxE,qGAAA,UAAU,OAAA;AAAE,sGAAA,WAAW,OAAA;AAAE,kGAAA,OAAO,OAAA;AAAW,qGAAA,UAAU,OAAA;AAE9D,OAAO;AACM,QAAA,+BAA+B,GAAG,eAAe,CAAA;AAC9D,WAAW;AACE,QAAA,6BAA6B,GAAG,YAAY,CAAA","sourcesContent":["export { BlockMap } from \"./blockMapApi\"\nexport { CancellationError, CancellationToken } from \"./CancellationToken\"\nexport { newError } from \"./error\"\nexport {\n configureRequestOptions,\n configureRequestOptionsFromUrl,\n configureRequestUrl,\n createHttpError,\n DigestTransform,\n DownloadOptions,\n HttpError,\n HttpExecutor,\n parseJson,\n RequestHeaders,\n safeGetHeader,\n safeStringifyJson,\n} from \"./httpExecutor\"\nexport { MemoLazy } from \"./MemoLazy\"\nexport { ProgressCallbackTransform, ProgressInfo } from \"./ProgressCallbackTransform\"\nexport {\n AllPublishOptions,\n BaseS3Options,\n BitbucketOptions,\n CustomPublishOptions,\n GenericServerOptions,\n getS3LikeProviderBaseUrl,\n GithubOptions,\n githubUrl,\n githubTagPrefix,\n GitlabOptions,\n KeygenOptions,\n PublishConfiguration,\n PublishProvider,\n S3Options,\n SnapStoreOptions,\n SpacesOptions,\n GitlabReleaseInfo,\n GitlabReleaseAsset,\n} from \"./publishOptions\"\nexport { retry } from \"./retry\"\nexport { parseDn } from \"./rfc2253Parser\"\nexport { BlockMapDataHolder, PackageFileInfo, ReleaseNoteInfo, UpdateFileInfo, UpdateInfo, WindowsUpdateInfo } from \"./updateInfo\"\nexport { UUID } from \"./uuid\"\nexport { parseXml, XElement } from \"./xml\"\nexport { isValidKey, mapToObject, asArray, Nullish, deepAssign } from \"./objects\"\n\n// nsis\nexport const CURRENT_APP_INSTALLER_FILE_NAME = \"installer.exe\"\n// nsis-web\nexport const CURRENT_APP_PACKAGE_FILE_NAME = \"package.7z\"\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mapToObject = mapToObject; exports.isValidKey = isValidKey; exports.asArray = asArray; exports.deepAssign = deepAssign; function mapToObject(map) { const obj = {}; for (const [key, value] of map) { if (!isValidKey(key)) { continue; } if (value instanceof Map) { obj[key] = mapToObject(value); } else { obj[key] = value; } } return obj; } function isValidKey(key) { const protectedProperties = ["__proto__", "prototype", "constructor"]; if (protectedProperties.includes(key)) { return false; } return ["string", "number", "symbol", "boolean"].includes(typeof key) || key === null; } function asArray(v) { if (v == null) { return []; } else if (Array.isArray(v)) { return v; } else { return [v]; } } function isObject(x) { if (Array.isArray(x)) { return false; } const type = typeof x; return type === "object" || type === "function"; } function assignKey(target, from, key) { const value = from[key]; // https://github.com/electron-userland/electron-builder/pull/562 if (value === undefined) { return; } const prevValue = target[key]; if (prevValue == null || value == null || !isObject(prevValue) || !isObject(value)) { // Merge arrays. if (Array.isArray(prevValue) && Array.isArray(value)) { target[key] = Array.from(new Set(prevValue.concat(value))); } else { target[key] = value; } } else { target[key] = assign(prevValue, value); } } function assign(to, from) { if (to !== from) { for (const key of Object.getOwnPropertyNames(from)) { if (isValidKey(key)) { assignKey(to, from, key); } } } return to; } function deepAssign(target, ...objects) { for (const o of objects) { if (o != null) { assign(target, o); } } return target; } //# sourceMappingURL=objects.js.map{"version":3,"file":"objects.js","sourceRoot":"","sources":["../src/objects.ts"],"names":[],"mappings":";;AAIA,kCAaC;AAED,gCAMC;AAED,0BAQC;AA0CD,gCAOC;AAhFD,SAAgB,WAAW,CAAC,GAAiB;IAC3C,MAAM,GAAG,GAAQ,EAAE,CAAA;IACnB,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC;QAC/B,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACrB,SAAQ;QACV,CAAC;QACD,IAAI,KAAK,YAAY,GAAG,EAAE,CAAC;YACzB,GAAG,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,KAAK,CAAC,CAAA;QAC/B,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QAClB,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED,SAAgB,UAAU,CAAC,GAAQ;IACjC,MAAM,mBAAmB,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,aAAa,CAAC,CAAA;IACrE,IAAI,mBAAmB,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACtC,OAAO,KAAK,CAAA;IACd,CAAC;IACD,OAAO,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,KAAK,IAAI,CAAA;AACvF,CAAC;AAED,SAAgB,OAAO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;QACN,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;IACxC,CAAC;AACH,CAAC;AAED,SAAS,MAAM,CAAC,EAAO,EAAE,IAAS;IAChC,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;QAChB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC;YACnD,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;gBACpB,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;YAC1B,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,EAAE,CAAA;AACX,CAAC;AAED,SAAgB,UAAU,CAAI,MAAS,EAAE,GAAG,OAAmB;IAC7D,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;YACd,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;QACnB,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["export type Nullish = null | undefined\n\ntype RecursiveMap = Map\n\nexport function mapToObject(map: RecursiveMap) {\n const obj: any = {}\n for (const [key, value] of map) {\n if (!isValidKey(key)) {\n continue\n }\n if (value instanceof Map) {\n obj[key] = mapToObject(value)\n } else {\n obj[key] = value\n }\n }\n return obj\n}\n\nexport function isValidKey(key: any) {\n const protectedProperties = [\"__proto__\", \"prototype\", \"constructor\"]\n if (protectedProperties.includes(key)) {\n return false\n }\n return [\"string\", \"number\", \"symbol\", \"boolean\"].includes(typeof key) || key === null\n}\n\nexport function asArray(v: Nullish | T | Array): Array {\n if (v == null) {\n return []\n } else if (Array.isArray(v)) {\n return v\n } else {\n return [v]\n }\n}\n\nfunction isObject(x: any) {\n if (Array.isArray(x)) {\n return false\n }\n\n const type = typeof x\n return type === \"object\" || type === \"function\"\n}\n\nfunction assignKey(target: any, from: any, key: string) {\n const value = from[key]\n // https://github.com/electron-userland/electron-builder/pull/562\n if (value === undefined) {\n return\n }\n\n const prevValue = target[key]\n if (prevValue == null || value == null || !isObject(prevValue) || !isObject(value)) {\n // Merge arrays.\n if (Array.isArray(prevValue) && Array.isArray(value)) {\n target[key] = Array.from(new Set(prevValue.concat(value)))\n } else {\n target[key] = value\n }\n } else {\n target[key] = assign(prevValue, value)\n }\n}\n\nfunction assign(to: any, from: any) {\n if (to !== from) {\n for (const key of Object.getOwnPropertyNames(from)) {\n if (isValidKey(key)) {\n assignKey(to, from, key)\n }\n }\n }\n return to\n}\n\nexport function deepAssign(target: T, ...objects: Array): T {\n for (const o of objects) {\n if (o != null) {\n assign(target, o)\n }\n }\n return target\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.githubUrl = githubUrl; exports.githubTagPrefix = githubTagPrefix; exports.getS3LikeProviderBaseUrl = getS3LikeProviderBaseUrl; /** @private */ function githubUrl(options, defaultHost = "github.com") { return `${options.protocol || "https"}://${options.host || defaultHost}`; } function githubTagPrefix(options) { var _a; if (options.tagNamePrefix) { return options.tagNamePrefix; } if ((_a = options.vPrefixedTagName) !== null && _a !== void 0 ? _a : true) { return "v"; } return ""; } function getS3LikeProviderBaseUrl(configuration) { const provider = configuration.provider; if (provider === "s3") { return s3Url(configuration); } if (provider === "spaces") { return spacesUrl(configuration); } throw new Error(`Not supported provider: ${provider}`); } function s3Url(options) { let url; if (options.accelerate == true) { url = `https://${options.bucket}.s3-accelerate.amazonaws.com`; } else if (options.endpoint != null) { url = `${options.endpoint}/${options.bucket}`; } else if (options.bucket.includes(".")) { if (options.region == null) { throw new Error(`Bucket name "${options.bucket}" includes a dot, but S3 region is missing`); } // special case, see http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro if (options.region === "us-east-1") { url = `https://s3.amazonaws.com/${options.bucket}`; } else { url = `https://s3-${options.region}.amazonaws.com/${options.bucket}`; } } else if (options.region === "cn-north-1") { url = `https://${options.bucket}.s3.${options.region}.amazonaws.com.cn`; } else { url = `https://${options.bucket}.s3.amazonaws.com`; } return appendPath(url, options.path); } function appendPath(url, p) { if (p != null && p.length > 0) { if (!p.startsWith("/")) { url += "/"; } url += p; } return url; } function spacesUrl(options) { if (options.name == null) { throw new Error(`name is missing`); } if (options.region == null) { throw new Error(`region is missing`); } return appendPath(`https://${options.name}.${options.region}.digitaloceanspaces.com`, options.path); } //# sourceMappingURL=publishOptions.js.map{"version":3,"file":"publishOptions.js","sourceRoot":"","sources":["../src/publishOptions.ts"],"names":[],"mappings":";;AAqJA,8BAEC;AAED,0CAQC;AAqUD,4DASC;AA3VD,eAAe;AACf,SAAgB,SAAS,CAAC,OAAsB,EAAE,WAAW,GAAG,YAAY;IAC1E,OAAO,GAAG,OAAO,CAAC,QAAQ,IAAI,OAAO,MAAM,OAAO,CAAC,IAAI,IAAI,WAAW,EAAE,CAAA;AAC1E,CAAC;AAED,SAAgB,eAAe,CAAC,OAAsB;;IACpD,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;QAC1B,OAAO,OAAO,CAAC,aAAa,CAAA;IAC9B,CAAC;IACD,IAAI,MAAA,OAAO,CAAC,gBAAgB,mCAAI,IAAI,EAAE,CAAC;QACrC,OAAO,GAAG,CAAA;IACZ,CAAC;IACD,OAAO,EAAE,CAAA;AACX,CAAC;AAqUD,SAAgB,wBAAwB,CAAC,aAAmC;IAC1E,MAAM,QAAQ,GAAG,aAAa,CAAC,QAAQ,CAAA;IACvC,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtB,OAAO,KAAK,CAAC,aAA0B,CAAC,CAAA;IAC1C,CAAC;IACD,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC,aAA8B,CAAC,CAAA;IAClD,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,2BAA2B,QAAQ,EAAE,CAAC,CAAA;AACxD,CAAC;AAED,SAAS,KAAK,CAAC,OAA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CAAC,GAAG,CAAC,EAAE,CAAC;YACvB,GAAG,IAAI,GAAG,CAAA;QACZ,CAAC;QACD,GAAG,IAAI,CAAC,CAAA;IACV,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED,SAAS,SAAS,CAAC,OAAsB;IACvC,IAAI,OAAO,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;IACpC,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,IAAI,IAAI,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAA;IACtC,CAAC;IACD,OAAO,UAAU,CAAC,WAAW,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC,MAAM,yBAAyB,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;AACrG,CAAC","sourcesContent":["import { OutgoingHttpHeaders } from \"http\"\nimport { Nullish } from \".\"\n\nexport type PublishProvider = \"github\" | \"gitlab\" | \"s3\" | \"spaces\" | \"generic\" | \"custom\" | \"snapStore\" | \"keygen\" | \"bitbucket\"\n\n// typescript-json-schema generates only PublishConfiguration if it is specified in the list, so, it is not added here\nexport type AllPublishOptions =\n | string\n | GithubOptions\n | GitlabOptions\n | S3Options\n | SpacesOptions\n | GenericServerOptions\n | CustomPublishOptions\n | KeygenOptions\n | SnapStoreOptions\n | BitbucketOptions\n\nexport interface PublishConfiguration {\n /**\n * The provider.\n */\n readonly provider: PublishProvider\n\n /**\n * @private\n * win-only\n */\n publisherName?: Array | null\n\n /**\n * @private\n * win-only\n */\n readonly updaterCacheDirName?: string | null\n\n /**\n * Whether to publish auto update info files.\n *\n * Auto update relies only on the first provider in the list (you can specify several publishers).\n * Thus, probably, there`s no need to upload the metadata files for the other configured providers. But by default will be uploaded.\n *\n * @default true\n */\n readonly publishAutoUpdate?: boolean\n\n /**\n * Any custom request headers\n */\n readonly requestHeaders?: OutgoingHttpHeaders\n\n /**\n * Request timeout in milliseconds. (Default is 2 minutes; O is ignored)\n *\n * @default 120000\n */\n readonly timeout?: number | null\n}\n\n// https://github.com/electron-userland/electron-builder/issues/3261\nexport interface CustomPublishOptions extends PublishConfiguration {\n /**\n * The provider. Must be `custom`.\n */\n readonly provider: \"custom\"\n\n /**\n * The Provider to provide UpdateInfo regarding available updates. Required\n * to use custom providers with electron-updater.\n */\n updateProvider?: new (options: CustomPublishOptions, updater: any, runtimeOptions: any) => any\n\n [index: string]: any\n}\n\n/**\n * [GitHub](https://help.github.com/articles/about-releases/) options.\n *\n * GitHub [personal access token](https://help.github.com/articles/creating-an-access-token-for-command-line-use/) is required. You can generate by going to [https://github.com/settings/tokens/new](https://github.com/settings/tokens/new). The access token should have the repo scope/permission.\n * Define `GH_TOKEN` environment variable.\n */\nexport interface GithubOptions extends PublishConfiguration {\n /**\n * The provider. Must be `github`.\n */\n readonly provider: \"github\"\n\n /**\n * The repository name. [Detected automatically](#github-repository-and-bintray-package).\n */\n readonly repo?: string | null\n\n /**\n * The owner.\n */\n readonly owner?: string | null\n\n /**\n * Whether to use `v`-prefixed tag name.\n * @default true\n * @deprecated please use #tagNamePrefix instead.\n */\n readonly vPrefixedTagName?: boolean\n\n /**\n * If defined, sets the prefix of the tag name that comes before the semver number.\n * e.g. \"v\" in \"v1.2.3\" or \"test\" of \"test1.2.3\".\n * Overrides `vPrefixedTagName`\n */\n readonly tagNamePrefix?: string\n\n /**\n * The host (including the port if need).\n * @default github.com\n */\n readonly host?: string | null\n\n /**\n * The protocol. GitHub Publisher supports only `https`.\n * @default https\n */\n readonly protocol?: \"https\" | \"http\" | null\n\n /**\n * The access token to support auto-update from private github repositories. Never specify it in the configuration files. Only for [setFeedURL](https://www.electron.build/auto-update#appupdatersetfeedurloptions).\n */\n readonly token?: string | null\n\n /**\n * Whether to use private github auto-update provider if `GH_TOKEN` environment variable is defined. See [Private GitHub Update Repo](https://www.electron.build/auto-update#private-github-update-repo).\n */\n readonly private?: boolean | null\n\n /**\n * The channel.\n * @default latest\n */\n readonly channel?: string | null\n\n /**\n * The type of release. By default `draft` release will be created.\n *\n * Also you can set release type using environment variable. If `EP_DRAFT`is set to `true` — `draft`, if `EP_PRE_RELEASE`is set to `true` — `prerelease`.\n * @default draft\n */\n releaseType?: \"draft\" | \"prerelease\" | \"release\" | null\n}\n\n/** @private */\nexport function githubUrl(options: GithubOptions, defaultHost = \"github.com\") {\n return `${options.protocol || \"https\"}://${options.host || defaultHost}`\n}\n\nexport function githubTagPrefix(options: GithubOptions) {\n if (options.tagNamePrefix) {\n return options.tagNamePrefix\n }\n if (options.vPrefixedTagName ?? true) {\n return \"v\"\n }\n return \"\"\n}\n\n/**\n * [GitLab](https://docs.gitlab.com/ee/user/project/releases/) options.\n *\n * GitLab [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) is required for private repositories. You can generate one by going to your GitLab profile settings.\n * Define `GITLAB_TOKEN` environment variable.\n */\nexport interface GitlabOptions extends PublishConfiguration {\n /**\n * The provider. Must be `gitlab`.\n */\n readonly provider: \"gitlab\"\n\n /**\n * The GitLab project ID or path (e.g., \"12345678\" or \"namespace/project\").\n */\n readonly projectId?: string | number | null\n\n /**\n * The GitLab host (including the port if need).\n * @default gitlab.com\n */\n readonly host?: string | null\n\n /**\n * The access token to support auto-update from private GitLab repositories. Never specify it in the configuration files.\n */\n readonly token?: string | null\n\n /**\n * Whether to use `v`-prefixed tag name.\n * @default true\n */\n readonly vPrefixedTagName?: boolean\n\n /**\n * The channel.\n * @default latest\n */\n readonly channel?: string | null\n\n /**\n * Upload target method. Can be \"project_upload\" for GitLab project uploads or \"generic_package\" for GitLab generic packages.\n * @default \"project_upload\"\n */\n readonly uploadTarget?: \"project_upload\" | \"generic_package\" | null\n}\n\n/**\n * Generic (any HTTP(S) server) options.\n * In all publish options [File Macros](https://www.electron.build/file-patterns#file-macros) are supported.\n */\nexport interface GenericServerOptions extends PublishConfiguration {\n /**\n * The provider. Must be `generic`.\n */\n readonly provider: \"generic\"\n\n /**\n * The base url. e.g. `https://bucket_name.s3.amazonaws.com`.\n */\n readonly url: string\n\n /**\n * The channel.\n * @default latest\n */\n readonly channel?: string | null\n\n /**\n * Whether to use multiple range requests for differential update. Defaults to `true` if `url` doesn't contain `s3.amazonaws.com`.\n */\n readonly useMultipleRangeRequest?: boolean\n}\n\n/**\n * Keygen options.\n * https://keygen.sh/\n * Define `KEYGEN_TOKEN` environment variable.\n */\nexport interface KeygenOptions extends PublishConfiguration {\n /**\n * The provider. Must be `keygen`.\n */\n readonly provider: \"keygen\"\n\n /**\n * Keygen host for self-hosted instances\n * @default \"api.keygen.sh\"\n */\n readonly host?: string\n\n /**\n * Keygen account's UUID\n */\n readonly account: string\n\n /**\n * Keygen product's UUID\n */\n readonly product: string\n\n /**\n * The channel.\n * @default stable\n */\n readonly channel?: \"stable\" | \"rc\" | \"beta\" | \"alpha\" | \"dev\" | null\n\n /**\n * The target Platform. Is set programmatically explicitly during publishing.\n */\n readonly platform?: string | null\n}\n\n/**\n * Bitbucket options.\n * https://bitbucket.org/\n * Define `BITBUCKET_TOKEN` environment variable.\n *\n * For converting an app password to a usable token, you can utilize this\n```typescript\nconvertAppPassword(owner: string, appPassword: string) {\n const base64encodedData = Buffer.from(`${owner}:${appPassword.trim()}`).toString(\"base64\")\n return `Basic ${base64encodedData}`\n}\n```\n */\nexport interface BitbucketOptions extends PublishConfiguration {\n /**\n * The provider. Must be `bitbucket`.\n */\n readonly provider: \"bitbucket\"\n\n /**\n * Repository owner\n */\n readonly owner: string\n\n /**\n * The [app password](https://bitbucket.org/account/settings/app-passwords) to support auto-update from private bitbucket repositories.\n */\n readonly token?: string | null\n\n /**\n * The user name to support auto-update from private bitbucket repositories.\n */\n readonly username?: string | null\n\n /**\n * Repository slug/name\n */\n readonly slug: string\n\n /**\n * The channel.\n * @default latest\n */\n readonly channel?: string | null\n}\n\n/**\n * [Snap Store](https://snapcraft.io/) options. To publish directly to Snapcraft, see Snapcraft authentication options for local or CI/CD authentication options.\n */\nexport interface SnapStoreOptions extends PublishConfiguration {\n /**\n * The provider. Must be `snapStore`.\n */\n readonly provider: \"snapStore\"\n\n /**\n * snapcraft repo name\n */\n readonly repo?: string\n\n /**\n * The list of channels the snap would be released.\n * @default [\"edge\"]\n */\n readonly channels?: string | Array | null\n}\n\nexport interface BaseS3Options extends PublishConfiguration {\n /**\n * The update channel.\n * @default latest\n */\n channel?: string | null\n\n /**\n * The directory path.\n * @default /\n */\n readonly path?: string | null\n\n /**\n * The ACL. Set to `null` to not [add](https://github.com/electron-userland/electron-builder/issues/1822).\n *\n * @default public-read\n */\n readonly acl?: \"private\" | \"public-read\" | null\n}\n\n/**\n * [Amazon S3](https://aws.amazon.com/s3/) options.\n * AWS credentials are required, please see [getting your credentials](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-your-credentials.html).\n * To set credentials define `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` [environment variables](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-environment.html) directly,\n * or use [~/.aws/credentials](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-shared.html) file,\n * or use [~/.aws/config](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) file. For the last method to work you will also need to define `AWS_SDK_LOAD_CONFIG=1` environment variable.\n *\n * Example configuration:\n *\n```json\n{\n \"build\":\n \"publish\": {\n \"provider\": \"s3\",\n \"bucket\": \"bucket-name\"\n }\n }\n}\n```\n */\nexport interface S3Options extends BaseS3Options {\n /**\n * The provider. Must be `s3`.\n */\n readonly provider: \"s3\"\n\n /**\n * The bucket name.\n */\n readonly bucket: string\n\n /**\n * The region. Is determined and set automatically when publishing.\n */\n region?: string | null\n\n /**\n * The ACL. Set to `null` to not [add](https://github.com/electron-userland/electron-builder/issues/1822).\n *\n * Please see [required permissions for the S3 provider](https://github.com/electron-userland/electron-builder/issues/1618#issuecomment-314679128).\n *\n * @default public-read\n */\n readonly acl?: \"private\" | \"public-read\" | null\n\n /**\n * The type of storage to use for the object.\n * @default STANDARD\n */\n readonly storageClass?: \"STANDARD\" | \"REDUCED_REDUNDANCY\" | \"STANDARD_IA\" | null\n\n /**\n * Server-side encryption algorithm to use for the object.\n */\n readonly encryption?: \"AES256\" | \"aws:kms\" | null\n\n /**\n * The endpoint URI to send requests to. The default endpoint is built from the configured region.\n * The endpoint should be a string like `https://{service}.{region}.amazonaws.com`.\n */\n readonly endpoint?: string | null\n\n /**\n * If set to true, this will enable the s3 accelerated endpoint\n * These endpoints have a particular format of:\n * ${bucketname}.s3-accelerate.amazonaws.com\n */\n readonly accelerate?: boolean\n\n /**\n * When true, force a path-style endpoint to be used where the bucket name is part of the path.\n * [Path-style Access](https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html#path-style-access)\n */\n readonly forcePathStyle?: boolean\n}\n\n/**\n * [DigitalOcean Spaces](https://www.digitalocean.com/community/tutorials/an-introduction-to-digitalocean-spaces) options.\n * Access key is required, define `DO_KEY_ID` and `DO_SECRET_KEY` environment variables.\n */\nexport interface SpacesOptions extends BaseS3Options {\n /**\n * The provider. Must be `spaces`.\n */\n readonly provider: \"spaces\"\n\n /**\n * The space name.\n */\n readonly name: string\n\n /**\n * The region (e.g. `nyc3`).\n */\n readonly region: string\n}\n\nexport interface GitlabReleaseInfo {\n name: string\n tag_name: string\n description: string\n created_at: string\n released_at: string\n upcoming_release: boolean\n assets: GitlabReleaseAsset\n}\n\nexport interface GitlabReleaseAsset {\n count: number\n sources: Array<{\n format: string\n url: string\n }>\n links: Array<{\n id: number\n name: string\n url: string\n direct_asset_url: string\n link_type: string\n }>\n}\n\nexport function getS3LikeProviderBaseUrl(configuration: PublishConfiguration) {\n const provider = configuration.provider\n if (provider === \"s3\") {\n return s3Url(configuration as S3Options)\n }\n if (provider === \"spaces\") {\n return spacesUrl(configuration as SpacesOptions)\n }\n throw new Error(`Not supported provider: ${provider}`)\n}\n\nfunction s3Url(options: S3Options) {\n let url: string\n if (options.accelerate == true) {\n url = `https://${options.bucket}.s3-accelerate.amazonaws.com`\n } else if (options.endpoint != null) {\n url = `${options.endpoint}/${options.bucket}`\n } else if (options.bucket.includes(\".\")) {\n if (options.region == null) {\n throw new Error(`Bucket name \"${options.bucket}\" includes a dot, but S3 region is missing`)\n }\n\n // special case, see http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro\n if (options.region === \"us-east-1\") {\n url = `https://s3.amazonaws.com/${options.bucket}`\n } else {\n url = `https://s3-${options.region}.amazonaws.com/${options.bucket}`\n }\n } else if (options.region === \"cn-north-1\") {\n url = `https://${options.bucket}.s3.${options.region}.amazonaws.com.cn`\n } else {\n url = `https://${options.bucket}.s3.amazonaws.com`\n }\n return appendPath(url, options.path)\n}\n\nfunction appendPath(url: string, p: string | Nullish): string {\n if (p != null && p.length > 0) {\n if (!p.startsWith(\"/\")) {\n url += \"/\"\n }\n url += p\n }\n return url\n}\n\nfunction spacesUrl(options: SpacesOptions) {\n if (options.name == null) {\n throw new Error(`name is missing`)\n }\n if (options.region == null) {\n throw new Error(`region is missing`)\n }\n return appendPath(`https://${options.name}.${options.region}.digitaloceanspaces.com`, options.path)\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.retry = retry; const CancellationToken_1 = require("./CancellationToken"); async function retry(task, options) { var _a; const { retries: retryCount, interval, backoff = 0, attempt = 0, shouldRetry, cancellationToken = new CancellationToken_1.CancellationToken() } = options; try { return await task(); } catch (error) { if ((await Promise.resolve((_a = shouldRetry === null || shouldRetry === void 0 ? void 0 : shouldRetry(error)) !== null && _a !== void 0 ? _a : true)) && retryCount > 0 && !cancellationToken.cancelled) { await new Promise(resolve => setTimeout(resolve, interval + backoff * attempt)); return await retry(task, { ...options, retries: retryCount - 1, attempt: attempt + 1 }); } else { throw error; } } } //# sourceMappingURL=retry.js.map{"version":3,"file":"retry.js","sourceRoot":"","sources":["../src/retry.ts"],"names":[],"mappings":";;AAEA,sBAeC;AAjBD,2DAAuD;AAEhD,KAAK,UAAU,KAAK,CACzB,IAAsB,EACtB,OAA+K;;IAE/K,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,CAAC,EAAE,WAAW,EAAE,iBAAiB,GAAG,IAAI,qCAAiB,EAAE,EAAE,GAAG,OAAO,CAAA;IACrI,IAAI,CAAC;QACH,OAAO,MAAM,IAAI,EAAE,CAAA;IACrB,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,IAAI,CAAC,MAAM,OAAO,CAAC,OAAO,CAAC,MAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAG,KAAK,CAAC,mCAAI,IAAI,CAAC,CAAC,IAAI,UAAU,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,SAAS,EAAE,CAAC;YAC5G,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,GAAG,OAAO,GAAG,OAAO,CAAC,CAAC,CAAA;YAC/E,OAAO,MAAM,KAAK,CAAC,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,UAAU,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,CAAC,EAAE,CAAC,CAAA;QACzF,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { CancellationToken } from \"./CancellationToken\"\n\nexport async function retry(\n task: () => Promise,\n options: { retries: number; interval: number; backoff?: number; attempt?: number; cancellationToken?: CancellationToken; shouldRetry?: (e: any) => boolean | Promise }\n): Promise {\n const { retries: retryCount, interval, backoff = 0, attempt = 0, shouldRetry, cancellationToken = new CancellationToken() } = options\n try {\n return await task()\n } catch (error: any) {\n if ((await Promise.resolve(shouldRetry?.(error) ?? true)) && retryCount > 0 && !cancellationToken.cancelled) {\n await new Promise(resolve => setTimeout(resolve, interval + backoff * attempt))\n return await retry(task, { ...options, retries: retryCount - 1, attempt: attempt + 1 })\n } else {\n throw error\n }\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseDn = parseDn; function parseDn(seq) { let quoted = false; let key = null; let token = ""; let nextNonSpace = 0; seq = seq.trim(); const result = new Map(); for (let i = 0; i <= seq.length; i++) { if (i === seq.length) { if (key !== null) { result.set(key, token); } break; } const ch = seq[i]; if (quoted) { if (ch === '"') { quoted = false; continue; } } else { if (ch === '"') { quoted = true; continue; } if (ch === "\\") { i++; const ord = parseInt(seq.slice(i, i + 2), 16); if (Number.isNaN(ord)) { token += seq[i]; } else { i++; token += String.fromCharCode(ord); } continue; } if (key === null && ch === "=") { key = token; token = ""; continue; } if (ch === "," || ch === ";" || ch === "+") { if (key !== null) { result.set(key, token); } key = null; token = ""; continue; } } if (ch === " " && !quoted) { if (token.length === 0) { continue; } if (i > nextNonSpace) { let j = i; while (seq[j] === " ") { j++; } nextNonSpace = j; } if (nextNonSpace >= seq.length || seq[nextNonSpace] === "," || seq[nextNonSpace] === ";" || (key === null && seq[nextNonSpace] === "=") || (key !== null && seq[nextNonSpace] === "+")) { i = nextNonSpace - 1; continue; } } token += ch; } return result; } //# sourceMappingURL=rfc2253Parser.js.map{"version":3,"file":"rfc2253Parser.js","sourceRoot":"","sources":["../src/rfc2253Parser.ts"],"names":[],"mappings":";;AAAA,0BAqFC;AArFD,SAAgB,OAAO,CAAC,GAAW;IACjC,IAAI,MAAM,GAAG,KAAK,CAAA;IAClB,IAAI,GAAG,GAAkB,IAAI,CAAA;IAC7B,IAAI,KAAK,GAAG,EAAE,CAAA;IACd,IAAI,YAAY,GAAG,CAAC,CAAA;IAEpB,GAAG,GAAG,GAAG,CAAC,IAAI,EAAE,CAAA;IAChB,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAA;IACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,CAAC,MAAM,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IAAI,EAAE,CAAC;oBACjB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;gBACxB,CAAC;gBACD,GAAG,GAAG,IAAI,CAAA;gBACV,KAAK,GAAG,EAAE,CAAA;gBACV,SAAQ;YACV,CAAC;QACH,CAAC;QAED,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;YAC1B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACvB,SAAQ;YACV,CAAC;YAED,IAAI,CAAC,GAAG,YAAY,EAAE,CAAC;gBACrB,IAAI,CAAC,GAAG,CAAC,CAAA;gBACT,OAAO,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;oBACtB,CAAC,EAAE,CAAA;gBACL,CAAC;gBACD,YAAY,GAAG,CAAC,CAAA;YAClB,CAAC;YAED,IACE,YAAY,IAAI,GAAG,CAAC,MAAM;gBAC1B,GAAG,CAAC,YAAY,CAAC,KAAK,GAAG;gBACzB,GAAG,CAAC,YAAY,CAAC,KAAK,GAAG;gBACzB,CAAC,GAAG,KAAK,IAAI,IAAI,GAAG,CAAC,YAAY,CAAC,KAAK,GAAG,CAAC;gBAC3C,CAAC,GAAG,KAAK,IAAI,IAAI,GAAG,CAAC,YAAY,CAAC,KAAK,GAAG,CAAC,EAC3C,CAAC;gBACD,CAAC,GAAG,YAAY,GAAG,CAAC,CAAA;gBACpB,SAAQ;YACV,CAAC;QACH,CAAC;QAED,KAAK,IAAI,EAAE,CAAA;IACb,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["export function parseDn(seq: string): Map {\n let quoted = false\n let key: string | null = null\n let token = \"\"\n let nextNonSpace = 0\n\n seq = seq.trim()\n const result = new Map()\n for (let i = 0; i <= seq.length; i++) {\n if (i === seq.length) {\n if (key !== null) {\n result.set(key, token)\n }\n break\n }\n\n const ch = seq[i]\n if (quoted) {\n if (ch === '\"') {\n quoted = false\n continue\n }\n } else {\n if (ch === '\"') {\n quoted = true\n continue\n }\n\n if (ch === \"\\\\\") {\n i++\n const ord = parseInt(seq.slice(i, i + 2), 16)\n if (Number.isNaN(ord)) {\n token += seq[i]\n } else {\n i++\n token += String.fromCharCode(ord)\n }\n continue\n }\n\n if (key === null && ch === \"=\") {\n key = token\n token = \"\"\n continue\n }\n\n if (ch === \",\" || ch === \";\" || ch === \"+\") {\n if (key !== null) {\n result.set(key, token)\n }\n key = null\n token = \"\"\n continue\n }\n }\n\n if (ch === \" \" && !quoted) {\n if (token.length === 0) {\n continue\n }\n\n if (i > nextNonSpace) {\n let j = i\n while (seq[j] === \" \") {\n j++\n }\n nextNonSpace = j\n }\n\n if (\n nextNonSpace >= seq.length ||\n seq[nextNonSpace] === \",\" ||\n seq[nextNonSpace] === \";\" ||\n (key === null && seq[nextNonSpace] === \"=\") ||\n (key !== null && seq[nextNonSpace] === \"+\")\n ) {\n i = nextNonSpace - 1\n continue\n }\n }\n\n token += ch\n }\n\n return result\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=updateInfo.js.map{"version":3,"file":"updateInfo.js","sourceRoot":"","sources":["../src/updateInfo.ts"],"names":[],"mappings":"","sourcesContent":["export interface ReleaseNoteInfo {\n /**\n * The version.\n */\n readonly version: string\n\n /**\n * The note.\n */\n readonly note: string | null\n}\n\nexport interface BlockMapDataHolder {\n /**\n * The file size. Used to verify downloaded size (save one HTTP request to get length).\n * Also used when block map data is embedded into the file (appimage, windows web installer package).\n */\n size?: number\n\n /**\n * The block map file size. Used when block map data is embedded into the file (appimage, windows web installer package).\n * This information can be obtained from the file itself, but it requires additional HTTP request,\n * so, to reduce request count, block map size is specified in the update metadata too.\n */\n blockMapSize?: number\n\n /**\n * The file checksum.\n */\n readonly sha512: string\n\n readonly isAdminRightsRequired?: boolean\n}\n\nexport interface PackageFileInfo extends BlockMapDataHolder {\n readonly path: string\n}\n\nexport interface UpdateFileInfo extends BlockMapDataHolder {\n url: string\n}\n\nexport interface UpdateInfo {\n /**\n * The version.\n */\n readonly version: string\n\n readonly files: Array\n\n /** @deprecated */\n readonly path: string\n\n /** @deprecated */\n readonly sha512: string\n\n /**\n * The release name.\n */\n releaseName?: string | null\n\n /**\n * The release notes. List if `updater.fullChangelog` is set to `true`, `string` otherwise.\n */\n releaseNotes?: string | Array | null\n\n /**\n * The release date.\n */\n releaseDate: string\n\n /**\n * The [staged rollout](https://www.electron.build/auto-update#staged-rollouts) percentage, 0-100.\n */\n readonly stagingPercentage?: number\n\n /**\n * The minimum version of system required for the app to run. Sample value: macOS `23.1.0`, Windows `10.0.22631`.\n * Same with os.release() value, this is a kernel version.\n */\n readonly minimumSystemVersion?: string\n}\n\nexport interface WindowsUpdateInfo extends UpdateInfo {\n packages?: { [arch: string]: PackageFileInfo } | null\n\n /**\n * @deprecated\n * @private\n */\n sha2?: string\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.nil = exports.UUID = void 0; const crypto_1 = require("crypto"); const error_1 = require("./error"); const invalidName = "options.name must be either a string or a Buffer"; // Node ID according to rfc4122#section-4.5 const randomHost = (0, crypto_1.randomBytes)(16); randomHost[0] = randomHost[0] | 0x01; // lookup table hex to byte const hex2byte = {}; // lookup table byte to hex const byte2hex = []; // populate lookup tables for (let i = 0; i < 256; i++) { const hex = (i + 0x100).toString(16).substr(1); hex2byte[hex] = i; byte2hex[i] = hex; } // UUID class class UUID { constructor(uuid) { this.ascii = null; this.binary = null; const check = UUID.check(uuid); if (!check) { throw new Error("not a UUID"); } this.version = check.version; if (check.format === "ascii") { this.ascii = uuid; } else { this.binary = uuid; } } static v5(name, namespace) { return uuidNamed(name, "sha1", 0x50, namespace); } toString() { if (this.ascii == null) { this.ascii = stringify(this.binary); } return this.ascii; } inspect() { return `UUID v${this.version} ${this.toString()}`; } static check(uuid, offset = 0) { if (typeof uuid === "string") { uuid = uuid.toLowerCase(); if (!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-([a-f0-9]{12})$/.test(uuid)) { return false; } if (uuid === "00000000-0000-0000-0000-000000000000") { return { version: undefined, variant: "nil", format: "ascii" }; } return { version: (hex2byte[uuid[14] + uuid[15]] & 0xf0) >> 4, variant: getVariant((hex2byte[uuid[19] + uuid[20]] & 0xe0) >> 5), format: "ascii", }; } if (Buffer.isBuffer(uuid)) { if (uuid.length < offset + 16) { return false; } let i = 0; for (; i < 16; i++) { if (uuid[offset + i] !== 0) { break; } } if (i === 16) { return { version: undefined, variant: "nil", format: "binary" }; } return { version: (uuid[offset + 6] & 0xf0) >> 4, variant: getVariant((uuid[offset + 8] & 0xe0) >> 5), format: "binary", }; } throw (0, error_1.newError)("Unknown type of uuid", "ERR_UNKNOWN_UUID_TYPE"); } // read stringified uuid into a Buffer static parse(input) { const buffer = Buffer.allocUnsafe(16); let j = 0; for (let i = 0; i < 16; i++) { buffer[i] = hex2byte[input[j++] + input[j++]]; if (i === 3 || i === 5 || i === 7 || i === 9) { j += 1; } } return buffer; } } exports.UUID = UUID; // from rfc4122#appendix-C UUID.OID = UUID.parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8"); // according to rfc4122#section-4.1.1 function getVariant(bits) { switch (bits) { case 0: case 1: case 3: return "ncs"; case 4: case 5: return "rfc4122"; case 6: return "microsoft"; default: return "future"; } } var UuidEncoding; (function (UuidEncoding) { UuidEncoding[UuidEncoding["ASCII"] = 0] = "ASCII"; UuidEncoding[UuidEncoding["BINARY"] = 1] = "BINARY"; UuidEncoding[UuidEncoding["OBJECT"] = 2] = "OBJECT"; })(UuidEncoding || (UuidEncoding = {})); // v3 + v5 function uuidNamed(name, hashMethod, version, namespace, encoding = UuidEncoding.ASCII) { const hash = (0, crypto_1.createHash)(hashMethod); const nameIsNotAString = typeof name !== "string"; if (nameIsNotAString && !Buffer.isBuffer(name)) { throw (0, error_1.newError)(invalidName, "ERR_INVALID_UUID_NAME"); } hash.update(namespace); hash.update(name); const buffer = hash.digest(); let result; switch (encoding) { case UuidEncoding.BINARY: buffer[6] = (buffer[6] & 0x0f) | version; buffer[8] = (buffer[8] & 0x3f) | 0x80; result = buffer; break; case UuidEncoding.OBJECT: buffer[6] = (buffer[6] & 0x0f) | version; buffer[8] = (buffer[8] & 0x3f) | 0x80; result = new UUID(buffer); break; default: result = byte2hex[buffer[0]] + byte2hex[buffer[1]] + byte2hex[buffer[2]] + byte2hex[buffer[3]] + "-" + byte2hex[buffer[4]] + byte2hex[buffer[5]] + "-" + byte2hex[(buffer[6] & 0x0f) | version] + byte2hex[buffer[7]] + "-" + byte2hex[(buffer[8] & 0x3f) | 0x80] + byte2hex[buffer[9]] + "-" + byte2hex[buffer[10]] + byte2hex[buffer[11]] + byte2hex[buffer[12]] + byte2hex[buffer[13]] + byte2hex[buffer[14]] + byte2hex[buffer[15]]; break; } return result; } function stringify(buffer) { return (byte2hex[buffer[0]] + byte2hex[buffer[1]] + byte2hex[buffer[2]] + byte2hex[buffer[3]] + "-" + byte2hex[buffer[4]] + byte2hex[buffer[5]] + "-" + byte2hex[buffer[6]] + byte2hex[buffer[7]] + "-" + byte2hex[buffer[8]] + byte2hex[buffer[9]] + "-" + byte2hex[buffer[10]] + byte2hex[buffer[11]] + byte2hex[buffer[12]] + byte2hex[buffer[13]] + byte2hex[buffer[14]] + byte2hex[buffer[15]]); } // according to rfc4122#section-4.1.7 exports.nil = new UUID("00000000-0000-0000-0000-000000000000"); // UUID.v4 = uuidRandom // UUID.v4fast = uuidRandomFast // UUID.v3 = function(options, callback) { // return uuidNamed("md5", 0x30, options, callback) // } //# sourceMappingURL=uuid.js.map{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../src/uuid.ts"],"names":[],"mappings":";;;AAAA,mCAAgD;AAChD,mCAAkC;AAElC,MAAM,WAAW,GAAG,kDAAkD,CAAA;AAEtE,2CAA2C;AAC3C,MAAM,UAAU,GAAG,IAAA,oBAAW,EAAC,EAAE,CAAC,CAAA;AAClC,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,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;AACvD,IAAI","sourcesContent":["import { createHash, randomBytes } from \"crypto\"\nimport { newError } from \"./error\"\n\nconst invalidName = \"options.name must be either a string or a Buffer\"\n\n// Node ID according to rfc4122#section-4.5\nconst randomHost = randomBytes(16)\nrandomHost[0] = randomHost[0] | 0x01\n\n// lookup table hex to byte\nconst hex2byte: any = {}\n\n// lookup table byte to hex\nconst byte2hex: Array = []\n// populate lookup tables\nfor (let i = 0; i < 256; i++) {\n const hex = (i + 0x100).toString(16).substr(1)\n hex2byte[hex] = i\n byte2hex[i] = hex\n}\n\n// UUID class\nexport class UUID {\n private ascii: string | null = null\n private readonly binary: Buffer | null = null\n private readonly version: number\n\n // from rfc4122#appendix-C\n static readonly OID: Buffer = UUID.parse(\"6ba7b812-9dad-11d1-80b4-00c04fd430c8\")\n\n constructor(uuid: Buffer | string) {\n const check = UUID.check(uuid)\n if (!check) {\n throw new Error(\"not a UUID\")\n }\n\n this.version = check.version!\n\n if (check.format === \"ascii\") {\n this.ascii = uuid as string\n } else {\n this.binary = uuid as Buffer\n }\n }\n\n static v5(name: string | Buffer, namespace: Buffer) {\n return uuidNamed(name, \"sha1\", 0x50, namespace)\n }\n\n toString() {\n if (this.ascii == null) {\n this.ascii = stringify(this.binary!)\n }\n return this.ascii\n }\n\n inspect() {\n return `UUID v${this.version} ${this.toString()}`\n }\n\n static check(uuid: Buffer | string, offset = 0) {\n if (typeof uuid === \"string\") {\n uuid = uuid.toLowerCase()\n\n if (!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-([a-f0-9]{12})$/.test(uuid)) {\n return false\n }\n\n if (uuid === \"00000000-0000-0000-0000-000000000000\") {\n return { version: undefined, variant: \"nil\", format: \"ascii\" }\n }\n\n return {\n version: (hex2byte[uuid[14] + uuid[15]] & 0xf0) >> 4,\n variant: getVariant((hex2byte[uuid[19] + uuid[20]] & 0xe0) >> 5),\n format: \"ascii\",\n }\n }\n\n if (Buffer.isBuffer(uuid)) {\n if (uuid.length < offset + 16) {\n return false\n }\n\n let i = 0\n for (; i < 16; i++) {\n if (uuid[offset + i] !== 0) {\n break\n }\n }\n if (i === 16) {\n return { version: undefined, variant: \"nil\", format: \"binary\" }\n }\n\n return {\n version: (uuid[offset + 6] & 0xf0) >> 4,\n variant: getVariant((uuid[offset + 8] & 0xe0) >> 5),\n format: \"binary\",\n }\n }\n\n throw newError(\"Unknown type of uuid\", \"ERR_UNKNOWN_UUID_TYPE\")\n }\n\n // read stringified uuid into a Buffer\n static parse(input: string): Buffer {\n const buffer = Buffer.allocUnsafe(16)\n let j = 0\n for (let i = 0; i < 16; i++) {\n buffer[i] = hex2byte[input[j++] + input[j++]]\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n j += 1\n }\n }\n return buffer\n }\n}\n\n// according to rfc4122#section-4.1.1\nfunction getVariant(bits: number) {\n switch (bits) {\n case 0:\n case 1:\n case 3:\n return \"ncs\"\n case 4:\n case 5:\n return \"rfc4122\"\n case 6:\n return \"microsoft\"\n default:\n return \"future\"\n }\n}\n\nenum UuidEncoding {\n ASCII,\n BINARY,\n OBJECT,\n}\n\n// v3 + v5\nfunction uuidNamed(name: string | Buffer, hashMethod: string, version: number, namespace: Buffer, encoding: UuidEncoding = UuidEncoding.ASCII) {\n const hash = createHash(hashMethod)\n\n const nameIsNotAString = typeof name !== \"string\"\n if (nameIsNotAString && !Buffer.isBuffer(name)) {\n throw newError(invalidName, \"ERR_INVALID_UUID_NAME\")\n }\n\n hash.update(namespace)\n hash.update(name)\n\n const buffer = hash.digest()\n let result: any\n switch (encoding) {\n case UuidEncoding.BINARY:\n buffer[6] = (buffer[6] & 0x0f) | version\n buffer[8] = (buffer[8] & 0x3f) | 0x80\n result = buffer\n break\n case UuidEncoding.OBJECT:\n buffer[6] = (buffer[6] & 0x0f) | version\n buffer[8] = (buffer[8] & 0x3f) | 0x80\n result = new UUID(buffer)\n break\n default:\n result =\n byte2hex[buffer[0]] +\n byte2hex[buffer[1]] +\n byte2hex[buffer[2]] +\n byte2hex[buffer[3]] +\n \"-\" +\n byte2hex[buffer[4]] +\n byte2hex[buffer[5]] +\n \"-\" +\n byte2hex[(buffer[6] & 0x0f) | version] +\n byte2hex[buffer[7]] +\n \"-\" +\n byte2hex[(buffer[8] & 0x3f) | 0x80] +\n byte2hex[buffer[9]] +\n \"-\" +\n byte2hex[buffer[10]] +\n byte2hex[buffer[11]] +\n byte2hex[buffer[12]] +\n byte2hex[buffer[13]] +\n byte2hex[buffer[14]] +\n byte2hex[buffer[15]]\n break\n }\n return result\n}\n\nfunction stringify(buffer: Buffer) {\n return (\n byte2hex[buffer[0]] +\n byte2hex[buffer[1]] +\n byte2hex[buffer[2]] +\n byte2hex[buffer[3]] +\n \"-\" +\n byte2hex[buffer[4]] +\n byte2hex[buffer[5]] +\n \"-\" +\n byte2hex[buffer[6]] +\n byte2hex[buffer[7]] +\n \"-\" +\n byte2hex[buffer[8]] +\n byte2hex[buffer[9]] +\n \"-\" +\n byte2hex[buffer[10]] +\n byte2hex[buffer[11]] +\n byte2hex[buffer[12]] +\n byte2hex[buffer[13]] +\n byte2hex[buffer[14]] +\n byte2hex[buffer[15]]\n )\n}\n\n// according to rfc4122#section-4.1.7\nexport const nil = new UUID(\"00000000-0000-0000-0000-000000000000\")\n\n// UUID.v4 = uuidRandom\n\n// UUID.v4fast = uuidRandomFast\n\n// UUID.v3 = function(options, callback) {\n// return uuidNamed(\"md5\", 0x30, options, callback)\n// }\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.XElement = void 0; exports.parseXml = parseXml; const sax = require("sax"); const error_1 = require("./error"); class XElement { constructor(name) { this.name = name; this.value = ""; this.attributes = null; this.isCData = false; this.elements = null; if (!name) { throw (0, error_1.newError)("Element name cannot be empty", "ERR_XML_ELEMENT_NAME_EMPTY"); } if (!isValidName(name)) { throw (0, error_1.newError)(`Invalid element name: ${name}`, "ERR_XML_ELEMENT_INVALID_NAME"); } } attribute(name) { const result = this.attributes === null ? null : this.attributes[name]; if (result == null) { throw (0, error_1.newError)(`No attribute "${name}"`, "ERR_XML_MISSED_ATTRIBUTE"); } return result; } removeAttribute(name) { if (this.attributes !== null) { delete this.attributes[name]; } } element(name, ignoreCase = false, errorIfMissed = null) { const result = this.elementOrNull(name, ignoreCase); if (result === null) { throw (0, error_1.newError)(errorIfMissed || `No element "${name}"`, "ERR_XML_MISSED_ELEMENT"); } return result; } elementOrNull(name, ignoreCase = false) { if (this.elements === null) { return null; } for (const element of this.elements) { if (isNameEquals(element, name, ignoreCase)) { return element; } } return null; } getElements(name, ignoreCase = false) { if (this.elements === null) { return []; } return this.elements.filter(it => isNameEquals(it, name, ignoreCase)); } elementValueOrEmpty(name, ignoreCase = false) { const element = this.elementOrNull(name, ignoreCase); return element === null ? "" : element.value; } } exports.XElement = XElement; const NAME_REG_EXP = new RegExp(/^[A-Za-z_][:A-Za-z0-9_-]*$/i); function isValidName(name) { return NAME_REG_EXP.test(name); } function isNameEquals(element, name, ignoreCase) { const elementName = element.name; return elementName === name || (ignoreCase === true && elementName.length === name.length && elementName.toLowerCase() === name.toLowerCase()); } function parseXml(data) { let rootElement = null; const parser = sax.parser(true, {}); const elements = []; parser.onopentag = saxElement => { const element = new XElement(saxElement.name); element.attributes = saxElement.attributes; if (rootElement === null) { rootElement = element; } else { const parent = elements[elements.length - 1]; if (parent.elements == null) { parent.elements = []; } parent.elements.push(element); } elements.push(element); }; parser.onclosetag = () => { elements.pop(); }; parser.ontext = text => { if (elements.length > 0) { elements[elements.length - 1].value = text; } }; parser.oncdata = cdata => { const element = elements[elements.length - 1]; element.value = cdata; element.isCData = true; }; parser.onerror = err => { throw err; }; parser.write(data); return rootElement; } //# sourceMappingURL=xml.js.map{"version":3,"file":"xml.js","sourceRoot":"","sources":["../src/xml.ts"],"names":[],"mappings":";;;AA8EA,4BA2CC;AAzHD,2BAA0B;AAC1B,mCAAkC;AAElC,MAAa,QAAQ;IAMnB,YAAqB,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;QALjC,UAAK,GAAG,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;QACvB,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;QAC7C,OAAO,CAAC,KAAK,GAAG,KAAK,CAAA;QACrB,OAAO,CAAC,OAAO,GAAG,IAAI,CAAA;IACxB,CAAC,CAAA;IAED,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC,EAAE;QACrB,MAAM,GAAG,CAAA;IACX,CAAC,CAAA;IAED,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAClB,OAAO,WAAY,CAAA;AACrB,CAAC","sourcesContent":["import * as sax from \"sax\"\nimport { newError } from \"./error\"\n\nexport class XElement {\n value = \"\"\n attributes: Record | null = null\n isCData = false\n elements: Array | null = null\n\n constructor(readonly name: string) {\n if (!name) {\n throw newError(\"Element name cannot be empty\", \"ERR_XML_ELEMENT_NAME_EMPTY\")\n }\n if (!isValidName(name)) {\n throw newError(`Invalid element name: ${name}`, \"ERR_XML_ELEMENT_INVALID_NAME\")\n }\n }\n\n attribute(name: string): string {\n const result = this.attributes === null ? null : this.attributes[name]\n if (result == null) {\n throw newError(`No attribute \"${name}\"`, \"ERR_XML_MISSED_ATTRIBUTE\")\n }\n return result\n }\n\n removeAttribute(name: string): void {\n if (this.attributes !== null) {\n delete this.attributes[name]\n }\n }\n\n element(name: string, ignoreCase = false, errorIfMissed: string | null = null): XElement {\n const result = this.elementOrNull(name, ignoreCase)\n if (result === null) {\n throw newError(errorIfMissed || `No element \"${name}\"`, \"ERR_XML_MISSED_ELEMENT\")\n }\n return result\n }\n\n elementOrNull(name: string, ignoreCase = false): XElement | null {\n if (this.elements === null) {\n return null\n }\n\n for (const element of this.elements) {\n if (isNameEquals(element, name, ignoreCase)) {\n return element\n }\n }\n\n return null\n }\n\n getElements(name: string, ignoreCase = false) {\n if (this.elements === null) {\n return []\n }\n return this.elements.filter(it => isNameEquals(it, name, ignoreCase))\n }\n\n elementValueOrEmpty(name: string, ignoreCase = false): string {\n const element = this.elementOrNull(name, ignoreCase)\n return element === null ? \"\" : element.value\n }\n}\n\nconst NAME_REG_EXP = new RegExp(/^[A-Za-z_][:A-Za-z0-9_-]*$/i)\n\nfunction isValidName(name: string) {\n return NAME_REG_EXP.test(name)\n}\n\nfunction isNameEquals(element: XElement, name: string, ignoreCase: boolean) {\n const elementName = element.name\n return elementName === name || (ignoreCase === true && elementName.length === name.length && elementName.toLowerCase() === name.toLowerCase())\n}\n\nexport function parseXml(data: string): XElement {\n let rootElement: XElement | null = null\n const parser = sax.parser(true, {})\n const elements: Array = []\n\n parser.onopentag = saxElement => {\n const element = new XElement(saxElement.name)\n element.attributes = saxElement.attributes as Record\n\n if (rootElement === null) {\n rootElement = element\n } else {\n const parent = elements[elements.length - 1]\n if (parent.elements == null) {\n parent.elements = []\n }\n parent.elements.push(element)\n }\n elements.push(element)\n }\n\n parser.onclosetag = () => {\n elements.pop()\n }\n\n parser.ontext = text => {\n if (elements.length > 0) {\n elements[elements.length - 1].value = text\n }\n }\n\n parser.oncdata = cdata => {\n const element = elements[elements.length - 1]\n element.value = cdata\n element.isCData = true\n }\n\n parser.onerror = err => {\n throw err\n }\n\n parser.write(data)\n return rootElement!\n}\n"]}{ "name": "builder-util-runtime", "version": "9.6.3", "main": "out/index.js", "author": "Vladimir Krivosheev", "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/electron-userland/electron-builder.git", "directory": "packages/builder-util-runtime" }, "homepage": "https://github.com/electron-userland/electron-builder", "files": [ "out" ], "engines": { "node": ">=12.0.0" }, "dependencies": { "debug": "^4.3.4", "sax": "^1.2.4" }, "devDependencies": { "@types/debug": "4.1.7", "@types/sax": "1.2.3" }, "types": "./out/index.d.ts" }/* eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/no-unsafe-return */ import { isDeepStrictEqual } from 'node:util'; import process from 'node:process'; import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; import assert from 'node:assert'; import { getProperty, hasProperty, setProperty, deleteProperty, } from 'dot-prop'; import envPaths from 'env-paths'; import { writeFileSync as atomicWriteFileSync } from 'atomically'; import { Ajv2020 as Ajv } from 'ajv/dist/2020.js'; import ajvFormatsModule from 'ajv-formats'; import debounceFn from 'debounce-fn'; import semver from 'semver'; import { concatUint8Arrays, stringToUint8Array, uint8ArrayToString, } from 'uint8array-extras'; const defaultEncryptionAlgorithm = 'aes-256-cbc'; const supportedEncryptionAlgorithms = new Set([ 'aes-256-cbc', 'aes-256-gcm', 'aes-256-ctr', ]); const isSupportedEncryptionAlgorithm = (value) => typeof value === 'string' && supportedEncryptionAlgorithms.has(value); const createPlainObject = () => Object.create(null); const isExist = (data) => data !== undefined; const checkValueType = (key, value) => { const nonJsonTypes = new Set([ 'undefined', 'symbol', 'function', ]); const type = typeof value; if (nonJsonTypes.has(type)) { throw new TypeError(`Setting a value of type \`${type}\` for key \`${key}\` is not allowed as it's not supported by JSON`); } }; const INTERNAL_KEY = '__internal__'; const MIGRATION_KEY = `${INTERNAL_KEY}.migrations.version`; export default class Conf { path; events; #validator; #encryptionKey; #encryptionAlgorithm; #options; #defaultValues = {}; #isInMigration = false; #watcher; #watchFile; #debouncedChangeHandler; constructor(partialOptions = {}) { const options = this.#prepareOptions(partialOptions); this.#options = options; this.#setupValidator(options); this.#applyDefaultValues(options); this.#configureSerialization(options); this.events = new EventTarget(); this.#encryptionKey = options.encryptionKey; this.#encryptionAlgorithm = options.encryptionAlgorithm ?? defaultEncryptionAlgorithm; this.path = this.#resolvePath(options); this.#initializeStore(options); if (options.watch) { this._watch(); } } get(key, defaultValue) { if (this.#options.accessPropertiesByDotNotation) { return this._get(key, defaultValue); } const { store } = this; return key in store ? store[key] : defaultValue; } set(key, value) { if (typeof key !== 'string' && typeof key !== 'object') { throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof key}`); } if (typeof key !== 'object' && value === undefined) { throw new TypeError('Use `delete()` to clear values'); } if (this._containsReservedKey(key)) { throw new TypeError(`Please don't use the ${INTERNAL_KEY} key, as it's used to manage this module internal operations.`); } const { store } = this; const set = (key, value) => { checkValueType(key, value); if (this.#options.accessPropertiesByDotNotation) { setProperty(store, key, value); } else { if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return; } store[key] = value; } }; if (typeof key === 'object') { const object = key; for (const [key, value] of Object.entries(object)) { set(key, value); } } else { set(key, value); } this.store = store; } has(key) { if (this.#options.accessPropertiesByDotNotation) { return hasProperty(this.store, key); } return key in this.store; } appendToArray(key, value) { checkValueType(key, value); const array = this.#options.accessPropertiesByDotNotation ? this._get(key, []) : (key in this.store ? this.store[key] : []); if (!Array.isArray(array)) { throw new TypeError(`The key \`${key}\` is already set to a non-array value`); } this.set(key, [...array, value]); } /** Reset items to their default values, as defined by the `defaults` or `schema` option. @see `clear()` to reset all items. @param keys - The keys of the items to reset. */ reset(...keys) { for (const key of keys) { if (isExist(this.#defaultValues[key])) { this.set(key, this.#defaultValues[key]); } } } delete(key) { const { store } = this; if (this.#options.accessPropertiesByDotNotation) { deleteProperty(store, key); } else { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete store[key]; } this.store = store; } /** Delete all items. This resets known items to their default values, if defined by the `defaults` or `schema` option. */ clear() { const newStore = createPlainObject(); for (const key of Object.keys(this.#defaultValues)) { if (isExist(this.#defaultValues[key])) { checkValueType(key, this.#defaultValues[key]); if (this.#options.accessPropertiesByDotNotation) { setProperty(newStore, key, this.#defaultValues[key]); } else { newStore[key] = this.#defaultValues[key]; } } } this.store = newStore; } onDidChange(key, callback) { if (typeof key !== 'string') { throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof key}`); } if (typeof callback !== 'function') { throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`); } return this._handleValueChange(() => this.get(key), callback); } /** Watches the whole config object, calling `callback` on any changes. @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`. @returns A function, that when called, will unsubscribe. */ onDidAnyChange(callback) { if (typeof callback !== 'function') { throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`); } return this._handleStoreChange(callback); } get size() { const entries = Object.keys(this.store); return entries.filter(key => !this._isReservedKeyPath(key)).length; } /** Get all the config as an object or replace the current config with an object. @example ``` console.log(config.store); //=> {name: 'John', age: 30} ``` @example ``` config.store = { hello: 'world' }; ``` */ get store() { try { const data = fs.readFileSync(this.path, this.#encryptionKey ? null : 'utf8'); const dataString = this._decryptData(data); const parseStore = (value) => { const deserializedData = this._deserialize(value); if (!this.#isInMigration) { this._validate(deserializedData); } return Object.assign(createPlainObject(), deserializedData); }; return parseStore(dataString); } catch (error) { if (error?.code === 'ENOENT') { this._ensureDirectory(); return createPlainObject(); } if (this.#options.clearInvalidConfig) { const errorInstance = error; // Handle JSON parsing errors (existing behavior) if (errorInstance.name === 'SyntaxError') { return createPlainObject(); } // Handle schema validation errors (new behavior) if (errorInstance.message?.startsWith('Config schema violation:')) { return createPlainObject(); } if (errorInstance.message === 'Failed to decrypt config data.') { return createPlainObject(); } } throw error; } } set store(value) { this._ensureDirectory(); // Preserve existing internal data if it exists and the new value doesn't contain it if (!hasProperty(value, INTERNAL_KEY)) { try { // Read directly from file to avoid recursion during migration const data = fs.readFileSync(this.path, this.#encryptionKey ? null : 'utf8'); const dataString = this._decryptData(data); const currentStore = this._deserialize(dataString); if (hasProperty(currentStore, INTERNAL_KEY)) { setProperty(value, INTERNAL_KEY, getProperty(currentStore, INTERNAL_KEY)); } } catch { // Silently ignore errors when trying to preserve internal data // This could happen if the file doesn't exist yet or is corrupted // In these cases, we just proceed without preserving internal data } } if (!this.#isInMigration) { this._validate(value); } this._write(value); this.events.dispatchEvent(new Event('change')); } *[Symbol.iterator]() { for (const [key, value] of Object.entries(this.store)) { if (!this._isReservedKeyPath(key)) { yield [key, value]; } } } /** Close the file watcher if one exists. This is useful in tests to prevent the process from hanging. */ _closeWatcher() { if (this.#watcher) { this.#watcher.close(); this.#watcher = undefined; } if (this.#watchFile) { fs.unwatchFile(this.path); this.#watchFile = false; } this.#debouncedChangeHandler = undefined; } _decryptData(data) { const encryptionKey = this.#encryptionKey; if (!encryptionKey) { return typeof data === 'string' ? data : uint8ArrayToString(data); } // Check if an initialization vector has been used to encrypt the data. const encryptionAlgorithm = this.#encryptionAlgorithm; const authenticationTagLength = encryptionAlgorithm === 'aes-256-gcm' ? 16 : 0; const separatorCodePoint = ':'.codePointAt(0); const separatorByte = typeof data === 'string' ? data.codePointAt(16) : data[16]; const hasSeparator = separatorCodePoint !== undefined && separatorByte === separatorCodePoint; if (!hasSeparator) { if (encryptionAlgorithm === 'aes-256-cbc') { return typeof data === 'string' ? data : uint8ArrayToString(data); } throw new Error('Failed to decrypt config data.'); } const getEncryptedPayload = (dataUpdate) => { if (authenticationTagLength === 0) { return { ciphertext: dataUpdate }; } const authenticationTagStart = dataUpdate.length - authenticationTagLength; if (authenticationTagStart < 0) { throw new Error('Invalid authentication tag length.'); } return { ciphertext: dataUpdate.slice(0, authenticationTagStart), authenticationTag: dataUpdate.slice(authenticationTagStart), }; }; const initializationVector = data.slice(0, 16); const slice = data.slice(17); const dataUpdate = typeof slice === 'string' ? stringToUint8Array(slice) : slice; const decrypt = (salt) => { const { ciphertext, authenticationTag } = getEncryptedPayload(dataUpdate); const password = crypto.pbkdf2Sync(encryptionKey, salt, 10_000, 32, 'sha512'); const decipher = crypto.createDecipheriv(encryptionAlgorithm, password, initializationVector); if (authenticationTag) { decipher.setAuthTag(authenticationTag); } return uint8ArrayToString(concatUint8Arrays([decipher.update(ciphertext), decipher.final()])); }; try { return decrypt(initializationVector); } catch { try { // Fallback to legacy scheme (iv.toString() as salt) return decrypt(initializationVector.toString()); } catch { } } if (encryptionAlgorithm === 'aes-256-cbc') { return typeof data === 'string' ? data : uint8ArrayToString(data); } throw new Error('Failed to decrypt config data.'); } _handleStoreChange(callback) { let currentValue = this.store; const onChange = () => { const oldValue = currentValue; const newValue = this.store; if (isDeepStrictEqual(newValue, oldValue)) { return; } currentValue = newValue; callback.call(this, newValue, oldValue); }; this.events.addEventListener('change', onChange); return () => { this.events.removeEventListener('change', onChange); }; } _handleValueChange(getter, callback) { let currentValue = getter(); const onChange = () => { const oldValue = currentValue; const newValue = getter(); if (isDeepStrictEqual(newValue, oldValue)) { return; } currentValue = newValue; callback.call(this, newValue, oldValue); }; this.events.addEventListener('change', onChange); return () => { this.events.removeEventListener('change', onChange); }; } _deserialize = value => JSON.parse(value); _serialize = value => JSON.stringify(value, undefined, '\t'); _validate(data) { if (!this.#validator) { return; } const valid = this.#validator(data); if (valid || !this.#validator.errors) { return; } const errors = this.#validator.errors .map(({ instancePath, message = '' }) => `\`${instancePath.slice(1)}\` ${message}`); throw new Error('Config schema violation: ' + errors.join('; ')); } _ensureDirectory() { // Ensure the directory exists as it could have been deleted in the meantime. fs.mkdirSync(path.dirname(this.path), { recursive: true }); } _write(value) { let data = this._serialize(value); const encryptionKey = this.#encryptionKey; if (encryptionKey) { const initializationVector = crypto.randomBytes(16); const password = crypto.pbkdf2Sync(encryptionKey, initializationVector, 10_000, 32, 'sha512'); const cipher = crypto.createCipheriv(this.#encryptionAlgorithm, password, initializationVector); const encryptedData = concatUint8Arrays([cipher.update(stringToUint8Array(data)), cipher.final()]); const encryptedParts = [initializationVector, stringToUint8Array(':'), encryptedData]; if (this.#encryptionAlgorithm === 'aes-256-gcm') { encryptedParts.push(cipher.getAuthTag()); } data = concatUint8Arrays(encryptedParts); } // Temporary workaround for Conf being packaged in a Ubuntu Snap app. // See https://github.com/sindresorhus/conf/pull/82 if (process.env.SNAP) { fs.writeFileSync(this.path, data, { mode: this.#options.configFileMode }); } else { try { atomicWriteFileSync(this.path, data, { mode: this.#options.configFileMode }); } catch (error) { // Fix for https://github.com/sindresorhus/electron-store/issues/106 // Sometimes on Windows, we will get an EXDEV error when atomic writing // (even though to the same directory), so we fall back to non atomic write if (error?.code === 'EXDEV') { fs.writeFileSync(this.path, data, { mode: this.#options.configFileMode }); return; } throw error; } } } _watch() { this._ensureDirectory(); if (!fs.existsSync(this.path)) { this._write(createPlainObject()); } // Use fs.watch on Windows and macOS, fs.watchFile on Linux for better reliability if (process.platform === 'win32' || process.platform === 'darwin') { this.#debouncedChangeHandler ??= debounceFn(() => { this.events.dispatchEvent(new Event('change')); }, { wait: 100 }); // Watch the directory instead of the file to handle atomic writes (rename events) const directory = path.dirname(this.path); const basename = path.basename(this.path); this.#watcher = fs.watch(directory, { persistent: false, encoding: 'utf8' }, (_eventType, filename) => { if (filename && filename !== basename) { return; } if (typeof this.#debouncedChangeHandler === 'function') { this.#debouncedChangeHandler(); } }); } else { // Fs.watchFile is used on Linux for better cross-platform reliability this.#debouncedChangeHandler ??= debounceFn(() => { this.events.dispatchEvent(new Event('change')); }, { wait: 1000 }); fs.watchFile(this.path, { persistent: false }, (_current, _previous) => { if (typeof this.#debouncedChangeHandler === 'function') { this.#debouncedChangeHandler(); } }); this.#watchFile = true; } } _migrate(migrations, versionToMigrate, beforeEachMigration) { let previousMigratedVersion = this._get(MIGRATION_KEY, '0.0.0'); const newerVersions = Object.keys(migrations) .filter(candidateVersion => this._shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate)); let storeBackup = structuredClone(this.store); for (const version of newerVersions) { try { if (beforeEachMigration) { beforeEachMigration(this, { fromVersion: previousMigratedVersion, toVersion: version, finalVersion: versionToMigrate, versions: newerVersions, }); } const migration = migrations[version]; migration?.(this); this._set(MIGRATION_KEY, version); previousMigratedVersion = version; storeBackup = structuredClone(this.store); } catch (error) { // Restore backup (validation is skipped during migration) this.store = storeBackup; const errorMessage = error instanceof Error ? error.message : String(error); throw new Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${errorMessage}`); } } if (this._isVersionInRangeFormat(previousMigratedVersion) || !semver.eq(previousMigratedVersion, versionToMigrate)) { this._set(MIGRATION_KEY, versionToMigrate); } } _containsReservedKey(key) { if (typeof key === 'string') { return this._isReservedKeyPath(key); } if (!key || typeof key !== 'object') { return false; } return this._objectContainsReservedKey(key); } _objectContainsReservedKey(value) { if (!value || typeof value !== 'object') { return false; } for (const [candidateKey, candidateValue] of Object.entries(value)) { if (this._isReservedKeyPath(candidateKey)) { return true; } if (this._objectContainsReservedKey(candidateValue)) { return true; } } return false; } _isReservedKeyPath(candidate) { return candidate === INTERNAL_KEY || candidate.startsWith(`${INTERNAL_KEY}.`); } _isVersionInRangeFormat(version) { return semver.clean(version) === null; } _shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate) { if (this._isVersionInRangeFormat(candidateVersion)) { if (previousMigratedVersion !== '0.0.0' && semver.satisfies(previousMigratedVersion, candidateVersion)) { return false; } return semver.satisfies(versionToMigrate, candidateVersion); } if (semver.lte(candidateVersion, previousMigratedVersion)) { return false; } if (semver.gt(candidateVersion, versionToMigrate)) { return false; } return true; } _get(key, defaultValue) { return getProperty(this.store, key, defaultValue); } _set(key, value) { const { store } = this; setProperty(store, key, value); this.store = store; } #prepareOptions(partialOptions) { const options = { configName: 'config', fileExtension: 'json', projectSuffix: 'nodejs', clearInvalidConfig: false, accessPropertiesByDotNotation: true, configFileMode: 0o666, ...partialOptions, }; options.encryptionAlgorithm ??= defaultEncryptionAlgorithm; if (!isSupportedEncryptionAlgorithm(options.encryptionAlgorithm)) { throw new TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...supportedEncryptionAlgorithms].join(', ')}`); } if (!options.cwd) { if (!options.projectName) { throw new Error('Please specify the `projectName` option.'); } options.cwd = envPaths(options.projectName, { suffix: options.projectSuffix }).config; } if (typeof options.fileExtension === 'string') { options.fileExtension = options.fileExtension.replace(/^\.+/, ''); } return options; } #setupValidator(options) { if (!(options.schema ?? options.ajvOptions ?? options.rootSchema)) { return; } if (options.schema && typeof options.schema !== 'object') { throw new TypeError('The `schema` option must be an object.'); } // Workaround for https://github.com/ajv-validator/ajv/issues/2047 const ajvFormats = ajvFormatsModule.default; const ajv = new Ajv({ allErrors: true, useDefaults: true, ...options.ajvOptions, }); ajvFormats(ajv); const schema = { ...options.rootSchema, type: 'object', properties: options.schema, }; this.#validator = ajv.compile(schema); this.#captureSchemaDefaults(options.schema); } #captureSchemaDefaults(schemaConfig) { const schemaEntries = Object.entries(schemaConfig ?? {}); for (const [key, schemaDefinition] of schemaEntries) { if (!schemaDefinition || typeof schemaDefinition !== 'object') { continue; } if (!Object.hasOwn(schemaDefinition, 'default')) { continue; } const { default: defaultValue } = schemaDefinition; if (defaultValue === undefined) { continue; } this.#defaultValues[key] = defaultValue; } } #applyDefaultValues(options) { if (options.defaults) { Object.assign(this.#defaultValues, options.defaults); } } #configureSerialization(options) { if (options.serialize) { this._serialize = options.serialize; } if (options.deserialize) { this._deserialize = options.deserialize; } } #resolvePath(options) { const normalizedFileExtension = typeof options.fileExtension === 'string' ? options.fileExtension : undefined; const fileExtension = normalizedFileExtension ? `.${normalizedFileExtension}` : ''; return path.resolve(options.cwd, `${options.configName ?? 'config'}${fileExtension}`); } #initializeStore(options) { if (options.migrations) { this.#runMigrations(options); this._validate(this.store); return; } const fileStore = this.store; const storeWithDefaults = Object.assign(createPlainObject(), options.defaults ?? {}, fileStore); this._validate(storeWithDefaults); try { assert.deepEqual(fileStore, storeWithDefaults); } catch { this.store = storeWithDefaults; } } #runMigrations(options) { const { migrations, projectVersion } = options; if (!migrations) { return; } if (!projectVersion) { throw new Error('Please specify the `projectVersion` option.'); } this.#isInMigration = true; try { const fileStore = this.store; const storeWithDefaults = Object.assign(createPlainObject(), options.defaults ?? {}, fileStore); try { assert.deepEqual(fileStore, storeWithDefaults); } catch { this._write(storeWithDefaults); } this._migrate(migrations, projectVersion, options.beforeEachMigration); } finally { this.#isInMigration = false; } } } export {}; MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "conf", "version": "15.1.0", "description": "Simple config handling for your app or module", "license": "MIT", "repository": "sindresorhus/conf", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./dist/source/index.d.ts", "default": "./dist/source/index.js" }, "sideEffects": false, "engines": { "node": ">=20" }, "files": [ "dist/source" ], "dependencies": { "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "atomically": "^2.0.3", "debounce-fn": "^6.0.0", "dot-prop": "^10.0.0", "env-paths": "^3.0.0", "json-schema-typed": "^8.0.1", "semver": "^7.7.2", "uint8array-extras": "^1.5.0" }, "devDependencies": { "@sindresorhus/tsconfig": "^8.0.1", "@types/node": "^24.5.2", "@types/semver": "^7.7.1", "del": "^8.0.1", "del-cli": "^7.0.0", "delay": "^6.0.0", "expect-type": "^1.2.2", "p-event": "^7.0.0", "tempy": "^3.1.0", "ts-node": "^10.9.2", "tsx": "^4.20.6", "typescript": "^5.9.2", "xo": "^1.2.2" } }import mimicFunction from 'mimic-function'; const debounceFunction = (inputFunction, options = {}) => { if (typeof inputFunction !== 'function') { throw new TypeError(`Expected the first argument to be a function, got \`${typeof inputFunction}\``); } const { wait = 0, maxWait = Number.POSITIVE_INFINITY, before = false, after = true, } = options; if (wait < 0 || maxWait < 0) { throw new RangeError('`wait` and `maxWait` must not be negative.'); } if (!before && !after) { throw new Error('Both `before` and `after` are false, function wouldn\'t be called.'); } let timeout; let maxTimeout; let result; const debouncedFunction = function (...arguments_) { const context = this; // eslint-disable-line unicorn/no-this-assignment const later = () => { timeout = undefined; if (maxTimeout) { clearTimeout(maxTimeout); maxTimeout = undefined; } if (after) { result = inputFunction.apply(context, arguments_); } }; const maxLater = () => { maxTimeout = undefined; if (timeout) { clearTimeout(timeout); timeout = undefined; } if (after) { result = inputFunction.apply(context, arguments_); } }; const shouldCallNow = before && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (maxWait > 0 && maxWait !== Number.POSITIVE_INFINITY && !maxTimeout) { maxTimeout = setTimeout(maxLater, maxWait); } if (shouldCallNow) { result = inputFunction.apply(context, arguments_); } return result; }; mimicFunction(debouncedFunction, inputFunction); debouncedFunction.cancel = () => { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (maxTimeout) { clearTimeout(maxTimeout); maxTimeout = undefined; } }; return debouncedFunction; }; export default debounceFunction; MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "debounce-fn", "version": "6.0.0", "description": "Debounce a function", "license": "MIT", "repository": "sindresorhus/debounce-fn", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "files": [ "index.js", "index.d.ts" ], "dependencies": { "mimic-function": "^5.0.0" }, "devDependencies": { "ava": "^5.3.1", "delay": "^6.0.0", "tsd": "^0.29.0", "xo": "^0.56.0" } }(The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk Copyright (c) 2018-2021 Josh Junon 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. { "name": "debug", "version": "4.4.1", "repository": { "type": "git", "url": "git://github.com/debug-js/debug.git" }, "description": "Lightweight debugging utility for Node.js and the browser", "files": [ "src", "LICENSE", "README.md" ], "author": "Josh Junon (https://github.com/qix-)", "license": "MIT", "dependencies": { "ms": "^2.1.3" }, "devDependencies": { "brfs": "^2.0.1", "browserify": "^16.2.3", "coveralls": "^3.0.2", "karma": "^3.1.4", "karma-browserify": "^6.0.0", "karma-chrome-launcher": "^2.2.0", "karma-mocha": "^1.3.0", "mocha": "^5.2.0", "mocha-lcov-reporter": "^1.2.0", "sinon": "^14.0.0", "xo": "^0.23.0" }, "peerDependenciesMeta": { "supports-color": { "optional": true } }, "main": "./src/index.js", "browser": "./src/browser.js", "engines": { "node": ">=6.0" } }/* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 // eslint-disable-next-line no-return-assign return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require('ms'); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === 'string' ? namespaces : '') .trim() .replace(/\s+/g, ',') .split(',') .filter(Boolean); for (const ns of split) { if (ns[0] === '-') { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } /** * Checks if the given string matches a namespace template, honoring * asterisks as wildcards. * * @param {String} search * @param {String} template * @return {Boolean} */ function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { // Match character or proceed with wildcard if (template[templateIndex] === '*') { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; // Skip the '*' } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition // Backtrack to the last '*' and try to match more characters templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; // No match } } // Handle trailing '*' in template while (templateIndex < template.length && template[templateIndex] === '*') { templateIndex++; } return templateIndex === template.length; } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = require('./browser.js'); } else { module.exports = require('./node.js'); } /** * Module dependencies. */ const tty = require('tty'); const util = require('util'); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; const isObject = value => { const type = typeof value; return value !== null && (type === 'object' || type === 'function'); }; // Optimized empty check without creating an array. const isEmptyObject = value => { if (!isObject(value)) { return false; } for (const key in value) { if (Object.hasOwn(value, key)) { return false; } } return true; }; const disallowedKeys = new Set([ '__proto__', 'prototype', 'constructor', ]); // Maximum allowed array index to prevent DoS via memory exhaustion. const MAX_ARRAY_INDEX = 1_000_000; // Optimized digit check without Set overhead. const isDigit = character => character >= '0' && character <= '9'; // Check if a segment should be coerced to a number. function shouldCoerceToNumber(segment) { // Only coerce valid non-negative integers without leading zeros. if (segment === '0') { return true; } if (/^[1-9]\d*$/.test(segment)) { const parsedNumber = Number.parseInt(segment, 10); // Check within safe integer range and under MAX_ARRAY_INDEX to prevent DoS. return parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX; } return false; } // Helper to process a path segment (eliminates duplication). function processSegment(segment, parts) { if (disallowedKeys.has(segment)) { return false; // Signal to return empty array. } if (segment && shouldCoerceToNumber(segment)) { parts.push(Number.parseInt(segment, 10)); } else { parts.push(segment); } return true; } export function parsePath(path) { // eslint-disable-line complexity if (typeof path !== 'string') { throw new TypeError(`Expected a string, got ${typeof path}`); } const parts = []; let currentSegment = ''; let currentPart = 'start'; let isEscaping = false; let position = 0; for (const character of path) { position++; // Handle escaping. if (isEscaping) { currentSegment += character; isEscaping = false; continue; } // Handle escape character. if (character === '\\') { if (currentPart === 'index') { throw new Error(`Invalid character '${character}' in an index at position ${position}`); } if (currentPart === 'indexEnd') { throw new Error(`Invalid character '${character}' after an index at position ${position}`); } isEscaping = true; currentPart = currentPart === 'start' ? 'property' : currentPart; continue; } switch (character) { case '.': { if (currentPart === 'index') { throw new Error(`Invalid character '${character}' in an index at position ${position}`); } if (currentPart === 'indexEnd') { currentPart = 'property'; break; } if (!processSegment(currentSegment, parts)) { return []; } currentSegment = ''; currentPart = 'property'; break; } case '[': { if (currentPart === 'index') { throw new Error(`Invalid character '${character}' in an index at position ${position}`); } if (currentPart === 'indexEnd') { currentPart = 'index'; break; } if (currentPart === 'property' || currentPart === 'start') { // Only push if we have content OR if we're in 'property' mode (not 'start') if ((currentSegment || currentPart === 'property') && !processSegment(currentSegment, parts)) { return []; } currentSegment = ''; } currentPart = 'index'; break; } case ']': { if (currentPart === 'index') { if (currentSegment === '') { // Empty brackets - backtrack and treat as literal const lastSegment = parts.pop() || ''; currentSegment = lastSegment + '[]'; currentPart = 'property'; } else { // Index must be digits only (enforced by default case) const parsedNumber = Number.parseInt(currentSegment, 10); const isValidInteger = !Number.isNaN(parsedNumber) && Number.isFinite(parsedNumber) && parsedNumber >= 0 && parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX && currentSegment === String(parsedNumber); if (isValidInteger) { parts.push(parsedNumber); } else { // Keep as string if not a valid integer representation or exceeds MAX_ARRAY_INDEX parts.push(currentSegment); } currentSegment = ''; currentPart = 'indexEnd'; } break; } if (currentPart === 'indexEnd') { throw new Error(`Invalid character '${character}' after an index at position ${position}`); } // In property context, treat ] as literal character currentSegment += character; break; } default: { if (currentPart === 'index' && !isDigit(character)) { throw new Error(`Invalid character '${character}' in an index at position ${position}`); } if (currentPart === 'indexEnd') { throw new Error(`Invalid character '${character}' after an index at position ${position}`); } if (currentPart === 'start') { currentPart = 'property'; } currentSegment += character; } } } // Handle unfinished escaping (trailing backslash) if (isEscaping) { currentSegment += '\\'; } // Handle end of path switch (currentPart) { case 'property': { if (!processSegment(currentSegment, parts)) { return []; } break; } case 'index': { throw new Error('Index was not closed'); } case 'start': { parts.push(''); break; } // No default } return parts; } function normalizePath(path) { if (typeof path === 'string') { return parsePath(path); } if (Array.isArray(path)) { const normalized = []; for (const [index, segment] of path.entries()) { // Type validation. if (typeof segment !== 'string' && typeof segment !== 'number') { throw new TypeError(`Expected a string or number for path segment at index ${index}, got ${typeof segment}`); } // Validate numbers are finite (reject NaN, Infinity, -Infinity). if (typeof segment === 'number' && !Number.isFinite(segment)) { throw new TypeError(`Path segment at index ${index} must be a finite number, got ${segment}`); } // Check for disallowed keys. if (disallowedKeys.has(segment)) { return []; } // Normalize numeric strings to numbers for simplicity. // This treats ['items', '0'] the same as ['items', 0]. if (typeof segment === 'string' && shouldCoerceToNumber(segment)) { normalized.push(Number.parseInt(segment, 10)); } else { normalized.push(segment); } } return normalized; } return []; } export function getProperty(object, path, value) { if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) { return value === undefined ? object : value; } const pathArray = normalizePath(path); if (pathArray.length === 0) { return value; } for (let index = 0; index < pathArray.length; index++) { const key = pathArray[index]; object = object[key]; if (object === undefined || object === null) { // Return default value if we hit undefined/null before the end of the path. // This ensures get({foo: null}, 'foo.bar') returns the default value, not null. if (index !== pathArray.length - 1) { return value; } break; } } return object === undefined ? value : object; } export function setProperty(object, path, value) { if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) { return object; } const root = object; const pathArray = normalizePath(path); if (pathArray.length === 0) { return object; } for (let index = 0; index < pathArray.length; index++) { const key = pathArray[index]; if (index === pathArray.length - 1) { object[key] = value; } else if (!isObject(object[key])) { const nextKey = pathArray[index + 1]; // Create arrays for numeric indices, objects for string keys const shouldCreateArray = typeof nextKey === 'number'; object[key] = shouldCreateArray ? [] : {}; } object = object[key]; } return root; } export function deleteProperty(object, path) { if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) { return false; } const pathArray = normalizePath(path); if (pathArray.length === 0) { return false; } for (let index = 0; index < pathArray.length; index++) { const key = pathArray[index]; if (index === pathArray.length - 1) { const existed = Object.hasOwn(object, key); if (!existed) { return false; } delete object[key]; return true; } object = object[key]; if (!isObject(object)) { return false; } } } export function hasProperty(object, path) { if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) { return false; } const pathArray = normalizePath(path); if (pathArray.length === 0) { return false; } for (const key of pathArray) { if (!isObject(object) || !(key in object)) { return false; } object = object[key]; } return true; } export function escapePath(path) { if (typeof path !== 'string') { throw new TypeError(`Expected a string, got ${typeof path}`); } // Escape special characters in one pass return path.replaceAll(/[\\.[]/g, String.raw`\$&`); } function normalizeEntries(value) { const entries = Object.entries(value); if (Array.isArray(value)) { return entries.map(([key, entryValue]) => { // Use shouldCoerceToNumber for consistency with parsePath const normalizedKey = shouldCoerceToNumber(key) ? Number.parseInt(key, 10) : key; return [normalizedKey, entryValue]; }); } return entries; } export function stringifyPath(pathSegments, options = {}) { if (!Array.isArray(pathSegments)) { throw new TypeError(`Expected an array, got ${typeof pathSegments}`); } const {preferDotForIndices = false} = options; const parts = []; for (const [index, segment] of pathSegments.entries()) { // Validate segment types at runtime if (typeof segment !== 'string' && typeof segment !== 'number') { throw new TypeError(`Expected a string or number for path segment at index ${index}, got ${typeof segment}`); } if (typeof segment === 'number') { // Handle numeric indices if (!Number.isInteger(segment) || segment < 0) { // Non-integer or negative numbers are treated as string keys const escaped = escapePath(String(segment)); parts.push(index === 0 ? escaped : `.${escaped}`); } else if (preferDotForIndices && index > 0) { parts.push(`.${segment}`); } else { parts.push(`[${segment}]`); } } else if (typeof segment === 'string') { if (segment === '') { // Empty string handling if (index === 0) { // Start with empty string, no prefix needed } else { parts.push('.'); } } else if (shouldCoerceToNumber(segment)) { // Numeric strings are normalized to numbers const numericValue = Number.parseInt(segment, 10); if (preferDotForIndices && index > 0) { parts.push(`.${numericValue}`); } else { parts.push(`[${numericValue}]`); } } else { // Regular strings use dot notation const escaped = escapePath(segment); parts.push(index === 0 ? escaped : `.${escaped}`); } } } return parts.join(''); } function * deepKeysIterator(object, currentPath = [], ancestors = new Set()) { if (!isObject(object) || isEmptyObject(object)) { if (currentPath.length > 0) { yield stringifyPath(currentPath); } return; } // Check if this object is already in the current path (circular reference) if (ancestors.has(object)) { return; } // Add to ancestors, recurse, then remove (backtrack) ancestors.add(object); // Reuse currentPath array by push/pop instead of creating new arrays for (const [key, value] of normalizeEntries(object)) { currentPath.push(key); yield * deepKeysIterator(value, currentPath, ancestors); currentPath.pop(); } ancestors.delete(object); } export function deepKeys(object) { return [...deepKeysIterator(object)]; } export function unflatten(object) { const result = {}; if (!isObject(object)) { return result; } for (const [path, value] of Object.entries(object)) { setProperty(result, path, value); } return result; } MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "dot-prop", "version": "10.1.0", "description": "Get, set, or delete a property from a nested object using a dot path", "license": "MIT", "repository": "sindresorhus/dot-prop", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=20" }, "files": [ "index.js", "index.d.ts" ], "dependencies": { "type-fest": "^5.0.0" }, "devDependencies": { "ava": "^6.4.1", "benchmark": "^2.1.4", "c8": "^10.1.3", "expect-type": "^1.2.2", "typescript": "^5.9.2", "xo": "^1.2.2" } }The MIT License (MIT) Copyright (c) 2016 Alexey Prokhorov 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.'use strict'; const main = require('./src/main'); module.exports = main; 'use strict'; const node = require('./src/node'); module.exports = node; { "name": "electron-log", "version": "5.4.4", "description": "Just a simple logging module for your Electron application", "main": "src/index.js", "browser": "src/renderer/index.js", "engines": { "node": ">= 14" }, "typings": "src/index.d.ts", "repository": "megahertz/electron-log", "files": [ "src/*", "!**/__specs__", "!**/.*", "main.js", "main.d.ts", "node.js", "node.d.ts", "preload.js", "renderer.js", "renderer.d.ts" ], "author": "Alexey Prokhorov", "license": "MIT", "homepage": "https://github.com/megahertz/electron-log#readme", "exports": { ".": { "types": "./src/index.d.ts", "browser": "./src/renderer/index.js", "default": "./src/index.js" }, "./*": "./*", "./main": { "types": "./main.d.ts", "default": "./main.js" }, "./node": { "types": "./node.d.ts", "default": "./node.js" }, "./preload": "./preload.js", "./renderer": { "types": "./renderer.d.ts", "default": "./renderer.js" } }, "devDependencies": { "@types/node": "^20.10.6", "electron": "*", "eslint": "^8.56.0", "eslint-config-airbnb-base": "^15.0.0", "eslint-plugin-import": "^2.29.1", "humile": "^0.5.3", "nw": "^0.100.1", "typescript": "^5.3.3", "vite": "^4.5.9", "vite-plugin-electron": "^0.15.5", "vite-plugin-electron-renderer": "^0.14.5", "webpack": "^5.89.0", "webpack-cli": "^5.1.4" } }'use strict'; const preload = require('./src/renderer/electron-log-preload'); module.exports = preload; 'use strict'; const renderer = require('./src/renderer'); module.exports = renderer; 'use strict'; class Buffering { constructor({ processMessage }) { this.processMessage = processMessage; this.buffer = []; this.enabled = false; this.begin = this.begin.bind(this); this.commit = this.commit.bind(this); this.reject = this.reject.bind(this); } addMessage(message) { this.buffer.push(message); } begin() { this.enabled = []; } commit() { this.enabled = false; this.buffer.forEach((item) => this.processMessage(item)); this.buffer = []; } reject() { this.enabled = false; this.buffer = []; } } module.exports = Buffering; 'use strict'; const scopeFactory = require('./scope'); const Buffering = require('./Buffering'); /** * @property {Function} error * @property {Function} warn * @property {Function} info * @property {Function} verbose * @property {Function} debug * @property {Function} silly */ class Logger { static instances = {}; dependencies = {}; errorHandler = null; eventLogger = null; functions = {}; hooks = []; isDev = false; levels = null; logId = null; scope = null; transports = {}; variables = {}; constructor({ allowUnknownLevel = false, dependencies = {}, errorHandler, eventLogger, initializeFn, isDev = false, levels = ['error', 'warn', 'info', 'verbose', 'debug', 'silly'], logId, transportFactories = {}, variables, } = {}) { this.addLevel = this.addLevel.bind(this); this.create = this.create.bind(this); this.initialize = this.initialize.bind(this); this.logData = this.logData.bind(this); this.processMessage = this.processMessage.bind(this); this.allowUnknownLevel = allowUnknownLevel; this.buffering = new Buffering(this); this.dependencies = dependencies; this.initializeFn = initializeFn; this.isDev = isDev; this.levels = levels; this.logId = logId; this.scope = scopeFactory(this); this.transportFactories = transportFactories; this.variables = variables || {}; for (const name of this.levels) { this.addLevel(name, false); } this.log = this.info; this.functions.log = this.log; this.errorHandler = errorHandler; errorHandler?.setOptions({ ...dependencies, logFn: this.error }); this.eventLogger = eventLogger; eventLogger?.setOptions({ ...dependencies, logger: this }); for (const [name, factory] of Object.entries(transportFactories)) { this.transports[name] = factory(this, dependencies); } Logger.instances[logId] = this; } static getInstance({ logId }) { return this.instances[logId] || this.instances.default; } addLevel(level, index = this.levels.length) { if (index !== false) { this.levels.splice(index, 0, level); } this[level] = (...args) => this.logData(args, { level }); this.functions[level] = this[level]; } catchErrors(options) { this.processMessage( { data: ['log.catchErrors is deprecated. Use log.errorHandler instead'], level: 'warn', }, { transports: ['console'] }, ); return this.errorHandler.startCatching(options); } create(options) { if (typeof options === 'string') { options = { logId: options }; } return new Logger({ dependencies: this.dependencies, errorHandler: this.errorHandler, initializeFn: this.initializeFn, isDev: this.isDev, transportFactories: this.transportFactories, variables: { ...this.variables }, ...options, }); } compareLevels(passLevel, checkLevel, levels = this.levels) { const pass = levels.indexOf(passLevel); const check = levels.indexOf(checkLevel); if (check === -1 || pass === -1) { return true; } return check <= pass; } initialize(options = {}) { this.initializeFn({ logger: this, ...this.dependencies, ...options }); } logData(data, options = {}) { if (this.buffering.enabled) { this.buffering.addMessage({ data, date: new Date(), ...options }); } else { this.processMessage({ data, ...options }); } } processMessage(message, { transports = this.transports } = {}) { if (message.cmd === 'errorHandler') { this.errorHandler.handle(message.error, { errorName: message.errorName, processType: 'renderer', showDialog: Boolean(message.showDialog), }); return; } let level = message.level; if (!this.allowUnknownLevel) { level = this.levels.includes(message.level) ? message.level : 'info'; } const normalizedMessage = { date: new Date(), logId: this.logId, ...message, level, variables: { ...this.variables, ...message.variables, }, }; for (const [transName, transFn] of this.transportEntries(transports)) { if (typeof transFn !== 'function' || transFn.level === false) { continue; } if (!this.compareLevels(transFn.level, message.level)) { continue; } try { // eslint-disable-next-line arrow-body-style const transformedMsg = this.hooks.reduce((msg, hook) => { return msg ? hook(msg, transFn, transName) : msg; }, normalizedMessage); if (transformedMsg) { transFn({ ...transformedMsg, data: [...transformedMsg.data] }); } } catch (e) { this.processInternalErrorFn(e); } } } processInternalErrorFn(_e) { // Do nothing by default } transportEntries(transports = this.transports) { const transportArray = Array.isArray(transports) ? transports : Object.entries(transports); return transportArray .map((item) => { switch (typeof item) { case 'string': return this.transports[item] ? [item, this.transports[item]] : null; case 'function': return [item.name, item]; default: return Array.isArray(item) ? item : null; } }) .filter(Boolean); } } module.exports = Logger; 'use strict'; module.exports = scopeFactory; function scopeFactory(logger) { return Object.defineProperties(scope, { defaultLabel: { value: '', writable: true }, labelPadding: { value: true, writable: true }, maxLabelLength: { value: 0, writable: true }, labelLength: { get() { switch (typeof scope.labelPadding) { case 'boolean': return scope.labelPadding ? scope.maxLabelLength : 0; case 'number': return scope.labelPadding; default: return 0; } }, }, }); function scope(label) { scope.maxLabelLength = Math.max(scope.maxLabelLength, label.length); const newScope = {}; for (const level of logger.levels) { newScope[level] = (...d) => logger.logData(d, { level, scope: label }); } newScope.log = newScope.info; return newScope; } } 'use strict'; const { transform } = require('./transform'); module.exports = { concatFirstStringElements, formatScope, formatText, formatVariables, timeZoneFromOffset, format({ message, logger, transport, data = message?.data }) { switch (typeof transport.format) { case 'string': { return transform({ message, logger, transforms: [formatVariables, formatScope, formatText], transport, initialData: [transport.format, ...data], }); } case 'function': { return transport.format({ data, level: message?.level || 'info', logger, message, transport, }); } default: { return data; } } }, }; /** * The first argument of console.log may contain a template. In the library * the first element is a string related to transports.console.format. So * this function concatenates first two elements to make templates like %d * work * @param {*[]} data * @return {*[]} */ function concatFirstStringElements({ data }) { if (typeof data[0] !== 'string' || typeof data[1] !== 'string') { return data; } if (data[0].match(/%[1cdfiOos]/)) { return data; } return [`${data[0]} ${data[1]}`, ...data.slice(2)]; } function timeZoneFromOffset(minutesOffset) { const minutesPositive = Math.abs(minutesOffset); const sign = minutesOffset > 0 ? '-' : '+'; const hours = Math.floor(minutesPositive / 60).toString().padStart(2, '0'); const minutes = (minutesPositive % 60).toString().padStart(2, '0'); return `${sign}${hours}:${minutes}`; } function formatScope({ data, logger, message }) { const { defaultLabel, labelLength } = logger?.scope || {}; const template = data[0]; let label = message.scope; if (!label) { label = defaultLabel; } let scopeText; if (label === '') { scopeText = labelLength > 0 ? ''.padEnd(labelLength + 3) : ''; } else if (typeof label === 'string') { scopeText = ` (${label})`.padEnd(labelLength + 3); } else { scopeText = ''; } data[0] = template.replace('{scope}', scopeText); return data; } function formatVariables({ data, message }) { let template = data[0]; if (typeof template !== 'string') { return data; } // Add additional space to the end of {level}] template to align messages template = template.replace('{level}]', `${message.level}]`.padEnd(6, ' ')); const date = message.date || new Date(); data[0] = template .replace(/\{(\w+)}/g, (substring, name) => { switch (name) { case 'level': return message.level || 'info'; case 'logId': return message.logId; case 'y': return date.getFullYear().toString(10); case 'm': return (date.getMonth() + 1).toString(10).padStart(2, '0'); case 'd': return date.getDate().toString(10).padStart(2, '0'); case 'h': return date.getHours().toString(10).padStart(2, '0'); case 'i': return date.getMinutes().toString(10).padStart(2, '0'); case 's': return date.getSeconds().toString(10).padStart(2, '0'); case 'ms': return date.getMilliseconds().toString(10).padStart(3, '0'); case 'z': return timeZoneFromOffset(date.getTimezoneOffset()); case 'iso': return date.toISOString(); default: { return message.variables?.[name] || substring; } } }) .trim(); return data; } function formatText({ data }) { const template = data[0]; if (typeof template !== 'string') { return data; } const textTplPosition = template.lastIndexOf('{text}'); if (textTplPosition === template.length - 6) { data[0] = template.replace(/\s?{text}/, ''); if (data[0] === '') { data.shift(); } return data; } const templatePieces = template.split('{text}'); let result = []; if (templatePieces[0] !== '') { result.push(templatePieces[0]); } result = result.concat(data.slice(1)); if (templatePieces[1] !== '') { result.push(templatePieces[1]); } return result; } 'use strict'; module.exports = { transformStyles, applyAnsiStyles({ data }) { return transformStyles(data, styleToAnsi, resetAnsiStyle); }, removeStyles({ data }) { return transformStyles(data, () => ''); }, }; const ANSI_COLORS = { unset: '\x1b[0m', black: '\x1b[30m', red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', blue: '\x1b[34m', magenta: '\x1b[35m', cyan: '\x1b[36m', white: '\x1b[37m', gray: '\x1b[90m', }; function styleToAnsi(style) { const color = style.replace(/color:\s*(\w+).*/, '$1').toLowerCase(); return ANSI_COLORS[color] || ''; } function resetAnsiStyle(string) { return string + ANSI_COLORS.unset; } function transformStyles(data, onStyleFound, onStyleApplied) { const foundStyles = {}; return data.reduce((result, item, index, array) => { if (foundStyles[index]) { return result; } if (typeof item === 'string') { let valueIndex = index; let styleApplied = false; item = item.replace(/%[1cdfiOos]/g, (match) => { valueIndex += 1; if (match !== '%c') { return match; } const style = array[valueIndex]; if (typeof style === 'string') { foundStyles[valueIndex] = true; styleApplied = true; return onStyleFound(style, item); } return match; }); if (styleApplied && onStyleApplied) { item = onStyleApplied(item); } } result.push(item); return result; }, []); } 'use strict'; module.exports = { transform }; function transform({ logger, message, transport, initialData = message?.data || [], transforms = transport?.transforms, }) { return transforms.reduce((data, trans) => { if (typeof trans === 'function') { return trans({ data, logger, message, transport }); } return data; }, initialData); } 'use strict'; /* eslint-disable global-require */ const isRenderer = typeof process === 'undefined' || (process.type === 'renderer' || process.type === 'worker'); const isMain = typeof process === 'object' && process.type === 'browser'; if (isRenderer) { // Makes sense when contextIsolation/sandbox disabled require('./renderer/electron-log-preload'); module.exports = require('./renderer'); } else if (isMain) { module.exports = require('./main'); } else { module.exports = require('./node'); } 'use strict'; const path = require('path'); const NodeExternalApi = require('../node/NodeExternalApi'); class ElectronExternalApi extends NodeExternalApi { /** * @type {typeof Electron} */ electron = undefined; /** * @param {object} options * @param {typeof Electron} [options.electron] */ constructor({ electron } = {}) { super(); this.electron = electron; } getAppName() { let appName; try { appName = this.appName || this.electron.app?.name || this.electron.app?.getName(); } catch { // fallback to default value below } return appName || super.getAppName(); } getAppUserDataPath(appName) { return this.getPath('userData') || super.getAppUserDataPath(appName); } getAppVersion() { let appVersion; try { appVersion = this.electron.app?.getVersion(); } catch { // fallback to default value below } return appVersion || super.getAppVersion(); } getElectronLogPath() { return this.getPath('logs') || super.getElectronLogPath(); } /** * @private * @param {any} name * @returns {string|undefined} */ getPath(name) { try { return this.electron.app?.getPath(name); } catch { return undefined; } } getVersions() { return { app: `${this.getAppName()} ${this.getAppVersion()}`, electron: `Electron ${process.versions.electron}`, os: this.getOsVersion(), }; } getSystemPathAppData() { return this.getPath('appData') || super.getSystemPathAppData(); } isDev() { if (this.electron.app?.isPackaged !== undefined) { return !this.electron.app.isPackaged; } if (typeof process.execPath === 'string') { const execFileName = path.basename(process.execPath).toLowerCase(); return execFileName.startsWith('electron'); } return super.isDev(); } onAppEvent(eventName, handler) { this.electron.app?.on(eventName, handler); return () => { this.electron.app?.off(eventName, handler); }; } onAppReady(handler) { if (this.electron.app?.isReady()) { handler(); } else if (this.electron.app?.once) { this.electron.app?.once('ready', handler); } else { handler(); } } onEveryWebContentsEvent(eventName, handler) { this.electron.webContents?.getAllWebContents()?.forEach((webContents) => { webContents.on(eventName, handler); }); this.electron.app?.on('web-contents-created', onWebContentsCreated); return () => { this.electron.webContents?.getAllWebContents().forEach((webContents) => { webContents.off(eventName, handler); }); this.electron.app?.off('web-contents-created', onWebContentsCreated); }; function onWebContentsCreated(_, webContents) { webContents.on(eventName, handler); } } /** * Listen to async messages sent from opposite process * @param {string} channel * @param {function} listener */ onIpc(channel, listener) { this.electron.ipcMain?.on(channel, listener); } onIpcInvoke(channel, listener) { this.electron.ipcMain?.handle?.(channel, listener); } /** * @param {string} url * @param {Function} [logFunction] */ openUrl(url, logFunction = console.error) { // eslint-disable-line no-console this.electron.shell?.openExternal(url).catch(logFunction); } setPreloadFileForSessions({ filePath, includeFutureSession = true, getSessions = () => [this.electron.session?.defaultSession], }) { for (const session of getSessions().filter(Boolean)) { setPreload(session); } if (includeFutureSession) { this.onAppEvent('session-created', (session) => { setPreload(session); }); } /** * @param {Session} session */ function setPreload(session) { if (typeof session.registerPreloadScript === 'function') { session.registerPreloadScript({ filePath, id: 'electron-log-preload', type: 'frame', }); } else { session.setPreloads([...session.getPreloads(), filePath]); } } } /** * Sent a message to opposite process * @param {string} channel * @param {any} message */ sendIpc(channel, message) { this.electron.BrowserWindow?.getAllWindows()?.forEach((wnd) => { if ( wnd.webContents?.isDestroyed() === false && wnd.webContents?.isCrashed() === false ) { wnd.webContents.send(channel, message); } }); } showErrorBox(title, message) { this.electron.dialog?.showErrorBox(title, message); } } module.exports = ElectronExternalApi; 'use strict'; const electron = require('electron'); const ElectronExternalApi = require('./ElectronExternalApi'); const { initialize } = require('./initialize'); const createDefaultLogger = require('../node/createDefaultLogger'); const externalApi = new ElectronExternalApi({ electron }); const defaultLogger = createDefaultLogger({ dependencies: { externalApi }, initializeFn: initialize, }); module.exports = defaultLogger; externalApi.onIpc('__ELECTRON_LOG__', (_, message) => { if (message.scope) { defaultLogger.Logger.getInstance(message).scope(message.scope); } const date = new Date(message.date); processMessage({ ...message, date: date.getTime() ? date : new Date(), }); }); externalApi.onIpcInvoke('__ELECTRON_LOG__', (_, { cmd = '', logId }) => { switch (cmd) { case 'getOptions': { const logger = defaultLogger.Logger.getInstance({ logId }); return { levels: logger.levels, logId, }; } default: { processMessage({ data: [`Unknown cmd '${cmd}'`], level: 'error' }); return {}; } } }); function processMessage(message) { defaultLogger.Logger.getInstance(message)?.processMessage(message); } 'use strict'; const fs = require('fs'); const os = require('os'); const path = require('path'); const preloadInitializeFn = require('../renderer/electron-log-preload'); let preloadInitialized = false; let spyConsoleInitialized = false; module.exports = { initialize({ externalApi, getSessions, includeFutureSession, logger, preload = true, spyRendererConsole = false, }) { externalApi.onAppReady(() => { try { if (preload) { initializePreload({ externalApi, getSessions, includeFutureSession, logger, preloadOption: preload, }); } if (spyRendererConsole) { initializeSpyRendererConsole({ externalApi, logger }); } } catch (err) { logger.warn(err); } }); }, }; function initializePreload({ externalApi, getSessions, includeFutureSession, logger, preloadOption, }) { let preloadPath = typeof preloadOption === 'string' ? preloadOption : undefined; if (preloadInitialized) { logger.warn(new Error('log.initialize({ preload }) already called').stack); return; } preloadInitialized = true; try { preloadPath = path.resolve( __dirname, '../renderer/electron-log-preload.js', ); } catch { // Ignore, the file is bundled to ESM } if (!preloadPath || !fs.existsSync(preloadPath)) { preloadPath = path.join( externalApi.getAppUserDataPath() || os.tmpdir(), 'electron-log-preload.js', ); const preloadCode = ` try { (${preloadInitializeFn.toString()})(require('electron')); } catch(e) { console.error(e); } `; fs.writeFileSync(preloadPath, preloadCode, 'utf8'); } externalApi.setPreloadFileForSessions({ filePath: preloadPath, includeFutureSession, getSessions, }); } function initializeSpyRendererConsole({ externalApi, logger }) { if (spyConsoleInitialized) { logger.warn( new Error('log.initialize({ spyRendererConsole }) already called').stack, ); return; } spyConsoleInitialized = true; const levels = ['debug', 'info', 'warn', 'error']; externalApi.onEveryWebContentsEvent( 'console-message', (event, level, message) => { logger.processMessage({ data: [message], level: levels[level], variables: { processType: 'renderer' }, }); }, ); } 'use strict'; class ErrorHandler { externalApi = undefined; isActive = false; logFn = undefined; onError = undefined; showDialog = true; constructor({ externalApi, logFn = undefined, onError = undefined, showDialog = undefined, } = {}) { this.createIssue = this.createIssue.bind(this); this.handleError = this.handleError.bind(this); this.handleRejection = this.handleRejection.bind(this); this.setOptions({ externalApi, logFn, onError, showDialog }); this.startCatching = this.startCatching.bind(this); this.stopCatching = this.stopCatching.bind(this); } handle(error, { logFn = this.logFn, onError = this.onError, processType = 'browser', showDialog = this.showDialog, errorName = '', } = {}) { error = normalizeError(error); try { if (typeof onError === 'function') { const versions = this.externalApi?.getVersions() || {}; const createIssue = this.createIssue; const result = onError({ createIssue, error, errorName, processType, versions, }); if (result === false) { return; } } errorName ? logFn(errorName, error) : logFn(error); if (showDialog && !errorName.includes('rejection') && this.externalApi) { this.externalApi.showErrorBox( `A JavaScript error occurred in the ${processType} process`, error.stack, ); } } catch { console.error(error); // eslint-disable-line no-console } } setOptions({ externalApi, logFn, onError, showDialog }) { if (typeof externalApi === 'object') { this.externalApi = externalApi; } if (typeof logFn === 'function') { this.logFn = logFn; } if (typeof onError === 'function') { this.onError = onError; } if (typeof showDialog === 'boolean') { this.showDialog = showDialog; } } startCatching({ onError, showDialog } = {}) { if (this.isActive) { return; } this.isActive = true; this.setOptions({ onError, showDialog }); process.on('uncaughtException', this.handleError); process.on('unhandledRejection', this.handleRejection); } stopCatching() { this.isActive = false; process.removeListener('uncaughtException', this.handleError); process.removeListener('unhandledRejection', this.handleRejection); } createIssue(pageUrl, queryParams) { this.externalApi?.openUrl( `${pageUrl}?${new URLSearchParams(queryParams).toString()}`, ); } handleError(error) { this.handle(error, { errorName: 'Unhandled' }); } handleRejection(reason) { const error = reason instanceof Error ? reason : new Error(JSON.stringify(reason)); this.handle(error, { errorName: 'Unhandled rejection' }); } } function normalizeError(e) { if (e instanceof Error) { return e; } if (e && typeof e === 'object') { if (e.message) { return Object.assign(new Error(e.message), e); } try { return new Error(JSON.stringify(e)); } catch (serErr) { return new Error(`Couldn't normalize error ${String(e)}: ${serErr}`); } } return new Error(`Can't normalize error ${String(e)}`); } module.exports = ErrorHandler; 'use strict'; class EventLogger { disposers = []; format = '{eventSource}#{eventName}:'; formatters = { app: { 'certificate-error': ({ args }) => { return this.arrayToObject(args.slice(1, 4), [ 'url', 'error', 'certificate', ]); }, 'child-process-gone': ({ args }) => { return args.length === 1 ? args[0] : args; }, 'render-process-gone': ({ args: [webContents, details] }) => { return details && typeof details === 'object' ? { ...details, ...this.getWebContentsDetails(webContents) } : []; }, }, webContents: { 'console-message': ({ args: [level, message, line, sourceId] }) => { // 0: debug, 1: info, 2: warning, 3: error if (level < 3) { return undefined; } return { message, source: `${sourceId}:${line}` }; }, 'did-fail-load': ({ args }) => { return this.arrayToObject(args, [ 'errorCode', 'errorDescription', 'validatedURL', 'isMainFrame', 'frameProcessId', 'frameRoutingId', ]); }, 'did-fail-provisional-load': ({ args }) => { return this.arrayToObject(args, [ 'errorCode', 'errorDescription', 'validatedURL', 'isMainFrame', 'frameProcessId', 'frameRoutingId', ]); }, 'plugin-crashed': ({ args }) => { return this.arrayToObject(args, ['name', 'version']); }, 'preload-error': ({ args }) => { return this.arrayToObject(args, ['preloadPath', 'error']); }, }, }; events = { app: { 'certificate-error': true, 'child-process-gone': true, 'render-process-gone': true, }, webContents: { // 'console-message': true, 'did-fail-load': true, 'did-fail-provisional-load': true, 'plugin-crashed': true, 'preload-error': true, 'unresponsive': true, }, }; externalApi = undefined; level = 'error'; scope = ''; constructor(options = {}) { this.setOptions(options); } setOptions({ events, externalApi, level, logger, format, formatters, scope, }) { if (typeof events === 'object') { this.events = events; } if (typeof externalApi === 'object') { this.externalApi = externalApi; } if (typeof level === 'string') { this.level = level; } if (typeof logger === 'object') { this.logger = logger; } if (typeof format === 'string' || typeof format === 'function') { this.format = format; } if (typeof formatters === 'object') { this.formatters = formatters; } if (typeof scope === 'string') { this.scope = scope; } } startLogging(options = {}) { this.setOptions(options); this.disposeListeners(); for (const eventName of this.getEventNames(this.events.app)) { this.disposers.push( this.externalApi.onAppEvent(eventName, (...handlerArgs) => { this.handleEvent({ eventSource: 'app', eventName, handlerArgs }); }), ); } for (const eventName of this.getEventNames(this.events.webContents)) { this.disposers.push( this.externalApi.onEveryWebContentsEvent( eventName, (...handlerArgs) => { this.handleEvent( { eventSource: 'webContents', eventName, handlerArgs }, ); }, ), ); } } stopLogging() { this.disposeListeners(); } arrayToObject(array, fieldNames) { const obj = {}; fieldNames.forEach((fieldName, index) => { obj[fieldName] = array[index]; }); if (array.length > fieldNames.length) { obj.unknownArgs = array.slice(fieldNames.length); } return obj; } disposeListeners() { this.disposers.forEach((disposer) => disposer()); this.disposers = []; } formatEventLog({ eventName, eventSource, handlerArgs }) { const [event, ...args] = handlerArgs; if (typeof this.format === 'function') { return this.format({ args, event, eventName, eventSource }); } const formatter = this.formatters[eventSource]?.[eventName]; let formattedArgs = args; if (typeof formatter === 'function') { formattedArgs = formatter({ args, event, eventName, eventSource }); } if (!formattedArgs) { return undefined; } const eventData = {}; if (Array.isArray(formattedArgs)) { eventData.args = formattedArgs; } else if (typeof formattedArgs === 'object') { Object.assign(eventData, formattedArgs); } if (eventSource === 'webContents') { Object.assign(eventData, this.getWebContentsDetails(event?.sender)); } const title = this.format .replace('{eventSource}', eventSource === 'app' ? 'App' : 'WebContents') .replace('{eventName}', eventName); return [title, eventData]; } getEventNames(eventMap) { if (!eventMap || typeof eventMap !== 'object') { return []; } return Object.entries(eventMap) .filter(([_, listen]) => listen) .map(([eventName]) => eventName); } getWebContentsDetails(webContents) { if (!webContents?.loadURL) { return {}; } try { return { webContents: { id: webContents.id, url: webContents.getURL(), }, }; } catch { return {}; } } handleEvent({ eventName, eventSource, handlerArgs }) { const log = this.formatEventLog({ eventName, eventSource, handlerArgs }); if (log) { const logFns = this.scope ? this.logger.scope(this.scope) : this.logger; logFns?.[this.level]?.(...log); } } } module.exports = EventLogger; 'use strict'; /* eslint-disable no-unused-vars */ const childProcess = require('child_process'); const os = require('os'); const path = require('path'); const packageJson = require('./packageJson'); class NodeExternalApi { appName = undefined; appPackageJson = undefined; platform = process.platform; getAppLogPath(appName = this.getAppName()) { if (this.platform === 'darwin') { return path.join(this.getSystemPathHome(), 'Library/Logs', appName); } return path.join(this.getAppUserDataPath(appName), 'logs'); } getAppName() { const appName = this.appName || this.getAppPackageJson()?.name; if (!appName) { throw new Error( 'electron-log can\'t determine the app name. It tried these methods:\n' + '1. Use `electron.app.name`\n' + '2. Use productName or name from the nearest package.json`\n' + 'You can also set it through log.transports.file.setAppName()', ); } return appName; } /** * @private * @returns {undefined} */ getAppPackageJson() { if (typeof this.appPackageJson !== 'object') { this.appPackageJson = packageJson.findAndReadPackageJson(); } return this.appPackageJson; } getAppUserDataPath(appName = this.getAppName()) { return appName ? path.join(this.getSystemPathAppData(), appName) : undefined; } getAppVersion() { return this.getAppPackageJson()?.version; } getElectronLogPath() { return this.getAppLogPath(); } getMacOsVersion() { const release = Number(os.release().split('.')[0]); if (release <= 19) { return `10.${release - 4}`; } return release - 9; } /** * @protected * @returns {string} */ getOsVersion() { let osName = os.type().replace('_', ' '); let osVersion = os.release(); if (osName === 'Darwin') { osName = 'macOS'; osVersion = this.getMacOsVersion(); } return `${osName} ${osVersion}`; } /** * @return {PathVariables} */ getPathVariables() { const appName = this.getAppName(); const appVersion = this.getAppVersion(); const self = this; return { appData: this.getSystemPathAppData(), appName, appVersion, get electronDefaultDir() { return self.getElectronLogPath(); }, home: this.getSystemPathHome(), libraryDefaultDir: this.getAppLogPath(appName), libraryTemplate: this.getAppLogPath('{appName}'), temp: this.getSystemPathTemp(), userData: this.getAppUserDataPath(appName), }; } getSystemPathAppData() { const home = this.getSystemPathHome(); switch (this.platform) { case 'darwin': { return path.join(home, 'Library/Application Support'); } case 'win32': { return process.env.APPDATA || path.join(home, 'AppData/Roaming'); } default: { return process.env.XDG_CONFIG_HOME || path.join(home, '.config'); } } } getSystemPathHome() { return os.homedir?.() || process.env.HOME; } getSystemPathTemp() { return os.tmpdir(); } getVersions() { return { app: `${this.getAppName()} ${this.getAppVersion()}`, electron: undefined, os: this.getOsVersion(), }; } isDev() { return process.env.NODE_ENV === 'development' || process.env.ELECTRON_IS_DEV === '1'; } isElectron() { return Boolean(process.versions.electron); } onAppEvent(_eventName, _handler) { // Ignored in node.js } onAppReady(handler) { handler(); } onEveryWebContentsEvent(eventName, handler) { // Ignored in node.js } /** * Listen to async messages sent from opposite process * @param {string} channel * @param {function} listener */ onIpc(channel, listener) { // Ignored in node.js } onIpcInvoke(channel, listener) { // Ignored in node.js } /** * @param {string} url * @param {Function} [logFunction] */ openUrl(url, logFunction = console.error) { // eslint-disable-line no-console const startMap = { darwin: 'open', win32: 'start', linux: 'xdg-open' }; const start = startMap[process.platform] || 'xdg-open'; childProcess.exec(`${start} ${url}`, {}, (err) => { if (err) { logFunction(err); } }); } setAppName(appName) { this.appName = appName; } setPlatform(platform) { this.platform = platform; } setPreloadFileForSessions({ filePath, // eslint-disable-line no-unused-vars includeFutureSession = true, // eslint-disable-line no-unused-vars getSessions = () => [], // eslint-disable-line no-unused-vars }) { // Ignored in node.js } /** * Sent a message to opposite process * @param {string} channel * @param {any} message */ sendIpc(channel, message) { // Ignored in node.js } showErrorBox(title, message) { // Ignored in node.js } } module.exports = NodeExternalApi; 'use strict'; const Logger = require('../core/Logger'); const ErrorHandler = require('./ErrorHandler'); const EventLogger = require('./EventLogger'); const transportConsole = require('./transports/console'); const transportFile = require('./transports/file'); const transportIpc = require('./transports/ipc'); const transportRemote = require('./transports/remote'); module.exports = createDefaultLogger; function createDefaultLogger({ dependencies, initializeFn }) { const defaultLogger = new Logger({ dependencies, errorHandler: new ErrorHandler(), eventLogger: new EventLogger(), initializeFn, isDev: dependencies.externalApi?.isDev(), logId: 'default', transportFactories: { console: transportConsole, file: transportFile, ipc: transportIpc, remote: transportRemote, }, variables: { processType: 'main', }, }); defaultLogger.default = defaultLogger; defaultLogger.Logger = Logger; defaultLogger.processInternalErrorFn = (e) => { defaultLogger.transports.console.writeFn({ message: { data: ['Unhandled electron-log error', e], level: 'error', }, }); }; return defaultLogger; } 'use strict'; const NodeExternalApi = require('./NodeExternalApi'); const createDefaultLogger = require('./createDefaultLogger'); const externalApi = new NodeExternalApi(); const defaultLogger = createDefaultLogger({ dependencies: { externalApi }, }); module.exports = defaultLogger; 'use strict'; const fs = require('fs'); const path = require('path'); module.exports = { findAndReadPackageJson, tryReadJsonAt, }; /** * @return {{ name?: string, version?: string}} */ function findAndReadPackageJson() { return tryReadJsonAt(getMainModulePath()) || tryReadJsonAt(extractPathFromArgs()) || tryReadJsonAt(process.resourcesPath, 'app.asar') || tryReadJsonAt(process.resourcesPath, 'app') || tryReadJsonAt(process.cwd()) || { name: undefined, version: undefined }; } /** * @param {...string} searchPaths * @return {{ name?: string, version?: string } | undefined} */ function tryReadJsonAt(...searchPaths) { if (!searchPaths[0]) { return undefined; } try { const searchPath = path.join(...searchPaths); const fileName = findUp('package.json', searchPath); if (!fileName) { return undefined; } const json = JSON.parse(fs.readFileSync(fileName, 'utf8')); const name = json?.productName || json?.name; if (!name || name.toLowerCase() === 'electron') { return undefined; } if (name) { return { name, version: json?.version }; } return undefined; } catch (e) { return undefined; } } /** * @param {string} fileName * @param {string} [cwd] * @return {string | null} */ function findUp(fileName, cwd) { let currentPath = cwd; // eslint-disable-next-line no-constant-condition while (true) { const parsedPath = path.parse(currentPath); const root = parsedPath.root; const dir = parsedPath.dir; if (fs.existsSync(path.join(currentPath, fileName))) { return path.resolve(path.join(currentPath, fileName)); } if (currentPath === root) { return null; } currentPath = dir; } } /** * Get app path from --user-data-dir cmd arg, passed to a renderer process * @return {string|null} */ function extractPathFromArgs() { const matchedArgs = process.argv.filter((arg) => { return arg.indexOf('--user-data-dir=') === 0; }); if (matchedArgs.length === 0 || typeof matchedArgs[0] !== 'string') { return null; } const userDataDir = matchedArgs[0]; return userDataDir.replace('--user-data-dir=', ''); } function getMainModulePath() { try { // Requires isn't available in ESM return require.main?.filename; } catch { return undefined; } } 'use strict'; const util = require('util'); module.exports = { serialize, maxDepth({ data, transport, depth = transport?.depth ?? 6 }) { if (!data) { return data; } if (depth < 1) { if (Array.isArray(data)) return '[array]'; if (typeof data === 'object' && data) return '[object]'; return data; } if (Array.isArray(data)) { return data.map((child) => module.exports.maxDepth({ data: child, depth: depth - 1, })); } if (typeof data !== 'object') { return data; } if (data && typeof data.toISOString === 'function') { return data; } // noinspection PointlessBooleanExpressionJS if (data === null) { return null; } if (data instanceof Error) { return data; } const newJson = {}; for (const i in data) { if (!Object.prototype.hasOwnProperty.call(data, i)) continue; newJson[i] = module.exports.maxDepth({ data: data[i], depth: depth - 1, }); } return newJson; }, toJSON({ data }) { return JSON.parse(JSON.stringify(data, createSerializer())); }, toString({ data, transport }) { const inspectOptions = transport?.inspectOptions || {}; const simplifiedData = data.map((item) => { if (item === undefined) { return undefined; } try { const str = JSON.stringify(item, createSerializer(), ' '); return str === undefined ? undefined : JSON.parse(str); } catch (e) { // There are some rare cases when an item can't be simplified. // In that case, it's fine to pass it to util.format directly. return item; } }); return util.formatWithOptions(inspectOptions, ...simplifiedData); }, }; /** * @param {object} options? * @param {boolean} options.serializeMapAndSet? * @return {function} */ function createSerializer(options = {}) { const seen = new WeakSet(); return function (key, value) { if (typeof value === 'object' && value !== null) { if (seen.has(value)) { return undefined; } seen.add(value); } return serialize(key, value, options); }; } /** * @param {string} key * @param {any} value * @param {object} options? * @return {any} */ function serialize(key, value, options = {}) { const serializeMapAndSet = options?.serializeMapAndSet !== false; if (value instanceof Error) { return value.stack; } if (!value) { return value; } if (typeof value === 'function') { return `[function] ${value.toString()}`; } if (value instanceof Date) { return value.toISOString(); } if (serializeMapAndSet && value instanceof Map && Object.fromEntries) { return Object.fromEntries(value); } if (serializeMapAndSet && value instanceof Set && Array.from) { return Array.from(value); } return value; } 'use strict'; /* eslint-disable no-console */ const { concatFirstStringElements, format, } = require('../../core/transforms/format'); const { maxDepth, toJSON } = require('../transforms/object'); const { applyAnsiStyles, removeStyles, } = require('../../core/transforms/style'); const { transform } = require('../../core/transforms/transform'); const consoleMethods = { error: console.error, warn: console.warn, info: console.info, verbose: console.info, debug: console.debug, silly: console.debug, log: console.log, }; module.exports = consoleTransportFactory; const separator = process.platform === 'win32' ? '>' : '›'; const DEFAULT_FORMAT = `%c{h}:{i}:{s}.{ms}{scope}%c ${separator} {text}`; Object.assign(consoleTransportFactory, { DEFAULT_FORMAT, }); function consoleTransportFactory(logger) { return Object.assign(transport, { colorMap: { error: 'red', warn: 'yellow', info: 'cyan', verbose: 'unset', debug: 'gray', silly: 'gray', default: 'unset', }, format: DEFAULT_FORMAT, level: 'silly', transforms: [ addTemplateColors, format, formatStyles, concatFirstStringElements, maxDepth, toJSON, ], useStyles: process.env.FORCE_STYLES, writeFn({ message }) { const consoleLogFn = consoleMethods[message.level] || consoleMethods.info; consoleLogFn(...message.data); }, }); function transport(message) { const data = transform({ logger, message, transport }); transport.writeFn({ message: { ...message, data }, }); } } function addTemplateColors({ data, message, transport }) { if ( typeof transport.format !== 'string' || !transport.format.includes('%c') ) { return data; } return [ `color:${levelToStyle(message.level, transport)}`, 'color:unset', ...data, ]; } function canUseStyles(useStyleValue, level) { if (typeof useStyleValue === 'boolean') { return useStyleValue; } const useStderr = level === 'error' || level === 'warn'; const stream = useStderr ? process.stderr : process.stdout; return stream && stream.isTTY; } function formatStyles(args) { const { message, transport } = args; const useStyles = canUseStyles(transport.useStyles, message.level); const nextTransform = useStyles ? applyAnsiStyles : removeStyles; return nextTransform(args); } function levelToStyle(level, transport) { return transport.colorMap[level] || transport.colorMap.default; } 'use strict'; const EventEmitter = require('events'); const fs = require('fs'); const os = require('os'); class File extends EventEmitter { asyncWriteQueue = []; bytesWritten = 0; hasActiveAsyncWriting = false; path = null; initialSize = undefined; writeOptions = null; writeAsync = false; constructor({ path, writeOptions = { encoding: 'utf8', flag: 'a', mode: 0o666 }, writeAsync = false, }) { super(); this.path = path; this.writeOptions = writeOptions; this.writeAsync = writeAsync; } get size() { return this.getSize(); } clear() { try { fs.writeFileSync(this.path, '', { mode: this.writeOptions.mode, flag: 'w', }); this.reset(); return true; } catch (e) { if (e.code === 'ENOENT') { return true; } this.emit('error', e, this); return false; } } crop(bytesAfter) { try { const content = readFileSyncFromEnd(this.path, bytesAfter || 4096); this.clear(); this.writeLine(`[log cropped]${os.EOL}${content}`); } catch (e) { this.emit( 'error', new Error(`Couldn't crop file ${this.path}. ${e.message}`), this, ); } } getSize() { if (this.initialSize === undefined) { try { const stats = fs.statSync(this.path); this.initialSize = stats.size; } catch (e) { this.initialSize = 0; } } return this.initialSize + this.bytesWritten; } increaseBytesWrittenCounter(text) { this.bytesWritten += Buffer.byteLength(text, this.writeOptions.encoding); } isNull() { return false; } nextAsyncWrite() { const file = this; if (this.hasActiveAsyncWriting || this.asyncWriteQueue.length === 0) { return; } const text = this.asyncWriteQueue.join(''); this.asyncWriteQueue = []; this.hasActiveAsyncWriting = true; fs.writeFile(this.path, text, this.writeOptions, (e) => { file.hasActiveAsyncWriting = false; if (e) { file.emit( 'error', new Error(`Couldn't write to ${file.path}. ${e.message}`), this, ); } else { file.increaseBytesWrittenCounter(text); } file.nextAsyncWrite(); }); } reset() { this.initialSize = undefined; this.bytesWritten = 0; } toString() { return this.path; } writeLine(text) { text += os.EOL; if (this.writeAsync) { this.asyncWriteQueue.push(text); this.nextAsyncWrite(); return; } try { fs.writeFileSync(this.path, text, this.writeOptions); this.increaseBytesWrittenCounter(text); } catch (e) { this.emit( 'error', new Error(`Couldn't write to ${this.path}. ${e.message}`), this, ); } } } module.exports = File; function readFileSyncFromEnd(filePath, bytesCount) { const buffer = Buffer.alloc(bytesCount); const stats = fs.statSync(filePath); const readLength = Math.min(stats.size, bytesCount); const offset = Math.max(0, stats.size - bytesCount); const fd = fs.openSync(filePath, 'r'); const totalBytes = fs.readSync(fd, buffer, 0, readLength, offset); fs.closeSync(fd); return buffer.toString('utf8', 0, totalBytes); } 'use strict'; const EventEmitter = require('events'); const fs = require('fs'); const path = require('path'); const File = require('./File'); const NullFile = require('./NullFile'); class FileRegistry extends EventEmitter { store = {}; constructor() { super(); this.emitError = this.emitError.bind(this); } /** * Provide a File object corresponding to the filePath * @param {string} filePath * @param {WriteOptions} [writeOptions] * @param {boolean} [writeAsync] * @return {File} */ provide({ filePath, writeOptions = {}, writeAsync = false }) { let file; try { filePath = path.resolve(filePath); if (this.store[filePath]) { return this.store[filePath]; } file = this.createFile({ filePath, writeOptions, writeAsync }); } catch (e) { file = new NullFile({ path: filePath }); this.emitError(e, file); } file.on('error', this.emitError); this.store[filePath] = file; return file; } /** * @param {string} filePath * @param {WriteOptions} writeOptions * @param {boolean} async * @return {File} * @private */ createFile({ filePath, writeOptions, writeAsync }) { this.testFileWriting({ filePath, writeOptions }); return new File({ path: filePath, writeOptions, writeAsync }); } /** * @param {Error} error * @param {File} file * @private */ emitError(error, file) { this.emit('error', error, file); } /** * @param {string} filePath * @param {WriteOptions} writeOptions * @private */ testFileWriting({ filePath, writeOptions }) { fs.mkdirSync(path.dirname(filePath), { recursive: true }); fs.writeFileSync(filePath, '', { flag: 'a', mode: writeOptions.mode }); } } module.exports = FileRegistry; 'use strict'; const File = require('./File'); class NullFile extends File { clear() { } crop() { } getSize() { return 0; } isNull() { return true; } writeLine() { } } module.exports = NullFile; 'use strict'; const fs = require('fs'); const os = require('os'); const path = require('path'); const FileRegistry = require('./FileRegistry'); const { transform } = require('../../../core/transforms/transform'); const { removeStyles } = require('../../../core/transforms/style'); const { format, concatFirstStringElements, } = require('../../../core/transforms/format'); const { toString } = require('../../transforms/object'); module.exports = fileTransportFactory; // Shared between multiple file transport instances const globalRegistry = new FileRegistry(); function fileTransportFactory( logger, { registry = globalRegistry, externalApi } = {}, ) { /** @type {PathVariables} */ let pathVariables; if (registry.listenerCount('error') < 1) { registry.on('error', (e, file) => { logConsole(`Can't write to ${file}`, e); }); } return Object.assign(transport, { fileName: getDefaultFileName(logger.variables.processType), format: '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}', getFile, inspectOptions: { depth: 5 }, level: 'silly', maxSize: 1024 ** 2, readAllLogs, sync: true, transforms: [removeStyles, format, concatFirstStringElements, toString], writeOptions: { flag: 'a', mode: 0o666, encoding: 'utf8' }, archiveLogFn(file) { const oldPath = file.toString(); const inf = path.parse(oldPath); try { fs.renameSync(oldPath, path.join(inf.dir, `${inf.name}.old${inf.ext}`)); } catch (e) { logConsole('Could not rotate log', e); const quarterOfMaxSize = Math.round(transport.maxSize / 4); file.crop(Math.min(quarterOfMaxSize, 256 * 1024)); } }, resolvePathFn(vars) { return path.join(vars.libraryDefaultDir, vars.fileName); }, setAppName(name) { logger.dependencies.externalApi.setAppName(name); }, }); function transport(message) { const file = getFile(message); const needLogRotation = transport.maxSize > 0 && file.size > transport.maxSize; if (needLogRotation) { transport.archiveLogFn(file); file.reset(); } const content = transform({ logger, message, transport }); file.writeLine(content); } function initializeOnFirstAccess() { if (pathVariables) { return; } // Make a shallow copy of pathVariables to keep getters intact pathVariables = Object.create( Object.prototype, { ...Object.getOwnPropertyDescriptors( externalApi.getPathVariables(), ), fileName: { get() { return transport.fileName; }, enumerable: true, }, }, ); if (typeof transport.archiveLog === 'function') { transport.archiveLogFn = transport.archiveLog; logConsole('archiveLog is deprecated. Use archiveLogFn instead'); } if (typeof transport.resolvePath === 'function') { transport.resolvePathFn = transport.resolvePath; logConsole('resolvePath is deprecated. Use resolvePathFn instead'); } } function logConsole(message, error = null, level = 'error') { const data = [`electron-log.transports.file: ${message}`]; if (error) { data.push(error); } logger.transports.console({ data, date: new Date(), level }); } function getFile(msg) { initializeOnFirstAccess(); const filePath = transport.resolvePathFn(pathVariables, msg); return registry.provide({ filePath, writeAsync: !transport.sync, writeOptions: transport.writeOptions, }); } function readAllLogs({ fileFilter = (f) => f.endsWith('.log') } = {}) { initializeOnFirstAccess(); const logsPath = path.dirname(transport.resolvePathFn(pathVariables)); if (!fs.existsSync(logsPath)) { return []; } return fs.readdirSync(logsPath) .map((fileName) => path.join(logsPath, fileName)) .filter(fileFilter) .map((logPath) => { try { return { path: logPath, lines: fs.readFileSync(logPath, 'utf8').split(os.EOL), }; } catch { return null; } }) .filter(Boolean); } } function getDefaultFileName(processType = process.type) { switch (processType) { case 'renderer': return 'renderer.log'; case 'worker': return 'worker.log'; default: return 'main.log'; } } 'use strict'; const { maxDepth, toJSON } = require('../transforms/object'); const { transform } = require('../../core/transforms/transform'); module.exports = ipcTransportFactory; /** * @param logger * @param {ElectronExternalApi} externalApi * @returns {transport|null} */ function ipcTransportFactory(logger, { externalApi }) { Object.assign(transport, { depth: 3, eventId: '__ELECTRON_LOG_IPC__', level: logger.isDev ? 'silly' : false, transforms: [toJSON, maxDepth], }); return externalApi?.isElectron() ? transport : undefined; function transport(message) { if (message?.variables?.processType === 'renderer') { return; } externalApi?.sendIpc(transport.eventId, { ...message, data: transform({ logger, message, transport }), }); } } 'use strict'; const http = require('http'); const https = require('https'); const { transform } = require('../../core/transforms/transform'); const { removeStyles } = require('../../core/transforms/style'); const { toJSON, maxDepth } = require('../transforms/object'); module.exports = remoteTransportFactory; function remoteTransportFactory(logger) { return Object.assign(transport, { client: { name: 'electron-application' }, depth: 6, level: false, requestOptions: {}, transforms: [removeStyles, toJSON, maxDepth], makeBodyFn({ message }) { return JSON.stringify({ client: transport.client, data: message.data, date: message.date.getTime(), level: message.level, scope: message.scope, variables: message.variables, }); }, processErrorFn({ error }) { logger.processMessage( { data: [`electron-log: can't POST ${transport.url}`, error], level: 'warn', }, { transports: ['console', 'file'] }, ); }, sendRequestFn({ serverUrl, requestOptions, body }) { const httpTransport = serverUrl.startsWith('https:') ? https : http; const request = httpTransport.request(serverUrl, { method: 'POST', ...requestOptions, headers: { 'Content-Type': 'application/json', 'Content-Length': body.length, ...requestOptions.headers, }, }); request.write(body); request.end(); return request; }, }); function transport(message) { if (!transport.url) { return; } const body = transport.makeBodyFn({ logger, message: { ...message, data: transform({ logger, message, transport }) }, transport, }); const request = transport.sendRequestFn({ serverUrl: transport.url, requestOptions: transport.requestOptions, body: Buffer.from(body, 'utf8'), }); request.on('error', (error) => transport.processErrorFn({ error, logger, message, request, transport, })); } } 'use strict'; let electron = {}; try { // eslint-disable-next-line global-require,import/no-extraneous-dependencies electron = require('electron'); } catch (e) { // require isn't available, not from a preload script } if (electron.ipcRenderer) { initialize(electron); } if (typeof module === 'object') { module.exports = initialize; } /** * @param {Electron.ContextBridge} contextBridge * @param {Electron.IpcRenderer} ipcRenderer */ function initialize({ contextBridge, ipcRenderer }) { if (!ipcRenderer) { return; } ipcRenderer.on('__ELECTRON_LOG_IPC__', (_, message) => { window.postMessage({ cmd: 'message', ...message }); }); ipcRenderer .invoke('__ELECTRON_LOG__', { cmd: 'getOptions' }) // eslint-disable-next-line no-console .catch((e) => console.error(new Error( 'electron-log isn\'t initialized in the main process. ' + `Please call log.initialize() before. ${e.message}`, ))); const electronLog = { sendToMain(message) { try { ipcRenderer.send('__ELECTRON_LOG__', message); } catch (e) { // eslint-disable-next-line no-console console.error('electronLog.sendToMain ', e, 'data:', message); ipcRenderer.send('__ELECTRON_LOG__', { cmd: 'errorHandler', error: { message: e?.message, stack: e?.stack }, errorName: 'sendToMain', }); } }, log(...data) { electronLog.sendToMain({ data, level: 'info' }); }, }; for (const level of ['error', 'warn', 'info', 'verbose', 'debug', 'silly']) { electronLog[level] = (...data) => electronLog.sendToMain({ data, level, }); } if (contextBridge && process.contextIsolated) { try { contextBridge.exposeInMainWorld('__electronLog', electronLog); } catch { // Sometimes this files can be included twice } } if (typeof window === 'object') { window.__electronLog = electronLog; } else { // noinspection JSConstantReassignment __electronLog = electronLog; } } 'use strict'; const Logger = require('../core/Logger'); const RendererErrorHandler = require('./lib/RendererErrorHandler'); const transportConsole = require('./lib/transports/console'); const transportIpc = require('./lib/transports/ipc'); if (typeof process === 'object' && process.type === 'browser') { // eslint-disable-next-line no-console console.warn( 'electron-log/renderer is loaded in the main process. ' + 'It could cause unexpected behaviour.', ); } module.exports = createLogger(); module.exports.Logger = Logger; module.exports.default = module.exports; function createLogger() { const logger = new Logger({ allowUnknownLevel: true, errorHandler: new RendererErrorHandler(), initializeFn: () => {}, logId: 'default', transportFactories: { console: transportConsole, ipc: transportIpc, }, variables: { processType: 'renderer', }, }); logger.errorHandler.setOptions({ logFn({ error, errorName, showDialog }) { logger.transports.console({ data: [errorName, error].filter(Boolean), level: 'error', }); logger.transports.ipc({ cmd: 'errorHandler', error: { cause: error?.cause, code: error?.code, name: error?.name, message: error?.message, stack: error?.stack, }, errorName, logId: logger.logId, showDialog, }); }, }); if (typeof window === 'object') { window.addEventListener('message', (event) => { const { cmd, logId, ...message } = event.data || {}; const instance = Logger.getInstance({ logId }); if (cmd === 'message') { instance.processMessage(message, { transports: ['console'] }); } }); } // To support custom levels return new Proxy(logger, { get(target, prop) { if (typeof target[prop] !== 'undefined') { return target[prop]; } return (...data) => logger.logData(data, { level: prop }); }, }); } 'use strict'; // eslint-disable-next-line no-console const consoleError = console.error; class RendererErrorHandler { logFn = null; onError = null; showDialog = false; preventDefault = true; constructor({ logFn = null } = {}) { this.handleError = this.handleError.bind(this); this.handleRejection = this.handleRejection.bind(this); this.startCatching = this.startCatching.bind(this); this.logFn = logFn; } handle(error, { logFn = this.logFn, errorName = '', onError = this.onError, showDialog = this.showDialog, } = {}) { try { if (onError?.({ error, errorName, processType: 'renderer' }) !== false) { logFn({ error, errorName, showDialog }); } } catch { consoleError(error); } } setOptions({ logFn, onError, preventDefault, showDialog }) { if (typeof logFn === 'function') { this.logFn = logFn; } if (typeof onError === 'function') { this.onError = onError; } if (typeof preventDefault === 'boolean') { this.preventDefault = preventDefault; } if (typeof showDialog === 'boolean') { this.showDialog = showDialog; } } startCatching({ onError, showDialog } = {}) { if (this.isActive) { return; } this.isActive = true; this.setOptions({ onError, showDialog }); window.addEventListener('error', (event) => { this.preventDefault && event.preventDefault?.(); this.handleError(event.error || event); }); window.addEventListener('unhandledrejection', (event) => { this.preventDefault && event.preventDefault?.(); this.handleRejection(event.reason || event); }); } handleError(error) { this.handle(error, { errorName: 'Unhandled' }); } handleRejection(reason) { const error = reason instanceof Error ? reason : new Error(JSON.stringify(reason)); this.handle(error, { errorName: 'Unhandled rejection' }); } } module.exports = RendererErrorHandler; 'use strict'; /* eslint-disable no-console */ const { transform } = require('../../../core/transforms/transform'); module.exports = consoleTransportRendererFactory; const consoleMethods = { error: console.error, warn: console.warn, info: console.info, verbose: console.info, debug: console.debug, silly: console.debug, log: console.log, }; function consoleTransportRendererFactory(logger) { return Object.assign(transport, { format: '{h}:{i}:{s}.{ms}{scope} › {text}', transforms: [formatDataFn], writeFn({ message: { level, data } }) { const consoleLogFn = consoleMethods[level] || consoleMethods.info; // make an empty call stack setTimeout(() => consoleLogFn(...data)); }, }); function transport(message) { transport.writeFn({ message: { ...message, data: transform({ logger, message, transport }) }, }); } } function formatDataFn({ data = [], logger = {}, message = {}, transport = {}, }) { if (typeof transport.format === 'function') { return transport.format({ data, level: message?.level || 'info', logger, message, transport, }); } if (typeof transport.format !== 'string') { return data; } data.unshift(transport.format); // Concatenate the first two data items to support printf-like templates if (typeof data[1] === 'string' && data[1].match(/%[1cdfiOos]/)) { data = [`${data[0]}${data[1]}`, ...data.slice(2)]; } const date = message.date || new Date(); data[0] = data[0] .replace(/\{(\w+)}/g, (substring, name) => { switch (name) { case 'level': return message.level; case 'logId': return message.logId; case 'scope': { const scope = message.scope || logger.scope?.defaultLabel; return scope ? ` (${scope})` : ''; } case 'text': return ''; case 'y': return date.getFullYear().toString(10); case 'm': return (date.getMonth() + 1).toString(10) .padStart(2, '0'); case 'd': return date.getDate().toString(10).padStart(2, '0'); case 'h': return date.getHours().toString(10).padStart(2, '0'); case 'i': return date.getMinutes().toString(10).padStart(2, '0'); case 's': return date.getSeconds().toString(10).padStart(2, '0'); case 'ms': return date.getMilliseconds().toString(10) .padStart(3, '0'); case 'iso': return date.toISOString(); default: return message.variables?.[name] || substring; } }) .trim(); return data; } 'use strict'; const { transform } = require('../../../core/transforms/transform'); module.exports = ipcTransportRendererFactory; const RESTRICTED_TYPES = new Set([Promise, WeakMap, WeakSet]); function ipcTransportRendererFactory(logger) { return Object.assign(transport, { depth: 5, transforms: [serializeFn], }); function transport(message) { if (!window.__electronLog) { logger.processMessage( { data: ['electron-log: logger isn\'t initialized in the main process'], level: 'error', }, { transports: ['console'] }, ); return; } try { const serialized = transform({ initialData: message, logger, message, transport, }); __electronLog.sendToMain(serialized); } catch (e) { logger.transports.console({ data: ['electronLog.transports.ipc', e, 'data:', message.data], level: 'error', }); } } } /** * Is type primitive, including null and undefined * @param {any} value * @returns {boolean} */ function isPrimitive(value) { return Object(value) !== value; } function serializeFn({ data, depth, seen = new WeakSet(), transport = {}, } = {}) { const actualDepth = depth || transport.depth || 5; if (seen.has(data)) { return '[Circular]'; } if (actualDepth < 1) { if (isPrimitive(data)) { return data; } if (Array.isArray(data)) { return '[Array]'; } return `[${typeof data}]`; } if (['function', 'symbol'].includes(typeof data)) { return data.toString(); } if (isPrimitive(data)) { return data; } // Object types if (RESTRICTED_TYPES.has(data.constructor)) { return `[${data.constructor.name}]`; } if (Array.isArray(data)) { return data.map((item) => serializeFn({ data: item, depth: actualDepth - 1, seen, })); } if (data instanceof Date) { return data.toISOString(); } if (data instanceof Error) { return data.stack; } if (data instanceof Map) { return new Map( Array .from(data) .map(([key, value]) => [ serializeFn({ data: key, depth: actualDepth - 1, seen }), serializeFn({ data: value, depth: actualDepth - 1, seen }), ]), ); } if (data instanceof Set) { return new Set( Array.from(data).map( (val) => serializeFn({ data: val, depth: actualDepth - 1, seen }), ), ); } seen.add(data); return Object.fromEntries( Object.entries(data).map( ([key, value]) => [ key, serializeFn({ data: value, depth: actualDepth - 1, seen }), ], ), ); } import process from 'node:process'; import path from 'node:path'; import electron from 'electron'; import Conf from 'conf'; const {app, ipcMain, shell} = electron; let isInitialized = false; // Set up the `ipcMain` handler for communication between renderer and main process. const initDataListener = () => { if (!ipcMain || !app) { throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.'); } const appData = { defaultCwd: app.getPath('userData'), appVersion: app.getVersion(), }; if (isInitialized) { return appData; } ipcMain.on('electron-store-get-data', event => { event.returnValue = appData; }); isInitialized = true; return appData; }; export default class ElectronStore extends Conf { constructor(options) { let defaultCwd; let appVersion; // If we are in the renderer process, we communicate with the main process // to get the required data for the module otherwise, we pull from the main process. if (process.type === 'renderer') { const appData = electron.ipcRenderer.sendSync('electron-store-get-data'); if (!appData) { throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.'); } ({defaultCwd, appVersion} = appData); } else if (ipcMain && app) { ({defaultCwd, appVersion} = initDataListener()); } options = { name: 'config', ...options, }; options.projectVersion ||= appVersion; if (options.cwd) { options.cwd = path.isAbsolute(options.cwd) ? options.cwd : path.join(defaultCwd, options.cwd); } else { options.cwd = defaultCwd; } options.configName = options.name; delete options.name; super(options); } static initRenderer() { initDataListener(); } async openInEditor() { const error = await shell.openPath(this.path); if (error) { throw new Error(error); } } } MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "electron-store", "version": "11.0.2", "description": "Simple data persistence for your Electron app or module - Save and load user settings, app state, cache, etc", "license": "MIT", "repository": "sindresorhus/electron-store", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=20" }, "files": [ "index.js", "index.d.ts" ], "dependencies": { "conf": "^15.0.2", "type-fest": "^5.0.1" }, "devDependencies": { "ava": "^6.4.1", "electron": "^38.1.2", "execa": "^9.6.0", "tsd": "^0.33.0", "xo": "^0.60.0" }, "tsd": { "compilerOptions": { "module": "node16", "moduleResolution": "node16", "moduleDetection": "force" } } }The MIT License (MIT) Copyright (c) 2015 Loopline Systems 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. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getAppCacheDir = getAppCacheDir; const path = require("path"); const os_1 = require("os"); function getAppCacheDir() { const homedir = (0, os_1.homedir)(); // https://github.com/electron/electron/issues/1404#issuecomment-194391247 let result; if (process.platform === "win32") { result = process.env["LOCALAPPDATA"] || path.join(homedir, "AppData", "Local"); } else if (process.platform === "darwin") { result = path.join(homedir, "Library", "Caches"); } else { result = process.env["XDG_CACHE_HOME"] || path.join(homedir, ".cache"); } return result; } //# sourceMappingURL=AppAdapter.js.map{"version":3,"file":"AppAdapter.js","sourceRoot":"","sources":["../src/AppAdapter.ts"],"names":[],"mappings":";;AAiCA,wCAYC;AA7CD,6BAA4B;AAC5B,2BAA0C;AAgC1C,SAAgB,cAAc;IAC5B,MAAM,OAAO,GAAG,IAAA,YAAU,GAAE,CAAA;IAC5B,0EAA0E;IAC1E,IAAI,MAAc,CAAA;IAClB,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;QACjC,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAAA;IAChF,CAAC;SAAM,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACzC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAA;IAClD,CAAC;SAAM,CAAC;QACN,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;IACxE,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import * as path from \"path\"\nimport { homedir as getHomedir } from \"os\"\n\nexport interface AppAdapter {\n readonly version: string\n readonly name: string\n\n readonly isPackaged: boolean\n\n /**\n * Path to update metadata file.\n */\n readonly appUpdateConfigPath: string\n\n /**\n * Path to user data directory.\n */\n readonly userDataPath: string\n\n /**\n * Path to cache directory.\n */\n readonly baseCachePath: string\n\n whenReady(): Promise\n\n relaunch(): void\n\n quit(): void\n\n onQuit(handler: (exitCode: number) => void): void\n}\n\nexport function getAppCacheDir() {\n const homedir = getHomedir()\n // https://github.com/electron/electron/issues/1404#issuecomment-194391247\n let result: string\n if (process.platform === \"win32\") {\n result = process.env[\"LOCALAPPDATA\"] || path.join(homedir, \"AppData\", \"Local\")\n } else if (process.platform === \"darwin\") {\n result = path.join(homedir, \"Library\", \"Caches\")\n } else {\n result = process.env[\"XDG_CACHE_HOME\"] || path.join(homedir, \".cache\")\n }\n return result\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AppImageUpdater = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const child_process_1 = require("child_process"); const fs_extra_1 = require("fs-extra"); const fs_1 = require("fs"); const path = require("path"); const BaseUpdater_1 = require("./BaseUpdater"); const FileWithEmbeddedBlockMapDifferentialDownloader_1 = require("./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader"); const Provider_1 = require("./providers/Provider"); const types_1 = require("./types"); class AppImageUpdater extends BaseUpdater_1.BaseUpdater { constructor(options, app) { super(options, app); } isUpdaterActive() { if (process.env["APPIMAGE"] == null && !this.forceDevUpdateConfig) { if (process.env["SNAP"] == null) { this._logger.warn("APPIMAGE env is not defined, current application is not an AppImage"); } else { this._logger.info("SNAP env is defined, updater is disabled"); } return false; } return super.isUpdaterActive(); } /*** @private */ doDownloadUpdate(downloadUpdateOptions) { const provider = downloadUpdateOptions.updateInfoAndProvider.provider; const fileInfo = (0, Provider_1.findFile)(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "AppImage", ["rpm", "deb", "pacman"]); return this.executeDownload({ fileExtension: "AppImage", fileInfo, downloadUpdateOptions, task: async (updateFile, downloadOptions) => { const oldFile = process.env["APPIMAGE"]; if (oldFile == null) { throw (0, builder_util_runtime_1.newError)("APPIMAGE env is not defined", "ERR_UPDATER_OLD_FILE_NOT_FOUND"); } if (downloadUpdateOptions.disableDifferentialDownload || (await this.downloadDifferential(fileInfo, oldFile, updateFile, provider, downloadUpdateOptions))) { await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions); } await (0, fs_extra_1.chmod)(updateFile, 0o755); }, }); } async downloadDifferential(fileInfo, oldFile, updateFile, provider, downloadUpdateOptions) { try { const downloadOptions = { newUrl: fileInfo.url, oldFile, logger: this._logger, newFile: updateFile, isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest, requestHeaders: downloadUpdateOptions.requestHeaders, cancellationToken: downloadUpdateOptions.cancellationToken, }; if (this.listenerCount(types_1.DOWNLOAD_PROGRESS) > 0) { downloadOptions.onProgress = it => this.emit(types_1.DOWNLOAD_PROGRESS, it); } await new FileWithEmbeddedBlockMapDifferentialDownloader_1.FileWithEmbeddedBlockMapDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download(); return false; } catch (e) { this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`); // during test (developer machine mac) we must throw error return process.platform === "linux"; } } doInstall(options) { const appImageFile = process.env["APPIMAGE"]; if (appImageFile == null) { throw (0, builder_util_runtime_1.newError)("APPIMAGE env is not defined", "ERR_UPDATER_OLD_FILE_NOT_FOUND"); } if (!path.isAbsolute(appImageFile) || appImageFile.includes("\0")) { throw (0, builder_util_runtime_1.newError)(`APPIMAGE env is not a valid absolute path: "${appImageFile}"`, "ERR_UPDATER_OLD_FILE_NOT_FOUND"); } // https://stackoverflow.com/a/1712051/1910191 (0, fs_1.unlinkSync)(appImageFile); let destination; const existingBaseName = path.basename(appImageFile); const installerPath = this.installerPath; if (installerPath == null) { this.dispatchError(new Error("No update filepath provided, can't quit and install")); return false; } // https://github.com/electron-userland/electron-builder/issues/2964 // if no version in existing file name, it means that user wants to preserve current custom name if (path.basename(installerPath) === existingBaseName || !/\d+\.\d+\.\d+/.test(existingBaseName)) { // no version in the file name, overwrite existing destination = appImageFile; } else { destination = path.join(path.dirname(appImageFile), path.basename(installerPath)); } (0, child_process_1.execFileSync)("mv", ["-f", installerPath, destination]); if (destination !== appImageFile) { this.emit("appimage-filename-updated", destination); } const env = { ...process.env, APPIMAGE_SILENT_INSTALL: "true", }; if (options.isForceRunAfter) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.spawnLog(destination, [], env); } else { env.APPIMAGE_EXIT_AFTER_INSTALL = "true"; (0, child_process_1.execFileSync)(destination, [], { env }); } return true; } } exports.AppImageUpdater = AppImageUpdater; //# sourceMappingURL=AppImageUpdater.js.map{"version":3,"file":"AppImageUpdater.js","sourceRoot":"","sources":["../src/AppImageUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAAkE;AAClE,iDAA4C;AAC5C,uCAAgC;AAChC,2BAA+B;AAC/B,6BAA4B;AAE5B,+CAA2D;AAE3D,4IAAwI;AACxI,mDAAyD;AACzD,mCAAmE;AAEnE,MAAa,eAAgB,SAAQ,yBAAW;IAC9C,YAAY,OAAkC,EAAE,GAAS;QACvD,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;IACrB,CAAC;IAEM,eAAe;QACpB,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,oBAAoB,EAAE,CAAC;YAClE,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;gBAChC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,qEAAqE,CAAC,CAAA;YAC1F,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAA;YAC/D,CAAC;YACD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,OAAO,KAAK,CAAC,eAAe,EAAE,CAAA;IAChC,CAAC;IAED,gBAAgB;IACN,gBAAgB,CAAC,qBAA4C;QACrE,MAAM,QAAQ,GAAG,qBAAqB,CAAC,qBAAqB,CAAC,QAAQ,CAAA;QACrE,MAAM,QAAQ,GAAG,IAAA,mBAAQ,EAAC,QAAQ,C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E,CAAC;YAC1B,IAAI,CAAC,aAAa,CAAC,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC,CAAA;YACpF,OAAO,KAAK,CAAA;QACd,CAAC;QACD,oEAAoE;QACpE,gGAAgG;QAChG,IAAI,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,KAAK,gBAAgB,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,gBAAgB,CAAC,EAAE,CAAC;YACjG,kDAAkD;YAClD,WAAW,GAAG,YAAY,CAAA;QAC5B,CAAC;aAAM,CAAC;YACN,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAA;QACnF,CAAC;QAED,IAAA,4BAAY,EAAC,IAAI,EAAE,CAAC,IAAI,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAA;QACtD,IAAI,WAAW,KAAK,YAAY,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,2BAA2B,EAAE,WAAW,CAAC,CAAA;QACrD,CAAC;QAED,MAAM,GAAG,GAAsB;YAC7B,GAAG,OAAO,CAAC,GAAG;YACd,uBAAuB,EAAE,MAAM;SAChC,CAAA;QAED,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;YAC5B,mEAAmE;YACnE,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,EAAE,EAAE,GAAG,CAAC,CAAA;QACrC,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,2BAA2B,GAAG,MAAM,CAAA;YACxC,IAAA,4BAAY,EAAC,WAAW,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAA;QACxC,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAhHD,0CAgHC","sourcesContent":["import { AllPublishOptions, newError } from \"builder-util-runtime\"\nimport { execFileSync } from \"child_process\"\nimport { chmod } from \"fs-extra\"\nimport { unlinkSync } from \"fs\"\nimport * as path from \"path\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { BaseUpdater, InstallOptions } from \"./BaseUpdater\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { FileWithEmbeddedBlockMapDifferentialDownloader } from \"./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader\"\nimport { findFile, Provider } from \"./providers/Provider\"\nimport { DOWNLOAD_PROGRESS, ResolvedUpdateFileInfo } from \"./types\"\n\nexport class AppImageUpdater extends BaseUpdater {\n constructor(options?: AllPublishOptions | null, app?: any) {\n super(options, app)\n }\n\n public isUpdaterActive(): boolean {\n if (process.env[\"APPIMAGE\"] == null && !this.forceDevUpdateConfig) {\n if (process.env[\"SNAP\"] == null) {\n this._logger.warn(\"APPIMAGE env is not defined, current application is not an AppImage\")\n } else {\n this._logger.info(\"SNAP env is defined, updater is disabled\")\n }\n return false\n }\n return super.isUpdaterActive()\n }\n\n /*** @private */\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise> {\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), \"AppImage\", [\"rpm\", \"deb\", \"pacman\"])!\n return this.executeDownload({\n fileExtension: \"AppImage\",\n fileInfo,\n downloadUpdateOptions,\n task: async (updateFile, downloadOptions) => {\n const oldFile = process.env[\"APPIMAGE\"]!\n if (oldFile == null) {\n throw newError(\"APPIMAGE env is not defined\", \"ERR_UPDATER_OLD_FILE_NOT_FOUND\")\n }\n\n if (downloadUpdateOptions.disableDifferentialDownload || (await this.downloadDifferential(fileInfo, oldFile, updateFile, provider, downloadUpdateOptions))) {\n await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions)\n }\n\n await chmod(updateFile, 0o755)\n },\n })\n }\n\n private async downloadDifferential(fileInfo: ResolvedUpdateFileInfo, oldFile: string, updateFile: string, provider: Provider, downloadUpdateOptions: DownloadUpdateOptions) {\n try {\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: fileInfo.url,\n oldFile,\n logger: this._logger,\n newFile: updateFile,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n requestHeaders: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n await new FileWithEmbeddedBlockMapDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download()\n return false\n } catch (e: any) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n // during test (developer machine mac) we must throw error\n return process.platform === \"linux\"\n }\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const appImageFile = process.env[\"APPIMAGE\"]!\n if (appImageFile == null) {\n throw newError(\"APPIMAGE env is not defined\", \"ERR_UPDATER_OLD_FILE_NOT_FOUND\")\n }\n if (!path.isAbsolute(appImageFile) || appImageFile.includes(\"\\0\")) {\n throw newError(`APPIMAGE env is not a valid absolute path: \"${appImageFile}\"`, \"ERR_UPDATER_OLD_FILE_NOT_FOUND\")\n }\n\n // https://stackoverflow.com/a/1712051/1910191\n unlinkSync(appImageFile)\n\n let destination: string\n const existingBaseName = path.basename(appImageFile)\n const installerPath = this.installerPath\n if (installerPath == null) {\n this.dispatchError(new Error(\"No update filepath provided, can't quit and install\"))\n return false\n }\n // https://github.com/electron-userland/electron-builder/issues/2964\n // if no version in existing file name, it means that user wants to preserve current custom name\n if (path.basename(installerPath) === existingBaseName || !/\\d+\\.\\d+\\.\\d+/.test(existingBaseName)) {\n // no version in the file name, overwrite existing\n destination = appImageFile\n } else {\n destination = path.join(path.dirname(appImageFile), path.basename(installerPath))\n }\n\n execFileSync(\"mv\", [\"-f\", installerPath, destination])\n if (destination !== appImageFile) {\n this.emit(\"appimage-filename-updated\", destination)\n }\n\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n APPIMAGE_SILENT_INSTALL: \"true\",\n }\n\n if (options.isForceRunAfter) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.spawnLog(destination, [], env)\n } else {\n env.APPIMAGE_EXIT_AFTER_INSTALL = \"true\"\n execFileSync(destination, [], { env })\n }\n return true\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NoOpLogger = exports.AppUpdater = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const crypto_1 = require("crypto"); const os_1 = require("os"); const events_1 = require("events"); const fs_extra_1 = require("fs-extra"); const js_yaml_1 = require("js-yaml"); const lazy_val_1 = require("lazy-val"); const path = require("path"); const semver_1 = require("semver"); const DownloadedUpdateHelper_1 = require("./DownloadedUpdateHelper"); const ElectronAppAdapter_1 = require("./ElectronAppAdapter"); const electronHttpExecutor_1 = require("./electronHttpExecutor"); const GenericProvider_1 = require("./providers/GenericProvider"); const providerFactory_1 = require("./providerFactory"); const zlib_1 = require("zlib"); const GenericDifferentialDownloader_1 = require("./differentialDownloader/GenericDifferentialDownloader"); const types_1 = require("./types"); class AppUpdater extends events_1.EventEmitter { /** * Get the update channel. Doesn't return `channel` from the update configuration, only if was previously set. */ get channel() { return this._channel; } /** * Set the update channel. Overrides `channel` in the update configuration. * * `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after. */ set channel(value) { if (this._channel != null) { // noinspection SuspiciousTypeOfGuard if (typeof value !== "string") { throw (0, builder_util_runtime_1.newError)(`Channel must be a string, but got: ${value}`, "ERR_UPDATER_INVALID_CHANNEL"); } else if (value.length === 0) { throw (0, builder_util_runtime_1.newError)(`Channel must be not an empty string`, "ERR_UPDATER_INVALID_CHANNEL"); } } this._channel = value; this.allowDowngrade = true; } /** * Shortcut for explicitly adding auth tokens to request headers */ addAuthHeader(token) { this.requestHeaders = Object.assign({}, this.requestHeaders, { authorization: token, }); } // noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols get netSession() { return (0, electronHttpExecutor_1.getNetSession)(); } /** * The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`. * Set it to `null` if you would like to disable a logging feature. */ get logger() { return this._logger; } set logger(value) { this._logger = value == null ? new NoOpLogger() : value; } // noinspection JSUnusedGlobalSymbols /** * test only * @private */ set updateConfigPath(value) { this.clientPromise = null; this._appUpdateConfigPath = value; this.configOnDisk = new lazy_val_1.Lazy(() => this.loadUpdateConfig()); } /** * Allows developer to override default logic for determining if an update is supported. * The default logic compares the `UpdateInfo` minimum system version against the `os.release()` with `semver` package */ get isUpdateSupported() { return this._isUpdateSupported; } set isUpdateSupported(value) { if (value) { this._isUpdateSupported = value; } } /** * Allows developer to override default logic for determining if the user is below the rollout threshold. * The default logic compares the staging percentage with numerical representation of user ID. * An override can define custom logic, or bypass it if needed. */ get isUserWithinRollout() { return this._isUserWithinRollout; } set isUserWithinRollout(value) { if (value) { this._isUserWithinRollout = value; } } constructor(options, app) { super(); /** * Whether to automatically download an update when it is found. * @default true */ this.autoDownload = true; /** * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before). * @default true */ this.autoInstallOnAppQuit = true; /** * Whether to run the app after finish install when run the installer is NOT in silent mode. * @default true */ this.autoRunAppAfterInstall = true; /** * *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`. * * If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`). */ this.allowPrerelease = false; /** * *GitHub provider only.* Get all release notes (from current version to latest), not just the latest. * @default false */ this.fullChangelog = false; /** * Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel). * * Taken in account only if channel differs (pre-release version component in terms of semantic versioning). * * @default false */ this.allowDowngrade = false; /** * Web installer files might not have signature verification, this switch prevents to load them unless it is needed. * * Currently false to prevent breaking the current API, but it should be changed to default true at some point that * breaking changes are allowed. * * @default false */ this.disableWebInstaller = false; /** * *NSIS only* Disable differential downloads and always perform full download of installer. * * @default false */ this.disableDifferentialDownload = false; /** * Allows developer to force the updater to work in "dev" mode, looking for "dev-app-update.yml" instead of "app-update.yml" * Dev: `path.join(this.app.getAppPath(), "dev-app-update.yml")` * Prod: `path.join(process.resourcesPath!, "app-update.yml")` * * @default false */ this.forceDevUpdateConfig = false; /** * The base URL of the old block map file. * * When null, the updater will use the base URL of the update file to download the update. * When set, the updater will use this string as the base URL of the old block map file. * Some servers like github cannot download the old block map file from latest release, * so you need to compute the old block map file base URL manually. * * @default null */ this.previousBlockmapBaseUrlOverride = null; this._channel = null; this.downloadedUpdateHelper = null; /** * The request headers. */ this.requestHeaders = null; this._logger = console; // noinspection JSUnusedGlobalSymbols /** * For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})` */ this.signals = new types_1.UpdaterSignal(this); this._appUpdateConfigPath = null; this._isUpdateSupported = updateInfo => this.checkIfUpdateSupported(updateInfo); this._isUserWithinRollout = updateInfo => this.isStagingMatch(updateInfo); this.clientPromise = null; this.stagingUserIdPromise = new lazy_val_1.Lazy(() => this.getOrCreateStagingUserId()); // public, allow to read old config for anyone /** @internal */ this.configOnDisk = new lazy_val_1.Lazy(() => this.loadUpdateConfig()); this.checkForUpdatesPromise = null; this.downloadPromise = null; this.updateInfoAndProvider = null; /** * @private * @internal */ this._testOnlyOptions = null; this.on("error", (error) => { this._logger.error(`Error: ${error.stack || error.message}`); }); if (app == null) { this.app = new ElectronAppAdapter_1.ElectronAppAdapter(); this.httpExecutor = new electronHttpExecutor_1.ElectronHttpExecutor((authInfo, callback) => this.emit("login", authInfo, callback)); } else { this.app = app; this.httpExecutor = null; } const currentVersionString = this.app.version; const currentVersion = (0, semver_1.parse)(currentVersionString); if (currentVersion == null) { throw (0, builder_util_runtime_1.newError)(`App version is not a valid semver version: "${currentVersionString}"`, "ERR_UPDATER_INVALID_VERSION"); } this.currentVersion = currentVersion; this.allowPrerelease = hasPrereleaseComponents(currentVersion); if (options != null) { this.setFeedURL(options); if (typeof options !== "string" && options.requestHeaders) { this.requestHeaders = options.requestHeaders; } } } //noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols getFeedURL() { return "Deprecated. Do not use it."; } /** * Configure update provider. If value is `string`, [GenericServerOptions](https://www.electron.build/publish#genericserveroptions) will be set with value as `url`. * @param options If you want to override configuration in the `app-update.yml`. */ setFeedURL(options) { const runtimeOptions = this.createProviderRuntimeOptions(); // https://github.com/electron-userland/electron-builder/issues/1105 let provider; if (typeof options === "string") { provider = new GenericProvider_1.GenericProvider({ provider: "generic", url: options }, this, { ...runtimeOptions, isUseMultipleRangeRequest: (0, providerFactory_1.isUrlProbablySupportMultiRangeRequests)(options), }); } else { provider = (0, providerFactory_1.createClient)(options, this, runtimeOptions); } this.clientPromise = Promise.resolve(provider); } /** * Asks the server whether there is an update. * @returns null if the updater is disabled, otherwise info about the latest version */ checkForUpdates() { if (!this.isUpdaterActive()) { return Promise.resolve(null); } let checkForUpdatesPromise = this.checkForUpdatesPromise; if (checkForUpdatesPromise != null) { this._logger.info("Checking for update (already in progress)"); return checkForUpdatesPromise; } const nullizePromise = () => (this.checkForUpdatesPromise = null); this._logger.info("Checking for update"); checkForUpdatesPromise = this.doCheckForUpdates() .then(it => { nullizePromise(); return it; }) .catch((e) => { nullizePromise(); this.emit("error", e, `Cannot check for updates: ${(e.stack || e).toString()}`); throw e; }); this.checkForUpdatesPromise = checkForUpdatesPromise; return checkForUpdatesPromise; } isUpdaterActive() { const isEnabled = this.app.isPackaged || this.forceDevUpdateConfig; if (!isEnabled) { this._logger.info("Skip checkForUpdates because application is not packed and dev update config is not forced"); return false; } return true; } // noinspection JSUnusedGlobalSymbols checkForUpdatesAndNotify(downloadNotification) { return this.checkForUpdates().then(it => { if (!(it === null || it === void 0 ? void 0 : it.downloadPromise)) { if (this._logger.debug != null) { this._logger.debug("checkForUpdatesAndNotify called, downloadPromise is null"); } return it; } void it.downloadPromise.then(() => { const notificationContent = AppUpdater.formatDownloadNotification(it.updateInfo.version, this.app.name, downloadNotification); new (require("electron").Notification)(notificationContent).show(); }); return it; }); } static formatDownloadNotification(version, appName, downloadNotification) { if (downloadNotification == null) { downloadNotification = { title: "A new update is ready to install", body: `{appName} version {version} has been downloaded and will be automatically installed on exit`, }; } downloadNotification = { title: downloadNotification.title.replace("{appName}", appName).replace("{version}", version), body: downloadNotification.body.replace("{appName}", appName).replace("{version}", version), }; return downloadNotification; } async isStagingMatch(updateInfo) { const rawStagingPercentage = updateInfo.stagingPercentage; let stagingPercentage = rawStagingPercentage; if (stagingPercentage == null) { return true; } stagingPercentage = parseInt(stagingPercentage, 10); if (isNaN(stagingPercentage)) { this._logger.warn(`Staging percentage is NaN: ${rawStagingPercentage}`); return true; } // convert from user 0-100 to internal 0-1 stagingPercentage = stagingPercentage / 100; const stagingUserId = await this.stagingUserIdPromise.value; const val = builder_util_runtime_1.UUID.parse(stagingUserId).readUInt32BE(12); const percentage = val / 0xffffffff; this._logger.info(`Staging percentage: ${stagingPercentage}, percentage: ${percentage}, user id: ${stagingUserId}`); return percentage < stagingPercentage; } computeFinalHeaders(headers) { if (this.requestHeaders != null) { Object.assign(headers, this.requestHeaders); } return headers; } async isUpdateAvailable(updateInfo) { const latestVersion = (0, semver_1.parse)(updateInfo.version); if (latestVersion == null) { throw (0, builder_util_runtime_1.newError)(`This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: "${updateInfo.version}"`, "ERR_UPDATER_INVALID_VERSION"); } const currentVersion = this.currentVersion; if ((0, semver_1.eq)(latestVersion, currentVersion)) { return false; } if (!(await Promise.resolve(this.isUpdateSupported(updateInfo)))) { return false; } const isUserWithinRollout = await Promise.resolve(this.isUserWithinRollout(updateInfo)); if (!isUserWithinRollout) { return false; } // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405033227 // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405030797 const isLatestVersionNewer = (0, semver_1.gt)(latestVersion, currentVersion); const isLatestVersionOlder = (0, semver_1.lt)(latestVersion, currentVersion); if (isLatestVersionNewer) { return true; } return this.allowDowngrade && isLatestVersionOlder; } checkIfUpdateSupported(updateInfo) { const minimumSystemVersion = updateInfo === null || updateInfo === void 0 ? void 0 : updateInfo.minimumSystemVersion; const currentOSVersion = (0, os_1.release)(); if (minimumSystemVersion) { try { if ((0, semver_1.lt)(currentOSVersion, minimumSystemVersion)) { this._logger.info(`Current OS version ${currentOSVersion} is less than the minimum OS version required ${minimumSystemVersion} for version ${currentOSVersion}`); return false; } } catch (e) { this._logger.warn(`Failed to compare current OS version(${currentOSVersion}) with minimum OS version(${minimumSystemVersion}): ${(e.message || e).toString()}`); } } return true; } async getUpdateInfoAndProvider() { await this.app.whenReady(); if (this.clientPromise == null) { this.clientPromise = this.configOnDisk.value.then(it => (0, providerFactory_1.createClient)(it, this, this.createProviderRuntimeOptions())); } const client = await this.clientPromise; const stagingUserId = await this.stagingUserIdPromise.value; client.setRequestHeaders(this.computeFinalHeaders({ "x-user-staging-id": stagingUserId })); return { info: await client.getLatestVersion(), provider: client, }; } createProviderRuntimeOptions() { return { isUseMultipleRangeRequest: true, platform: this._testOnlyOptions == null ? process.platform : this._testOnlyOptions.platform, executor: this.httpExecutor, }; } async doCheckForUpdates() { this.emit("checking-for-update"); const result = await this.getUpdateInfoAndProvider(); const updateInfo = result.info; if (!(await this.isUpdateAvailable(updateInfo))) { this._logger.info(`Update for version ${this.currentVersion.format()} is not available (latest version: ${updateInfo.version}, downgrade is ${this.allowDowngrade ? "allowed" : "disallowed"}).`); this.emit("update-not-available", updateInfo); return { isUpdateAvailable: false, versionInfo: updateInfo, updateInfo, }; } this.updateInfoAndProvider = result; this.onUpdateAvailable(updateInfo); const cancellationToken = new builder_util_runtime_1.CancellationToken(); //noinspection ES6MissingAwait return { isUpdateAvailable: true, versionInfo: updateInfo, updateInfo, cancellationToken, downloadPromise: this.autoDownload ? this.downloadUpdate(cancellationToken) : null, }; } onUpdateAvailable(updateInfo) { this._logger.info(`Found version ${updateInfo.version} (url: ${(0, builder_util_runtime_1.asArray)(updateInfo.files) .map(it => it.url) .join(", ")})`); this.emit("update-available", updateInfo); } /** * Start downloading update manually. You can use this method if `autoDownload` option is set to `false`. * @returns {Promise>} Paths to downloaded files. */ downloadUpdate(cancellationToken = new builder_util_runtime_1.CancellationToken()) { const updateInfoAndProvider = this.updateInfoAndProvider; if (updateInfoAndProvider == null) { const error = new Error("Please check update first"); this.dispatchError(error); return Promise.reject(error); } if (this.downloadPromise != null) { this._logger.info("Downloading update (already in progress)"); return this.downloadPromise; } this._logger.info(`Downloading update from ${(0, builder_util_runtime_1.asArray)(updateInfoAndProvider.info.files) .map(it => it.url) .join(", ")}`); const errorHandler = (e) => { // https://github.com/electron-userland/electron-builder/issues/1150#issuecomment-436891159 if (!(e instanceof builder_util_runtime_1.CancellationError)) { try { this.dispatchError(e); } catch (nestedError) { this._logger.warn(`Cannot dispatch error event: ${nestedError.stack || nestedError}`); } } return e; }; this.downloadPromise = this.doDownloadUpdate({ updateInfoAndProvider, requestHeaders: this.computeRequestHeaders(updateInfoAndProvider.provider), cancellationToken, disableWebInstaller: this.disableWebInstaller, disableDifferentialDownload: this.disableDifferentialDownload, }) .catch((e) => { throw errorHandler(e); }) .finally(() => { this.downloadPromise = null; }); return this.downloadPromise; } dispatchError(e) { this.emit("error", e, (e.stack || e).toString()); } dispatchUpdateDownloaded(event) { this.emit(types_1.UPDATE_DOWNLOADED, event); } async loadUpdateConfig() { if (this._appUpdateConfigPath == null) { this._appUpdateConfigPath = this.app.appUpdateConfigPath; } return (0, js_yaml_1.load)(await (0, fs_extra_1.readFile)(this._appUpdateConfigPath, "utf-8")); } computeRequestHeaders(provider) { const fileExtraDownloadHeaders = provider.fileExtraDownloadHeaders; if (fileExtraDownloadHeaders != null) { const requestHeaders = this.requestHeaders; return requestHeaders == null ? fileExtraDownloadHeaders : { ...fileExtraDownloadHeaders, ...requestHeaders, }; } return this.computeFinalHeaders({ accept: "*/*" }); } async getOrCreateStagingUserId() { const file = path.join(this.app.userDataPath, ".updaterId"); try { const id = await (0, fs_extra_1.readFile)(file, "utf-8"); if (builder_util_runtime_1.UUID.check(id)) { return id; } else { this._logger.warn(`Staging user id file exists, but content was invalid: ${id}`); } } catch (e) { if (e.code !== "ENOENT") { this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`); } } const id = builder_util_runtime_1.UUID.v5((0, crypto_1.randomBytes)(4096), builder_util_runtime_1.UUID.OID); this._logger.info(`Generated new staging user ID: ${id}`); try { await (0, fs_extra_1.outputFile)(file, id); } catch (e) { this._logger.warn(`Couldn't write out staging user ID: ${e}`); } return id; } /** @internal */ get isAddNoCacheQuery() { const headers = this.requestHeaders; // https://github.com/electron-userland/electron-builder/issues/3021 if (headers == null) { return true; } for (const headerName of Object.keys(headers)) { const s = headerName.toLowerCase(); if (s === "authorization" || s === "private-token") { return false; } } return true; } async getOrCreateDownloadHelper() { let result = this.downloadedUpdateHelper; if (result == null) { const dirName = (await this.configOnDisk.value).updaterCacheDirName; const logger = this._logger; if (dirName == null) { logger.error("updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?"); } const cacheDir = path.join(this.app.baseCachePath, dirName || this.app.name); if (logger.debug != null) { logger.debug(`updater cache dir: ${cacheDir}`); } result = new DownloadedUpdateHelper_1.DownloadedUpdateHelper(cacheDir); this.downloadedUpdateHelper = result; } return result; } async executeDownload(taskOptions) { const fileInfo = taskOptions.fileInfo; const downloadOptions = { headers: taskOptions.downloadUpdateOptions.requestHeaders, cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken, sha2: fileInfo.info.sha2, sha512: fileInfo.info.sha512, }; if (this.listenerCount(types_1.DOWNLOAD_PROGRESS) > 0) { downloadOptions.onProgress = it => this.emit(types_1.DOWNLOAD_PROGRESS, it); } const updateInfo = taskOptions.downloadUpdateOptions.updateInfoAndProvider.info; const version = updateInfo.version; const packageInfo = fileInfo.packageInfo; function getCacheUpdateFileName() { // NodeJS URL doesn't decode automatically const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname); if (urlPath.toLowerCase().endsWith(`.${taskOptions.fileExtension.toLowerCase()}`)) { return path.basename(urlPath); } else { // url like /latest — use basename so a server-supplied path like "../../etc/evil" // cannot escape the cache directory via path.join return path.basename(taskOptions.fileInfo.info.url); } } const downloadedUpdateHelper = await this.getOrCreateDownloadHelper(); const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate; await (0, fs_extra_1.mkdir)(cacheDir, { recursive: true }); const updateFileName = getCacheUpdateFileName(); let updateFile = path.join(cacheDir, updateFileName); const packageFile = packageInfo == null ? null : path.join(cacheDir, `package-${version}${path.extname(packageInfo.path) || ".7z"}`); const done = async (isSaveCache) => { await downloadedUpdateHelper.setDownloadedFile(updateFile, packageFile, updateInfo, fileInfo, updateFileName, isSaveCache); await taskOptions.done({ ...updateInfo, downloadedFile: updateFile, }); const currentBlockMapFile = path.join(cacheDir, "current.blockmap"); if (await (0, fs_extra_1.pathExists)(currentBlockMapFile)) { await (0, fs_extra_1.copyFile)(currentBlockMapFile, path.join(downloadedUpdateHelper.cacheDir, "current.blockmap")); } return packageFile == null ? [updateFile] : [updateFile, packageFile]; }; const log = this._logger; const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(updateFile, updateInfo, fileInfo, log); if (cachedUpdateFile != null) { updateFile = cachedUpdateFile; return await done(false); } const removeFileIfAny = async () => { await downloadedUpdateHelper.clear().catch(() => { // ignore }); return await (0, fs_extra_1.unlink)(updateFile).catch(() => { // ignore }); }; const tempUpdateFile = await (0, DownloadedUpdateHelper_1.createTempUpdateFile)(`temp-${updateFileName}`, cacheDir, log); try { await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny); await (0, builder_util_runtime_1.retry)(() => (0, fs_extra_1.rename)(tempUpdateFile, updateFile), { retries: 60, interval: 500, shouldRetry: (error) => { if (error instanceof Error && /^EBUSY:/.test(error.message)) { return true; } log.warn(`Cannot rename temp file to final file: ${error.message || error.stack}`); return false; }, }); } catch (e) { await removeFileIfAny(); if (e instanceof builder_util_runtime_1.CancellationError) { log.info("cancelled"); this.emit("update-cancelled", updateInfo); } throw e; } log.info(`New version ${version} has been downloaded to ${updateFile}`); return await done(true); } async differentialDownloadInstaller(fileInfo, downloadUpdateOptions, installerPath, provider, oldInstallerFileName) { try { if (this._testOnlyOptions != null && !this._testOnlyOptions.isUseDifferentialDownload) { return true; } const provider = downloadUpdateOptions.updateInfoAndProvider.provider; const blockmapFileUrls = await provider.getBlockMapFiles(fileInfo.url, this.app.version, downloadUpdateOptions.updateInfoAndProvider.info.version, this.previousBlockmapBaseUrlOverride); this._logger.info(`Download block maps (old: "${blockmapFileUrls[0]}", new: ${blockmapFileUrls[1]})`); const downloadBlockMap = async (url) => { const data = await this.httpExecutor.downloadToBuffer(url, { headers: downloadUpdateOptions.requestHeaders, cancellationToken: downloadUpdateOptions.cancellationToken, }); if (data == null || data.length === 0) { throw new Error(`Blockmap "${url.href}" is empty`); } try { return JSON.parse((0, zlib_1.gunzipSync)(data).toString()); } catch (e) { throw new Error(`Cannot parse blockmap "${url.href}", error: ${e}`); } }; const downloadOptions = { newUrl: fileInfo.url, oldFile: path.join(this.downloadedUpdateHelper.cacheDir, oldInstallerFileName), logger: this._logger, newFile: installerPath, isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest, requestHeaders: downloadUpdateOptions.requestHeaders, cancellationToken: downloadUpdateOptions.cancellationToken, }; if (this.listenerCount(types_1.DOWNLOAD_PROGRESS) > 0) { downloadOptions.onProgress = it => this.emit(types_1.DOWNLOAD_PROGRESS, it); } const saveBlockMapToCacheDir = async (blockMapData, cacheDir) => { const blockMapFile = path.join(cacheDir, "current.blockmap"); await (0, fs_extra_1.outputFile)(blockMapFile, (0, zlib_1.gzipSync)(JSON.stringify(blockMapData))); }; const getBlockMapFromCacheDir = async (cacheDir) => { const blockMapFile = path.join(cacheDir, "current.blockmap"); try { if (await (0, fs_extra_1.pathExists)(blockMapFile)) { return JSON.parse((0, zlib_1.gunzipSync)(await (0, fs_extra_1.readFile)(blockMapFile)).toString()); } } catch (e) { this._logger.warn(`Cannot parse blockmap "${blockMapFile}", error: ${e}`); } return null; }; const newBlockMapData = await downloadBlockMap(blockmapFileUrls[1]); await saveBlockMapToCacheDir(newBlockMapData, this.downloadedUpdateHelper.cacheDirForPendingUpdate); // get old blockmap from cache dir first, if not found, download it let oldBlockMapData = await getBlockMapFromCacheDir(this.downloadedUpdateHelper.cacheDir); if (oldBlockMapData == null) { oldBlockMapData = await downloadBlockMap(blockmapFileUrls[0]); } await new GenericDifferentialDownloader_1.GenericDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download(oldBlockMapData, newBlockMapData); return false; } catch (e) { this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`); if (this._testOnlyOptions != null) { // test mode throw e; } return true; } } } exports.AppUpdater = AppUpdater; function hasPrereleaseComponents(version) { const versionPrereleaseComponent = (0, semver_1.prerelease)(version); return versionPrereleaseComponent != null && versionPrereleaseComponent.length > 0; } /** @private */ class NoOpLogger { // eslint-disable-next-line @typescript-eslint/no-unused-vars info(message) { // ignore } // eslint-disable-next-line @typescript-eslint/no-unused-vars warn(message) { // ignore } // eslint-disable-next-line @typescript-eslint/no-unused-vars error(message) { // ignore } } exports.NoOpLogger = NoOpLogger; //# sourceMappingURL=AppUpdater.js.map{"version":3,"file":"AppUpdater.js","sourceRoot":"","sources":["../src/AppUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAa6B;AAC7B,mCAAoC;AACpC,2BAA4B;AAC5B,mCAAqC;AACrC,uCAA4F;AAE5F,qCAA8B;AAC9B,uCAA+B;AAC/B,6BAA4B;AAC5B,mCAA8K;AAE9K,qEAAuF;AACvF,6DAAyD;AACzD,iEAA2F;AAC3F,iEAA6D;AAC7D,uDAAwF;AAKxF,+BAA2C;AAE3C,0GAAs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ellationToken,\n newError,\n PublishConfiguration,\n UpdateInfo,\n UUID,\n DownloadOptions,\n CancellationError,\n ProgressInfo,\n BlockMap,\n retry,\n} from \"builder-util-runtime\"\nimport { randomBytes } from \"crypto\"\nimport { release } from \"os\"\nimport { EventEmitter } from \"events\"\nimport { mkdir, outputFile, readFile, rename, unlink, copyFile, pathExists } from \"fs-extra\"\nimport { OutgoingHttpHeaders } from \"http\"\nimport { load } from \"js-yaml\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { eq as isVersionsEqual, gt as isVersionGreaterThan, lt as isVersionLessThan, parse as parseVersion, prerelease as getVersionPreleaseComponents, SemVer } from \"semver\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { createTempUpdateFile, DownloadedUpdateHelper } from \"./DownloadedUpdateHelper\"\nimport { ElectronAppAdapter } from \"./ElectronAppAdapter\"\nimport { ElectronHttpExecutor, getNetSession, LoginCallback } from \"./electronHttpExecutor\"\nimport { GenericProvider } from \"./providers/GenericProvider\"\nimport { createClient, isUrlProbablySupportMultiRangeRequests } from \"./providerFactory\"\nimport { Provider, ProviderPlatform } from \"./providers/Provider\"\nimport type { TypedEmitter } from \"tiny-typed-emitter\"\nimport Session = Electron.Session\nimport type { AuthInfo } from \"electron\"\nimport { gunzipSync, gzipSync } from \"zlib\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { GenericDifferentialDownloader } from \"./differentialDownloader/GenericDifferentialDownloader\"\nimport { DOWNLOAD_PROGRESS, Logger, ResolvedUpdateFileInfo, UPDATE_DOWNLOADED, UpdateCheckResult, UpdateDownloadedEvent, UpdaterSignal } from \"./types\"\nimport { VerifyUpdateSupport } from \"./main\"\n\nexport type AppUpdaterEvents = {\n error: (error: Error, message?: string) => void\n login: (info: AuthInfo, callback: LoginCallback) => void\n \"checking-for-update\": () => void\n \"update-not-available\": (info: UpdateInfo) => void\n \"update-available\": (info: UpdateInfo) => void\n \"update-downloaded\": (event: UpdateDownloadedEvent) => void\n \"download-progress\": (info: ProgressInfo) => void\n \"update-cancelled\": (info: UpdateInfo) => void\n \"appimage-filename-updated\": (path: string) => void\n}\n\nexport abstract class AppUpdater extends (EventEmitter as new () => TypedEmitter) {\n /**\n * Whether to automatically download an update when it is found.\n * @default true\n */\n autoDownload = true\n\n /**\n * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).\n * @default true\n */\n autoInstallOnAppQuit = true\n\n /**\n * Whether to run the app after finish install when run the installer is NOT in silent mode.\n * @default true\n */\n autoRunAppAfterInstall = true\n\n /**\n * *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`.\n *\n * If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`).\n */\n allowPrerelease = false\n\n /**\n * *GitHub provider only.* Get all release notes (from current version to latest), not just the latest.\n * @default false\n */\n fullChangelog = false\n\n /**\n * Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).\n *\n * Taken in account only if channel differs (pre-release version component in terms of semantic versioning).\n *\n * @default false\n */\n allowDowngrade = false\n\n /**\n * Web installer files might not have signature verification, this switch prevents to load them unless it is needed.\n *\n * Currently false to prevent breaking the current API, but it should be changed to default true at some point that\n * breaking changes are allowed.\n *\n * @default false\n */\n disableWebInstaller = false\n\n /**\n * *NSIS only* Disable differential downloads and always perform full download of installer.\n *\n * @default false\n */\n disableDifferentialDownload = false\n\n /**\n * Allows developer to force the updater to work in \"dev\" mode, looking for \"dev-app-update.yml\" instead of \"app-update.yml\"\n * Dev: `path.join(this.app.getAppPath(), \"dev-app-update.yml\")`\n * Prod: `path.join(process.resourcesPath!, \"app-update.yml\")`\n *\n * @default false\n */\n forceDevUpdateConfig = false\n\n /**\n * The base URL of the old block map file.\n *\n * When null, the updater will use the base URL of the update file to download the update.\n * When set, the updater will use this string as the base URL of the old block map file.\n * Some servers like github cannot download the old block map file from latest release,\n * so you need to compute the old block map file base URL manually.\n *\n * @default null\n */\n public previousBlockmapBaseUrlOverride: string | null = null\n\n /**\n * The current application version.\n */\n readonly currentVersion: SemVer\n\n private _channel: string | null = null\n\n protected downloadedUpdateHelper: DownloadedUpdateHelper | null = null\n\n /**\n * Get the update channel. Doesn't return `channel` from the update configuration, only if was previously set.\n */\n get channel(): string | null {\n return this._channel\n }\n\n /**\n * Set the update channel. Overrides `channel` in the update configuration.\n *\n * `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after.\n */\n set channel(value: string | null) {\n if (this._channel != null) {\n // noinspection SuspiciousTypeOfGuard\n if (typeof value !== \"string\") {\n throw newError(`Channel must be a string, but got: ${value}`, \"ERR_UPDATER_INVALID_CHANNEL\")\n } else if (value.length === 0) {\n throw newError(`Channel must be not an empty string`, \"ERR_UPDATER_INVALID_CHANNEL\")\n }\n }\n\n this._channel = value\n this.allowDowngrade = true\n }\n\n /**\n * The request headers.\n */\n requestHeaders: OutgoingHttpHeaders | null = null\n\n /**\n * Shortcut for explicitly adding auth tokens to request headers\n */\n addAuthHeader(token: string) {\n this.requestHeaders = Object.assign({}, this.requestHeaders, {\n authorization: token,\n })\n }\n\n protected _logger: Logger = console\n\n // noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n get netSession(): Session {\n return getNetSession()\n }\n\n /**\n * The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`.\n * Set it to `null` if you would like to disable a logging feature.\n */\n get logger(): Logger | null {\n return this._logger\n }\n\n set logger(value: Logger | null) {\n this._logger = value == null ? new NoOpLogger() : value\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})`\n */\n readonly signals = new UpdaterSignal(this)\n\n private _appUpdateConfigPath: string | null = null\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * test only\n * @private\n */\n set updateConfigPath(value: string | null) {\n this.clientPromise = null\n this._appUpdateConfigPath = value\n this.configOnDisk = new Lazy(() => this.loadUpdateConfig())\n }\n\n protected _isUpdateSupported: VerifyUpdateSupport = updateInfo => this.checkIfUpdateSupported(updateInfo)\n\n /**\n * Allows developer to override default logic for determining if an update is supported.\n * The default logic compares the `UpdateInfo` minimum system version against the `os.release()` with `semver` package\n */\n get isUpdateSupported(): VerifyUpdateSupport {\n return this._isUpdateSupported\n }\n\n set isUpdateSupported(value: VerifyUpdateSupport) {\n if (value) {\n this._isUpdateSupported = value\n }\n }\n\n protected _isUserWithinRollout: VerifyUpdateSupport = updateInfo => this.isStagingMatch(updateInfo)\n\n /**\n * Allows developer to override default logic for determining if the user is below the rollout threshold.\n * The default logic compares the staging percentage with numerical representation of user ID.\n * An override can define custom logic, or bypass it if needed.\n */\n get isUserWithinRollout(): VerifyUpdateSupport {\n return this._isUserWithinRollout\n }\n\n set isUserWithinRollout(value: VerifyUpdateSupport) {\n if (value) {\n this._isUserWithinRollout = value\n }\n }\n\n private clientPromise: Promise> | null = null\n\n protected readonly stagingUserIdPromise = new Lazy(() => this.getOrCreateStagingUserId())\n\n // public, allow to read old config for anyone\n /** @internal */\n configOnDisk = new Lazy(() => this.loadUpdateConfig())\n\n private checkForUpdatesPromise: Promise | null = null\n private downloadPromise: Promise> | null = null\n\n protected readonly app: AppAdapter\n\n protected updateInfoAndProvider: UpdateInfoAndProvider | null = null\n\n /** @internal */\n readonly httpExecutor: ElectronHttpExecutor\n\n protected constructor(options: AllPublishOptions | null | undefined, app?: AppAdapter) {\n super()\n\n this.on(\"error\", (error: Error) => {\n this._logger.error(`Error: ${error.stack || error.message}`)\n })\n\n if (app == null) {\n this.app = new ElectronAppAdapter()\n this.httpExecutor = new ElectronHttpExecutor((authInfo, callback) => this.emit(\"login\", authInfo, callback))\n } else {\n this.app = app\n this.httpExecutor = null as any\n }\n\n const currentVersionString = this.app.version\n const currentVersion = parseVersion(currentVersionString)\n if (currentVersion == null) {\n throw newError(`App version is not a valid semver version: \"${currentVersionString}\"`, \"ERR_UPDATER_INVALID_VERSION\")\n }\n this.currentVersion = currentVersion\n this.allowPrerelease = hasPrereleaseComponents(currentVersion)\n\n if (options != null) {\n this.setFeedURL(options)\n\n if (typeof options !== \"string\" && options.requestHeaders) {\n this.requestHeaders = options.requestHeaders\n }\n }\n }\n\n //noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n getFeedURL(): string | null | undefined {\n return \"Deprecated. Do not use it.\"\n }\n\n /**\n * Configure update provider. If value is `string`, [GenericServerOptions](https://www.electron.build/publish#genericserveroptions) will be set with value as `url`.\n * @param options If you want to override configuration in the `app-update.yml`.\n */\n setFeedURL(options: PublishConfiguration | AllPublishOptions | string) {\n const runtimeOptions = this.createProviderRuntimeOptions()\n // https://github.com/electron-userland/electron-builder/issues/1105\n let provider: Provider\n if (typeof options === \"string\") {\n provider = new GenericProvider({ provider: \"generic\", url: options }, this, {\n ...runtimeOptions,\n isUseMultipleRangeRequest: isUrlProbablySupportMultiRangeRequests(options),\n })\n } else {\n provider = createClient(options, this, runtimeOptions)\n }\n this.clientPromise = Promise.resolve(provider)\n }\n\n /**\n * Asks the server whether there is an update.\n * @returns null if the updater is disabled, otherwise info about the latest version\n */\n checkForUpdates(): Promise {\n if (!this.isUpdaterActive()) {\n return Promise.resolve(null)\n }\n\n let checkForUpdatesPromise = this.checkForUpdatesPromise\n if (checkForUpdatesPromise != null) {\n this._logger.info(\"Checking for update (already in progress)\")\n return checkForUpdatesPromise\n }\n\n const nullizePromise = () => (this.checkForUpdatesPromise = null)\n\n this._logger.info(\"Checking for update\")\n checkForUpdatesPromise = this.doCheckForUpdates()\n .then(it => {\n nullizePromise()\n return it\n })\n .catch((e: any) => {\n nullizePromise()\n this.emit(\"error\", e, `Cannot check for updates: ${(e.stack || e).toString()}`)\n throw e\n })\n\n this.checkForUpdatesPromise = checkForUpdatesPromise\n return checkForUpdatesPromise\n }\n\n public isUpdaterActive(): boolean {\n const isEnabled = this.app.isPackaged || this.forceDevUpdateConfig\n if (!isEnabled) {\n this._logger.info(\"Skip checkForUpdates because application is not packed and dev update config is not forced\")\n return false\n }\n return true\n }\n\n // noinspection JSUnusedGlobalSymbols\n checkForUpdatesAndNotify(downloadNotification?: DownloadNotification): Promise {\n return this.checkForUpdates().then(it => {\n if (!it?.downloadPromise) {\n if (this._logger.debug != null) {\n this._logger.debug(\"checkForUpdatesAndNotify called, downloadPromise is null\")\n }\n return it\n }\n\n void it.downloadPromise.then(() => {\n const notificationContent = AppUpdater.formatDownloadNotification(it.updateInfo.version, this.app.name, downloadNotification)\n new (require(\"electron\").Notification)(notificationContent).show()\n })\n\n return it\n })\n }\n\n private static formatDownloadNotification(version: string, appName: string, downloadNotification?: DownloadNotification): DownloadNotification {\n if (downloadNotification == null) {\n downloadNotification = {\n title: \"A new update is ready to install\",\n body: `{appName} version {version} has been downloaded and will be automatically installed on exit`,\n }\n }\n downloadNotification = {\n title: downloadNotification.title.replace(\"{appName}\", appName).replace(\"{version}\", version),\n body: downloadNotification.body.replace(\"{appName}\", appName).replace(\"{version}\", version),\n }\n return downloadNotification\n }\n\n private async isStagingMatch(updateInfo: UpdateInfo): Promise {\n const rawStagingPercentage = updateInfo.stagingPercentage\n let stagingPercentage = rawStagingPercentage\n if (stagingPercentage == null) {\n return true\n }\n\n stagingPercentage = parseInt(stagingPercentage as any, 10)\n if (isNaN(stagingPercentage)) {\n this._logger.warn(`Staging percentage is NaN: ${rawStagingPercentage}`)\n return true\n }\n\n // convert from user 0-100 to internal 0-1\n stagingPercentage = stagingPercentage / 100\n\n const stagingUserId = await this.stagingUserIdPromise.value\n const val = UUID.parse(stagingUserId).readUInt32BE(12)\n const percentage = val / 0xffffffff\n this._logger.info(`Staging percentage: ${stagingPercentage}, percentage: ${percentage}, user id: ${stagingUserId}`)\n return percentage < stagingPercentage\n }\n\n private computeFinalHeaders(headers: OutgoingHttpHeaders) {\n if (this.requestHeaders != null) {\n Object.assign(headers, this.requestHeaders)\n }\n return headers\n }\n\n private async isUpdateAvailable(updateInfo: UpdateInfo): Promise {\n const latestVersion = parseVersion(updateInfo.version)\n if (latestVersion == null) {\n throw newError(\n `This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: \"${updateInfo.version}\"`,\n \"ERR_UPDATER_INVALID_VERSION\"\n )\n }\n\n const currentVersion = this.currentVersion\n if (isVersionsEqual(latestVersion, currentVersion)) {\n return false\n }\n\n if (!(await Promise.resolve(this.isUpdateSupported(updateInfo)))) {\n return false\n }\n\n const isUserWithinRollout = await Promise.resolve(this.isUserWithinRollout(updateInfo))\n if (!isUserWithinRollout) {\n return false\n }\n\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405033227\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405030797\n const isLatestVersionNewer = isVersionGreaterThan(latestVersion, currentVersion)\n const isLatestVersionOlder = isVersionLessThan(latestVersion, currentVersion)\n\n if (isLatestVersionNewer) {\n return true\n }\n return this.allowDowngrade && isLatestVersionOlder\n }\n\n private checkIfUpdateSupported(updateInfo: UpdateInfo) {\n const minimumSystemVersion = updateInfo?.minimumSystemVersion\n const currentOSVersion = release()\n if (minimumSystemVersion) {\n try {\n if (isVersionLessThan(currentOSVersion, minimumSystemVersion)) {\n this._logger.info(`Current OS version ${currentOSVersion} is less than the minimum OS version required ${minimumSystemVersion} for version ${currentOSVersion}`)\n return false\n }\n } catch (e: any) {\n this._logger.warn(`Failed to compare current OS version(${currentOSVersion}) with minimum OS version(${minimumSystemVersion}): ${(e.message || e).toString()}`)\n }\n }\n return true\n }\n\n protected async getUpdateInfoAndProvider(): Promise {\n await this.app.whenReady()\n\n if (this.clientPromise == null) {\n this.clientPromise = this.configOnDisk.value.then(it => createClient(it, this, this.createProviderRuntimeOptions()))\n }\n\n const client = await this.clientPromise\n const stagingUserId = await this.stagingUserIdPromise.value\n client.setRequestHeaders(this.computeFinalHeaders({ \"x-user-staging-id\": stagingUserId }))\n return {\n info: await client.getLatestVersion(),\n provider: client,\n }\n }\n\n private createProviderRuntimeOptions() {\n return {\n isUseMultipleRangeRequest: true,\n platform: this._testOnlyOptions == null ? (process.platform as ProviderPlatform) : this._testOnlyOptions.platform,\n executor: this.httpExecutor,\n }\n }\n\n private async doCheckForUpdates(): Promise {\n this.emit(\"checking-for-update\")\n\n const result = await this.getUpdateInfoAndProvider()\n const updateInfo = result.info\n if (!(await this.isUpdateAvailable(updateInfo))) {\n this._logger.info(\n `Update for version ${this.currentVersion.format()} is not available (latest version: ${updateInfo.version}, downgrade is ${\n this.allowDowngrade ? \"allowed\" : \"disallowed\"\n }).`\n )\n this.emit(\"update-not-available\", updateInfo)\n return {\n isUpdateAvailable: false,\n versionInfo: updateInfo,\n updateInfo,\n }\n }\n\n this.updateInfoAndProvider = result\n this.onUpdateAvailable(updateInfo)\n\n const cancellationToken = new CancellationToken()\n //noinspection ES6MissingAwait\n return {\n isUpdateAvailable: true,\n versionInfo: updateInfo,\n updateInfo,\n cancellationToken,\n downloadPromise: this.autoDownload ? this.downloadUpdate(cancellationToken) : null,\n }\n }\n\n protected onUpdateAvailable(updateInfo: UpdateInfo): void {\n this._logger.info(\n `Found version ${updateInfo.version} (url: ${asArray(updateInfo.files)\n .map(it => it.url)\n .join(\", \")})`\n )\n this.emit(\"update-available\", updateInfo)\n }\n\n /**\n * Start downloading update manually. You can use this method if `autoDownload` option is set to `false`.\n * @returns {Promise>} Paths to downloaded files.\n */\n downloadUpdate(cancellationToken: CancellationToken = new CancellationToken()): Promise> {\n const updateInfoAndProvider = this.updateInfoAndProvider\n if (updateInfoAndProvider == null) {\n const error = new Error(\"Please check update first\")\n this.dispatchError(error)\n return Promise.reject(error)\n }\n\n if (this.downloadPromise != null) {\n this._logger.info(\"Downloading update (already in progress)\")\n return this.downloadPromise\n }\n\n this._logger.info(\n `Downloading update from ${asArray(updateInfoAndProvider.info.files)\n .map(it => it.url)\n .join(\", \")}`\n )\n const errorHandler = (e: Error): Error => {\n // https://github.com/electron-userland/electron-builder/issues/1150#issuecomment-436891159\n if (!(e instanceof CancellationError)) {\n try {\n this.dispatchError(e)\n } catch (nestedError: any) {\n this._logger.warn(`Cannot dispatch error event: ${nestedError.stack || nestedError}`)\n }\n }\n\n return e\n }\n\n this.downloadPromise = this.doDownloadUpdate({\n updateInfoAndProvider,\n requestHeaders: this.computeRequestHeaders(updateInfoAndProvider.provider),\n cancellationToken,\n disableWebInstaller: this.disableWebInstaller,\n disableDifferentialDownload: this.disableDifferentialDownload,\n })\n .catch((e: any) => {\n throw errorHandler(e)\n })\n .finally(() => {\n this.downloadPromise = null\n })\n\n return this.downloadPromise\n }\n\n protected dispatchError(e: Error): void {\n this.emit(\"error\", e, (e.stack || e).toString())\n }\n\n protected dispatchUpdateDownloaded(event: UpdateDownloadedEvent): void {\n this.emit(UPDATE_DOWNLOADED, event)\n }\n\n protected abstract doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise>\n\n /**\n * Restarts the app and installs the update after it has been downloaded.\n * It should only be called after `update-downloaded` has been emitted.\n *\n * **Note:** `autoUpdater.quitAndInstall()` will close all application windows first and only emit `before-quit` event on `app` after that.\n * This is different from the normal quit event sequence.\n *\n * @param isSilent *windows-only* Runs the installer in silent mode. Defaults to `false`.\n * @param isForceRunAfter Run the app after finish even on silent install. Not applicable for macOS.\n * Ignored if `isSilent` is set to `false`(In this case you can still set `autoRunAppAfterInstall` to `false` to prevent run the app after finish).\n */\n abstract quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void\n\n private async loadUpdateConfig(): Promise {\n if (this._appUpdateConfigPath == null) {\n this._appUpdateConfigPath = this.app.appUpdateConfigPath\n }\n return load(await readFile(this._appUpdateConfigPath, \"utf-8\"))\n }\n\n private computeRequestHeaders(provider: Provider): OutgoingHttpHeaders {\n const fileExtraDownloadHeaders = provider.fileExtraDownloadHeaders\n if (fileExtraDownloadHeaders != null) {\n const requestHeaders = this.requestHeaders\n return requestHeaders == null\n ? fileExtraDownloadHeaders\n : {\n ...fileExtraDownloadHeaders,\n ...requestHeaders,\n }\n }\n return this.computeFinalHeaders({ accept: \"*/*\" })\n }\n\n private async getOrCreateStagingUserId(): Promise {\n const file = path.join(this.app.userDataPath, \".updaterId\")\n try {\n const id = await readFile(file, \"utf-8\")\n if (UUID.check(id)) {\n return id\n } else {\n this._logger.warn(`Staging user id file exists, but content was invalid: ${id}`)\n }\n } catch (e: any) {\n if (e.code !== \"ENOENT\") {\n this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`)\n }\n }\n\n const id = UUID.v5(randomBytes(4096), UUID.OID)\n this._logger.info(`Generated new staging user ID: ${id}`)\n try {\n await outputFile(file, id)\n } catch (e: any) {\n this._logger.warn(`Couldn't write out staging user ID: ${e}`)\n }\n return id\n }\n\n /** @internal */\n get isAddNoCacheQuery(): boolean {\n const headers = this.requestHeaders\n // https://github.com/electron-userland/electron-builder/issues/3021\n if (headers == null) {\n return true\n }\n\n for (const headerName of Object.keys(headers)) {\n const s = headerName.toLowerCase()\n if (s === \"authorization\" || s === \"private-token\") {\n return false\n }\n }\n return true\n }\n\n /**\n * @private\n * @internal\n */\n _testOnlyOptions: TestOnlyUpdaterOptions | null = null\n\n private async getOrCreateDownloadHelper(): Promise {\n let result = this.downloadedUpdateHelper\n if (result == null) {\n const dirName = (await this.configOnDisk.value).updaterCacheDirName\n const logger = this._logger\n if (dirName == null) {\n logger.error(\"updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?\")\n }\n const cacheDir = path.join(this.app.baseCachePath, dirName || this.app.name)\n if (logger.debug != null) {\n logger.debug(`updater cache dir: ${cacheDir}`)\n }\n\n result = new DownloadedUpdateHelper(cacheDir)\n this.downloadedUpdateHelper = result\n }\n return result\n }\n\n protected async executeDownload(taskOptions: DownloadExecutorTask): Promise> {\n const fileInfo = taskOptions.fileInfo\n const downloadOptions: DownloadOptions = {\n headers: taskOptions.downloadUpdateOptions.requestHeaders,\n cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken,\n sha2: (fileInfo.info as any).sha2,\n sha512: fileInfo.info.sha512,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const updateInfo = taskOptions.downloadUpdateOptions.updateInfoAndProvider.info\n const version = updateInfo.version\n const packageInfo = fileInfo.packageInfo\n\n function getCacheUpdateFileName(): string {\n // NodeJS URL doesn't decode automatically\n const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname)\n if (urlPath.toLowerCase().endsWith(`.${taskOptions.fileExtension.toLowerCase()}`)) {\n return path.basename(urlPath)\n } else {\n // url like /latest — use basename so a server-supplied path like \"../../etc/evil\"\n // cannot escape the cache directory via path.join\n return path.basename(taskOptions.fileInfo.info.url)\n }\n }\n\n const downloadedUpdateHelper = await this.getOrCreateDownloadHelper()\n const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate\n await mkdir(cacheDir, { recursive: true })\n const updateFileName = getCacheUpdateFileName()\n let updateFile = path.join(cacheDir, updateFileName)\n const packageFile = packageInfo == null ? null : path.join(cacheDir, `package-${version}${path.extname(packageInfo.path) || \".7z\"}`)\n\n const done = async (isSaveCache: boolean) => {\n await downloadedUpdateHelper.setDownloadedFile(updateFile, packageFile, updateInfo, fileInfo, updateFileName, isSaveCache)\n await taskOptions.done!({\n ...updateInfo,\n downloadedFile: updateFile,\n })\n const currentBlockMapFile = path.join(cacheDir, \"current.blockmap\")\n if (await pathExists(currentBlockMapFile)) {\n await copyFile(currentBlockMapFile, path.join(downloadedUpdateHelper.cacheDir, \"current.blockmap\"))\n }\n return packageFile == null ? [updateFile] : [updateFile, packageFile]\n }\n\n const log = this._logger\n const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(updateFile, updateInfo, fileInfo, log)\n if (cachedUpdateFile != null) {\n updateFile = cachedUpdateFile\n return await done(false)\n }\n\n const removeFileIfAny = async () => {\n await downloadedUpdateHelper.clear().catch(() => {\n // ignore\n })\n return await unlink(updateFile).catch(() => {\n // ignore\n })\n }\n\n const tempUpdateFile = await createTempUpdateFile(`temp-${updateFileName}`, cacheDir, log)\n try {\n await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny)\n await retry(() => rename(tempUpdateFile, updateFile), {\n retries: 60,\n interval: 500,\n shouldRetry: (error: Error) => {\n if (error instanceof Error && /^EBUSY:/.test(error.message)) {\n return true\n }\n log.warn(`Cannot rename temp file to final file: ${error.message || error.stack}`)\n return false\n },\n })\n } catch (e: any) {\n await removeFileIfAny()\n\n if (e instanceof CancellationError) {\n log.info(\"cancelled\")\n this.emit(\"update-cancelled\", updateInfo)\n }\n throw e\n }\n\n log.info(`New version ${version} has been downloaded to ${updateFile}`)\n return await done(true)\n }\n protected async differentialDownloadInstaller(\n fileInfo: ResolvedUpdateFileInfo,\n downloadUpdateOptions: DownloadUpdateOptions,\n installerPath: string,\n provider: Provider,\n oldInstallerFileName: string\n ): Promise {\n try {\n if (this._testOnlyOptions != null && !this._testOnlyOptions.isUseDifferentialDownload) {\n return true\n }\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const blockmapFileUrls = await provider.getBlockMapFiles(\n fileInfo.url,\n this.app.version,\n downloadUpdateOptions.updateInfoAndProvider.info.version,\n this.previousBlockmapBaseUrlOverride\n )\n this._logger.info(`Download block maps (old: \"${blockmapFileUrls[0]}\", new: ${blockmapFileUrls[1]})`)\n\n const downloadBlockMap = async (url: URL): Promise => {\n const data = await this.httpExecutor.downloadToBuffer(url, {\n headers: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n })\n\n if (data == null || data.length === 0) {\n throw new Error(`Blockmap \"${url.href}\" is empty`)\n }\n\n try {\n return JSON.parse(gunzipSync(data).toString())\n } catch (e: any) {\n throw new Error(`Cannot parse blockmap \"${url.href}\", error: ${e}`)\n }\n }\n\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: fileInfo.url,\n oldFile: path.join(this.downloadedUpdateHelper!.cacheDir, oldInstallerFileName),\n logger: this._logger,\n newFile: installerPath,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n requestHeaders: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const saveBlockMapToCacheDir = async (blockMapData: BlockMap, cacheDir: string) => {\n const blockMapFile = path.join(cacheDir, \"current.blockmap\")\n await outputFile(blockMapFile, gzipSync(JSON.stringify(blockMapData)))\n }\n\n const getBlockMapFromCacheDir = async (cacheDir: string) => {\n const blockMapFile = path.join(cacheDir, \"current.blockmap\")\n try {\n if (await pathExists(blockMapFile)) {\n return JSON.parse(gunzipSync(await readFile(blockMapFile)).toString())\n }\n } catch (e: any) {\n this._logger.warn(`Cannot parse blockmap \"${blockMapFile}\", error: ${e}`)\n }\n return null\n }\n\n const newBlockMapData = await downloadBlockMap(blockmapFileUrls[1])\n await saveBlockMapToCacheDir(newBlockMapData, this.downloadedUpdateHelper!.cacheDirForPendingUpdate)\n\n // get old blockmap from cache dir first, if not found, download it\n let oldBlockMapData = await getBlockMapFromCacheDir(this.downloadedUpdateHelper!.cacheDir)\n if (oldBlockMapData == null) {\n oldBlockMapData = await downloadBlockMap(blockmapFileUrls[0])\n }\n\n await new GenericDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download(oldBlockMapData, newBlockMapData)\n return false\n } catch (e: any) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n if (this._testOnlyOptions != null) {\n // test mode\n throw e\n }\n return true\n }\n }\n}\n\nexport interface DownloadUpdateOptions {\n readonly updateInfoAndProvider: UpdateInfoAndProvider\n readonly requestHeaders: OutgoingHttpHeaders\n readonly cancellationToken: CancellationToken\n readonly disableWebInstaller?: boolean\n readonly disableDifferentialDownload?: boolean\n}\n\nfunction hasPrereleaseComponents(version: SemVer) {\n const versionPrereleaseComponent = getVersionPreleaseComponents(version)\n return versionPrereleaseComponent != null && versionPrereleaseComponent.length > 0\n}\n\n/** @private */\nexport class NoOpLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n warn(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(message?: any) {\n // ignore\n }\n}\n\nexport interface UpdateInfoAndProvider {\n info: UpdateInfo\n provider: Provider\n}\n\nexport interface DownloadExecutorTask {\n readonly fileExtension: string\n readonly fileInfo: ResolvedUpdateFileInfo\n readonly downloadUpdateOptions: DownloadUpdateOptions\n readonly task: (destinationFile: string, downloadOptions: DownloadOptions, packageFile: string | null, removeTempDirIfAny: () => Promise) => Promise\n\n readonly done?: (event: UpdateDownloadedEvent) => Promise\n}\n\nexport interface DownloadNotification {\n body: string\n title: string\n}\n\n/** @private */\nexport interface TestOnlyUpdaterOptions {\n platform: ProviderPlatform\n\n isUseDifferentialDownload?: boolean\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseUpdater = void 0; const child_process_1 = require("child_process"); const path = require("path"); const AppUpdater_1 = require("./AppUpdater"); class BaseUpdater extends AppUpdater_1.AppUpdater { constructor(options, app) { super(options, app); this.quitAndInstallCalled = false; this.quitHandlerAdded = false; } quitAndInstall(isSilent = false, isForceRunAfter = false) { this._logger.info(`Install on explicit quitAndInstall`); // If NOT in silent mode use `autoRunAppAfterInstall` to determine whether to force run the app const isInstalled = this.install(isSilent, isSilent ? isForceRunAfter : this.autoRunAppAfterInstall); if (isInstalled) { setImmediate(() => { // this event is normally emitted when calling quitAndInstall, this emulates that require("electron").autoUpdater.emit("before-quit-for-update"); this.app.quit(); }); } else { this.quitAndInstallCalled = false; } } executeDownload(taskOptions) { return super.executeDownload({ ...taskOptions, done: event => { this.dispatchUpdateDownloaded(event); this.addQuitHandler(); return Promise.resolve(); }, }); } get installerPath() { return this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.file; } // must be sync (because quit even handler is not async) install(isSilent = false, isForceRunAfter = false) { if (this.quitAndInstallCalled) { this._logger.warn("install call ignored: quitAndInstallCalled is set to true"); return false; } const downloadedUpdateHelper = this.downloadedUpdateHelper; const installerPath = this.installerPath; const downloadedFileInfo = downloadedUpdateHelper == null ? null : downloadedUpdateHelper.downloadedFileInfo; if (installerPath == null || downloadedFileInfo == null) { this.dispatchError(new Error("No update filepath provided, can't quit and install")); return false; } // prevent calling several times this.quitAndInstallCalled = true; try { this._logger.info(`Install: isSilent: ${isSilent}, isForceRunAfter: ${isForceRunAfter}`); return this.doInstall({ isSilent, isForceRunAfter, isAdminRightsRequired: downloadedFileInfo.isAdminRightsRequired, }); } catch (e) { this.dispatchError(e); return false; } } addQuitHandler() { if (this.quitHandlerAdded || !this.autoInstallOnAppQuit) { return; } this.quitHandlerAdded = true; this.app.onQuit(exitCode => { if (this.quitAndInstallCalled) { this._logger.info("Update installer has already been triggered. Quitting application."); return; } if (!this.autoInstallOnAppQuit) { this._logger.info("Update will not be installed on quit because autoInstallOnAppQuit is set to false."); return; } if (exitCode !== 0) { this._logger.info(`Update will be not installed on quit because application is quitting with exit code ${exitCode}`); return; } this._logger.info("Auto install update on quit"); this.install(true, false); }); } /** * Strips relative-path entries from a PATH string. * Prevents PATH-poisoning where a writable directory earlier in PATH shadows * a trusted package manager binary. */ sanitizeEnvPath(envPath) { return envPath .split(path.delimiter) .filter((dir) => path.isAbsolute(dir)) .join(path.delimiter); } spawnSyncLog(cmd, args = [], env = {}) { var _a; this._logger.info(`Executing: ${cmd} with args: ${args}`); const mergedEnv = { ...process.env, ...env }; const response = (0, child_process_1.spawnSync)(cmd, args, { env: { ...mergedEnv, PATH: this.sanitizeEnvPath((_a = mergedEnv.PATH) !== null && _a !== void 0 ? _a : "") }, encoding: "utf-8", shell: true, }); const { error, status, stdout, stderr } = response; if (error != null) { this._logger.error(stderr); throw error; } else if (status != null && status !== 0) { this._logger.error(stderr); throw new Error(`Command ${cmd} exited with code ${status}`); } return stdout.trim(); } /** * This handles both node 8 and node 10 way of emitting error when spawning a process * - node 8: Throws the error * - node 10: Emit the error(Need to listen with on) */ // https://github.com/electron-userland/electron-builder/issues/1129 // Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors async spawnLog(cmd, args = [], env = undefined, stdio = "ignore") { this._logger.info(`Executing: ${cmd} with args: ${args}`); return new Promise((resolve, reject) => { try { const params = { stdio, env, detached: true }; const p = (0, child_process_1.spawn)(cmd, args, params); p.on("error", error => { reject(error); }); p.unref(); if (p.pid !== undefined) { resolve(true); } } catch (error) { reject(error); } }); } } exports.BaseUpdater = BaseUpdater; //# sourceMappingURL=BaseUpdater.js.map{"version":3,"file":"BaseUpdater.js","sourceRoot":"","sources":["../src/BaseUpdater.ts"],"names":[],"mappings":";;;AACA,iDAA4E;AAC5E,6BAA4B;AAE5B,6CAA+D;AAE/D,MAAsB,WAAY,SAAQ,uBAAU;IAIlD,YAAsB,OAAkC,EAAE,GAAgB;QACxE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;QAJX,yBAAoB,GAAG,KAAK,CAAA;QAC9B,qBAAgB,GAAG,KAAK,CAAA;IAIhC,CAAC;IAED,cAAc,CAAC,QAAQ,GAAG,KAAK,EAAE,eAAe,GAAG,KAAK;QACtD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAA;QACvD,+FAA+F;QAC/F,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAA;QACpG,IAAI,WAAW,EAAE,CAAC;YAChB,YAAY,CAAC,GAAG,EAAE;gBAChB,iFA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CAAC,CAAA;QAC9D,CAAC;QAED,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;IAED;;;;OAIG;IACH,oEAAoE;IACpE,4GAA4G;IAClG,KAAK,CAAC,QAAQ,CAAC,GAAW,EAAE,OAAiB,EAAE,EAAE,MAAW,SAAS,EAAE,QAAsB,QAAQ;QAC7G,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,GAAG,eAAe,IAAI,EAAE,CAAC,CAAA;QACzD,OAAO,IAAI,OAAO,CAAU,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC9C,IAAI,CAAC;gBACH,MAAM,MAAM,GAAiB,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAA;gBAC3D,MAAM,CAAC,GAAG,IAAA,qBAAK,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAA;gBAClC,CAAC,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE;oBACpB,MAAM,CAAC,KAAK,CAAC,CAAA;gBACf,CAAC,CAAC,CAAA;gBACF,CAAC,CAAC,KAAK,EAAE,CAAA;gBACT,IAAI,CAAC,CAAC,GAAG,KAAK,SAAS,EAAE,CAAC;oBACxB,OAAO,CAAC,IAAI,CAAC,CAAA;gBACf,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,KAAK,CAAC,CAAA;YACf,CAAC;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA9JD,kCA8JC","sourcesContent":["import { AllPublishOptions } from \"builder-util-runtime\"\nimport { spawn, SpawnOptions, spawnSync, StdioOptions } from \"child_process\"\nimport * as path from \"path\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { AppUpdater, DownloadExecutorTask } from \"./AppUpdater\"\n\nexport abstract class BaseUpdater extends AppUpdater {\n protected quitAndInstallCalled = false\n private quitHandlerAdded = false\n\n protected constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n quitAndInstall(isSilent = false, isForceRunAfter = false): void {\n this._logger.info(`Install on explicit quitAndInstall`)\n // If NOT in silent mode use `autoRunAppAfterInstall` to determine whether to force run the app\n const isInstalled = this.install(isSilent, isSilent ? isForceRunAfter : this.autoRunAppAfterInstall)\n if (isInstalled) {\n setImmediate(() => {\n // this event is normally emitted when calling quitAndInstall, this emulates that\n require(\"electron\").autoUpdater.emit(\"before-quit-for-update\")\n this.app.quit()\n })\n } else {\n this.quitAndInstallCalled = false\n }\n }\n\n protected executeDownload(taskOptions: DownloadExecutorTask): Promise> {\n return super.executeDownload({\n ...taskOptions,\n done: event => {\n this.dispatchUpdateDownloaded(event)\n this.addQuitHandler()\n return Promise.resolve()\n },\n })\n }\n\n protected get installerPath(): string | null {\n return this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.file\n }\n\n // must be sync\n protected abstract doInstall(options: InstallOptions): boolean\n\n // must be sync (because quit even handler is not async)\n install(isSilent = false, isForceRunAfter = false): boolean {\n if (this.quitAndInstallCalled) {\n this._logger.warn(\"install call ignored: quitAndInstallCalled is set to true\")\n return false\n }\n\n const downloadedUpdateHelper = this.downloadedUpdateHelper\n const installerPath = this.installerPath\n const downloadedFileInfo = downloadedUpdateHelper == null ? null : downloadedUpdateHelper.downloadedFileInfo\n if (installerPath == null || downloadedFileInfo == null) {\n this.dispatchError(new Error(\"No update filepath provided, can't quit and install\"))\n return false\n }\n\n // prevent calling several times\n this.quitAndInstallCalled = true\n\n try {\n this._logger.info(`Install: isSilent: ${isSilent}, isForceRunAfter: ${isForceRunAfter}`)\n return this.doInstall({\n isSilent,\n isForceRunAfter,\n isAdminRightsRequired: downloadedFileInfo.isAdminRightsRequired,\n })\n } catch (e: any) {\n this.dispatchError(e)\n return false\n }\n }\n\n protected addQuitHandler(): void {\n if (this.quitHandlerAdded || !this.autoInstallOnAppQuit) {\n return\n }\n\n this.quitHandlerAdded = true\n\n this.app.onQuit(exitCode => {\n if (this.quitAndInstallCalled) {\n this._logger.info(\"Update installer has already been triggered. Quitting application.\")\n return\n }\n\n if (!this.autoInstallOnAppQuit) {\n this._logger.info(\"Update will not be installed on quit because autoInstallOnAppQuit is set to false.\")\n return\n }\n\n if (exitCode !== 0) {\n this._logger.info(`Update will be not installed on quit because application is quitting with exit code ${exitCode}`)\n return\n }\n\n this._logger.info(\"Auto install update on quit\")\n this.install(true, false)\n })\n }\n\n /**\n * Strips relative-path entries from a PATH string.\n * Prevents PATH-poisoning where a writable directory earlier in PATH shadows\n * a trusted package manager binary.\n */\n protected sanitizeEnvPath(envPath: string): string {\n return envPath\n .split(path.delimiter)\n .filter((dir: string) => path.isAbsolute(dir))\n .join(path.delimiter)\n }\n\n protected spawnSyncLog(cmd: string, args: string[] = [], env = {}): string {\n this._logger.info(`Executing: ${cmd} with args: ${args}`)\n const mergedEnv: NodeJS.ProcessEnv = { ...process.env, ...env }\n const response = spawnSync(cmd, args, {\n env: { ...mergedEnv, PATH: this.sanitizeEnvPath(mergedEnv.PATH ?? \"\") },\n encoding: \"utf-8\",\n shell: true,\n })\n\n const { error, status, stdout, stderr } = response\n if (error != null) {\n this._logger.error(stderr)\n throw error\n } else if (status != null && status !== 0) {\n this._logger.error(stderr)\n throw new Error(`Command ${cmd} exited with code ${status}`)\n }\n\n return stdout.trim()\n }\n\n /**\n * This handles both node 8 and node 10 way of emitting error when spawning a process\n * - node 8: Throws the error\n * - node 10: Emit the error(Need to listen with on)\n */\n // https://github.com/electron-userland/electron-builder/issues/1129\n // Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors\n protected async spawnLog(cmd: string, args: string[] = [], env: any = undefined, stdio: StdioOptions = \"ignore\"): Promise {\n this._logger.info(`Executing: ${cmd} with args: ${args}`)\n return new Promise((resolve, reject) => {\n try {\n const params: SpawnOptions = { stdio, env, detached: true }\n const p = spawn(cmd, args, params)\n p.on(\"error\", error => {\n reject(error)\n })\n p.unref()\n if (p.pid !== undefined) {\n resolve(true)\n }\n } catch (error) {\n reject(error)\n }\n })\n }\n}\n\nexport interface InstallOptions {\n readonly isSilent: boolean\n readonly isForceRunAfter: boolean\n readonly isAdminRightsRequired: boolean\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DebUpdater = void 0; const Provider_1 = require("./providers/Provider"); const types_1 = require("./types"); const LinuxUpdater_1 = require("./LinuxUpdater"); class DebUpdater extends LinuxUpdater_1.LinuxUpdater { constructor(options, app) { super(options, app); } /*** @private */ doDownloadUpdate(downloadUpdateOptions) { const provider = downloadUpdateOptions.updateInfoAndProvider.provider; const fileInfo = (0, Provider_1.findFile)(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "deb", ["AppImage", "rpm", "pacman"]); return this.executeDownload({ fileExtension: "deb", fileInfo, downloadUpdateOptions, task: async (updateFile, downloadOptions) => { if (this.listenerCount(types_1.DOWNLOAD_PROGRESS) > 0) { downloadOptions.onProgress = it => this.emit(types_1.DOWNLOAD_PROGRESS, it); } await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions); }, }); } doInstall(options) { const installerPath = this.installerPath; if (installerPath == null) { this.dispatchError(new Error("No update filepath provided, can't quit and install")); return false; } if (!this.hasCommand("dpkg") && !this.hasCommand("apt")) { this.dispatchError(new Error("Neither dpkg nor apt command found. Cannot install .deb package.")); return false; } const priorityList = ["dpkg", "apt"]; const packageManager = this.detectPackageManager(priorityList); try { DebUpdater.installWithCommandRunner(packageManager, installerPath, this.runCommandWithSudoIfNeeded.bind(this), this._logger); } catch (error) { this.dispatchError(error); return false; } if (options.isForceRunAfter) { this.app.relaunch(); } return true; } static installWithCommandRunner(packageManager, installerPath, commandRunner, logger) { var _a; if (packageManager === "dpkg") { try { // Primary: Install unsigned .deb directly with dpkg commandRunner(["dpkg", "-i", installerPath]); } catch (error) { // Handle missing dependencies via apt-get logger.warn((_a = error.message) !== null && _a !== void 0 ? _a : error); logger.warn("dpkg installation failed, trying to fix broken dependencies with apt-get"); commandRunner(["apt-get", "install", "-f", "-y"]); } } else if (packageManager === "apt") { // Fallback: Use apt for direct install (less safe for unsigned .deb) logger.warn("Using apt to install a local .deb. This may fail for unsigned packages unless properly configured."); commandRunner([ "apt", "install", "-y", "--allow-unauthenticated", // needed for unsigned .debs "--allow-downgrades", // allow lower version installs "--allow-change-held-packages", installerPath, ]); } else { throw new Error(`Package manager ${packageManager} not supported`); } } } exports.DebUpdater = DebUpdater; //# sourceMappingURL=DebUpdater.js.map{"version":3,"file":"DebUpdater.js","sourceRoot":"","sources":["../src/DebUpdater.ts"],"names":[],"mappings":";;;AAIA,mDAA+C;AAC/C,mCAAmD;AACnD,iDAA6C;AAE7C,MAAa,UAAW,SAAQ,2BAAY;IAC1C,YAAY,OAAkC,EAAE,GAAgB;QAC9D,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;IACrB,CAAC;IAED,gBAAgB;IACN,gBAAgB,CAAC,qBAA4C;QACrE,MAAM,QAAQ,GAAG,qBAAqB,CAAC,qBAAqB,CAAC,QAAQ,CAAA;QACrE,MAAM,QAAQ,GAAG,IAAA,mBAAQ,EAAC,QAAQ,CAAC,YAAY,CAAC,qBAAqB,CAAC,qBAAqB,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC,UAAU,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAE,CAAA;QACzI,OAAO,IAAI,CAAC,eAAe,CAAC;YAC1B,aAAa,EAAE,KAAK;YACpB,QAAQ;YACR,qBAAqB;YACrB,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,EAAE;gBAC1C,IAAI,IAAI,CAAC,aAAa,CAAC,yBAAiB,CAAC,GAAG,CAAC,EAAE,CAAC;oBAC9C,eAAe,CAAC,UAAU,GAAG,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,yBAAiB,EAAE,EAAE,CAAC,CAAA;gBACrE,CAAC;gBACD,MAAM,IAAI,CAAC,YAA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E,CAAC;YAC9B,IAAI,CAAC;gBACH,oDAAoD;gBACpD,aAAa,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAA;YAC9C,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,0CAA0C;gBAC1C,MAAM,CAAC,IAAI,CAAC,MAAA,KAAK,CAAC,OAAO,mCAAI,KAAK,CAAC,CAAA;gBACnC,MAAM,CAAC,IAAI,CAAC,0EAA0E,CAAC,CAAA;gBACvF,aAAa,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;YACnD,CAAC;QACH,CAAC;aAAM,IAAI,cAAc,KAAK,KAAK,EAAE,CAAC;YACpC,qEAAqE;YACrE,MAAM,CAAC,IAAI,CAAC,oGAAoG,CAAC,CAAA;YACjH,aAAa,CAAC;gBACZ,KAAK;gBACL,SAAS;gBACT,IAAI;gBACJ,yBAAyB,EAAE,4BAA4B;gBACvD,oBAAoB,EAAE,+BAA+B;gBACrD,8BAA8B;gBAC9B,aAAa;aACd,CAAC,CAAA;QACJ,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC,mBAAmB,cAAc,gBAAgB,CAAC,CAAA;QACpE,CAAC;IACH,CAAC;CACF;AAzED,gCAyEC","sourcesContent":["import { AllPublishOptions } from \"builder-util-runtime\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { InstallOptions } from \"./BaseUpdater\"\nimport { findFile } from \"./providers/Provider\"\nimport { DOWNLOAD_PROGRESS, Logger } from \"./types\"\nimport { LinuxUpdater } from \"./LinuxUpdater\"\n\nexport class DebUpdater extends LinuxUpdater {\n constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n /*** @private */\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise> {\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), \"deb\", [\"AppImage\", \"rpm\", \"pacman\"])!\n return this.executeDownload({\n fileExtension: \"deb\",\n fileInfo,\n downloadUpdateOptions,\n task: async (updateFile, downloadOptions) => {\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions)\n },\n })\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const installerPath = this.installerPath\n if (installerPath == null) {\n this.dispatchError(new Error(\"No update filepath provided, can't quit and install\"))\n return false\n }\n if (!this.hasCommand(\"dpkg\") && !this.hasCommand(\"apt\")) {\n this.dispatchError(new Error(\"Neither dpkg nor apt command found. Cannot install .deb package.\"))\n return false\n }\n const priorityList = [\"dpkg\", \"apt\"]\n const packageManager = this.detectPackageManager(priorityList)\n try {\n DebUpdater.installWithCommandRunner(packageManager as any, installerPath, this.runCommandWithSudoIfNeeded.bind(this), this._logger)\n } catch (error: any) {\n this.dispatchError(error)\n return false\n }\n if (options.isForceRunAfter) {\n this.app.relaunch()\n }\n return true\n }\n\n static installWithCommandRunner(packageManager: \"dpkg\" | \"apt\", installerPath: string, commandRunner: (commandWithArgs: string[]) => void, logger: Logger) {\n if (packageManager === \"dpkg\") {\n try {\n // Primary: Install unsigned .deb directly with dpkg\n commandRunner([\"dpkg\", \"-i\", installerPath])\n } catch (error: any) {\n // Handle missing dependencies via apt-get\n logger.warn(error.message ?? error)\n logger.warn(\"dpkg installation failed, trying to fix broken dependencies with apt-get\")\n commandRunner([\"apt-get\", \"install\", \"-f\", \"-y\"])\n }\n } else if (packageManager === \"apt\") {\n // Fallback: Use apt for direct install (less safe for unsigned .deb)\n logger.warn(\"Using apt to install a local .deb. This may fail for unsigned packages unless properly configured.\")\n commandRunner([\n \"apt\",\n \"install\",\n \"-y\",\n \"--allow-unauthenticated\", // needed for unsigned .debs\n \"--allow-downgrades\", // allow lower version installs\n \"--allow-change-held-packages\",\n installerPath,\n ])\n } else {\n throw new Error(`Package manager ${packageManager} not supported`)\n }\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DownloadedUpdateHelper = void 0; exports.createTempUpdateFile = createTempUpdateFile; const crypto_1 = require("crypto"); const fs_1 = require("fs"); // @ts-ignore const isEqual = require("lodash.isequal"); const fs_extra_1 = require("fs-extra"); const path = require("path"); /** @private **/ class DownloadedUpdateHelper { constructor(cacheDir) { this.cacheDir = cacheDir; this._file = null; this._packageFile = null; this.versionInfo = null; this.fileInfo = null; this._downloadedFileInfo = null; } get downloadedFileInfo() { return this._downloadedFileInfo; } get file() { return this._file; } get packageFile() { return this._packageFile; } get cacheDirForPendingUpdate() { return path.join(this.cacheDir, "pending"); } async validateDownloadedPath(updateFile, updateInfo, fileInfo, logger) { if (this.versionInfo != null && this.file === updateFile && this.fileInfo != null) { // update has already been downloaded from this running instance // check here only existence, not checksum if (isEqual(this.versionInfo, updateInfo) && isEqual(this.fileInfo.info, fileInfo.info) && (await (0, fs_extra_1.pathExists)(updateFile))) { return updateFile; } else { return null; } } // update has already been downloaded from some previous app launch const cachedUpdateFile = await this.getValidCachedUpdateFile(fileInfo, logger); if (cachedUpdateFile === null) { return null; } logger.info(`Update has already been downloaded to ${updateFile}).`); this._file = cachedUpdateFile; return cachedUpdateFile; } async setDownloadedFile(downloadedFile, packageFile, versionInfo, fileInfo, updateFileName, isSaveCache) { this._file = downloadedFile; this._packageFile = packageFile; this.versionInfo = versionInfo; this.fileInfo = fileInfo; this._downloadedFileInfo = { fileName: updateFileName, sha512: fileInfo.info.sha512, isAdminRightsRequired: fileInfo.info.isAdminRightsRequired === true, }; if (isSaveCache) { await (0, fs_extra_1.outputJson)(this.getUpdateInfoFile(), this._downloadedFileInfo); } } async clear() { this._file = null; this._packageFile = null; this.versionInfo = null; this.fileInfo = null; await this.cleanCacheDirForPendingUpdate(); } async cleanCacheDirForPendingUpdate() { try { // remove stale data await (0, fs_extra_1.emptyDir)(this.cacheDirForPendingUpdate); } catch (_ignore) { // ignore } } /** * Returns "update-info.json" which is created in the update cache directory's "pending" subfolder after the first update is downloaded. If the update file does not exist then the cache is cleared and recreated. If the update file exists then its properties are validated. * @param fileInfo * @param logger */ async getValidCachedUpdateFile(fileInfo, logger) { const updateInfoFilePath = this.getUpdateInfoFile(); const doesUpdateInfoFileExist = await (0, fs_extra_1.pathExists)(updateInfoFilePath); if (!doesUpdateInfoFileExist) { return null; } let cachedInfo; try { cachedInfo = await (0, fs_extra_1.readJson)(updateInfoFilePath); } catch (error) { let message = `No cached update info available`; if (error.code !== "ENOENT") { await this.cleanCacheDirForPendingUpdate(); message += ` (error on read: ${error.message})`; } logger.info(message); return null; } const isCachedInfoFileNameValid = (cachedInfo === null || cachedInfo === void 0 ? void 0 : cachedInfo.fileName) !== null; if (!isCachedInfoFileNameValid) { logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`); await this.cleanCacheDirForPendingUpdate(); return null; } if (fileInfo.info.sha512 !== cachedInfo.sha512) { logger.info(`Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${cachedInfo.sha512}, expected: ${fileInfo.info.sha512}. Directory for cached update will be cleaned`); await this.cleanCacheDirForPendingUpdate(); return null; } const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName); if (!(await (0, fs_extra_1.pathExists)(updateFile))) { logger.info("Cached update file doesn't exist"); return null; } const sha512 = await hashFile(updateFile); if (fileInfo.info.sha512 !== sha512) { logger.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${sha512}, expected: ${fileInfo.info.sha512}`); await this.cleanCacheDirForPendingUpdate(); return null; } this._downloadedFileInfo = cachedInfo; return updateFile; } getUpdateInfoFile() { return path.join(this.cacheDirForPendingUpdate, "update-info.json"); } } exports.DownloadedUpdateHelper = DownloadedUpdateHelper; function hashFile(file, algorithm = "sha512", encoding = "base64", options) { return new Promise((resolve, reject) => { const hash = (0, crypto_1.createHash)(algorithm); hash.on("error", reject).setEncoding(encoding); (0, fs_1.createReadStream)(file, { ...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */ }) .on("error", reject) .on("end", () => { hash.end(); resolve(hash.read()); }) .pipe(hash, { end: false }); }); } async function createTempUpdateFile(name, cacheDir, log) { // https://github.com/electron-userland/electron-builder/pull/2474#issuecomment-366481912 let nameCounter = 0; let result = path.join(cacheDir, name); for (let i = 0; i < 3; i++) { try { await (0, fs_extra_1.unlink)(result); return result; } catch (e) { if (e.code === "ENOENT") { return result; } log.warn(`Error on remove temp update file: ${e}`); result = path.join(cacheDir, `${nameCounter++}-${name}`); } } return result; } //# sourceMappingURL=DownloadedUpdateHelper.js.map{"version":3,"file":"DownloadedUpdateHelper.js","sourceRoot":"","sources":["../src/DownloadedUpdateHelper.ts"],"names":[],"mappings":";;;AAqLA,oDAkBC;AAtMD,mCAAmC;AACnC,2BAAqC;AACrC,aAAa;AACb,0CAAyC;AAGzC,uCAA6E;AAC7E,6BAA4B;AAE5B,gBAAgB;AAChB,MAAa,sBAAsB;IAOjC,YAAqB,QAAgB;QAAhB,aAAQ,GAAR,QAAQ,CAAQ;QAN7B,UAAK,GAAkB,IAAI,CAAA;QAC3B,iBAAY,GAAkB,IAAI,CAAA;QAElC,gBAAW,GAAsB,IAAI,CAAA;QACrC,aAAQ,GAAkC,IAAI,CAAA;QAI9C,wBAAmB,GAA4B,IAAI,CAAA;IAFnB,CAAC;IAGzC,IAAI,kBAAkB;QACpB,OAAO,IAAI,CAAC,mBAAmB,CAAA;IACjC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;IAED,IAAI,WAAW;QACb,OAAO,IAAI,CAAC,YAAY,CAAA;IAC1B,CAAC;IAED,IAAI,wBAAwB;QAC1B,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAC,CAA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IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC3B,IAAI,CAAC;YACH,MAAM,IAAA,iBAAM,EAAC,MAAM,CAAC,CAAA;YACpB,OAAO,MAAM,CAAA;QACf,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACxB,OAAO,MAAM,CAAA;YACf,CAAC;YAED,GAAG,CAAC,IAAI,CAAC,qCAAqC,CAAC,EAAE,CAAC,CAAA;YAClD,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,CAAA;QAC1D,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { UpdateInfo } from \"builder-util-runtime\"\nimport { createHash } from \"crypto\"\nimport { createReadStream } from \"fs\"\n// @ts-ignore\nimport * as isEqual from \"lodash.isequal\"\nimport { ResolvedUpdateFileInfo } from \"./types\"\nimport { Logger } from \"./types\"\nimport { pathExists, readJson, emptyDir, outputJson, unlink } from \"fs-extra\"\nimport * as path from \"path\"\n\n/** @private **/\nexport class DownloadedUpdateHelper {\n private _file: string | null = null\n private _packageFile: string | null = null\n\n private versionInfo: UpdateInfo | null = null\n private fileInfo: ResolvedUpdateFileInfo | null = null\n\n constructor(readonly cacheDir: string) {}\n\n private _downloadedFileInfo: CachedUpdateInfo | null = null\n get downloadedFileInfo(): CachedUpdateInfo | null {\n return this._downloadedFileInfo\n }\n\n get file(): string | null {\n return this._file\n }\n\n get packageFile(): string | null {\n return this._packageFile\n }\n\n get cacheDirForPendingUpdate(): string {\n return path.join(this.cacheDir, \"pending\")\n }\n\n async validateDownloadedPath(updateFile: string, updateInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise {\n if (this.versionInfo != null && this.file === updateFile && this.fileInfo != null) {\n // update has already been downloaded from this running instance\n // check here only existence, not checksum\n if (isEqual(this.versionInfo, updateInfo) && isEqual(this.fileInfo.info, fileInfo.info) && (await pathExists(updateFile))) {\n return updateFile\n } else {\n return null\n }\n }\n\n // update has already been downloaded from some previous app launch\n const cachedUpdateFile = await this.getValidCachedUpdateFile(fileInfo, logger)\n if (cachedUpdateFile === null) {\n return null\n }\n logger.info(`Update has already been downloaded to ${updateFile}).`)\n this._file = cachedUpdateFile\n return cachedUpdateFile\n }\n\n async setDownloadedFile(\n downloadedFile: string,\n packageFile: string | null,\n versionInfo: UpdateInfo,\n fileInfo: ResolvedUpdateFileInfo,\n updateFileName: string,\n isSaveCache: boolean\n ): Promise {\n this._file = downloadedFile\n this._packageFile = packageFile\n this.versionInfo = versionInfo\n this.fileInfo = fileInfo\n this._downloadedFileInfo = {\n fileName: updateFileName,\n sha512: fileInfo.info.sha512,\n isAdminRightsRequired: fileInfo.info.isAdminRightsRequired === true,\n }\n\n if (isSaveCache) {\n await outputJson(this.getUpdateInfoFile(), this._downloadedFileInfo)\n }\n }\n\n async clear(): Promise {\n this._file = null\n this._packageFile = null\n this.versionInfo = null\n this.fileInfo = null\n await this.cleanCacheDirForPendingUpdate()\n }\n\n private async cleanCacheDirForPendingUpdate(): Promise {\n try {\n // remove stale data\n await emptyDir(this.cacheDirForPendingUpdate)\n } catch (_ignore) {\n // ignore\n }\n }\n\n /**\n * Returns \"update-info.json\" which is created in the update cache directory's \"pending\" subfolder after the first update is downloaded. If the update file does not exist then the cache is cleared and recreated. If the update file exists then its properties are validated.\n * @param fileInfo\n * @param logger\n */\n private async getValidCachedUpdateFile(fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise {\n const updateInfoFilePath: string = this.getUpdateInfoFile()\n\n const doesUpdateInfoFileExist = await pathExists(updateInfoFilePath)\n if (!doesUpdateInfoFileExist) {\n return null\n }\n\n let cachedInfo: CachedUpdateInfo\n try {\n cachedInfo = await readJson(updateInfoFilePath)\n } catch (error: any) {\n let message = `No cached update info available`\n if (error.code !== \"ENOENT\") {\n await this.cleanCacheDirForPendingUpdate()\n message += ` (error on read: ${error.message})`\n }\n logger.info(message)\n return null\n }\n\n const isCachedInfoFileNameValid = cachedInfo?.fileName !== null\n if (!isCachedInfoFileNameValid) {\n logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`)\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n\n if (fileInfo.info.sha512 !== cachedInfo.sha512) {\n logger.info(\n `Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${cachedInfo.sha512}, expected: ${fileInfo.info.sha512}. Directory for cached update will be cleaned`\n )\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n\n const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName)\n if (!(await pathExists(updateFile))) {\n logger.info(\"Cached update file doesn't exist\")\n return null\n }\n\n const sha512 = await hashFile(updateFile)\n if (fileInfo.info.sha512 !== sha512) {\n logger.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${sha512}, expected: ${fileInfo.info.sha512}`)\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n this._downloadedFileInfo = cachedInfo\n return updateFile\n }\n\n private getUpdateInfoFile(): string {\n return path.join(this.cacheDirForPendingUpdate, \"update-info.json\")\n }\n}\n\ninterface CachedUpdateInfo {\n fileName: string\n sha512: string\n readonly isAdminRightsRequired: boolean\n}\n\nfunction hashFile(file: string, algorithm = \"sha512\", encoding: \"base64\" | \"hex\" = \"base64\", options?: any): Promise {\n return new Promise((resolve, reject) => {\n const hash = createHash(algorithm)\n hash.on(\"error\", reject).setEncoding(encoding)\n\n createReadStream(file, { ...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */ })\n .on(\"error\", reject)\n .on(\"end\", () => {\n hash.end()\n resolve(hash.read() as string)\n })\n .pipe(hash, { end: false })\n })\n}\n\nexport async function createTempUpdateFile(name: string, cacheDir: string, log: Logger): Promise {\n // https://github.com/electron-userland/electron-builder/pull/2474#issuecomment-366481912\n let nameCounter = 0\n let result = path.join(cacheDir, name)\n for (let i = 0; i < 3; i++) {\n try {\n await unlink(result)\n return result\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n return result\n }\n\n log.warn(`Error on remove temp update file: ${e}`)\n result = path.join(cacheDir, `${nameCounter++}-${name}`)\n }\n }\n return result\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ElectronAppAdapter = void 0; const path = require("path"); const AppAdapter_1 = require("./AppAdapter"); class ElectronAppAdapter { constructor(app = require("electron").app) { this.app = app; } whenReady() { return this.app.whenReady(); } get version() { return this.app.getVersion(); } get name() { return this.app.getName(); } get isPackaged() { return this.app.isPackaged === true; } get appUpdateConfigPath() { return this.isPackaged ? path.join(process.resourcesPath, "app-update.yml") : path.join(this.app.getAppPath(), "dev-app-update.yml"); } get userDataPath() { return this.app.getPath("userData"); } get baseCachePath() { return (0, AppAdapter_1.getAppCacheDir)(); } quit() { this.app.quit(); } relaunch() { this.app.relaunch(); } onQuit(handler) { this.app.once("quit", (_, exitCode) => handler(exitCode)); } } exports.ElectronAppAdapter = ElectronAppAdapter; //# sourceMappingURL=ElectronAppAdapter.js.map{"version":3,"file":"ElectronAppAdapter.js","sourceRoot":"","sources":["../src/ElectronAppAdapter.ts"],"names":[],"mappings":";;;AAAA,6BAA4B;AAC5B,6CAAyD;AAEzD,MAAa,kBAAkB;IAC7B,YAA6B,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG;QAA7B,QAAG,GAAH,GAAG,CAA0B;IAAG,CAAC;IAE9D,SAAS;QACP,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,CAAA;IAC7B,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,CAAA;IAC9B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAA;IAC3B,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,KAAK,IAAI,CAAA;IACrC,CAAC;IAED,IAAI,mBAAmB;QACrB,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,EAAE,oBAAoB,CAAC,CAAA;IACtI,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;IACrC,CAAC;IAED,IAAI,aAAa;QACf,OAAO,IAAA,2BAAc,GAAE,CAAA;IACzB,CAAC;IAED,IAAI;QACF,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAA;IACrB,CAAC;IAED,MAAM,CAAC,OAAmC;QACxC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAiB,EAAE,QAAgB,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;IACnF,CAAC;CACF;AA1CD,gDA0CC","sourcesContent":["import * as path from \"path\"\nimport { AppAdapter, getAppCacheDir } from \"./AppAdapter\"\n\nexport class ElectronAppAdapter implements AppAdapter {\n constructor(private readonly app = require(\"electron\").app) {}\n\n whenReady(): Promise {\n return this.app.whenReady()\n }\n\n get version(): string {\n return this.app.getVersion()\n }\n\n get name(): string {\n return this.app.getName()\n }\n\n get isPackaged(): boolean {\n return this.app.isPackaged === true\n }\n\n get appUpdateConfigPath(): string {\n return this.isPackaged ? path.join(process.resourcesPath, \"app-update.yml\") : path.join(this.app.getAppPath(), \"dev-app-update.yml\")\n }\n\n get userDataPath(): string {\n return this.app.getPath(\"userData\")\n }\n\n get baseCachePath(): string {\n return getAppCacheDir()\n }\n\n quit(): void {\n this.app.quit()\n }\n\n relaunch(): void {\n this.app.relaunch()\n }\n\n onQuit(handler: (exitCode: number) => void): void {\n this.app.once(\"quit\", (_: Electron.Event, exitCode: number) => handler(exitCode))\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LinuxUpdater = void 0; const BaseUpdater_1 = require("./BaseUpdater"); // Matches safe package manager names: alphanumeric, hyphens, underscores only. // Rejects names with shell metacharacters that could cause command injection. const SAFE_PM_REGEX = /^[a-zA-Z0-9_-]+$/; class LinuxUpdater extends BaseUpdater_1.BaseUpdater { constructor(options, app) { super(options, app); } /** * Returns true if the current process is running as root. */ isRunningAsRoot() { var _a; return ((_a = process.getuid) === null || _a === void 0 ? void 0 : _a.call(process)) === 0; } /** * Sanitizes the installer path for use with shell:true spawn calls. * Backslash-escapes metacharacters that have special meaning in POSIX shell. * Note: paths containing single-quotes (') are not supported. */ get installerPath() { const raw = super.installerPath; if (raw == null) { return null; } return raw .replace(/\\/g, "\\\\") // must come first .replace(/([`$!" ;|&()<>])/g, "\\$1") .replace(/[\n\r]/g, ""); } runCommandWithSudoIfNeeded(commandWithArgs) { if (this.isRunningAsRoot()) { this._logger.info("Running as root, no need to use sudo"); return this.spawnSyncLog(commandWithArgs[0], commandWithArgs.slice(1)); } const { name } = this.app; // Strip characters that could break shell quoting in the sudo dialog comment string const safeName = name.replace(/["`$\\!\n\r;|&<>(){}*?[\]#~]/g, ""); const installComment = `"${safeName} would like to update"`; const sudo = this.sudoWithArgs(installComment); this._logger.info(`Running as non-root user, using sudo to install: ${sudo}`); let wrapper = `"`; // some sudo commands dont want the command to be wrapped in " quotes if (/pkexec/i.test(sudo[0]) || sudo[0] === "sudo") { wrapper = ""; } return this.spawnSyncLog(sudo[0], [...(sudo.length > 1 ? sudo.slice(1) : []), `${wrapper}/bin/bash`, "-c", `'${commandWithArgs.join(" ")}'${wrapper}`]); } sudoWithArgs(installComment) { const sudo = this.determineSudoCommand(); const command = [sudo]; if (/kdesudo/i.test(sudo)) { command.push("--comment", installComment); command.push("-c"); } else if (/gksudo/i.test(sudo)) { command.push("--message", installComment); } else if (/pkexec/i.test(sudo)) { command.push("--disable-internal-agent"); } return command; } hasCommand(cmd) { try { this.spawnSyncLog(`command`, ["-v", cmd]); return true; } catch { return false; } } determineSudoCommand() { const sudos = ["gksudo", "kdesudo", "pkexec", "beesu"]; for (const sudo of sudos) { if (this.hasCommand(sudo)) { return sudo; } } return "sudo"; } /** * Detects the package manager to use based on the available commands. * Allows overriding the default behavior by setting the ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER environment variable. * If the environment variable is set, it will be used directly. (This is useful for testing each package manager logic path.) * Otherwise, it checks for the presence of the specified package manager commands in the order provided. * @param pms - An array of package manager commands to check for, in priority order. * @returns The detected package manager command or "unknown" if none are found. */ detectPackageManager(pms) { var _a; let availablePMs = pms; const pmOverride = (_a = process.env.ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER) === null || _a === void 0 ? void 0 : _a.trim(); if (pmOverride) { if (!SAFE_PM_REGEX.test(pmOverride)) { this._logger.warn(`ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER "${pmOverride}" contains unsafe characters. Ignoring override.`); } else { availablePMs = [pmOverride]; } } // Check for the package manager in the order of priority for (const pm of availablePMs) { if (this.hasCommand(pm)) { return pm; } } // return the first/default package manager in the original list if none are found, this will throw upstream for proper logging const searchList = pmOverride ? `ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER override "${pmOverride}", ` : ""; const defaultPM = pms[0]; this._logger.warn(`No package manager found in the list: ${searchList}${pms.join(", ")}. Utilizing default: ${defaultPM}`); return defaultPM; } } exports.LinuxUpdater = LinuxUpdater; //# sourceMappingURL=LinuxUpdater.js.map{"version":3,"file":"LinuxUpdater.js","sourceRoot":"","sources":["../src/LinuxUpdater.ts"],"names":[],"mappings":";;;AAEA,+CAA2C;AAE3C,+EAA+E;AAC/E,8EAA8E;AAC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yCAAyC,UAAU,GAAG,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,wBAAwB,SAAS,EAAE,CAAC,CAAA;QAC1H,OAAO,SAAS,CAAA;IAClB,CAAC;CACF;AA/GD,oCA+GC","sourcesContent":["import { AllPublishOptions } from \"builder-util-runtime\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { BaseUpdater } from \"./BaseUpdater\"\n\n// Matches safe package manager names: alphanumeric, hyphens, underscores only.\n// Rejects names with shell metacharacters that could cause command injection.\nconst SAFE_PM_REGEX = /^[a-zA-Z0-9_-]+$/\n\nexport abstract class LinuxUpdater extends BaseUpdater {\n constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n /**\n * Returns true if the current process is running as root.\n */\n protected isRunningAsRoot(): boolean {\n return process.getuid?.() === 0\n }\n\n /**\n * Sanitizes the installer path for use with shell:true spawn calls.\n * Backslash-escapes metacharacters that have special meaning in POSIX shell.\n * Note: paths containing single-quotes (') are not supported.\n */\n protected get installerPath(): string | null {\n const raw = super.installerPath\n if (raw == null) {\n return null\n }\n return raw\n .replace(/\\\\/g, \"\\\\\\\\\") // must come first\n .replace(/([`$!\" ;|&()<>])/g, \"\\\\$1\")\n .replace(/[\\n\\r]/g, \"\")\n }\n\n protected runCommandWithSudoIfNeeded(commandWithArgs: string[]) {\n if (this.isRunningAsRoot()) {\n this._logger.info(\"Running as root, no need to use sudo\")\n return this.spawnSyncLog(commandWithArgs[0], commandWithArgs.slice(1))\n }\n\n const { name } = this.app\n // Strip characters that could break shell quoting in the sudo dialog comment string\n const safeName = name.replace(/[\"`$\\\\!\\n\\r;|&<>(){}*?[\\]#~]/g, \"\")\n const installComment = `\"${safeName} would like to update\"`\n const sudo = this.sudoWithArgs(installComment)\n this._logger.info(`Running as non-root user, using sudo to install: ${sudo}`)\n let wrapper = `\"`\n // some sudo commands dont want the command to be wrapped in \" quotes\n if (/pkexec/i.test(sudo[0]) || sudo[0] === \"sudo\") {\n wrapper = \"\"\n }\n return this.spawnSyncLog(sudo[0], [...(sudo.length > 1 ? sudo.slice(1) : []), `${wrapper}/bin/bash`, \"-c\", `'${commandWithArgs.join(\" \")}'${wrapper}`])\n }\n\n protected sudoWithArgs(installComment: string): string[] {\n const sudo = this.determineSudoCommand()\n const command = [sudo]\n if (/kdesudo/i.test(sudo)) {\n command.push(\"--comment\", installComment)\n command.push(\"-c\")\n } else if (/gksudo/i.test(sudo)) {\n command.push(\"--message\", installComment)\n } else if (/pkexec/i.test(sudo)) {\n command.push(\"--disable-internal-agent\")\n }\n return command\n }\n\n protected hasCommand(cmd: string): boolean {\n try {\n this.spawnSyncLog(`command`, [\"-v\", cmd])\n return true\n } catch {\n return false\n }\n }\n\n protected determineSudoCommand(): string {\n const sudos = [\"gksudo\", \"kdesudo\", \"pkexec\", \"beesu\"]\n for (const sudo of sudos) {\n if (this.hasCommand(sudo)) {\n return sudo\n }\n }\n return \"sudo\"\n }\n\n /**\n * Detects the package manager to use based on the available commands.\n * Allows overriding the default behavior by setting the ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER environment variable.\n * If the environment variable is set, it will be used directly. (This is useful for testing each package manager logic path.)\n * Otherwise, it checks for the presence of the specified package manager commands in the order provided.\n * @param pms - An array of package manager commands to check for, in priority order.\n * @returns The detected package manager command or \"unknown\" if none are found.\n */\n protected detectPackageManager(pms: string[]): string {\n let availablePMs = pms\n const pmOverride = process.env.ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER?.trim()\n if (pmOverride) {\n if (!SAFE_PM_REGEX.test(pmOverride)) {\n this._logger.warn(`ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER \"${pmOverride}\" contains unsafe characters. Ignoring override.`)\n } else {\n availablePMs = [pmOverride]\n }\n }\n // Check for the package manager in the order of priority\n for (const pm of availablePMs) {\n if (this.hasCommand(pm)) {\n return pm\n }\n }\n // return the first/default package manager in the original list if none are found, this will throw upstream for proper logging\n const searchList = pmOverride ? `ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER override \"${pmOverride}\", ` : \"\"\n const defaultPM = pms[0]\n this._logger.warn(`No package manager found in the list: ${searchList}${pms.join(\", \")}. Utilizing default: ${defaultPM}`)\n return defaultPM\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MacUpdater = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const fs_extra_1 = require("fs-extra"); const fs_1 = require("fs"); const path = require("path"); const http_1 = require("http"); const AppUpdater_1 = require("./AppUpdater"); const Provider_1 = require("./providers/Provider"); const child_process_1 = require("child_process"); const crypto_1 = require("crypto"); class MacUpdater extends AppUpdater_1.AppUpdater { constructor(options, app) { super(options, app); this.nativeUpdater = require("electron").autoUpdater; this.squirrelDownloadedUpdate = false; this.nativeUpdater.on("error", it => { this._logger.warn(it); this.emit("error", it); }); this.nativeUpdater.on("update-downloaded", () => { this.squirrelDownloadedUpdate = true; this.debug("nativeUpdater.update-downloaded"); }); } /** Filters update files to the appropriate architecture. * On arm64 Macs (including Rosetta), arm64 files are preferred when available. * On x64 Macs, arm64 files are excluded. */ static filterFilesForArch(files, isArm64Mac) { const isArm64File = (file) => { var _a; return file.url.pathname.includes("arm64") || ((_a = file.info.url) === null || _a === void 0 ? void 0 : _a.includes("arm64")); }; if (isArm64Mac && files.some(isArm64File)) { return files.filter(file => isArm64Mac === isArm64File(file)); } return files.filter(file => !isArm64File(file)); } debug(message) { if (this._logger.debug != null) { this._logger.debug(message); } } closeServerIfExists() { if (this.server) { this.debug("Closing proxy server"); this.server.close(err => { if (err) { this.debug("proxy server wasn't already open, probably attempted closing again as a safety check before quit"); } }); } } async doDownloadUpdate(downloadUpdateOptions) { let files = downloadUpdateOptions.updateInfoAndProvider.provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info); const log = this._logger; // detect if we are running inside Rosetta emulation const sysctlRosettaInfoKey = "sysctl.proc_translated"; let isRosetta = false; try { this.debug("Checking for macOS Rosetta environment"); const result = (0, child_process_1.execFileSync)("sysctl", [sysctlRosettaInfoKey], { encoding: "utf8" }); isRosetta = result.includes(`${sysctlRosettaInfoKey}: 1`); log.info(`Checked for macOS Rosetta environment (isRosetta=${isRosetta})`); } catch (e) { log.warn(`sysctl shell command to check for macOS Rosetta environment failed: ${e}`); } let isArm64Mac = false; try { this.debug("Checking for arm64 in uname"); const result = (0, child_process_1.execFileSync)("uname", ["-a"], { encoding: "utf8" }); const isArm = result.includes("ARM"); log.info(`Checked 'uname -a': arm64=${isArm}`); isArm64Mac = isArm64Mac || isArm; } catch (e) { log.warn(`uname shell command to check for arm64 failed: ${e}`); } isArm64Mac = isArm64Mac || process.arch === "arm64" || isRosetta; // allow arm64 macs to install universal or rosetta2(x64) - https://github.com/electron-userland/electron-builder/pull/5524 files = MacUpdater.filterFilesForArch(files, isArm64Mac); const zipFileInfo = (0, Provider_1.findFile)(files, "zip", ["pkg", "dmg"]); if (zipFileInfo == null) { throw (0, builder_util_runtime_1.newError)(`ZIP file not provided: ${(0, builder_util_runtime_1.safeStringifyJson)(files)}`, "ERR_UPDATER_ZIP_FILE_NOT_FOUND"); } const provider = downloadUpdateOptions.updateInfoAndProvider.provider; const CURRENT_MAC_APP_ZIP_FILE_NAME = "update.zip"; return this.executeDownload({ fileExtension: "zip", fileInfo: zipFileInfo, downloadUpdateOptions, task: async (destinationFile, downloadOptions) => { const cachedUpdateFilePath = path.join(this.downloadedUpdateHelper.cacheDir, CURRENT_MAC_APP_ZIP_FILE_NAME); const canDifferentialDownload = () => { if (!(0, fs_extra_1.pathExistsSync)(cachedUpdateFilePath)) { log.info("Unable to locate previous update.zip for differential download (is this first install?), falling back to full download"); return false; } return !downloadUpdateOptions.disableDifferentialDownload; }; let differentialDownloadFailed = true; if (canDifferentialDownload()) { differentialDownloadFailed = await this.differentialDownloadInstaller(zipFileInfo, downloadUpdateOptions, destinationFile, provider, CURRENT_MAC_APP_ZIP_FILE_NAME); } if (differentialDownloadFailed) { await this.httpExecutor.download(zipFileInfo.url, destinationFile, downloadOptions); } }, done: async (event) => { if (!downloadUpdateOptions.disableDifferentialDownload) { try { const cachedUpdateFilePath = path.join(this.downloadedUpdateHelper.cacheDir, CURRENT_MAC_APP_ZIP_FILE_NAME); await (0, fs_extra_1.copyFile)(event.downloadedFile, cachedUpdateFilePath); } catch (error) { this._logger.warn(`Unable to copy file for caching for future differential downloads: ${error.message}`); } } return this.updateDownloaded(zipFileInfo, event); }, }); } async updateDownloaded(zipFileInfo, event) { var _a; const downloadedFile = event.downloadedFile; const updateFileSize = (_a = zipFileInfo.info.size) !== null && _a !== void 0 ? _a : (await (0, fs_extra_1.stat)(downloadedFile)).size; const log = this._logger; const logContext = `fileToProxy=${zipFileInfo.url.href}`; this.closeServerIfExists(); this.debug(`Creating proxy server for native Squirrel.Mac (${logContext})`); this.server = (0, http_1.createServer)(); this.debug(`Proxy server for native Squirrel.Mac is created (${logContext})`); this.server.on("close", () => { log.info(`Proxy server for native Squirrel.Mac is closed (${logContext})`); }); // must be called after server is listening, otherwise address is null const getServerUrl = (s) => { const address = s.address(); if (typeof address === "string") { return address; } return `http://127.0.0.1:${address === null || address === void 0 ? void 0 : address.port}`; }; return await new Promise((resolve, reject) => { const pass = (0, crypto_1.randomBytes)(64).toString("base64").replace(/\//g, "_").replace(/\+/g, "-"); const authInfo = Buffer.from(`autoupdater:${pass}`, "ascii"); // insecure random is ok const fileUrl = `/${(0, crypto_1.randomBytes)(64).toString("hex")}.zip`; this.server.on("request", (request, response) => { const requestUrl = request.url; log.info(`${requestUrl} requested`); if (requestUrl === "/") { // check for basic auth header if (!request.headers.authorization || request.headers.authorization.indexOf("Basic ") === -1) { response.statusCode = 401; response.statusMessage = "Invalid Authentication Credentials"; response.end(); log.warn("No authenthication info"); return; } // verify auth credentials const base64Credentials = request.headers.authorization.split(" ")[1]; const credentials = Buffer.from(base64Credentials, "base64").toString("ascii"); const [username, password] = credentials.split(":"); if (username !== "autoupdater" || password !== pass) { response.statusCode = 401; response.statusMessage = "Invalid Authentication Credentials"; response.end(); log.warn("Invalid authenthication credentials"); return; } const data = Buffer.from(`{ "url": "${getServerUrl(this.server)}${fileUrl}" }`); response.writeHead(200, { "Content-Type": "application/json", "Content-Length": data.length }); response.end(data); return; } if (!requestUrl.startsWith(fileUrl)) { log.warn(`${requestUrl} requested, but not supported`); response.writeHead(404); response.end(); return; } log.info(`${fileUrl} requested by Squirrel.Mac, pipe ${downloadedFile}`); let errorOccurred = false; response.on("finish", () => { if (!errorOccurred) { this.nativeUpdater.removeListener("error", reject); resolve([]); } }); const readStream = (0, fs_1.createReadStream)(downloadedFile); readStream.on("error", error => { try { response.end(); } catch (e) { log.warn(`cannot end response: ${e}`); } errorOccurred = true; this.nativeUpdater.removeListener("error", reject); reject(new Error(`Cannot pipe "${downloadedFile}": ${error}`)); }); response.writeHead(200, { "Content-Type": "application/zip", "Content-Length": updateFileSize, }); readStream.pipe(response); }); this.debug(`Proxy server for native Squirrel.Mac is starting to listen (${logContext})`); this.server.listen(0, "127.0.0.1", () => { this.debug(`Proxy server for native Squirrel.Mac is listening (address=${getServerUrl(this.server)}, ${logContext})`); this.nativeUpdater.setFeedURL({ url: getServerUrl(this.server), headers: { "Cache-Control": "no-cache", Authorization: `Basic ${authInfo.toString("base64")}`, }, }); // The update has been downloaded and is ready to be served to Squirrel this.dispatchUpdateDownloaded(event); if (this.autoInstallOnAppQuit) { this.nativeUpdater.once("error", reject); // This will trigger fetching and installing the file on Squirrel side this.nativeUpdater.checkForUpdates(); } else { resolve([]); } }); }); } handleUpdateDownloaded() { if (this.autoRunAppAfterInstall) { this.nativeUpdater.quitAndInstall(); } else { this.app.quit(); } this.closeServerIfExists(); } quitAndInstall() { if (this.squirrelDownloadedUpdate) { // update already fetched by Squirrel, it's ready to install this.handleUpdateDownloaded(); } else { // Quit and install as soon as Squirrel get the update this.nativeUpdater.on("update-downloaded", () => this.handleUpdateDownloaded()); if (!this.autoInstallOnAppQuit) { /** * If this was not `true` previously then MacUpdater.doDownloadUpdate() * would not actually initiate the downloading by electron's autoUpdater */ this.nativeUpdater.checkForUpdates(); } } } } exports.MacUpdater = MacUpdater; //# sourceMappingURL=MacUpdater.js.map{"version":3,"file":"MacUpdater.js","sourceRoot":"","sources":["../src/MacUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAAqF;AACrF,uCAAyD;AACzD,2BAAqC;AACrC,6BAA4B;AAC5B,+BAA4E;AAE5E,6CAAgE;AAGhE,mDAA+C;AAE/C,iDAA4C;AAC5C,mCAAoC;AAEpC,MAAa,UAAW,SAAQ,uBAAU;IAOxC,YAAY,OAA2B,EAAE,GAAgB;QACvD,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;QAPJ,kBAAa,GAAgB,OAAO,CAAC,UAAU,CAAC,CAAC,WAAW,CAAA;QAErE,6BAAwB,GAAG,KAAK,CAAA;QAOtC,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE;YAClC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACrB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;QACxB,CAAC,CAAC,CAAA;QACF,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC,mBAAmB,EAAE,GAAG,EAAE;YAC9C,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAA;YACpC,IAAI,CAAC,KAAK,CAAC,iCAAiC,CAAC,CAAA;QAC/C,CAAC,CAAC,CAAA;IACJ,CAAC;IAED;;gDAE4C;IAClC,MAAM,CAAC,kBAAkB,CAAC,KAA+B,EAAE,UAAmB;QACtF,MAAM,WAAW,GAAG,CAAC,IAA4B,EAAE,EAAE,WAAC,OAAA,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAI,MAAA,IAAI,CAAC,IAAI,CAAC,GAAG,0CAAE,QAAQ,CAAC,OAAO,CAAC,CAAA,CAAA,EAAA,CAAA;QAC7H,IAAI,UAAU,IA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,IAAI,CAAC,oBAAoB,EAAE,CAAC;gBAC/B;;;mBAGG;gBACH,IAAI,CAAC,aAAa,CAAC,eAAe,EAAE,CAAA;YACtC,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAlRD,gCAkRC","sourcesContent":["import { AllPublishOptions, newError, safeStringifyJson } from \"builder-util-runtime\"\nimport { pathExistsSync, stat, copyFile } from \"fs-extra\"\nimport { createReadStream } from \"fs\"\nimport * as path from \"path\"\nimport { createServer, IncomingMessage, Server, ServerResponse } from \"http\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { AppUpdater, DownloadUpdateOptions } from \"./AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"./main\"\nimport { UpdateDownloadedEvent } from \"./types\"\nimport { findFile } from \"./providers/Provider\"\nimport AutoUpdater = Electron.AutoUpdater\nimport { execFileSync } from \"child_process\"\nimport { randomBytes } from \"crypto\"\n\nexport class MacUpdater extends AppUpdater {\n private readonly nativeUpdater: AutoUpdater = require(\"electron\").autoUpdater\n\n private squirrelDownloadedUpdate = false\n\n private server?: Server\n\n constructor(options?: AllPublishOptions, app?: AppAdapter) {\n super(options, app)\n\n this.nativeUpdater.on(\"error\", it => {\n this._logger.warn(it)\n this.emit(\"error\", it)\n })\n this.nativeUpdater.on(\"update-downloaded\", () => {\n this.squirrelDownloadedUpdate = true\n this.debug(\"nativeUpdater.update-downloaded\")\n })\n }\n\n /** Filters update files to the appropriate architecture.\n * On arm64 Macs (including Rosetta), arm64 files are preferred when available.\n * On x64 Macs, arm64 files are excluded. */\n protected static filterFilesForArch(files: ResolvedUpdateFileInfo[], isArm64Mac: boolean): ResolvedUpdateFileInfo[] {\n const isArm64File = (file: ResolvedUpdateFileInfo) => file.url.pathname.includes(\"arm64\") || file.info.url?.includes(\"arm64\")\n if (isArm64Mac && files.some(isArm64File)) {\n return files.filter(file => isArm64Mac === isArm64File(file))\n }\n return files.filter(file => !isArm64File(file))\n }\n\n private debug(message: string): void {\n if (this._logger.debug != null) {\n this._logger.debug(message)\n }\n }\n\n private closeServerIfExists() {\n if (this.server) {\n this.debug(\"Closing proxy server\")\n this.server.close(err => {\n if (err) {\n this.debug(\"proxy server wasn't already open, probably attempted closing again as a safety check before quit\")\n }\n })\n }\n }\n\n protected async doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise> {\n let files = downloadUpdateOptions.updateInfoAndProvider.provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info)\n\n const log = this._logger\n\n // detect if we are running inside Rosetta emulation\n const sysctlRosettaInfoKey = \"sysctl.proc_translated\"\n let isRosetta = false\n try {\n this.debug(\"Checking for macOS Rosetta environment\")\n const result = execFileSync(\"sysctl\", [sysctlRosettaInfoKey], { encoding: \"utf8\" })\n isRosetta = result.includes(`${sysctlRosettaInfoKey}: 1`)\n log.info(`Checked for macOS Rosetta environment (isRosetta=${isRosetta})`)\n } catch (e: any) {\n log.warn(`sysctl shell command to check for macOS Rosetta environment failed: ${e}`)\n }\n\n let isArm64Mac = false\n try {\n this.debug(\"Checking for arm64 in uname\")\n const result = execFileSync(\"uname\", [\"-a\"], { encoding: \"utf8\" })\n const isArm = result.includes(\"ARM\")\n log.info(`Checked 'uname -a': arm64=${isArm}`)\n isArm64Mac = isArm64Mac || isArm\n } catch (e: any) {\n log.warn(`uname shell command to check for arm64 failed: ${e}`)\n }\n\n isArm64Mac = isArm64Mac || process.arch === \"arm64\" || isRosetta\n\n // allow arm64 macs to install universal or rosetta2(x64) - https://github.com/electron-userland/electron-builder/pull/5524\n files = MacUpdater.filterFilesForArch(files, isArm64Mac)\n\n const zipFileInfo = findFile(files, \"zip\", [\"pkg\", \"dmg\"])\n\n if (zipFileInfo == null) {\n throw newError(`ZIP file not provided: ${safeStringifyJson(files)}`, \"ERR_UPDATER_ZIP_FILE_NOT_FOUND\")\n }\n\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const CURRENT_MAC_APP_ZIP_FILE_NAME = \"update.zip\"\n\n return this.executeDownload({\n fileExtension: \"zip\",\n fileInfo: zipFileInfo,\n downloadUpdateOptions,\n task: async (destinationFile, downloadOptions) => {\n const cachedUpdateFilePath = path.join(this.downloadedUpdateHelper!.cacheDir, CURRENT_MAC_APP_ZIP_FILE_NAME)\n const canDifferentialDownload = () => {\n if (!pathExistsSync(cachedUpdateFilePath)) {\n log.info(\"Unable to locate previous update.zip for differential download (is this first install?), falling back to full download\")\n return false\n }\n return !downloadUpdateOptions.disableDifferentialDownload\n }\n let differentialDownloadFailed = true\n if (canDifferentialDownload()) {\n differentialDownloadFailed = await this.differentialDownloadInstaller(zipFileInfo, downloadUpdateOptions, destinationFile, provider, CURRENT_MAC_APP_ZIP_FILE_NAME)\n }\n\n if (differentialDownloadFailed) {\n await this.httpExecutor.download(zipFileInfo.url, destinationFile, downloadOptions)\n }\n },\n done: async event => {\n if (!downloadUpdateOptions.disableDifferentialDownload) {\n try {\n const cachedUpdateFilePath = path.join(this.downloadedUpdateHelper!.cacheDir, CURRENT_MAC_APP_ZIP_FILE_NAME)\n await copyFile(event.downloadedFile, cachedUpdateFilePath)\n } catch (error: any) {\n this._logger.warn(`Unable to copy file for caching for future differential downloads: ${error.message}`)\n }\n }\n return this.updateDownloaded(zipFileInfo, event)\n },\n })\n }\n\n private async updateDownloaded(zipFileInfo: ResolvedUpdateFileInfo, event: UpdateDownloadedEvent): Promise> {\n const downloadedFile = event.downloadedFile\n const updateFileSize = zipFileInfo.info.size ?? (await stat(downloadedFile)).size\n\n const log = this._logger\n const logContext = `fileToProxy=${zipFileInfo.url.href}`\n this.closeServerIfExists()\n this.debug(`Creating proxy server for native Squirrel.Mac (${logContext})`)\n this.server = createServer()\n this.debug(`Proxy server for native Squirrel.Mac is created (${logContext})`)\n this.server.on(\"close\", () => {\n log.info(`Proxy server for native Squirrel.Mac is closed (${logContext})`)\n })\n\n // must be called after server is listening, otherwise address is null\n const getServerUrl = (s: Server): string => {\n const address = s.address()\n if (typeof address === \"string\") {\n return address\n }\n return `http://127.0.0.1:${address?.port}`\n }\n\n return await new Promise>((resolve, reject) => {\n const pass = randomBytes(64).toString(\"base64\").replace(/\\//g, \"_\").replace(/\\+/g, \"-\")\n const authInfo = Buffer.from(`autoupdater:${pass}`, \"ascii\")\n\n // insecure random is ok\n const fileUrl = `/${randomBytes(64).toString(\"hex\")}.zip`\n this.server!.on(\"request\", (request: IncomingMessage, response: ServerResponse) => {\n const requestUrl = request.url!\n log.info(`${requestUrl} requested`)\n if (requestUrl === \"/\") {\n // check for basic auth header\n if (!request.headers.authorization || request.headers.authorization.indexOf(\"Basic \") === -1) {\n response.statusCode = 401\n response.statusMessage = \"Invalid Authentication Credentials\"\n response.end()\n log.warn(\"No authenthication info\")\n return\n }\n\n // verify auth credentials\n const base64Credentials = request.headers.authorization.split(\" \")[1]\n const credentials = Buffer.from(base64Credentials, \"base64\").toString(\"ascii\")\n const [username, password] = credentials.split(\":\")\n if (username !== \"autoupdater\" || password !== pass) {\n response.statusCode = 401\n response.statusMessage = \"Invalid Authentication Credentials\"\n response.end()\n log.warn(\"Invalid authenthication credentials\")\n return\n }\n\n const data = Buffer.from(`{ \"url\": \"${getServerUrl(this.server!)}${fileUrl}\" }`)\n response.writeHead(200, { \"Content-Type\": \"application/json\", \"Content-Length\": data.length })\n response.end(data)\n return\n }\n\n if (!requestUrl.startsWith(fileUrl)) {\n log.warn(`${requestUrl} requested, but not supported`)\n response.writeHead(404)\n response.end()\n return\n }\n\n log.info(`${fileUrl} requested by Squirrel.Mac, pipe ${downloadedFile}`)\n\n let errorOccurred = false\n response.on(\"finish\", () => {\n if (!errorOccurred) {\n this.nativeUpdater.removeListener(\"error\", reject)\n resolve([])\n }\n })\n\n const readStream = createReadStream(downloadedFile)\n readStream.on(\"error\", error => {\n try {\n response.end()\n } catch (e: any) {\n log.warn(`cannot end response: ${e}`)\n }\n errorOccurred = true\n this.nativeUpdater.removeListener(\"error\", reject)\n reject(new Error(`Cannot pipe \"${downloadedFile}\": ${error}`))\n })\n\n response.writeHead(200, {\n \"Content-Type\": \"application/zip\",\n \"Content-Length\": updateFileSize,\n })\n readStream.pipe(response)\n })\n\n this.debug(`Proxy server for native Squirrel.Mac is starting to listen (${logContext})`)\n\n this.server!.listen(0, \"127.0.0.1\", () => {\n this.debug(`Proxy server for native Squirrel.Mac is listening (address=${getServerUrl(this.server!)}, ${logContext})`)\n this.nativeUpdater.setFeedURL({\n url: getServerUrl(this.server!),\n headers: {\n \"Cache-Control\": \"no-cache\",\n Authorization: `Basic ${authInfo.toString(\"base64\")}`,\n },\n })\n\n // The update has been downloaded and is ready to be served to Squirrel\n this.dispatchUpdateDownloaded(event)\n\n if (this.autoInstallOnAppQuit) {\n this.nativeUpdater.once(\"error\", reject)\n // This will trigger fetching and installing the file on Squirrel side\n this.nativeUpdater.checkForUpdates()\n } else {\n resolve([])\n }\n })\n })\n }\n\n private handleUpdateDownloaded() {\n if (this.autoRunAppAfterInstall) {\n this.nativeUpdater.quitAndInstall()\n } else {\n this.app.quit()\n }\n this.closeServerIfExists()\n }\n\n quitAndInstall(): void {\n if (this.squirrelDownloadedUpdate) {\n // update already fetched by Squirrel, it's ready to install\n this.handleUpdateDownloaded()\n } else {\n // Quit and install as soon as Squirrel get the update\n this.nativeUpdater.on(\"update-downloaded\", () => this.handleUpdateDownloaded())\n\n if (!this.autoInstallOnAppQuit) {\n /**\n * If this was not `true` previously then MacUpdater.doDownloadUpdate()\n * would not actually initiate the downloading by electron's autoUpdater\n */\n this.nativeUpdater.checkForUpdates()\n }\n }\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NsisUpdater = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const path = require("path"); const BaseUpdater_1 = require("./BaseUpdater"); const FileWithEmbeddedBlockMapDifferentialDownloader_1 = require("./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader"); const types_1 = require("./types"); const Provider_1 = require("./providers/Provider"); const fs_extra_1 = require("fs-extra"); const windowsExecutableCodeSignatureVerifier_1 = require("./windowsExecutableCodeSignatureVerifier"); const url_1 = require("url"); class NsisUpdater extends BaseUpdater_1.BaseUpdater { constructor(options, app) { super(options, app); this._verifyUpdateCodeSignature = (publisherNames, unescapedTempUpdateFile) => (0, windowsExecutableCodeSignatureVerifier_1.verifySignature)(publisherNames, unescapedTempUpdateFile, this._logger); } /** * The verifyUpdateCodeSignature. You can pass [win-verify-signature](https://github.com/beyondkmp/win-verify-trust) or another custom verify function: ` (publisherName: string[], path: string) => Promise`. * The default verify function uses [windowsExecutableCodeSignatureVerifier](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/windowsExecutableCodeSignatureVerifier.ts) */ get verifyUpdateCodeSignature() { return this._verifyUpdateCodeSignature; } set verifyUpdateCodeSignature(value) { if (value) { this._verifyUpdateCodeSignature = value; } } /*** @private */ doDownloadUpdate(downloadUpdateOptions) { const provider = downloadUpdateOptions.updateInfoAndProvider.provider; const fileInfo = (0, Provider_1.findFile)(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "exe"); return this.executeDownload({ fileExtension: "exe", downloadUpdateOptions, fileInfo, task: async (destinationFile, downloadOptions, packageFile, removeTempDirIfAny) => { const packageInfo = fileInfo.packageInfo; const isWebInstaller = packageInfo != null && packageFile != null; if (isWebInstaller && downloadUpdateOptions.disableWebInstaller) { throw (0, builder_util_runtime_1.newError)(`Unable to download new version ${downloadUpdateOptions.updateInfoAndProvider.info.version}. Web Installers are disabled`, "ERR_UPDATER_WEB_INSTALLER_DISABLED"); } if (!isWebInstaller && !downloadUpdateOptions.disableWebInstaller) { this._logger.warn("disableWebInstaller is set to false, you should set it to true if you do not plan on using a web installer. This will default to true in a future version."); } if (isWebInstaller || downloadUpdateOptions.disableDifferentialDownload || (await this.differentialDownloadInstaller(fileInfo, downloadUpdateOptions, destinationFile, provider, builder_util_runtime_1.CURRENT_APP_INSTALLER_FILE_NAME))) { await this.httpExecutor.download(fileInfo.url, destinationFile, downloadOptions); } const signatureVerificationStatus = await this.verifySignature(destinationFile); if (signatureVerificationStatus != null) { await removeTempDirIfAny(); // noinspection ThrowInsideFinallyBlockJS throw (0, builder_util_runtime_1.newError)(`New version ${downloadUpdateOptions.updateInfoAndProvider.info.version} is not signed by the application owner: ${signatureVerificationStatus}`, "ERR_UPDATER_INVALID_SIGNATURE"); } if (isWebInstaller) { if (await this.differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packageFile, provider)) { try { await this.httpExecutor.download(new url_1.URL(packageInfo.path), packageFile, { headers: downloadUpdateOptions.requestHeaders, cancellationToken: downloadUpdateOptions.cancellationToken, sha512: packageInfo.sha512, }); } catch (e) { try { await (0, fs_extra_1.unlink)(packageFile); } catch (_ignored) { // ignore } throw e; } } } }, }); } // $certificateInfo = (Get-AuthenticodeSignature 'xxx\yyy.exe' // | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains("CN=siemens.com")}) // | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 } async verifySignature(tempUpdateFile) { let publisherName; try { publisherName = (await this.configOnDisk.value).publisherName; if (publisherName == null) { return null; } } catch (e) { if (e.code === "ENOENT") { // no app-update.yml return null; } throw e; } return await this._verifyUpdateCodeSignature(Array.isArray(publisherName) ? publisherName : [publisherName], tempUpdateFile); } doInstall(options) { const installerPath = this.installerPath; if (installerPath == null) { this.dispatchError(new Error("No update filepath provided, can't quit and install")); return false; } const args = ["--updated"]; if (options.isSilent) { args.push("/S"); } if (options.isForceRunAfter) { args.push("--force-run"); } if (this.installDirectory) { // maybe check if folder exists args.push(`/D=${this.installDirectory}`); } const packagePath = this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.packageFile; if (packagePath != null) { // only = form is supported args.push(`--package-file=${packagePath}`); } const callUsingElevation = () => { this.spawnLog(path.join(process.resourcesPath, "elevate.exe"), [installerPath].concat(args)).catch(e => this.dispatchError(e)); }; if (options.isAdminRightsRequired) { this._logger.info("isAdminRightsRequired is set to true, run installer using elevate.exe"); callUsingElevation(); return true; } this.spawnLog(installerPath, args).catch((e) => { // https://github.com/electron-userland/electron-builder/issues/1129 // Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors const errorCode = e.code; this._logger.info(`Cannot run installer: error code: ${errorCode}, error message: "${e.message}", will be executed again using elevate if EACCES, and will try to use electron.shell.openItem if ENOENT`); if (errorCode === "UNKNOWN" || errorCode === "EACCES") { callUsingElevation(); } else if (errorCode === "ENOENT") { require("electron") .shell.openPath(installerPath) .catch((err) => this.dispatchError(err)); } else { this.dispatchError(e); } }); return true; } async differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packagePath, provider) { if (packageInfo.blockMapSize == null) { return true; } try { const downloadOptions = { newUrl: new url_1.URL(packageInfo.path), oldFile: path.join(this.downloadedUpdateHelper.cacheDir, builder_util_runtime_1.CURRENT_APP_PACKAGE_FILE_NAME), logger: this._logger, newFile: packagePath, requestHeaders: this.requestHeaders, isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest, cancellationToken: downloadUpdateOptions.cancellationToken, }; if (this.listenerCount(types_1.DOWNLOAD_PROGRESS) > 0) { downloadOptions.onProgress = it => this.emit(types_1.DOWNLOAD_PROGRESS, it); } await new FileWithEmbeddedBlockMapDifferentialDownloader_1.FileWithEmbeddedBlockMapDifferentialDownloader(packageInfo, this.httpExecutor, downloadOptions).download(); } catch (e) { this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`); // during test (developer machine mac or linux) we must throw error return process.platform === "win32"; } return false; } } exports.NsisUpdater = NsisUpdater; //# sourceMappingURL=NsisUpdater.js.map{"version":3,"file":"NsisUpdater.js","sourceRoot":"","sources":["../src/NsisUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAAmJ;AACnJ,6BAA4B;AAG5B,+CAA2D;AAE3D,4IAAwI;AACxI,mCAA2C;AAE3C,mDAAyD;AACzD,uCAAiC;AACjC,qGAA0E;AAC1E,6BAAyB;AAEzB,MAAa,WAAY,SAAQ,yBAAW;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AAE,CAAC,CAAA;YACrE,CAAC;YAED,MAAM,IAAI,+FAA8C,CAAC,WAAW,EAAE,IAAI,CAAC,YAAY,EAAE,eAAe,CAAC,CAAC,QAAQ,EAAE,CAAA;QACtH,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC,CAAA;YAChG,mEAAmE;YACnE,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;QACrC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAzMD,kCAyMC","sourcesContent":["import { AllPublishOptions, newError, PackageFileInfo, CURRENT_APP_INSTALLER_FILE_NAME, CURRENT_APP_PACKAGE_FILE_NAME } from \"builder-util-runtime\"\nimport * as path from \"path\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { BaseUpdater, InstallOptions } from \"./BaseUpdater\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { FileWithEmbeddedBlockMapDifferentialDownloader } from \"./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader\"\nimport { DOWNLOAD_PROGRESS } from \"./types\"\nimport { VerifyUpdateCodeSignature } from \"./main\"\nimport { findFile, Provider } from \"./providers/Provider\"\nimport { unlink } from \"fs-extra\"\nimport { verifySignature } from \"./windowsExecutableCodeSignatureVerifier\"\nimport { URL } from \"url\"\n\nexport class NsisUpdater extends BaseUpdater {\n /**\n * Specify custom install directory path\n *\n */\n installDirectory?: string\n\n constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n protected _verifyUpdateCodeSignature: VerifyUpdateCodeSignature = (publisherNames: Array, unescapedTempUpdateFile: string) =>\n verifySignature(publisherNames, unescapedTempUpdateFile, this._logger)\n\n /**\n * The verifyUpdateCodeSignature. You can pass [win-verify-signature](https://github.com/beyondkmp/win-verify-trust) or another custom verify function: ` (publisherName: string[], path: string) => Promise`.\n * The default verify function uses [windowsExecutableCodeSignatureVerifier](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/windowsExecutableCodeSignatureVerifier.ts)\n */\n get verifyUpdateCodeSignature(): VerifyUpdateCodeSignature {\n return this._verifyUpdateCodeSignature\n }\n\n set verifyUpdateCodeSignature(value: VerifyUpdateCodeSignature) {\n if (value) {\n this._verifyUpdateCodeSignature = value\n }\n }\n\n /*** @private */\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise> {\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), \"exe\")!\n return this.executeDownload({\n fileExtension: \"exe\",\n downloadUpdateOptions,\n fileInfo,\n task: async (destinationFile, downloadOptions, packageFile, removeTempDirIfAny) => {\n const packageInfo = fileInfo.packageInfo\n const isWebInstaller = packageInfo != null && packageFile != null\n if (isWebInstaller && downloadUpdateOptions.disableWebInstaller) {\n throw newError(\n `Unable to download new version ${downloadUpdateOptions.updateInfoAndProvider.info.version}. Web Installers are disabled`,\n \"ERR_UPDATER_WEB_INSTALLER_DISABLED\"\n )\n }\n if (!isWebInstaller && !downloadUpdateOptions.disableWebInstaller) {\n this._logger.warn(\n \"disableWebInstaller is set to false, you should set it to true if you do not plan on using a web installer. This will default to true in a future version.\"\n )\n }\n if (\n isWebInstaller ||\n downloadUpdateOptions.disableDifferentialDownload ||\n (await this.differentialDownloadInstaller(fileInfo, downloadUpdateOptions, destinationFile, provider, CURRENT_APP_INSTALLER_FILE_NAME))\n ) {\n await this.httpExecutor.download(fileInfo.url, destinationFile, downloadOptions)\n }\n\n const signatureVerificationStatus = await this.verifySignature(destinationFile)\n if (signatureVerificationStatus != null) {\n await removeTempDirIfAny()\n // noinspection ThrowInsideFinallyBlockJS\n throw newError(\n `New version ${downloadUpdateOptions.updateInfoAndProvider.info.version} is not signed by the application owner: ${signatureVerificationStatus}`,\n \"ERR_UPDATER_INVALID_SIGNATURE\"\n )\n }\n\n if (isWebInstaller) {\n if (await this.differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packageFile, provider)) {\n try {\n await this.httpExecutor.download(new URL(packageInfo.path), packageFile, {\n headers: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n sha512: packageInfo.sha512,\n })\n } catch (e: any) {\n try {\n await unlink(packageFile)\n } catch (_ignored) {\n // ignore\n }\n\n throw e\n }\n }\n }\n },\n })\n }\n\n // $certificateInfo = (Get-AuthenticodeSignature 'xxx\\yyy.exe'\n // | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains(\"CN=siemens.com\")})\n // | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }\n private async verifySignature(tempUpdateFile: string): Promise {\n let publisherName: Array | string | null\n try {\n publisherName = (await this.configOnDisk.value).publisherName\n if (publisherName == null) {\n return null\n }\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // no app-update.yml\n return null\n }\n throw e\n }\n return await this._verifyUpdateCodeSignature(Array.isArray(publisherName) ? publisherName : [publisherName], tempUpdateFile)\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const installerPath = this.installerPath\n if (installerPath == null) {\n this.dispatchError(new Error(\"No update filepath provided, can't quit and install\"))\n return false\n }\n\n const args = [\"--updated\"]\n if (options.isSilent) {\n args.push(\"/S\")\n }\n\n if (options.isForceRunAfter) {\n args.push(\"--force-run\")\n }\n\n if (this.installDirectory) {\n // maybe check if folder exists\n args.push(`/D=${this.installDirectory}`)\n }\n\n const packagePath = this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.packageFile\n if (packagePath != null) {\n // only = form is supported\n args.push(`--package-file=${packagePath}`)\n }\n\n const callUsingElevation = (): void => {\n this.spawnLog(path.join(process.resourcesPath, \"elevate.exe\"), [installerPath].concat(args)).catch(e => this.dispatchError(e))\n }\n\n if (options.isAdminRightsRequired) {\n this._logger.info(\"isAdminRightsRequired is set to true, run installer using elevate.exe\")\n callUsingElevation()\n return true\n }\n\n this.spawnLog(installerPath, args).catch((e: Error) => {\n // https://github.com/electron-userland/electron-builder/issues/1129\n // Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors\n const errorCode = (e as NodeJS.ErrnoException).code\n this._logger.info(\n `Cannot run installer: error code: ${errorCode}, error message: \"${e.message}\", will be executed again using elevate if EACCES, and will try to use electron.shell.openItem if ENOENT`\n )\n if (errorCode === \"UNKNOWN\" || errorCode === \"EACCES\") {\n callUsingElevation()\n } else if (errorCode === \"ENOENT\") {\n require(\"electron\")\n .shell.openPath(installerPath)\n .catch((err: Error) => this.dispatchError(err))\n } else {\n this.dispatchError(e)\n }\n })\n return true\n }\n\n private async differentialDownloadWebPackage(\n downloadUpdateOptions: DownloadUpdateOptions,\n packageInfo: PackageFileInfo,\n packagePath: string,\n provider: Provider\n ): Promise {\n if (packageInfo.blockMapSize == null) {\n return true\n }\n\n try {\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: new URL(packageInfo.path),\n oldFile: path.join(this.downloadedUpdateHelper!.cacheDir, CURRENT_APP_PACKAGE_FILE_NAME),\n logger: this._logger,\n newFile: packagePath,\n requestHeaders: this.requestHeaders,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n await new FileWithEmbeddedBlockMapDifferentialDownloader(packageInfo, this.httpExecutor, downloadOptions).download()\n } catch (e: any) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n // during test (developer machine mac or linux) we must throw error\n return process.platform === \"win32\"\n }\n return false\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PacmanUpdater = void 0; const types_1 = require("./types"); const Provider_1 = require("./providers/Provider"); const LinuxUpdater_1 = require("./LinuxUpdater"); class PacmanUpdater extends LinuxUpdater_1.LinuxUpdater { constructor(options, app) { super(options, app); } /*** @private */ doDownloadUpdate(downloadUpdateOptions) { const provider = downloadUpdateOptions.updateInfoAndProvider.provider; const fileInfo = (0, Provider_1.findFile)(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "pacman", ["AppImage", "deb", "rpm"]); return this.executeDownload({ fileExtension: "pacman", fileInfo, downloadUpdateOptions, task: async (updateFile, downloadOptions) => { if (this.listenerCount(types_1.DOWNLOAD_PROGRESS) > 0) { downloadOptions.onProgress = it => this.emit(types_1.DOWNLOAD_PROGRESS, it); } await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions); }, }); } doInstall(options) { const installerPath = this.installerPath; if (installerPath == null) { this.dispatchError(new Error("No update filepath provided, can't quit and install")); return false; } try { PacmanUpdater.installWithCommandRunner(installerPath, this.runCommandWithSudoIfNeeded.bind(this), this._logger); } catch (error) { this.dispatchError(error); return false; } if (options.isForceRunAfter) { this.app.relaunch(); // note: `app` is undefined in tests since vite doesn't run in electron } return true; } static installWithCommandRunner(installerPath, commandRunner, logger) { var _a; try { commandRunner(["pacman", "-U", "--noconfirm", installerPath]); } catch (error) { logger.warn((_a = error.message) !== null && _a !== void 0 ? _a : error); logger.warn("pacman installation failed, attempting to update package database and retry"); try { // Update package database (not a full upgrade, just sync) commandRunner(["pacman", "-Sy", "--noconfirm"]); // Retry installation commandRunner(["pacman", "-U", "--noconfirm", installerPath]); } catch (retryError) { logger.error("Retry after pacman -Sy failed"); throw retryError; } } } } exports.PacmanUpdater = PacmanUpdater; //# sourceMappingURL=PacmanUpdater.js.map{"version":3,"file":"PacmanUpdater.js","sourceRoot":"","sources":["../src/PacmanUpdater.ts"],"names":[],"mappings":";;;AAIA,mCAAmD;AACnD,mDAA+C;AAC/C,iDAA6C;AAE7C,MAAa,aA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AI,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;QACjH,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;YACzB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;YAC5B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAA,CAAC,uEAAuE;QAC7F,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,CAAC,wBAAwB,CAAC,aAAqB,EAAE,aAAkD,EAAE,MAAc;;QACvH,IAAI,CAAC;YACH,aAAa,CAAC,CAAC,QAAQ,EAAE,IAAI,EAAE,aAAa,EAAE,aAAa,CAAC,CAAC,CAAA;QAC/D,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC,MAAA,KAAK,CAAC,OAAO,mCAAI,KAAK,CAAC,CAAA;YACnC,MAAM,CAAC,IAAI,CAAC,6EAA6E,CAAC,CAAA;YAE1F,IAAI,CAAC;gBACH,0DAA0D;gBAC1D,aAAa,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,aAAa,CAAC,CAAC,CAAA;gBAC/C,qBAAqB;gBACrB,aAAa,CAAC,CAAC,QAAQ,EAAE,IAAI,EAAE,aAAa,EAAE,aAAa,CAAC,CAAC,CAAA;YAC/D,CAAC;YAAC,OAAO,UAAe,EAAE,CAAC;gBACzB,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAA;gBAC7C,MAAM,UAAU,CAAA;YAClB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA1DD,sCA0DC","sourcesContent":["import { AllPublishOptions } from \"builder-util-runtime\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { InstallOptions } from \"./BaseUpdater\"\nimport { DOWNLOAD_PROGRESS, Logger } from \"./types\"\nimport { findFile } from \"./providers/Provider\"\nimport { LinuxUpdater } from \"./LinuxUpdater\"\n\nexport class PacmanUpdater extends LinuxUpdater {\n constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n /*** @private */\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise> {\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), \"pacman\", [\"AppImage\", \"deb\", \"rpm\"])!\n return this.executeDownload({\n fileExtension: \"pacman\",\n fileInfo,\n downloadUpdateOptions,\n task: async (updateFile, downloadOptions) => {\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions)\n },\n })\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const installerPath = this.installerPath\n if (installerPath == null) {\n this.dispatchError(new Error(\"No update filepath provided, can't quit and install\"))\n return false\n }\n try {\n PacmanUpdater.installWithCommandRunner(installerPath, this.runCommandWithSudoIfNeeded.bind(this), this._logger)\n } catch (error: any) {\n this.dispatchError(error)\n return false\n }\n if (options.isForceRunAfter) {\n this.app.relaunch() // note: `app` is undefined in tests since vite doesn't run in electron\n }\n return true\n }\n\n static installWithCommandRunner(installerPath: string, commandRunner: (commandWithArgs: string[]) => void, logger: Logger) {\n try {\n commandRunner([\"pacman\", \"-U\", \"--noconfirm\", installerPath])\n } catch (error: any) {\n logger.warn(error.message ?? error)\n logger.warn(\"pacman installation failed, attempting to update package database and retry\")\n\n try {\n // Update package database (not a full upgrade, just sync)\n commandRunner([\"pacman\", \"-Sy\", \"--noconfirm\"])\n // Retry installation\n commandRunner([\"pacman\", \"-U\", \"--noconfirm\", installerPath])\n } catch (retryError: any) {\n logger.error(\"Retry after pacman -Sy failed\")\n throw retryError\n }\n }\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RpmUpdater = void 0; const types_1 = require("./types"); const Provider_1 = require("./providers/Provider"); const LinuxUpdater_1 = require("./LinuxUpdater"); class RpmUpdater extends LinuxUpdater_1.LinuxUpdater { constructor(options, app) { super(options, app); } /*** @private */ doDownloadUpdate(downloadUpdateOptions) { const provider = downloadUpdateOptions.updateInfoAndProvider.provider; const fileInfo = (0, Provider_1.findFile)(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "rpm", ["AppImage", "deb", "pacman"]); return this.executeDownload({ fileExtension: "rpm", fileInfo, downloadUpdateOptions, task: async (updateFile, downloadOptions) => { if (this.listenerCount(types_1.DOWNLOAD_PROGRESS) > 0) { downloadOptions.onProgress = it => this.emit(types_1.DOWNLOAD_PROGRESS, it); } await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions); }, }); } doInstall(options) { const installerPath = this.installerPath; if (installerPath == null) { this.dispatchError(new Error("No update filepath provided, can't quit and install")); return false; } const priorityList = ["zypper", "dnf", "yum", "rpm"]; const packageManager = this.detectPackageManager(priorityList); try { RpmUpdater.installWithCommandRunner(packageManager, installerPath, this.runCommandWithSudoIfNeeded.bind(this), this._logger); } catch (error) { this.dispatchError(error); return false; } if (options.isForceRunAfter) { this.app.relaunch(); } return true; } static installWithCommandRunner(packageManager, installerPath, commandRunner, logger) { if (packageManager === "zypper") { return commandRunner(["zypper", "--non-interactive", "--no-refresh", "install", "--allow-unsigned-rpm", "-f", installerPath]); } if (packageManager === "dnf") { return commandRunner(["dnf", "install", "--nogpgcheck", "-y", installerPath]); } if (packageManager === "yum") { return commandRunner(["yum", "install", "--nogpgcheck", "-y", installerPath]); } if (packageManager === "rpm") { logger.warn("Installing with rpm only (no dependency resolution)."); return commandRunner(["rpm", "-Uvh", "--replacepkgs", "--replacefiles", "--nodeps", installerPath]); } throw new Error(`Package manager ${packageManager} not supported`); } } exports.RpmUpdater = RpmUpdater; //# sourceMappingURL=RpmUpdater.js.map{"version":3,"file":"RpmUpd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AAI,CAAC,sDAAsD,CAAC,CAAA;YACnE,OAAO,aAAa,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,gBAAgB,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC,CAAA;QACrG,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,mBAAmB,cAAc,gBAAgB,CAAC,CAAA;IACpE,CAAC;CACF;AA3DD,gCA2DC","sourcesContent":["import { AllPublishOptions } from \"builder-util-runtime\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { InstallOptions } from \"./BaseUpdater\"\nimport { DOWNLOAD_PROGRESS, Logger } from \"./types\"\nimport { findFile } from \"./providers/Provider\"\nimport { LinuxUpdater } from \"./LinuxUpdater\"\n\nexport class RpmUpdater extends LinuxUpdater {\n constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n /*** @private */\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise> {\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), \"rpm\", [\"AppImage\", \"deb\", \"pacman\"])!\n return this.executeDownload({\n fileExtension: \"rpm\",\n fileInfo,\n downloadUpdateOptions,\n task: async (updateFile, downloadOptions) => {\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions)\n },\n })\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const installerPath = this.installerPath\n if (installerPath == null) {\n this.dispatchError(new Error(\"No update filepath provided, can't quit and install\"))\n return false\n }\n\n const priorityList = [\"zypper\", \"dnf\", \"yum\", \"rpm\"]\n const packageManager = this.detectPackageManager(priorityList)\n try {\n RpmUpdater.installWithCommandRunner(packageManager as any, installerPath, this.runCommandWithSudoIfNeeded.bind(this), this._logger)\n } catch (error: any) {\n this.dispatchError(error)\n return false\n }\n if (options.isForceRunAfter) {\n this.app.relaunch()\n }\n return true\n }\n\n static installWithCommandRunner(packageManager: \"zypper\" | \"dnf\" | \"yum\" | \"rpm\", installerPath: string, commandRunner: (commandWithArgs: string[]) => void, logger: Logger) {\n if (packageManager === \"zypper\") {\n return commandRunner([\"zypper\", \"--non-interactive\", \"--no-refresh\", \"install\", \"--allow-unsigned-rpm\", \"-f\", installerPath])\n }\n if (packageManager === \"dnf\") {\n return commandRunner([\"dnf\", \"install\", \"--nogpgcheck\", \"-y\", installerPath])\n }\n if (packageManager === \"yum\") {\n return commandRunner([\"yum\", \"install\", \"--nogpgcheck\", \"-y\", installerPath])\n }\n if (packageManager === \"rpm\") {\n logger.warn(\"Installing with rpm only (no dependency resolution).\")\n return commandRunner([\"rpm\", \"-Uvh\", \"--replacepkgs\", \"--replacefiles\", \"--nodeps\", installerPath])\n }\n throw new Error(`Package manager ${packageManager} not supported`)\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DataSplitter = void 0; exports.copyData = copyData; const builder_util_runtime_1 = require("builder-util-runtime"); const fs_1 = require("fs"); const stream_1 = require("stream"); const downloadPlanBuilder_1 = require("./downloadPlanBuilder"); const DOUBLE_CRLF = Buffer.from("\r\n\r\n"); var ReadState; (function (ReadState) { ReadState[ReadState["INIT"] = 0] = "INIT"; ReadState[ReadState["HEADER"] = 1] = "HEADER"; ReadState[ReadState["BODY"] = 2] = "BODY"; })(ReadState || (ReadState = {})); function copyData(task, out, oldFileFd, reject, resolve) { const readStream = (0, fs_1.createReadStream)("", { fd: oldFileFd, autoClose: false, start: task.start, // end is inclusive end: task.end - 1, }); readStream.on("error", reject); readStream.once("end", resolve); readStream.pipe(out, { end: false, }); } class DataSplitter extends stream_1.Writable { constructor(out, options, partIndexToTaskIndex, boundary, partIndexToLength, finishHandler, grandTotalBytes, onProgress) { super(); this.out = out; this.options = options; this.partIndexToTaskIndex = partIndexToTaskIndex; this.partIndexToLength = partIndexToLength; this.finishHandler = finishHandler; this.grandTotalBytes = grandTotalBytes; this.onProgress = onProgress; // properties for progress update calculations this.start = Date.now(); // download start time used to calculate average rate this.nextUpdate = this.start + 1000; // timestamp of next update to prevent updates more often than once per second this.transferred = 0; // total number of bytes transferred this.delta = 0; // number of bytes transferred since last update, reset after each update this.partIndex = -1; this.headerListBuffer = null; this.readState = ReadState.INIT; this.ignoreByteCount = 0; this.remainingPartDataCount = 0; this.actualPartLength = 0; this.boundaryLength = boundary.length + 4; /* size of \r\n-- */ // first chunk doesn't start with \r\n this.ignoreByteCount = this.boundaryLength - 2; } get isFinished() { return this.partIndex === this.partIndexToLength.length; } // noinspection JSUnusedGlobalSymbols _write(data, encoding, callback) { if (this.isFinished) { console.error(`Trailing ignored data: ${data.length} bytes`); return; } this.handleData(data) .then(() => { if (this.onProgress) { const now = Date.now(); if ((now >= this.nextUpdate || this.transferred === this.grandTotalBytes) && this.grandTotalBytes && (now - this.start) / 1000) { this.nextUpdate = now + 1000; this.onProgress({ total: this.grandTotalBytes, delta: this.delta, transferred: this.transferred, percent: (this.transferred / this.grandTotalBytes) * 100, bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)), }); this.delta = 0; } } callback(); }) .catch(callback); } async handleData(chunk) { let start = 0; if (this.ignoreByteCount !== 0 && this.remainingPartDataCount !== 0) { throw (0, builder_util_runtime_1.newError)("Internal error", "ERR_DATA_SPLITTER_BYTE_COUNT_MISMATCH"); } if (this.ignoreByteCount > 0) { const toIgnore = Math.min(this.ignoreByteCount, chunk.length); this.ignoreByteCount -= toIgnore; start = toIgnore; } else if (this.remainingPartDataCount > 0) { const toRead = Math.min(this.remainingPartDataCount, chunk.length); this.remainingPartDataCount -= toRead; await this.processPartData(chunk, 0, toRead); start = toRead; } if (start === chunk.length) { return; } if (this.readState === ReadState.HEADER) { const headerListEnd = this.searchHeaderListEnd(chunk, start); if (headerListEnd === -1) { return; } start = headerListEnd; this.readState = ReadState.BODY; // header list is ignored, we don't need it this.headerListBuffer = null; } while (true) { if (this.readState === ReadState.BODY) { this.readState = ReadState.INIT; } else { this.partIndex++; let taskIndex = this.partIndexToTaskIndex.get(this.partIndex); if (taskIndex == null) { if (this.isFinished) { taskIndex = this.options.end; } else { throw (0, builder_util_runtime_1.newError)("taskIndex is null", "ERR_DATA_SPLITTER_TASK_INDEX_IS_NULL"); } } const prevTaskIndex = this.partIndex === 0 ? this.options.start : this.partIndexToTaskIndex.get(this.partIndex - 1) + 1; /* prev part is download, next maybe copy */ if (prevTaskIndex < taskIndex) { await this.copyExistingData(prevTaskIndex, taskIndex); } else if (prevTaskIndex > taskIndex) { throw (0, builder_util_runtime_1.newError)("prevTaskIndex must be < taskIndex", "ERR_DATA_SPLITTER_TASK_INDEX_ASSERT_FAILED"); } if (this.isFinished) { this.onPartEnd(); this.finishHandler(); return; } start = this.searchHeaderListEnd(chunk, start); if (start === -1) { this.readState = ReadState.HEADER; return; } } const partLength = this.partIndexToLength[this.partIndex]; const end = start + partLength; const effectiveEnd = Math.min(end, chunk.length); await this.processPartStarted(chunk, start, effectiveEnd); this.remainingPartDataCount = partLength - (effectiveEnd - start); if (this.remainingPartDataCount > 0) { return; } start = end + this.boundaryLength; if (start >= chunk.length) { this.ignoreByteCount = this.boundaryLength - (chunk.length - end); return; } } } copyExistingData(index, end) { return new Promise((resolve, reject) => { const w = () => { if (index === end) { resolve(); return; } const task = this.options.tasks[index]; if (task.kind !== downloadPlanBuilder_1.OperationKind.COPY) { reject(new Error("Task kind must be COPY")); return; } copyData(task, this.out, this.options.oldFileFd, reject, () => { index++; w(); }); }; w(); }); } searchHeaderListEnd(chunk, readOffset) { const headerListEnd = chunk.indexOf(DOUBLE_CRLF, readOffset); if (headerListEnd !== -1) { return headerListEnd + DOUBLE_CRLF.length; } // not all headers data were received, save to buffer const partialChunk = readOffset === 0 ? chunk : chunk.slice(readOffset); if (this.headerListBuffer == null) { this.headerListBuffer = partialChunk; } else { this.headerListBuffer = Buffer.concat([this.headerListBuffer, partialChunk]); } return -1; } onPartEnd() { const expectedLength = this.partIndexToLength[this.partIndex - 1]; if (this.actualPartLength !== expectedLength) { throw (0, builder_util_runtime_1.newError)(`Expected length: ${expectedLength} differs from actual: ${this.actualPartLength}`, "ERR_DATA_SPLITTER_LENGTH_MISMATCH"); } this.actualPartLength = 0; } processPartStarted(data, start, end) { if (this.partIndex !== 0) { this.onPartEnd(); } return this.processPartData(data, start, end); } processPartData(data, start, end) { this.actualPartLength += end - start; this.transferred += end - start; this.delta += end - start; const out = this.out; if (out.write(start === 0 && data.length === end ? data : data.slice(start, end))) { return Promise.resolve(); } else { return new Promise((resolve, reject) => { out.on("error", reject); out.once("drain", () => { out.removeListener("error", reject); resolve(); }); }); } } } exports.DataSplitter = DataSplitter; //# sourceMappingURL=DataSplitter.js.map{"version":3,"file":"DataSplitter.js","sourceRoot":"","sources":["../../src/differentialDownloader/DataSplitter.ts"],"names":[],"mappings":";;;AAqBA,4BAaC;AAlCD,+DAA+C;AAC/C,2BAAqC;AACrC,mCAAiC;AACjC,+DAAgE;AAGhE,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;AAE3C,IAAK,SAIJ;AAJD,WAAK,SAAS;IACZ,yCAAI,CAAA;IACJ,6CAAM,CAAA;IACN,yCAAI,CAAA;AACN,CAAC,EAJI,SAAS,KAAT,SAAS,QAIb;AASD,SAAgB,QAAQ,CAAC,IAAe,EAAE,GAAa,EAAE,SAAiB,EAAE,MAA8B,EAAE,OAAmB;IAC7H,MAAM,UAAU,GAAG,IAAA,qBAAgB,EAAC,EAAE,EAAE;QACtC,EAAE,EAAE,SAAS;QACb,SAAS,EAAE,KAAK;QAChB,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,mBAAmB;QACnB,GAAG,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC;KAClB,CAAC,CAAA;IACF,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,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AAC,CAAA;oBACnC,OAAO,EAAE,CAAA;gBACX,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF;AAnOD,oCAmOC","sourcesContent":["import { newError } from \"builder-util-runtime\"\nimport { createReadStream } from \"fs\"\nimport { Writable } from \"stream\"\nimport { Operation, OperationKind } from \"./downloadPlanBuilder\"\nimport { ProgressInfo } from \"./ProgressDifferentialDownloadCallbackTransform\"\n\nconst DOUBLE_CRLF = Buffer.from(\"\\r\\n\\r\\n\")\n\nenum ReadState {\n INIT,\n HEADER,\n BODY,\n}\n\nexport interface PartListDataTask {\n readonly oldFileFd: number\n readonly tasks: Array\n readonly start: number\n readonly end: number\n}\n\nexport function copyData(task: Operation, out: Writable, oldFileFd: number, reject: (error: Error) => void, resolve: () => void): void {\n const readStream = createReadStream(\"\", {\n fd: oldFileFd,\n autoClose: false,\n start: task.start,\n // end is inclusive\n end: task.end - 1,\n })\n readStream.on(\"error\", reject)\n readStream.once(\"end\", resolve)\n readStream.pipe(out, {\n end: false,\n })\n}\n\nexport class DataSplitter extends Writable {\n // properties for progress update calculations\n private start = Date.now() // download start time used to calculate average rate\n private nextUpdate = this.start + 1000 // timestamp of next update to prevent updates more often than once per second\n private transferred = 0 // total number of bytes transferred\n private delta = 0 // number of bytes transferred since last update, reset after each update\n\n partIndex = -1\n\n private headerListBuffer: Buffer | null = null\n private readState = ReadState.INIT\n private ignoreByteCount = 0\n private remainingPartDataCount = 0\n\n private readonly boundaryLength: number\n\n constructor(\n private readonly out: Writable,\n private readonly options: PartListDataTask,\n private readonly partIndexToTaskIndex: Map,\n boundary: string,\n private readonly partIndexToLength: Array,\n private readonly finishHandler: () => any,\n private readonly grandTotalBytes: number,\n private readonly onProgress?: (info: ProgressInfo) => any\n ) {\n super()\n\n this.boundaryLength = boundary.length + 4 /* size of \\r\\n-- */\n // first chunk doesn't start with \\r\\n\n this.ignoreByteCount = this.boundaryLength - 2\n }\n\n get isFinished(): boolean {\n return this.partIndex === this.partIndexToLength.length\n }\n\n // noinspection JSUnusedGlobalSymbols\n _write(data: Buffer, encoding: string, callback: (error?: Error) => void): void {\n if (this.isFinished) {\n console.error(`Trailing ignored data: ${data.length} bytes`)\n return\n }\n\n this.handleData(data)\n .then(() => {\n if (this.onProgress) {\n const now = Date.now()\n if ((now >= this.nextUpdate || this.transferred === this.grandTotalBytes) && this.grandTotalBytes && (now - this.start) / 1000) {\n this.nextUpdate = now + 1000\n\n this.onProgress({\n total: this.grandTotalBytes,\n delta: this.delta,\n transferred: this.transferred,\n percent: (this.transferred / this.grandTotalBytes) * 100,\n bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)),\n })\n this.delta = 0\n }\n }\n\n callback()\n })\n .catch(callback)\n }\n\n private async handleData(chunk: Buffer): Promise {\n let start = 0\n\n if (this.ignoreByteCount !== 0 && this.remainingPartDataCount !== 0) {\n throw newError(\"Internal error\", \"ERR_DATA_SPLITTER_BYTE_COUNT_MISMATCH\")\n }\n\n if (this.ignoreByteCount > 0) {\n const toIgnore = Math.min(this.ignoreByteCount, chunk.length)\n this.ignoreByteCount -= toIgnore\n start = toIgnore\n } else if (this.remainingPartDataCount > 0) {\n const toRead = Math.min(this.remainingPartDataCount, chunk.length)\n this.remainingPartDataCount -= toRead\n await this.processPartData(chunk, 0, toRead)\n start = toRead\n }\n\n if (start === chunk.length) {\n return\n }\n\n if (this.readState === ReadState.HEADER) {\n const headerListEnd = this.searchHeaderListEnd(chunk, start)\n if (headerListEnd === -1) {\n return\n }\n\n start = headerListEnd\n this.readState = ReadState.BODY\n // header list is ignored, we don't need it\n this.headerListBuffer = null\n }\n\n while (true) {\n if (this.readState === ReadState.BODY) {\n this.readState = ReadState.INIT\n } else {\n this.partIndex++\n\n let taskIndex = this.partIndexToTaskIndex.get(this.partIndex)\n if (taskIndex == null) {\n if (this.isFinished) {\n taskIndex = this.options.end\n } else {\n throw newError(\"taskIndex is null\", \"ERR_DATA_SPLITTER_TASK_INDEX_IS_NULL\")\n }\n }\n\n const prevTaskIndex = this.partIndex === 0 ? this.options.start : this.partIndexToTaskIndex.get(this.partIndex - 1)! + 1 /* prev part is download, next maybe copy */\n if (prevTaskIndex < taskIndex) {\n await this.copyExistingData(prevTaskIndex, taskIndex)\n } else if (prevTaskIndex > taskIndex) {\n throw newError(\"prevTaskIndex must be < taskIndex\", \"ERR_DATA_SPLITTER_TASK_INDEX_ASSERT_FAILED\")\n }\n\n if (this.isFinished) {\n this.onPartEnd()\n this.finishHandler()\n return\n }\n\n start = this.searchHeaderListEnd(chunk, start)\n\n if (start === -1) {\n this.readState = ReadState.HEADER\n return\n }\n }\n\n const partLength = this.partIndexToLength[this.partIndex]\n const end = start + partLength\n const effectiveEnd = Math.min(end, chunk.length)\n await this.processPartStarted(chunk, start, effectiveEnd)\n this.remainingPartDataCount = partLength - (effectiveEnd - start)\n if (this.remainingPartDataCount > 0) {\n return\n }\n\n start = end + this.boundaryLength\n if (start >= chunk.length) {\n this.ignoreByteCount = this.boundaryLength - (chunk.length - end)\n return\n }\n }\n }\n\n private copyExistingData(index: number, end: number): Promise {\n return new Promise((resolve, reject) => {\n const w = (): void => {\n if (index === end) {\n resolve()\n return\n }\n\n const task = this.options.tasks[index]\n if (task.kind !== OperationKind.COPY) {\n reject(new Error(\"Task kind must be COPY\"))\n return\n }\n\n copyData(task, this.out, this.options.oldFileFd, reject, () => {\n index++\n w()\n })\n }\n w()\n })\n }\n\n private searchHeaderListEnd(chunk: Buffer, readOffset: number): number {\n const headerListEnd = chunk.indexOf(DOUBLE_CRLF, readOffset)\n if (headerListEnd !== -1) {\n return headerListEnd + DOUBLE_CRLF.length\n }\n\n // not all headers data were received, save to buffer\n const partialChunk = readOffset === 0 ? chunk : chunk.slice(readOffset)\n if (this.headerListBuffer == null) {\n this.headerListBuffer = partialChunk\n } else {\n this.headerListBuffer = Buffer.concat([this.headerListBuffer, partialChunk])\n }\n return -1\n }\n\n private actualPartLength = 0\n\n private onPartEnd(): void {\n const expectedLength = this.partIndexToLength[this.partIndex - 1]\n if (this.actualPartLength !== expectedLength) {\n throw newError(`Expected length: ${expectedLength} differs from actual: ${this.actualPartLength}`, \"ERR_DATA_SPLITTER_LENGTH_MISMATCH\")\n }\n this.actualPartLength = 0\n }\n\n private processPartStarted(data: Buffer, start: number, end: number): Promise {\n if (this.partIndex !== 0) {\n this.onPartEnd()\n }\n return this.processPartData(data, start, end)\n }\n\n private processPartData(data: Buffer, start: number, end: number): Promise {\n this.actualPartLength += end - start\n this.transferred += end - start\n this.delta += end - start\n const out = this.out\n if (out.write(start === 0 && data.length === end ? data : data.slice(start, end))) {\n return Promise.resolve()\n } else {\n return new Promise((resolve, reject) => {\n out.on(\"error\", reject)\n out.once(\"drain\", () => {\n out.removeListener(\"error\", reject)\n resolve()\n })\n })\n }\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DifferentialDownloader = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const fs_extra_1 = require("fs-extra"); const fs_1 = require("fs"); const DataSplitter_1 = require("./DataSplitter"); const url_1 = require("url"); const downloadPlanBuilder_1 = require("./downloadPlanBuilder"); const multipleRangeDownloader_1 = require("./multipleRangeDownloader"); const ProgressDifferentialDownloadCallbackTransform_1 = require("./ProgressDifferentialDownloadCallbackTransform"); class DifferentialDownloader { // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected constructor(blockAwareFileInfo, httpExecutor, options) { this.blockAwareFileInfo = blockAwareFileInfo; this.httpExecutor = httpExecutor; this.options = options; this.fileMetadataBuffer = null; this.logger = options.logger; } createRequestOptions() { const result = { headers: { ...this.options.requestHeaders, accept: "*/*", }, }; (0, builder_util_runtime_1.configureRequestUrl)(this.options.newUrl, result); // user-agent, cache-control and other common options (0, builder_util_runtime_1.configureRequestOptions)(result); return result; } doDownload(oldBlockMap, newBlockMap) { // we don't check other metadata like compressionMethod - generic check that it is make sense to differentially update is suitable for it if (oldBlockMap.version !== newBlockMap.version) { throw new Error(`version is different (${oldBlockMap.version} - ${newBlockMap.version}), full download is required`); } const logger = this.logger; const operations = (0, downloadPlanBuilder_1.computeOperations)(oldBlockMap, newBlockMap, logger); if (logger.debug != null) { logger.debug(JSON.stringify(operations, null, 2)); } let downloadSize = 0; let copySize = 0; for (const operation of operations) { const length = operation.end - operation.start; if (operation.kind === downloadPlanBuilder_1.OperationKind.DOWNLOAD) { downloadSize += length; } else { copySize += length; } } const newSize = this.blockAwareFileInfo.size; if (downloadSize + copySize + (this.fileMetadataBuffer == null ? 0 : this.fileMetadataBuffer.length) !== newSize) { throw new Error(`Internal error, size mismatch: downloadSize: ${downloadSize}, copySize: ${copySize}, newSize: ${newSize}`); } logger.info(`Full: ${formatBytes(newSize)}, To download: ${formatBytes(downloadSize)} (${Math.round(downloadSize / (newSize / 100))}%)`); return this.downloadFile(operations); } downloadFile(tasks) { const fdList = []; const closeFiles = () => { return Promise.all(fdList.map(openedFile => { return (0, fs_extra_1.close)(openedFile.descriptor).catch((e) => { this.logger.error(`cannot close file "${openedFile.path}": ${e}`); }); })); }; return this.doDownloadFile(tasks, fdList) .then(closeFiles) .catch((e) => { // then must be after catch here (since then always throws error) return closeFiles() .catch(closeFilesError => { // closeFiles never throw error, but just to be sure try { this.logger.error(`cannot close files: ${closeFilesError}`); } catch (errorOnLog) { try { console.error(errorOnLog); } catch (_ignored) { // ok, give up and ignore error } } throw e; }) .then(() => { throw e; }); }); } async doDownloadFile(tasks, fdList) { const oldFileFd = await (0, fs_extra_1.open)(this.options.oldFile, "r"); fdList.push({ descriptor: oldFileFd, path: this.options.oldFile }); const newFileFd = await (0, fs_extra_1.open)(this.options.newFile, "w"); fdList.push({ descriptor: newFileFd, path: this.options.newFile }); const fileOut = (0, fs_1.createWriteStream)(this.options.newFile, { fd: newFileFd }); await new Promise((resolve, reject) => { const streams = []; // Create our download info transformer if we have one let downloadInfoTransform = undefined; if (!this.options.isUseMultipleRangeRequest && this.options.onProgress) { const expectedByteCounts = []; let grandTotalBytes = 0; for (const task of tasks) { if (task.kind === downloadPlanBuilder_1.OperationKind.DOWNLOAD) { expectedByteCounts.push(task.end - task.start); grandTotalBytes += task.end - task.start; } } const progressDifferentialDownloadInfo = { expectedByteCounts: expectedByteCounts, grandTotal: grandTotalBytes, }; downloadInfoTransform = new ProgressDifferentialDownloadCallbackTransform_1.ProgressDifferentialDownloadCallbackTransform(progressDifferentialDownloadInfo, this.options.cancellationToken, this.options.onProgress); streams.push(downloadInfoTransform); } const digestTransform = new builder_util_runtime_1.DigestTransform(this.blockAwareFileInfo.sha512); // to simply debug, do manual validation to allow file to be fully written digestTransform.isValidateOnEnd = false; streams.push(digestTransform); // noinspection JSArrowFunctionCanBeReplacedWithShorthand fileOut.on("finish", () => { ; fileOut.close(() => { // remove from fd list because closed successfully fdList.splice(1, 1); try { digestTransform.validate(); } catch (e) { reject(e); return; } resolve(undefined); }); }); streams.push(fileOut); let lastStream = null; for (const stream of streams) { stream.on("error", reject); if (lastStream == null) { lastStream = stream; } else { lastStream = lastStream.pipe(stream); } } const firstStream = streams[0]; let w; if (this.options.isUseMultipleRangeRequest) { w = (0, multipleRangeDownloader_1.executeTasksUsingMultipleRangeRequests)(this, tasks, firstStream, oldFileFd, reject); w(0); return; } let downloadOperationCount = 0; let actualUrl = null; this.logger.info(`Differential download: ${this.options.newUrl}`); const requestOptions = this.createRequestOptions(); requestOptions.redirect = "manual"; w = (index) => { var _a, _b; if (index >= tasks.length) { if (this.fileMetadataBuffer != null) { firstStream.write(this.fileMetadataBuffer); } firstStream.end(); return; } const operation = tasks[index++]; if (operation.kind === downloadPlanBuilder_1.OperationKind.COPY) { // We are copying, let's not send status updates to the UI if (downloadInfoTransform) { downloadInfoTransform.beginFileCopy(); } (0, DataSplitter_1.copyData)(operation, firstStream, oldFileFd, reject, () => w(index)); return; } const range = `bytes=${operation.start}-${operation.end - 1}`; requestOptions.headers.range = range; (_b = (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `download range: ${range}`); // We are starting to download if (downloadInfoTransform) { downloadInfoTransform.beginRangeDownload(); } const request = this.httpExecutor.createRequest(requestOptions, response => { response.on("error", reject); response.on("aborted", () => { reject(new Error("response has been aborted by the server")); }); // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes. if (response.statusCode >= 400) { reject((0, builder_util_runtime_1.createHttpError)(response)); } response.pipe(firstStream, { end: false, }); response.once("end", () => { // Pass on that we are downloading a segment if (downloadInfoTransform) { downloadInfoTransform.endRangeDownload(); } if (++downloadOperationCount === 100) { downloadOperationCount = 0; setTimeout(() => w(index), 1000); } else { w(index); } }); }); request.on("redirect", (statusCode, method, redirectUrl) => { this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`); actualUrl = redirectUrl; (0, builder_util_runtime_1.configureRequestUrl)(new url_1.URL(actualUrl), requestOptions); request.followRedirect(); }); this.httpExecutor.addErrorAndTimeoutHandlers(request, reject); request.end(); }; w(0); }); } async readRemoteBytes(start, endInclusive) { const buffer = Buffer.allocUnsafe(endInclusive + 1 - start); const requestOptions = this.createRequestOptions(); requestOptions.headers.range = `bytes=${start}-${endInclusive}`; let position = 0; await this.request(requestOptions, chunk => { chunk.copy(buffer, position); position += chunk.length; }); if (position !== buffer.length) { throw new Error(`Received data length ${position} is not equal to expected ${buffer.length}`); } return buffer; } request(requestOptions, dataHandler) { return new Promise((resolve, reject) => { const request = this.httpExecutor.createRequest(requestOptions, response => { if (!(0, multipleRangeDownloader_1.checkIsRangesSupported)(response, reject)) { return; } response.on("error", reject); response.on("aborted", () => { reject(new Error("response has been aborted by the server")); }); response.on("data", dataHandler); response.on("end", () => resolve()); }); this.httpExecutor.addErrorAndTimeoutHandlers(request, reject); request.end(); }); } } exports.DifferentialDownloader = DifferentialDownloader; function formatBytes(value, symbol = " KB") { return new Intl.NumberFormat("en").format((value / 1024).toFixed(2)) + symbol; } // safety function removeQuery(url) { const index = url.indexOf("?"); return index < 0 ? url : url.substring(0, index); } //# sourceMappingURL=DifferentialDownloader.js.map{"version":3,"file":"DifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/DifferentialDownloader.ts"],"names":[],"mappings":";;;AAAA,+DAAuJ;AAEvJ,uCAAsC;AACtC,2BAAsC;AAItC,iDAAyC;AACzC,6BAAyB;AACzB,+DAAmF;AACnF,uEAA0G;AAC1G,mHAAiJ;AAgBjJ,MAAsB,sBAAsB;IAK1C,oEAAoE;IACpE,YACqB,kBAAsC,EAChD,YAA+B,EAC/B,OAAsC;QAF5B,uBAAkB,GAAlB,kBAAkB,CAAoB;QAChD,iBAAY,GAAZ,YAAY,CAAmB;QAC/B,YAAO,GAAP,OAAO,CAA+B;QARjD,uBAAkB,GAAkB,IAAI,CAAA;QAUtC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;IAC9B,CAAC;IAED,oBAAoB;QAClB,MAAM,MAAM,GAAG;YACb,OAAO,EAAE;gBACP,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc;gBAC9B,MAAM,EAAE,KAAK;aACd;SACF,CAAA;QACD,IAAA,0CAAmB,EAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChD,qDAAqD;QACrD,IAAA,8CAAuB,EAAC,MAAM,CAAC,CAAA;QAC/B,OAAO,MAAM,CAAA;IACf,CAAC;IAES,UAAU,CAAC,WAAqB,EAAE,WAAqB;QAC/D,yIAAyI;QACzI,IAAI,WAAW,CAAC,OAAO,KAAK,WAAW,CAAC,OAAO,EAAE,CAAC;YAChD,MAAM,IAAI,KAAK,CAAC,yBAAyB,WAAW,CAAC,OAAO,MAAM,WAAW,CAAC,OAAO,8BAA8B,CAAC,CAAA;QACtH,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAC1B,MAAM,UAAU,GAAG,IAAA,uCAAiB,EAAC,WAAW,EAAE,WAAW,EAAE,MAAM,CAAC,CAAA;QACtE,IAAI,MAAM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AG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;AAClD,CAAC","sourcesContent":["import { BlockMapDataHolder, createHttpError, DigestTransform, HttpExecutor, configureRequestUrl, configureRequestOptions } from \"builder-util-runtime\"\nimport { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { close, open } from \"fs-extra\"\nimport { createWriteStream } from \"fs\"\nimport { OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { ProgressInfo, CancellationToken } from \"builder-util-runtime\"\nimport { Logger } from \"../types\"\nimport { copyData } from \"./DataSplitter\"\nimport { URL } from \"url\"\nimport { computeOperations, Operation, OperationKind } from \"./downloadPlanBuilder\"\nimport { checkIsRangesSupported, executeTasksUsingMultipleRangeRequests } from \"./multipleRangeDownloader\"\nimport { ProgressDifferentialDownloadCallbackTransform, ProgressDifferentialDownloadInfo } from \"./ProgressDifferentialDownloadCallbackTransform\"\n\nexport interface DifferentialDownloaderOptions {\n readonly oldFile: string\n readonly newUrl: URL\n readonly logger: Logger\n readonly newFile: string\n\n readonly requestHeaders: OutgoingHttpHeaders | null\n\n readonly isUseMultipleRangeRequest?: boolean\n\n readonly cancellationToken: CancellationToken\n onProgress?: (progress: ProgressInfo) => void\n}\n\nexport abstract class DifferentialDownloader {\n fileMetadataBuffer: Buffer | null = null\n\n private readonly logger: Logger\n\n // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected\n constructor(\n protected readonly blockAwareFileInfo: BlockMapDataHolder,\n readonly httpExecutor: HttpExecutor,\n readonly options: DifferentialDownloaderOptions\n ) {\n this.logger = options.logger\n }\n\n createRequestOptions(): RequestOptions {\n const result = {\n headers: {\n ...this.options.requestHeaders,\n accept: \"*/*\",\n },\n }\n configureRequestUrl(this.options.newUrl, result)\n // user-agent, cache-control and other common options\n configureRequestOptions(result)\n return result\n }\n\n protected doDownload(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise {\n // we don't check other metadata like compressionMethod - generic check that it is make sense to differentially update is suitable for it\n if (oldBlockMap.version !== newBlockMap.version) {\n throw new Error(`version is different (${oldBlockMap.version} - ${newBlockMap.version}), full download is required`)\n }\n\n const logger = this.logger\n const operations = computeOperations(oldBlockMap, newBlockMap, logger)\n if (logger.debug != null) {\n logger.debug(JSON.stringify(operations, null, 2))\n }\n\n let downloadSize = 0\n let copySize = 0\n for (const operation of operations) {\n const length = operation.end - operation.start\n if (operation.kind === OperationKind.DOWNLOAD) {\n downloadSize += length\n } else {\n copySize += length\n }\n }\n\n const newSize = this.blockAwareFileInfo.size\n if (downloadSize + copySize + (this.fileMetadataBuffer == null ? 0 : this.fileMetadataBuffer.length) !== newSize) {\n throw new Error(`Internal error, size mismatch: downloadSize: ${downloadSize}, copySize: ${copySize}, newSize: ${newSize}`)\n }\n\n logger.info(`Full: ${formatBytes(newSize)}, To download: ${formatBytes(downloadSize)} (${Math.round(downloadSize / (newSize / 100))}%)`)\n\n return this.downloadFile(operations)\n }\n\n private downloadFile(tasks: Array): Promise {\n const fdList: Array = []\n const closeFiles = (): Promise> => {\n return Promise.all(\n fdList.map(openedFile => {\n return close(openedFile.descriptor).catch((e: any) => {\n this.logger.error(`cannot close file \"${openedFile.path}\": ${e}`)\n })\n })\n )\n }\n return this.doDownloadFile(tasks, fdList)\n .then(closeFiles)\n .catch((e: any) => {\n // then must be after catch here (since then always throws error)\n return closeFiles()\n .catch(closeFilesError => {\n // closeFiles never throw error, but just to be sure\n try {\n this.logger.error(`cannot close files: ${closeFilesError}`)\n } catch (errorOnLog) {\n try {\n console.error(errorOnLog)\n } catch (_ignored) {\n // ok, give up and ignore error\n }\n }\n throw e\n })\n .then(() => {\n throw e\n })\n })\n }\n\n private async doDownloadFile(tasks: Array, fdList: Array): Promise {\n const oldFileFd = await open(this.options.oldFile, \"r\")\n fdList.push({ descriptor: oldFileFd, path: this.options.oldFile })\n const newFileFd = await open(this.options.newFile, \"w\")\n fdList.push({ descriptor: newFileFd, path: this.options.newFile })\n const fileOut = createWriteStream(this.options.newFile, { fd: newFileFd })\n await new Promise((resolve, reject) => {\n const streams: Array = []\n\n // Create our download info transformer if we have one\n let downloadInfoTransform: ProgressDifferentialDownloadCallbackTransform | undefined = undefined\n if (!this.options.isUseMultipleRangeRequest && this.options.onProgress) {\n const expectedByteCounts: Array = []\n let grandTotalBytes = 0\n\n for (const task of tasks) {\n if (task.kind === OperationKind.DOWNLOAD) {\n expectedByteCounts.push(task.end - task.start)\n grandTotalBytes += task.end - task.start\n }\n }\n\n const progressDifferentialDownloadInfo: ProgressDifferentialDownloadInfo = {\n expectedByteCounts: expectedByteCounts,\n grandTotal: grandTotalBytes,\n }\n\n downloadInfoTransform = new ProgressDifferentialDownloadCallbackTransform(progressDifferentialDownloadInfo, this.options.cancellationToken, this.options.onProgress)\n streams.push(downloadInfoTransform)\n }\n\n const digestTransform = new DigestTransform(this.blockAwareFileInfo.sha512)\n // to simply debug, do manual validation to allow file to be fully written\n digestTransform.isValidateOnEnd = false\n streams.push(digestTransform)\n\n // noinspection JSArrowFunctionCanBeReplacedWithShorthand\n fileOut.on(\"finish\", () => {\n ;(fileOut.close as any)(() => {\n // remove from fd list because closed successfully\n fdList.splice(1, 1)\n try {\n digestTransform.validate()\n } catch (e: any) {\n reject(e)\n return\n }\n\n resolve(undefined)\n })\n })\n\n streams.push(fileOut)\n\n let lastStream = null\n for (const stream of streams) {\n stream.on(\"error\", reject)\n if (lastStream == null) {\n lastStream = stream\n } else {\n lastStream = lastStream.pipe(stream)\n }\n }\n\n const firstStream = streams[0]\n\n let w: any\n if (this.options.isUseMultipleRangeRequest) {\n w = executeTasksUsingMultipleRangeRequests(this, tasks, firstStream, oldFileFd, reject)\n w(0)\n return\n }\n\n let downloadOperationCount = 0\n let actualUrl: string | null = null\n this.logger.info(`Differential download: ${this.options.newUrl}`)\n\n const requestOptions = this.createRequestOptions()\n ;(requestOptions as any).redirect = \"manual\"\n\n w = (index: number): void => {\n if (index >= tasks.length) {\n if (this.fileMetadataBuffer != null) {\n firstStream.write(this.fileMetadataBuffer)\n }\n firstStream.end()\n return\n }\n\n const operation = tasks[index++]\n if (operation.kind === OperationKind.COPY) {\n // We are copying, let's not send status updates to the UI\n if (downloadInfoTransform) {\n downloadInfoTransform.beginFileCopy()\n }\n\n copyData(operation, firstStream, oldFileFd, reject, () => w(index))\n return\n }\n\n const range = `bytes=${operation.start}-${operation.end - 1}`\n requestOptions.headers!.range = range\n\n this.logger?.debug?.(`download range: ${range}`)\n\n // We are starting to download\n if (downloadInfoTransform) {\n downloadInfoTransform.beginRangeDownload()\n }\n\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.\n if (response.statusCode >= 400) {\n reject(createHttpError(response))\n }\n\n response.pipe(firstStream, {\n end: false,\n })\n response.once(\"end\", () => {\n // Pass on that we are downloading a segment\n if (downloadInfoTransform) {\n downloadInfoTransform.endRangeDownload()\n }\n\n if (++downloadOperationCount === 100) {\n downloadOperationCount = 0\n setTimeout(() => w(index), 1000)\n } else {\n w(index)\n }\n })\n })\n request.on(\"redirect\", (statusCode: number, method: string, redirectUrl: string) => {\n this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`)\n actualUrl = redirectUrl\n configureRequestUrl(new URL(actualUrl), requestOptions)\n request.followRedirect()\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n }\n\n w(0)\n })\n }\n\n protected async readRemoteBytes(start: number, endInclusive: number): Promise {\n const buffer = Buffer.allocUnsafe(endInclusive + 1 - start)\n const requestOptions = this.createRequestOptions()\n requestOptions.headers!.range = `bytes=${start}-${endInclusive}`\n let position = 0\n await this.request(requestOptions, chunk => {\n chunk.copy(buffer, position)\n position += chunk.length\n })\n\n if (position !== buffer.length) {\n throw new Error(`Received data length ${position} is not equal to expected ${buffer.length}`)\n }\n return buffer\n }\n\n private request(requestOptions: RequestOptions, dataHandler: (chunk: Buffer) => void): Promise {\n return new Promise((resolve, reject) => {\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n if (!checkIsRangesSupported(response, reject)) {\n return\n }\n\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n\n response.on(\"data\", dataHandler)\n response.on(\"end\", () => resolve())\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n })\n }\n}\n\nfunction formatBytes(value: number, symbol = \" KB\"): string {\n return new Intl.NumberFormat(\"en\").format((value / 1024).toFixed(2) as any) + symbol\n}\n\n// safety\nfunction removeQuery(url: string): string {\n const index = url.indexOf(\"?\")\n return index < 0 ? url : url.substring(0, index)\n}\n\ninterface OpenedFile {\n readonly descriptor: number\n readonly path: string\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileWithEmbeddedBlockMapDifferentialDownloader = void 0; const fs_extra_1 = require("fs-extra"); const DifferentialDownloader_1 = require("./DifferentialDownloader"); const zlib_1 = require("zlib"); class FileWithEmbeddedBlockMapDifferentialDownloader extends DifferentialDownloader_1.DifferentialDownloader { async download() { const packageInfo = this.blockAwareFileInfo; const fileSize = packageInfo.size; const offset = fileSize - (packageInfo.blockMapSize + 4); this.fileMetadataBuffer = await this.readRemoteBytes(offset, fileSize - 1); const newBlockMap = readBlockMap(this.fileMetadataBuffer.slice(0, this.fileMetadataBuffer.length - 4)); await this.doDownload(await readEmbeddedBlockMapData(this.options.oldFile), newBlockMap); } } exports.FileWithEmbeddedBlockMapDifferentialDownloader = FileWithEmbeddedBlockMapDifferentialDownloader; function readBlockMap(data) { return JSON.parse((0, zlib_1.inflateRawSync)(data).toString()); } async function readEmbeddedBlockMapData(file) { const fd = await (0, fs_extra_1.open)(file, "r"); try { const fileSize = (await (0, fs_extra_1.fstat)(fd)).size; const sizeBuffer = Buffer.allocUnsafe(4); await (0, fs_extra_1.read)(fd, sizeBuffer, 0, sizeBuffer.length, fileSize - sizeBuffer.length); const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0)); await (0, fs_extra_1.read)(fd, dataBuffer, 0, dataBuffer.length, fileSize - sizeBuffer.length - dataBuffer.length); await (0, fs_extra_1.close)(fd); return readBlockMap(dataBuffer); } catch (e) { await (0, fs_extra_1.close)(fd); throw e; } } //# sourceMappingURL=FileWithEmbeddedBlockMapDifferentialDownloader.js.map{"version":3,"file":"FileWithEmbeddedBlockMapDifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader.ts"],"names":[],"mappings":";;;AACA,uCAAmD;AACnD,qEAAiE;AACjE,+BAAqC;AAErC,MAAa,8CAA+C,SAAQ,+CAAsB;IACxF,KAAK,CAAC,QAAQ;QACZ,MAAM,WAAW,GAAG,IAAI,CAAC,kBAAkB,CAAA;QAC3C,MAAM,QAAQ,GAAG,WAAW,CAAC,IAAK,CAAA;QAClC,MAAM,MAAM,GAAG,QAAQ,GAAG,CAAC,WAAW,CAAC,YAAa,GAAG,CAAC,CAAC,CAAA;QACzD,IAAI,CAAC,kBAAkB,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAA;QAC1E,MAAM,WAAW,GAAG,YAAY,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,kBAAkB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAA;QACtG,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,WAAW,CAAC,CAAA;IAC1F,CAAC;CACF;AATD,wGASC;AAED,SAAS,YAAY,CAAC,IAAY;IAChC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,qBAAc,EAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAA;AACpD,CAAC;AAED,KAAK,UAAU,wBAAwB,CAAC,IAAY;IAClD,MAAM,EAAE,GAAG,MAAM,IAAA,eAAI,EAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAChC,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAA,gBAAK,EAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAA;QACvC,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;QACxC,MAAM,IAAA,eAAI,EAAC,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,CAAC,MAAM,EAAE,QAAQ,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;QAE9E,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;QACjE,MAAM,IAAA,eAAI,EAAC,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,CAAC,MAAM,EAAE,QAAQ,GAAG,UAAU,CAAC,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAA;QAClG,MAAM,IAAA,gBAAK,EAAC,EAAE,CAAC,CAAA;QAEf,OAAO,YAAY,CAAC,UAAU,CAAC,CAAA;IACjC,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,MAAM,IAAA,gBAAK,EAAC,EAAE,CAAC,CAAA;QACf,MAAM,CAAC,CAAA;IACT,CAAC;AACH,CAAC","sourcesContent":["import { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { close, fstat, open, read } from \"fs-extra\"\nimport { DifferentialDownloader } from \"./DifferentialDownloader\"\nimport { inflateRawSync } from \"zlib\"\n\nexport class FileWithEmbeddedBlockMapDifferentialDownloader extends DifferentialDownloader {\n async download(): Promise {\n const packageInfo = this.blockAwareFileInfo\n const fileSize = packageInfo.size!\n const offset = fileSize - (packageInfo.blockMapSize! + 4)\n this.fileMetadataBuffer = await this.readRemoteBytes(offset, fileSize - 1)\n const newBlockMap = readBlockMap(this.fileMetadataBuffer.slice(0, this.fileMetadataBuffer.length - 4))\n await this.doDownload(await readEmbeddedBlockMapData(this.options.oldFile), newBlockMap)\n }\n}\n\nfunction readBlockMap(data: Buffer): BlockMap {\n return JSON.parse(inflateRawSync(data).toString())\n}\n\nasync function readEmbeddedBlockMapData(file: string): Promise {\n const fd = await open(file, \"r\")\n try {\n const fileSize = (await fstat(fd)).size\n const sizeBuffer = Buffer.allocUnsafe(4)\n await read(fd, sizeBuffer, 0, sizeBuffer.length, fileSize - sizeBuffer.length)\n\n const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0))\n await read(fd, dataBuffer, 0, dataBuffer.length, fileSize - sizeBuffer.length - dataBuffer.length)\n await close(fd)\n\n return readBlockMap(dataBuffer)\n } catch (e: any) {\n await close(fd)\n throw e\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GenericDifferentialDownloader = void 0; const DifferentialDownloader_1 = require("./DifferentialDownloader"); class GenericDifferentialDownloader extends DifferentialDownloader_1.DifferentialDownloader { download(oldBlockMap, newBlockMap) { return this.doDownload(oldBlockMap, newBlockMap); } } exports.GenericDifferentialDownloader = GenericDifferentialDownloader; //# sourceMappingURL=GenericDifferentialDownloader.js.map{"version":3,"file":"GenericDifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/GenericDifferentialDownloader.ts"],"names":[],"mappings":";;;AACA,qEAAiE;AAEjE,MAAa,6BAA8B,SAAQ,+CAAsB;IACvE,QAAQ,CAAC,WAAqB,EAAE,WAAqB;QACnD,OAAO,IAAI,CAAC,UAAU,CAAC,WAAW,EAAE,WAAW,CAAC,CAAA;IAClD,CAAC;CACF;AAJD,sEAIC","sourcesContent":["import { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { DifferentialDownloader } from \"./DifferentialDownloader\"\n\nexport class GenericDifferentialDownloader extends DifferentialDownloader {\n download(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise {\n return this.doDownload(oldBlockMap, newBlockMap)\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProgressDifferentialDownloadCallbackTransform = void 0; const stream_1 = require("stream"); var OperationKind; (function (OperationKind) { OperationKind[OperationKind["COPY"] = 0] = "COPY"; OperationKind[OperationKind["DOWNLOAD"] = 1] = "DOWNLOAD"; })(OperationKind || (OperationKind = {})); class ProgressDifferentialDownloadCallbackTransform extends stream_1.Transform { constructor(progressDifferentialDownloadInfo, cancellationToken, onProgress) { super(); this.progressDifferentialDownloadInfo = progressDifferentialDownloadInfo; this.cancellationToken = cancellationToken; this.onProgress = onProgress; this.start = Date.now(); this.transferred = 0; this.delta = 0; this.expectedBytes = 0; this.index = 0; this.operationType = OperationKind.COPY; this.nextUpdate = this.start + 1000; } _transform(chunk, encoding, callback) { if (this.cancellationToken.cancelled) { callback(new Error("cancelled"), null); return; } // Don't send progress update when copying from disk if (this.operationType == OperationKind.COPY) { callback(null, chunk); return; } this.transferred += chunk.length; this.delta += chunk.length; const now = Date.now(); if (now >= this.nextUpdate && this.transferred !== this.expectedBytes /* will be emitted by endRangeDownload() */ && this.transferred !== this.progressDifferentialDownloadInfo.grandTotal /* will be emitted on _flush */) { this.nextUpdate = now + 1000; this.onProgress({ total: this.progressDifferentialDownloadInfo.grandTotal, delta: this.delta, transferred: this.transferred, percent: (this.transferred / this.progressDifferentialDownloadInfo.grandTotal) * 100, bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)), }); this.delta = 0; } callback(null, chunk); } beginFileCopy() { this.operationType = OperationKind.COPY; } beginRangeDownload() { this.operationType = OperationKind.DOWNLOAD; this.expectedBytes += this.progressDifferentialDownloadInfo.expectedByteCounts[this.index++]; } endRangeDownload() { // _flush() will doour final 100% if (this.transferred !== this.progressDifferentialDownloadInfo.grandTotal) { this.onProgress({ total: this.progressDifferentialDownloadInfo.grandTotal, delta: this.delta, transferred: this.transferred, percent: (this.transferred / this.progressDifferentialDownloadInfo.grandTotal) * 100, bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)), }); } } // Called when we are 100% done with the connection/download _flush(callback) { if (this.cancellationToken.cancelled) { callback(new Error("cancelled")); return; } this.onProgress({ total: this.progressDifferentialDownloadInfo.grandTotal, delta: this.delta, transferred: this.transferred, percent: 100, bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)), }); this.delta = 0; this.transferred = 0; callback(null); } } exports.ProgressDifferentialDownloadCallbackTransform = ProgressDifferentialDownloadCallbackTransform; //# sourceMappingURL=ProgressDifferentialDownloadCallbackTransform.js.map{"version":3,"file":"ProgressDifferentialDownloadCallbackTransform.js","sourceRoot":"","sources":["../../src/differentialDownloader/ProgressDifferentialDownloadCallbackTransform.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAGlC,IAAK,aAGJ;AAHD,WAAK,aAAa;IAChB,iDAAI,CAAA;IACJ,yDAAQ,CAAA;AACV,CAAC,EAHI,aAAa,KAAb,aAAa,QAGjB;AAeD,MAAa,6CAA8C,SAAQ,kBAAS;IAU1E,YACmB,gCAAkE,EAClE,iBAAoC,EACpC,UAAuC;QAExD,KAAK,EAAE,CAAA;QAJU,qCAAgC,GAAhC,gCAAgC,CAAkC;QAClE,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,eAAU,GAAV,UAAU,CAA6B;QAZlD,UAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QAClB,gBAAW,GAAG,CAAC,CAAA;QACf,UAAK,GAAG,CAAC,CAAA;QACT,kBAAa,GAAG,CAAC,CAAA;QACjB,UAAK,GAAG,CAAC,CAAA;QACT,kBAAa,GAAG,aAAa,CAAC,IAAI,CAAA;QAElC,eAAU,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAA;IAQtC,CAAC;IA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E,GAAG;YACZ,cAAc,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;SAClF,CAAC,CAAA;QACF,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;QACd,IAAI,CAAC,WAAW,GAAG,CAAC,CAAA;QAEpB,QAAQ,CAAC,IAAI,CAAC,CAAA;IAChB,CAAC;CACF;AAhGD,sGAgGC","sourcesContent":["import { Transform } from \"stream\"\nimport { CancellationToken } from \"builder-util-runtime\"\n\nenum OperationKind {\n COPY,\n DOWNLOAD,\n}\n\nexport interface ProgressInfo {\n total: number\n delta: number\n transferred: number\n percent: number\n bytesPerSecond: number\n}\n\nexport interface ProgressDifferentialDownloadInfo {\n expectedByteCounts: Array\n grandTotal: number\n}\n\nexport class ProgressDifferentialDownloadCallbackTransform extends Transform {\n private start = Date.now()\n private transferred = 0\n private delta = 0\n private expectedBytes = 0\n private index = 0\n private operationType = OperationKind.COPY\n\n private nextUpdate = this.start + 1000\n\n constructor(\n private readonly progressDifferentialDownloadInfo: ProgressDifferentialDownloadInfo,\n private readonly cancellationToken: CancellationToken,\n private readonly onProgress: (info: ProgressInfo) => any\n ) {\n super()\n }\n\n _transform(chunk: any, encoding: string, callback: any) {\n if (this.cancellationToken.cancelled) {\n callback(new Error(\"cancelled\"), null)\n return\n }\n\n // Don't send progress update when copying from disk\n if (this.operationType == OperationKind.COPY) {\n callback(null, chunk)\n return\n }\n\n this.transferred += chunk.length\n this.delta += chunk.length\n\n const now = Date.now()\n if (\n now >= this.nextUpdate &&\n this.transferred !== this.expectedBytes /* will be emitted by endRangeDownload() */ &&\n this.transferred !== this.progressDifferentialDownloadInfo.grandTotal /* will be emitted on _flush */\n ) {\n this.nextUpdate = now + 1000\n\n this.onProgress({\n total: this.progressDifferentialDownloadInfo.grandTotal,\n delta: this.delta,\n transferred: this.transferred,\n percent: (this.transferred / this.progressDifferentialDownloadInfo.grandTotal) * 100,\n bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)),\n })\n this.delta = 0\n }\n\n callback(null, chunk)\n }\n\n beginFileCopy(): void {\n this.operationType = OperationKind.COPY\n }\n\n beginRangeDownload(): void {\n this.operationType = OperationKind.DOWNLOAD\n\n this.expectedBytes += this.progressDifferentialDownloadInfo.expectedByteCounts[this.index++]\n }\n\n endRangeDownload(): void {\n // _flush() will doour final 100%\n if (this.transferred !== this.progressDifferentialDownloadInfo.grandTotal) {\n this.onProgress({\n total: this.progressDifferentialDownloadInfo.grandTotal,\n delta: this.delta,\n transferred: this.transferred,\n percent: (this.transferred / this.progressDifferentialDownloadInfo.grandTotal) * 100,\n bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)),\n })\n }\n }\n\n // Called when we are 100% done with the connection/download\n _flush(callback: any): void {\n if (this.cancellationToken.cancelled) {\n callback(new Error(\"cancelled\"))\n return\n }\n\n this.onProgress({\n total: this.progressDifferentialDownloadInfo.grandTotal,\n delta: this.delta,\n transferred: this.transferred,\n percent: 100,\n bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)),\n })\n this.delta = 0\n this.transferred = 0\n\n callback(null)\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OperationKind = void 0; exports.computeOperations = computeOperations; var OperationKind; (function (OperationKind) { OperationKind[OperationKind["COPY"] = 0] = "COPY"; OperationKind[OperationKind["DOWNLOAD"] = 1] = "DOWNLOAD"; })(OperationKind || (exports.OperationKind = OperationKind = {})); function computeOperations(oldBlockMap, newBlockMap, logger) { const nameToOldBlocks = buildBlockFileMap(oldBlockMap.files); const nameToNewBlocks = buildBlockFileMap(newBlockMap.files); let lastOperation = null; // for now only one file is supported in block map const blockMapFile = newBlockMap.files[0]; const operations = []; const name = blockMapFile.name; const oldEntry = nameToOldBlocks.get(name); if (oldEntry == null) { // new file (unrealistic case for now, because in any case both blockmap contain the only file named as "file") throw new Error(`no file ${name} in old blockmap`); } const newFile = nameToNewBlocks.get(name); let changedBlockCount = 0; const { checksumToOffset: checksumToOldOffset, checksumToOldSize } = buildChecksumMap(nameToOldBlocks.get(name), oldEntry.offset, logger); let newOffset = blockMapFile.offset; for (let i = 0; i < newFile.checksums.length; newOffset += newFile.sizes[i], i++) { const blockSize = newFile.sizes[i]; const checksum = newFile.checksums[i]; let oldOffset = checksumToOldOffset.get(checksum); if (oldOffset != null && checksumToOldSize.get(checksum) !== blockSize) { logger.warn(`Checksum ("${checksum}") matches, but size differs (old: ${checksumToOldSize.get(checksum)}, new: ${blockSize})`); oldOffset = undefined; } if (oldOffset === undefined) { // download data from new file changedBlockCount++; if (lastOperation != null && lastOperation.kind === OperationKind.DOWNLOAD && lastOperation.end === newOffset) { lastOperation.end += blockSize; } else { lastOperation = { kind: OperationKind.DOWNLOAD, start: newOffset, end: newOffset + blockSize, // oldBlocks: null, }; validateAndAdd(lastOperation, operations, checksum, i); } } else { // reuse data from old file if (lastOperation != null && lastOperation.kind === OperationKind.COPY && lastOperation.end === oldOffset) { lastOperation.end += blockSize; // lastOperation.oldBlocks!!.push(checksum) } else { lastOperation = { kind: OperationKind.COPY, start: oldOffset, end: oldOffset + blockSize, // oldBlocks: [checksum] }; validateAndAdd(lastOperation, operations, checksum, i); } } } if (changedBlockCount > 0) { logger.info(`File${blockMapFile.name === "file" ? "" : " " + blockMapFile.name} has ${changedBlockCount} changed blocks`); } return operations; } const isValidateOperationRange = process.env["DIFFERENTIAL_DOWNLOAD_PLAN_BUILDER_VALIDATE_RANGES"] === "true"; function validateAndAdd(operation, operations, checksum, index) { if (isValidateOperationRange && operations.length !== 0) { const lastOperation = operations[operations.length - 1]; if (lastOperation.kind === operation.kind && operation.start < lastOperation.end && operation.start > lastOperation.start) { const min = [lastOperation.start, lastOperation.end, operation.start, operation.end].reduce((p, v) => (p < v ? p : v)); throw new Error(`operation (block index: ${index}, checksum: ${checksum}, kind: ${OperationKind[operation.kind]}) overlaps previous operation (checksum: ${checksum}):\n` + `abs: ${lastOperation.start} until ${lastOperation.end} and ${operation.start} until ${operation.end}\n` + `rel: ${lastOperation.start - min} until ${lastOperation.end - min} and ${operation.start - min} until ${operation.end - min}`); } } operations.push(operation); } function buildChecksumMap(file, fileOffset, logger) { const checksumToOffset = new Map(); const checksumToSize = new Map(); let offset = fileOffset; for (let i = 0; i < file.checksums.length; i++) { const checksum = file.checksums[i]; const size = file.sizes[i]; const existing = checksumToSize.get(checksum); if (existing === undefined) { checksumToOffset.set(checksum, offset); checksumToSize.set(checksum, size); } else if (logger.debug != null) { const sizeExplanation = existing === size ? "(same size)" : `(size: ${existing}, this size: ${size})`; logger.debug(`${checksum} duplicated in blockmap ${sizeExplanation}, it doesn't lead to broken differential downloader, just corresponding block will be skipped)`); } offset += size; } return { checksumToOffset, checksumToOldSize: checksumToSize }; } function buildBlockFileMap(list) { const result = new Map(); for (const item of list) { result.set(item.name, item); } return result; } //# sourceMappingURL=downloadPlanBuilder.js.map{"version":3,"file":"downloadPlanBuilder.js","sourceRoot":"","sources":["../../src/differentialDownloader/downloadPlanBuilder.ts"],"names":[],"mappings":";;;AAoBA,8CAmEC;AApFD,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,iDAAI,CAAA;IACJ,yDAAQ,CAAA;AACV,CAAC,EAHW,aAAa,6BAAb,aAAa,QAGxB;AAcD,SAAgB,iBAAiB,CAAC,WAAqB,EAAE,WAAqB,EAAE,MAAc;IAC5F,MAAM,eAAe,GAAG,iBAAiB,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;IAC5D,MAAM,eAAe,GAAG,iBAAiB,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;IAE5D,IAAI,aAAa,GAAqB,IAAI,CAAA;IAE1C,kDAAkD;IAClD,MAAM,YAAY,GAAqC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC3E,MAAM,UAAU,GAAqB,EAAE,CAAA;IACvC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AAE,CAAC;QACxB,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IAC7B,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { BlockMap, BlockMapFile } from \"builder-util-runtime/out/blockMapApi\"\nimport { Logger } from \"../types\"\n\nexport enum OperationKind {\n COPY,\n DOWNLOAD,\n}\n\nexport interface Operation {\n kind: OperationKind\n\n // inclusive\n start: number\n // exclusive\n end: number\n\n // debug only\n // oldBlocks: Array | null\n}\n\nexport function computeOperations(oldBlockMap: BlockMap, newBlockMap: BlockMap, logger: Logger): Array {\n const nameToOldBlocks = buildBlockFileMap(oldBlockMap.files)\n const nameToNewBlocks = buildBlockFileMap(newBlockMap.files)\n\n let lastOperation: Operation | null = null\n\n // for now only one file is supported in block map\n const blockMapFile: { name: string; offset: number } = newBlockMap.files[0]\n const operations: Array = []\n const name = blockMapFile.name\n const oldEntry = nameToOldBlocks.get(name)\n if (oldEntry == null) {\n // new file (unrealistic case for now, because in any case both blockmap contain the only file named as \"file\")\n throw new Error(`no file ${name} in old blockmap`)\n }\n\n const newFile = nameToNewBlocks.get(name)!\n let changedBlockCount = 0\n\n const { checksumToOffset: checksumToOldOffset, checksumToOldSize } = buildChecksumMap(nameToOldBlocks.get(name)!, oldEntry.offset, logger)\n\n let newOffset = blockMapFile.offset\n for (let i = 0; i < newFile.checksums.length; newOffset += newFile.sizes[i], i++) {\n const blockSize: number = newFile.sizes[i]\n const checksum = newFile.checksums[i]\n let oldOffset = checksumToOldOffset.get(checksum)\n if (oldOffset != null && checksumToOldSize.get(checksum) !== blockSize) {\n logger.warn(`Checksum (\"${checksum}\") matches, but size differs (old: ${checksumToOldSize.get(checksum)}, new: ${blockSize})`)\n oldOffset = undefined\n }\n\n if (oldOffset === undefined) {\n // download data from new file\n changedBlockCount++\n\n if (lastOperation != null && lastOperation.kind === OperationKind.DOWNLOAD && lastOperation.end === newOffset) {\n lastOperation.end += blockSize\n } else {\n lastOperation = {\n kind: OperationKind.DOWNLOAD,\n start: newOffset,\n end: newOffset + blockSize,\n // oldBlocks: null,\n }\n validateAndAdd(lastOperation, operations, checksum, i)\n }\n } else {\n // reuse data from old file\n if (lastOperation != null && lastOperation.kind === OperationKind.COPY && lastOperation.end === oldOffset) {\n lastOperation.end += blockSize\n // lastOperation.oldBlocks!!.push(checksum)\n } else {\n lastOperation = {\n kind: OperationKind.COPY,\n start: oldOffset,\n end: oldOffset + blockSize,\n // oldBlocks: [checksum]\n }\n validateAndAdd(lastOperation, operations, checksum, i)\n }\n }\n }\n\n if (changedBlockCount > 0) {\n logger.info(`File${blockMapFile.name === \"file\" ? \"\" : \" \" + blockMapFile.name} has ${changedBlockCount} changed blocks`)\n }\n return operations\n}\n\nconst isValidateOperationRange = process.env[\"DIFFERENTIAL_DOWNLOAD_PLAN_BUILDER_VALIDATE_RANGES\"] === \"true\"\n\nfunction validateAndAdd(operation: Operation, operations: Array, checksum: string, index: number): void {\n if (isValidateOperationRange && operations.length !== 0) {\n const lastOperation = operations[operations.length - 1]\n if (lastOperation.kind === operation.kind && operation.start < lastOperation.end && operation.start > lastOperation.start) {\n const min = [lastOperation.start, lastOperation.end, operation.start, operation.end].reduce((p, v) => (p < v ? p : v))\n throw new Error(\n `operation (block index: ${index}, checksum: ${checksum}, kind: ${OperationKind[operation.kind]}) overlaps previous operation (checksum: ${checksum}):\\n` +\n `abs: ${lastOperation.start} until ${lastOperation.end} and ${operation.start} until ${operation.end}\\n` +\n `rel: ${lastOperation.start - min} until ${lastOperation.end - min} and ${operation.start - min} until ${operation.end - min}`\n )\n }\n }\n operations.push(operation)\n}\n\nfunction buildChecksumMap(file: BlockMapFile, fileOffset: number, logger: Logger) {\n const checksumToOffset = new Map()\n const checksumToSize = new Map()\n let offset = fileOffset\n for (let i = 0; i < file.checksums.length; i++) {\n const checksum = file.checksums[i]\n const size = file.sizes[i]\n\n const existing = checksumToSize.get(checksum)\n if (existing === undefined) {\n checksumToOffset.set(checksum, offset)\n checksumToSize.set(checksum, size)\n } else if (logger.debug != null) {\n const sizeExplanation = existing === size ? \"(same size)\" : `(size: ${existing}, this size: ${size})`\n logger.debug(`${checksum} duplicated in blockmap ${sizeExplanation}, it doesn't lead to broken differential downloader, just corresponding block will be skipped)`)\n }\n offset += size\n }\n return { checksumToOffset, checksumToOldSize: checksumToSize }\n}\n\nfunction buildBlockFileMap(list: Array): Map {\n const result = new Map()\n for (const item of list) {\n result.set(item.name, item)\n }\n return result\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.executeTasksUsingMultipleRangeRequests = executeTasksUsingMultipleRangeRequests; exports.checkIsRangesSupported = checkIsRangesSupported; const builder_util_runtime_1 = require("builder-util-runtime"); const DataSplitter_1 = require("./DataSplitter"); const downloadPlanBuilder_1 = require("./downloadPlanBuilder"); function executeTasksUsingMultipleRangeRequests(differentialDownloader, tasks, out, oldFileFd, reject) { const w = (taskOffset) => { if (taskOffset >= tasks.length) { if (differentialDownloader.fileMetadataBuffer != null) { out.write(differentialDownloader.fileMetadataBuffer); } out.end(); return; } const nextOffset = taskOffset + 1000; doExecuteTasks(differentialDownloader, { tasks, start: taskOffset, end: Math.min(tasks.length, nextOffset), oldFileFd, }, out, () => w(nextOffset), reject); }; return w; } function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { let ranges = "bytes="; let partCount = 0; let grandTotalBytes = 0; const partIndexToTaskIndex = new Map(); const partIndexToLength = []; for (let i = options.start; i < options.end; i++) { const task = options.tasks[i]; if (task.kind === downloadPlanBuilder_1.OperationKind.DOWNLOAD) { ranges += `${task.start}-${task.end - 1}, `; partIndexToTaskIndex.set(partCount, i); partCount++; partIndexToLength.push(task.end - task.start); grandTotalBytes += task.end - task.start; } } if (partCount <= 1) { // the only remote range - copy const w = (index) => { if (index >= options.end) { resolve(); return; } const task = options.tasks[index++]; if (task.kind === downloadPlanBuilder_1.OperationKind.COPY) { (0, DataSplitter_1.copyData)(task, out, options.oldFileFd, reject, () => w(index)); } else { const requestOptions = differentialDownloader.createRequestOptions(); requestOptions.headers.Range = `bytes=${task.start}-${task.end - 1}`; const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => { response.on("error", reject); if (!checkIsRangesSupported(response, reject)) { return; } response.pipe(out, { end: false, }); response.once("end", () => w(index)); }); differentialDownloader.httpExecutor.addErrorAndTimeoutHandlers(request, reject); request.end(); } }; w(options.start); return; } const requestOptions = differentialDownloader.createRequestOptions(); requestOptions.headers.Range = ranges.substring(0, ranges.length - 2); const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => { if (!checkIsRangesSupported(response, reject)) { return; } const contentType = (0, builder_util_runtime_1.safeGetHeader)(response, "content-type"); const m = /^multipart\/.+?\s*;\s*boundary=(?:"([^"]+)"|([^\s";]+))\s*$/i.exec(contentType); if (m == null) { reject(new Error(`Content-Type "multipart/byteranges" is expected, but got "${contentType}"`)); return; } const dicer = new DataSplitter_1.DataSplitter(out, options, partIndexToTaskIndex, m[1] || m[2], partIndexToLength, resolve, grandTotalBytes, differentialDownloader.options.onProgress); dicer.on("error", reject); response.pipe(dicer); response.on("end", () => { setTimeout(() => { request.abort(); reject(new Error("Response ends without calling any handlers")); }, 10000); }); }); differentialDownloader.httpExecutor.addErrorAndTimeoutHandlers(request, reject); request.end(); } function checkIsRangesSupported(response, reject) { // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes. if (response.statusCode >= 400) { reject((0, builder_util_runtime_1.createHttpError)(response)); return false; } if (response.statusCode !== 206) { const acceptRanges = (0, builder_util_runtime_1.safeGetHeader)(response, "accept-ranges"); if (acceptRanges == null || acceptRanges === "none") { reject(new Error(`Server doesn't support Accept-Ranges (response code ${response.statusCode})`)); return false; } } return true; } //# sourceMappingURL=multipleRangeDownloader.js.map{"version":3,"file":"multipleRangeDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/multipleRangeDownloader.ts"],"names":[],"mappings":";;AAOA,wFA+BC;AAoFD,wDAe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KAAK,CAAA;QACd,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import { createHttpError, safeGetHeader } from \"builder-util-runtime\"\nimport { IncomingMessage } from \"http\"\nimport { Writable } from \"stream\"\nimport { copyData, DataSplitter, PartListDataTask } from \"./DataSplitter\"\nimport { DifferentialDownloader } from \"./DifferentialDownloader\"\nimport { Operation, OperationKind } from \"./downloadPlanBuilder\"\n\nexport function executeTasksUsingMultipleRangeRequests(\n differentialDownloader: DifferentialDownloader,\n tasks: Array,\n out: Writable,\n oldFileFd: number,\n reject: (error: Error) => void\n): (taskOffset: number) => void {\n const w = (taskOffset: number): void => {\n if (taskOffset >= tasks.length) {\n if (differentialDownloader.fileMetadataBuffer != null) {\n out.write(differentialDownloader.fileMetadataBuffer)\n }\n out.end()\n return\n }\n\n const nextOffset = taskOffset + 1000\n doExecuteTasks(\n differentialDownloader,\n {\n tasks,\n start: taskOffset,\n end: Math.min(tasks.length, nextOffset),\n oldFileFd,\n },\n out,\n () => w(nextOffset),\n reject\n )\n }\n return w\n}\n\nfunction doExecuteTasks(differentialDownloader: DifferentialDownloader, options: PartListDataTask, out: Writable, resolve: () => void, reject: (error: Error) => void): void {\n let ranges = \"bytes=\"\n let partCount = 0\n let grandTotalBytes = 0\n const partIndexToTaskIndex = new Map()\n const partIndexToLength: Array = []\n for (let i = options.start; i < options.end; i++) {\n const task = options.tasks[i]\n if (task.kind === OperationKind.DOWNLOAD) {\n ranges += `${task.start}-${task.end - 1}, `\n partIndexToTaskIndex.set(partCount, i)\n partCount++\n partIndexToLength.push(task.end - task.start)\n grandTotalBytes += task.end - task.start\n }\n }\n\n if (partCount <= 1) {\n // the only remote range - copy\n const w = (index: number): void => {\n if (index >= options.end) {\n resolve()\n return\n }\n\n const task = options.tasks[index++]\n\n if (task.kind === OperationKind.COPY) {\n copyData(task, out, options.oldFileFd, reject, () => w(index))\n } else {\n const requestOptions = differentialDownloader.createRequestOptions()\n requestOptions.headers!.Range = `bytes=${task.start}-${task.end - 1}`\n const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => {\n response.on(\"error\", reject)\n\n if (!checkIsRangesSupported(response, reject)) {\n return\n }\n\n response.pipe(out, {\n end: false,\n })\n response.once(\"end\", () => w(index))\n })\n differentialDownloader.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n }\n }\n\n w(options.start)\n return\n }\n\n const requestOptions = differentialDownloader.createRequestOptions()\n requestOptions.headers!.Range = ranges.substring(0, ranges.length - 2)\n const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => {\n if (!checkIsRangesSupported(response, reject)) {\n return\n }\n\n const contentType = safeGetHeader(response, \"content-type\")\n const m = /^multipart\\/.+?\\s*;\\s*boundary=(?:\"([^\"]+)\"|([^\\s\";]+))\\s*$/i.exec(contentType)\n if (m == null) {\n reject(new Error(`Content-Type \"multipart/byteranges\" is expected, but got \"${contentType}\"`))\n return\n }\n\n const dicer = new DataSplitter(out, options, partIndexToTaskIndex, m[1] || m[2], partIndexToLength, resolve, grandTotalBytes, differentialDownloader.options.onProgress)\n dicer.on(\"error\", reject)\n response.pipe(dicer)\n\n response.on(\"end\", () => {\n setTimeout(() => {\n request.abort()\n reject(new Error(\"Response ends without calling any handlers\"))\n }, 10000)\n })\n })\n differentialDownloader.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n}\n\nexport function checkIsRangesSupported(response: IncomingMessage, reject: (error: Error) => void): boolean {\n // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.\n if (response.statusCode! >= 400) {\n reject(createHttpError(response))\n return false\n }\n\n if (response.statusCode !== 206) {\n const acceptRanges = safeGetHeader(response, \"accept-ranges\")\n if (acceptRanges == null || acceptRanges === \"none\") {\n reject(new Error(`Server doesn't support Accept-Ranges (response code ${response.statusCode})`))\n return false\n }\n }\n return true\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ElectronHttpExecutor = exports.NET_SESSION_NAME = void 0; exports.getNetSession = getNetSession; const builder_util_runtime_1 = require("builder-util-runtime"); exports.NET_SESSION_NAME = "electron-updater"; function getNetSession() { return require("electron").session.fromPartition(exports.NET_SESSION_NAME, { cache: false, }); } class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { constructor(proxyLoginCallback) { super(); this.proxyLoginCallback = proxyLoginCallback; this.cachedSession = null; } async download(url, destination, options) { return await options.cancellationToken.createPromise((resolve, reject, onCancel) => { const requestOptions = { headers: options.headers || undefined, redirect: "manual", }; (0, builder_util_runtime_1.configureRequestUrl)(url, requestOptions); (0, builder_util_runtime_1.configureRequestOptions)(requestOptions); this.doDownload(requestOptions, { destination, options, onCancel, callback: error => { if (error == null) { resolve(destination); } else { reject(error); } }, responseHandler: null, }, 0); }); } createRequest(options, callback) { // fix (node 7+) for making electron updater work when using AWS private buckets, check if headers contain Host property if (options.headers && options.headers.Host) { // set host value from headers.Host options.host = options.headers.Host; // remove header property 'Host', if not removed causes net::ERR_INVALID_ARGUMENT exception delete options.headers.Host; } // differential downloader can call this method very often, so, better to cache session if (this.cachedSession == null) { this.cachedSession = getNetSession(); } const request = require("electron").net.request({ ...options, session: this.cachedSession, }); request.on("response", callback); if (this.proxyLoginCallback != null) { request.on("login", this.proxyLoginCallback); } return request; } addRedirectHandlers(request, options, reject, redirectCount, handler) { request.on("redirect", (statusCode, method, redirectUrl) => { // no way to modify request options, abort old and make a new one // https://github.com/electron/electron/issues/11505 request.abort(); if (redirectCount > this.maxRedirects) { reject(this.createMaxRedirectError()); } else { handler(builder_util_runtime_1.HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options)); } }); } } exports.ElectronHttpExecutor = ElectronHttpExecutor; //# sourceMappingURL=electronHttpExecutor.js.map{"version":3,"file":"electronHttpExecutor.js","sourceRoot":"","sources":["../src/electronHttpExecutor.ts"],"names":[],"mappings":";;;AASA,sCAIC;AAbD,+DAAkH;AAOrG,QAAA,gBAAgB,GAAG,kBAAkB,CAAA;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-util-runtime\"\nimport type { AuthInfo } from \"electron\"\nimport { RequestOptions } from \"http\"\nimport Session = Electron.Session\nimport ClientRequest = Electron.ClientRequest\n\nexport type LoginCallback = (username: string, password: string) => void\nexport const NET_SESSION_NAME = \"electron-updater\"\n\nexport function getNetSession(): Session {\n return require(\"electron\").session.fromPartition(NET_SESSION_NAME, {\n cache: false,\n })\n}\n\nexport class ElectronHttpExecutor extends HttpExecutor {\n private cachedSession: Session | null = null\n\n constructor(private readonly proxyLoginCallback?: (authInfo: AuthInfo, callback: LoginCallback) => void) {\n super()\n }\n\n async download(url: URL, destination: string, options: DownloadOptions): Promise {\n return await options.cancellationToken.createPromise((resolve, reject, onCancel) => {\n const requestOptions = {\n headers: options.headers || undefined,\n redirect: \"manual\",\n }\n configureRequestUrl(url, requestOptions)\n configureRequestOptions(requestOptions)\n this.doDownload(\n requestOptions,\n {\n destination,\n options,\n onCancel,\n callback: error => {\n if (error == null) {\n resolve(destination)\n } else {\n reject(error)\n }\n },\n responseHandler: null,\n },\n 0\n )\n })\n }\n\n createRequest(options: any, callback: (response: any) => void): Electron.ClientRequest {\n // fix (node 7+) for making electron updater work when using AWS private buckets, check if headers contain Host property\n if (options.headers && options.headers.Host) {\n // set host value from headers.Host\n options.host = options.headers.Host\n // remove header property 'Host', if not removed causes net::ERR_INVALID_ARGUMENT exception\n delete options.headers.Host\n }\n\n // differential downloader can call this method very often, so, better to cache session\n if (this.cachedSession == null) {\n this.cachedSession = getNetSession()\n }\n\n const request = require(\"electron\").net.request({\n ...options,\n session: this.cachedSession,\n })\n request.on(\"response\", callback)\n if (this.proxyLoginCallback != null) {\n request.on(\"login\", this.proxyLoginCallback)\n }\n return request\n }\n\n protected addRedirectHandlers(\n request: ClientRequest,\n options: RequestOptions,\n reject: (error: Error) => void,\n redirectCount: number,\n handler: (options: RequestOptions) => void\n ): void {\n request.on(\"redirect\", (statusCode: number, method: string, redirectUrl: string) => {\n // no way to modify request options, abort old and make a new one\n // https://github.com/electron/electron/issues/11505\n request.abort()\n\n if (redirectCount > this.maxRedirects) {\n reject(this.createMaxRedirectError())\n } else {\n handler(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options))\n }\n })\n }\n}\n"]}"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NsisUpdater = exports.MacUpdater = exports.RpmUpdater = exports.PacmanUpdater = exports.DebUpdater = exports.AppImageUpdater = exports.Provider = exports.NoOpLogger = exports.AppUpdater = exports.BaseUpdater = void 0; const fs_extra_1 = require("fs-extra"); const path = require("path"); var BaseUpdater_1 = require("./BaseUpdater"); Object.defineProperty(exports, "BaseUpdater", { enumerable: true, get: function () { return BaseUpdater_1.BaseUpdater; } }); var AppUpdater_1 = require("./AppUpdater"); Object.defineProperty(exports, "AppUpdater", { enumerable: true, get: function () { return AppUpdater_1.AppUpdater; } }); Object.defineProperty(exports, "NoOpLogger", { enumerable: true, get: function () { return AppUpdater_1.NoOpLogger; } }); var Provider_1 = require("./providers/Provider"); Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return Provider_1.Provider; } }); var AppImageUpdater_1 = require("./AppImageUpdater"); Object.defineProperty(exports, "AppImageUpdater", { enumerable: true, get: function () { return AppImageUpdater_1.AppImageUpdater; } }); var DebUpdater_1 = require("./DebUpdater"); Object.defineProperty(exports, "DebUpdater", { enumerable: true, get: function () { return DebUpdater_1.DebUpdater; } }); var PacmanUpdater_1 = require("./PacmanUpdater"); Object.defineProperty(exports, "PacmanUpdater", { enumerable: true, get: function () { return PacmanUpdater_1.PacmanUpdater; } }); var RpmUpdater_1 = require("./RpmUpdater"); Object.defineProperty(exports, "RpmUpdater", { enumerable: true, get: function () { return RpmUpdater_1.RpmUpdater; } }); var MacUpdater_1 = require("./MacUpdater"); Object.defineProperty(exports, "MacUpdater", { enumerable: true, get: function () { return MacUpdater_1.MacUpdater; } }); var NsisUpdater_1 = require("./NsisUpdater"); Object.defineProperty(exports, "NsisUpdater", { enumerable: true, get: function () { return NsisUpdater_1.NsisUpdater; } }); __exportStar(require("./types"), exports); // autoUpdater to mimic electron bundled autoUpdater let _autoUpdater; function doLoadAutoUpdater() { // tslint:disable:prefer-conditional-expression if (process.platform === "win32") { _autoUpdater = new (require("./NsisUpdater").NsisUpdater)(); } else if (process.platform === "darwin") { _autoUpdater = new (require("./MacUpdater").MacUpdater)(); } else { _autoUpdater = new (require("./AppImageUpdater").AppImageUpdater)(); try { const identity = path.join(process.resourcesPath, "package-type"); if (!(0, fs_extra_1.existsSync)(identity)) { return _autoUpdater; } const fileType = (0, fs_extra_1.readFileSync)(identity).toString().trim(); switch (fileType) { case "deb": _autoUpdater = new (require("./DebUpdater").DebUpdater)(); break; case "rpm": _autoUpdater = new (require("./RpmUpdater").RpmUpdater)(); break; case "pacman": _autoUpdater = new (require("./PacmanUpdater").PacmanUpdater)(); break; default: break; } } catch (error) { console.warn("Unable to detect 'package-type' for autoUpdater (rpm/deb/pacman support). If you'd like to expand support, please consider contributing to electron-builder", error.message); } } return _autoUpdater; } Object.defineProperty(exports, "autoUpdater", { enumerable: true, get: () => { return _autoUpdater || doLoadAutoUpdater(); }, }); //# sourceMappingURL=main.js.map{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,uCAAmD;AACnD,6BAA4B;AAI5B,6CAA2C;AAAlC,0GAAA,WAAW,OAAA;AACpB,2CAAqD;AAA5C,wGAAA,UAAU,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,CAAC,UAAU,CAAC,EAAE,CAAA;oBACzD,MAAK;gBACP,KAAK,KAAK;oBACR,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,UAAU,CAAC,EAAE,CAAA;oBACzD,MAAK;gBACP,KAAK,QAAQ;oBACX,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,aAAa,CAAC,EAAE,CAAA;oBAC/D,MAAK;gBACP;oBACE,MAAK;YACT,CAAC;QACH,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,OAAO,CAAC,IAAI,CACV,6JAA6J,EAC7J,KAAK,CAAC,OAAO,CACd,CAAA;QACH,CAAC;IACH,CAAC;IACD,OAAO,YAAY,CAAA;AACrB,CAAC;AAED,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,aAAa,EAAE;IAC5C,UAAU,EAAE,IAAI;IAChB,GAAG,EAAE,GAAG,EAAE;QACR,OAAO,YAAY,IAAI,iBAAiB,EAAE,CAAA;IAC5C,CAAC;CACF,CAAC,CAAA","sourcesContent":["import { existsSync, readFileSync } from \"fs-extra\"\nimport * as path from \"path\"\nimport { AppUpdater } from \"./AppUpdater\"\nimport { UpdateInfo } from \"builder-util-runtime\"\n\nexport { BaseUpdater } from \"./BaseUpdater\"\nexport { AppUpdater, NoOpLogger } from \"./AppUpdater\"\nexport { Provider } from \"./providers/Provider\"\nexport { AppImageUpdater } from \"./AppImageUpdater\"\nexport { DebUpdater } from \"./DebUpdater\"\nexport { PacmanUpdater } from \"./PacmanUpdater\"\nexport { RpmUpdater } from \"./RpmUpdater\"\nexport { MacUpdater } from \"./MacUpdater\"\nexport { NsisUpdater } from \"./NsisUpdater\"\n\nexport * from \"./types\"\n\n// autoUpdater to mimic electron bundled autoUpdater\nlet _autoUpdater: any\n\n// required for jsdoc\nexport declare const autoUpdater: AppUpdater\n\nfunction doLoadAutoUpdater(): AppUpdater {\n // tslint:disable:prefer-conditional-expression\n if (process.platform === \"win32\") {\n _autoUpdater = new (require(\"./NsisUpdater\").NsisUpdater)()\n } else if (process.platform === \"darwin\") {\n _autoUpdater = new (require(\"./MacUpdater\").MacUpdater)()\n } else {\n _autoUpdater = new (require(\"./AppImageUpdater\").AppImageUpdater)()\n try {\n const identity = path.join(process.resourcesPath, \"package-type\")\n if (!existsSync(identity)) {\n return _autoUpdater\n }\n const fileType = readFileSync(identity).toString().trim()\n switch (fileType) {\n case \"deb\":\n _autoUpdater = new (require(\"./DebUpdater\").DebUpdater)()\n break\n case \"rpm\":\n _autoUpdater = new (require(\"./RpmUpdater\").RpmUpdater)()\n break\n case \"pacman\":\n _autoUpdater = new (require(\"./PacmanUpdater\").PacmanUpdater)()\n break\n default:\n break\n }\n } catch (error: any) {\n console.warn(\n \"Unable to detect 'package-type' for autoUpdater (rpm/deb/pacman support). If you'd like to expand support, please consider contributing to electron-builder\",\n error.message\n )\n }\n }\n return _autoUpdater\n}\n\nObject.defineProperty(exports, \"autoUpdater\", {\n enumerable: true,\n get: () => {\n return _autoUpdater || doLoadAutoUpdater()\n },\n})\n\n/**\n * return null if verify signature succeed\n * return error message if verify signature failed\n */\nexport type VerifyUpdateCodeSignature = (publisherName: string[], path: string) => Promise\n\nexport type VerifyUpdateSupport = (updateInfo: UpdateInfo) => boolean | Promise\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isUrlProbablySupportMultiRangeRequests = isUrlProbablySupportMultiRangeRequests; exports.createClient = createClient; const builder_util_runtime_1 = require("builder-util-runtime"); const BitbucketProvider_1 = require("./providers/BitbucketProvider"); const GenericProvider_1 = require("./providers/GenericProvider"); const GitHubProvider_1 = require("./providers/GitHubProvider"); const GitLabProvider_1 = require("./providers/GitLabProvider"); const KeygenProvider_1 = require("./providers/KeygenProvider"); const PrivateGitHubProvider_1 = require("./providers/PrivateGitHubProvider"); function isUrlProbablySupportMultiRangeRequests(url) { return !url.includes("s3.amazonaws.com"); } function createClient(data, updater, runtimeOptions) { // noinspection SuspiciousTypeOfGuard if (typeof data === "string") { throw (0, builder_util_runtime_1.newError)("Please pass PublishConfiguration object", "ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION"); } const provider = data.provider; switch (provider) { case "github": { const githubOptions = data; const token = (githubOptions.private ? process.env["GH_TOKEN"] || process.env["GITHUB_TOKEN"] : null) || githubOptions.token; if (token == null) { return new GitHubProvider_1.GitHubProvider(githubOptions, updater, runtimeOptions); } else { return new PrivateGitHubProvider_1.PrivateGitHubProvider(githubOptions, updater, token, runtimeOptions); } } case "bitbucket": return new BitbucketProvider_1.BitbucketProvider(data, updater, runtimeOptions); case "gitlab": return new GitLabProvider_1.GitLabProvider(data, updater, runtimeOptions); case "keygen": return new KeygenProvider_1.KeygenProvider(data, updater, runtimeOptions); case "s3": case "spaces": return new GenericProvider_1.GenericProvider({ provider: "generic", url: (0, builder_util_runtime_1.getS3LikeProviderBaseUrl)(data), channel: data.channel || null, }, updater, { ...runtimeOptions, // https://github.com/minio/minio/issues/5285#issuecomment-350428955 isUseMultipleRangeRequest: false, }); case "generic": { const options = data; return new GenericProvider_1.GenericProvider(options, updater, { ...runtimeOptions, isUseMultipleRangeRequest: options.useMultipleRangeRequest !== false && isUrlProbablySupportMultiRangeRequests(options.url), }); } case "custom": { const options = data; const constructor = options.updateProvider; if (!constructor) { throw (0, builder_util_runtime_1.newError)("Custom provider not specified", "ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION"); } return new constructor(options, updater, runtimeOptions); } default: throw (0, builder_util_runtime_1.newError)(`Unsupported provider: ${provider}`, "ERR_UPDATER_UNSUPPORTED_PROVIDER"); } } //# sourceMappingURL=providerFactory.js.map{"version":3,"file":"providerFactory.js","sourceRoot":"","sources":["../src/providerFactory.ts"],"names":[],"mappings":";;AAsBA,wFAEC;AAED,oCA+DC;AAzFD,+DAY6B;AAE7B,qEAAiE;AACjE,iEAA6D;AAC7D,+DAA2D;AAC3D,+DAA2D;AAC3D,+DAA2D;AAC3D,6EAAyE;AAGzE,SAA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,QAAQ;YACX,OAAO,IAAI,iCAAe,CACxB;gBACE,QAAQ,EAAE,SAAS;gBACnB,GAAG,EAAE,IAAA,+CAAwB,EAAC,IAAI,CAAC;gBACnC,OAAO,EAAG,IAAsB,CAAC,OAAO,IAAI,IAAI;aACjD,EACD,OAAO,EACP;gBACE,GAAG,cAAc;gBACjB,oEAAoE;gBACpE,yBAAyB,EAAE,KAAK;aACjC,CACF,CAAA;QAEH,KAAK,SAAS,CAAC,CAAC,CAAC;YACf,MAAM,OAAO,GAAG,IAA4B,CAAA;YAC5C,OAAO,IAAI,iCAAe,CAAC,OAAO,EAAE,OAAO,EAAE;gBAC3C,GAAG,cAAc;gBACjB,yBAAyB,EAAE,OAAO,CAAC,uBAAuB,KAAK,KAAK,IAAI,sCAAsC,CAAC,OAAO,CAAC,GAAG,CAAC;aAC5H,CAAC,CAAA;QACJ,CAAC;QAED,KAAK,QAAQ,CAAC,CAAC,CAAC;YACd,MAAM,OAAO,GAAG,IAA4B,CAAA;YAC5C,MAAM,WAAW,GAAG,OAAO,CAAC,cAAc,CAAA;YAC1C,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,MAAM,IAAA,+BAAQ,EAAC,+BAA+B,EAAE,4CAA4C,CAAC,CAAA;YAC/F,CAAC;YACD,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,cAAc,CAAC,CAAA;QAC1D,CAAC;QAED;YACE,MAAM,IAAA,+BAAQ,EAAC,yBAAyB,QAAQ,EAAE,EAAE,kCAAkC,CAAC,CAAA;IAC3F,CAAC;AACH,CAAC","sourcesContent":["import {\n AllPublishOptions,\n BaseS3Options,\n BitbucketOptions,\n CustomPublishOptions,\n GenericServerOptions,\n getS3LikeProviderBaseUrl,\n GithubOptions,\n GitlabOptions,\n KeygenOptions,\n newError,\n PublishConfiguration,\n} from \"builder-util-runtime\"\nimport { AppUpdater } from \"./AppUpdater\"\nimport { BitbucketProvider } from \"./providers/BitbucketProvider\"\nimport { GenericProvider } from \"./providers/GenericProvider\"\nimport { GitHubProvider } from \"./providers/GitHubProvider\"\nimport { GitLabProvider } from \"./providers/GitLabProvider\"\nimport { KeygenProvider } from \"./providers/KeygenProvider\"\nimport { PrivateGitHubProvider } from \"./providers/PrivateGitHubProvider\"\nimport { Provider, ProviderRuntimeOptions } from \"./providers/Provider\"\n\nexport function isUrlProbablySupportMultiRangeRequests(url: string): boolean {\n return !url.includes(\"s3.amazonaws.com\")\n}\n\nexport function createClient(data: PublishConfiguration | AllPublishOptions, updater: AppUpdater, runtimeOptions: ProviderRuntimeOptions): Provider {\n // noinspection SuspiciousTypeOfGuard\n if (typeof data === \"string\") {\n throw newError(\"Please pass PublishConfiguration object\", \"ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION\")\n }\n\n const provider = data.provider\n switch (provider) {\n case \"github\": {\n const githubOptions = data as GithubOptions\n const token = (githubOptions.private ? process.env[\"GH_TOKEN\"] || process.env[\"GITHUB_TOKEN\"] : null) || githubOptions.token\n if (token == null) {\n return new GitHubProvider(githubOptions, updater, runtimeOptions)\n } else {\n return new PrivateGitHubProvider(githubOptions, updater, token, runtimeOptions)\n }\n }\n\n case \"bitbucket\":\n return new BitbucketProvider(data as BitbucketOptions, updater, runtimeOptions)\n\n case \"gitlab\":\n return new GitLabProvider(data as GitlabOptions, updater, runtimeOptions)\n\n case \"keygen\":\n return new KeygenProvider(data as KeygenOptions, updater, runtimeOptions)\n\n case \"s3\":\n case \"spaces\":\n return new GenericProvider(\n {\n provider: \"generic\",\n url: getS3LikeProviderBaseUrl(data),\n channel: (data as BaseS3Options).channel || null,\n },\n updater,\n {\n ...runtimeOptions,\n // https://github.com/minio/minio/issues/5285#issuecomment-350428955\n isUseMultipleRangeRequest: false,\n }\n )\n\n case \"generic\": {\n const options = data as GenericServerOptions\n return new GenericProvider(options, updater, {\n ...runtimeOptions,\n isUseMultipleRangeRequest: options.useMultipleRangeRequest !== false && isUrlProbablySupportMultiRangeRequests(options.url),\n })\n }\n\n case \"custom\": {\n const options = data as CustomPublishOptions\n const constructor = options.updateProvider\n if (!constructor) {\n throw newError(\"Custom provider not specified\", \"ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION\")\n }\n return new constructor(options, updater, runtimeOptions)\n }\n\n default:\n throw newError(`Unsupported provider: ${provider}`, \"ERR_UPDATER_UNSUPPORTED_PROVIDER\")\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BitbucketProvider = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const util_1 = require("../util"); const Provider_1 = require("./Provider"); class BitbucketProvider extends Provider_1.Provider { constructor(configuration, updater, runtimeOptions) { super({ ...runtimeOptions, isUseMultipleRangeRequest: false, }); this.configuration = configuration; this.updater = updater; const { owner, slug } = configuration; this.baseUrl = (0, util_1.newBaseUrl)(`https://api.bitbucket.org/2.0/repositories/${owner}/${slug}/downloads`); } get channel() { return this.updater.channel || this.configuration.channel || "latest"; } async getLatestVersion() { const cancellationToken = new builder_util_runtime_1.CancellationToken(); const channelFile = (0, util_1.getChannelFilename)(this.getCustomChannelName(this.channel)); const channelUrl = (0, util_1.newUrlFromBase)(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery); try { const updateInfo = await this.httpRequest(channelUrl, undefined, cancellationToken); return (0, Provider_1.parseUpdateInfo)(updateInfo, channelFile, channelUrl); } catch (e) { throw (0, builder_util_runtime_1.newError)(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"); } } resolveFiles(updateInfo) { return (0, Provider_1.resolveFiles)(updateInfo, this.baseUrl); } toString() { const { owner, slug } = this.configuration; return `Bitbucket (owner: ${owner}, slug: ${slug}, channel: ${this.channel})`; } } exports.BitbucketProvider = BitbucketProvider; //# sourceMappingURL=BitbucketProvider.js.map{"version":3,"file":"BitbucketProvider.js","sourceRoot":"","sources":["../../src/providers/BitbucketProvider.ts"],"names":[],"mappings":";;;AAAA,+DAAgG;AAG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CAAC,CAAA;QACtK,CAAC;IACH,CAAC;IAED,YAAY,CAAC,UAAsB;QACjC,OAAO,IAAA,uBAAY,EAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/C,CAAC;IAED,QAAQ;QACN,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,aAAa,CAAA;QAC1C,OAAO,qBAAqB,KAAK,WAAW,IAAI,cAAc,IAAI,CAAC,OAAO,GAAG,CAAA;IAC/E,CAAC;CACF;AAxCD,8CAwCC","sourcesContent":["import { CancellationToken, BitbucketOptions, newError, UpdateInfo } from \"builder-util-runtime\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"../types\"\nimport { getChannelFilename, newBaseUrl, newUrlFromBase } from \"../util\"\nimport { parseUpdateInfo, Provider, ProviderRuntimeOptions, resolveFiles } from \"./Provider\"\n\nexport class BitbucketProvider extends Provider {\n private readonly baseUrl: URL\n\n constructor(\n private readonly configuration: BitbucketOptions,\n private readonly updater: AppUpdater,\n runtimeOptions: ProviderRuntimeOptions\n ) {\n super({\n ...runtimeOptions,\n isUseMultipleRangeRequest: false,\n })\n const { owner, slug } = configuration\n this.baseUrl = newBaseUrl(`https://api.bitbucket.org/2.0/repositories/${owner}/${slug}/downloads`)\n }\n\n private get channel(): string {\n return this.updater.channel || this.configuration.channel || \"latest\"\n }\n\n async getLatestVersion(): Promise {\n const cancellationToken = new CancellationToken()\n const channelFile = getChannelFilename(this.getCustomChannelName(this.channel))\n const channelUrl = newUrlFromBase(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery)\n try {\n const updateInfo = await this.httpRequest(channelUrl, undefined, cancellationToken)\n return parseUpdateInfo(updateInfo, channelFile, channelUrl)\n } catch (e: any) {\n throw newError(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack || e.message}`, \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\")\n }\n }\n\n resolveFiles(updateInfo: UpdateInfo): Array {\n return resolveFiles(updateInfo, this.baseUrl)\n }\n\n toString() {\n const { owner, slug } = this.configuration\n return `Bitbucket (owner: ${owner}, slug: ${slug}, channel: ${this.channel})`\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GenericProvider = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const util_1 = require("../util"); const Provider_1 = require("./Provider"); class GenericProvider extends Provider_1.Provider { constructor(configuration, updater, runtimeOptions) { super(runtimeOptions); this.configuration = configuration; this.updater = updater; this.baseUrl = (0, util_1.newBaseUrl)(this.configuration.url); } get channel() { const result = this.updater.channel || this.configuration.channel; return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result); } async getLatestVersion() { const channelFile = (0, util_1.getChannelFilename)(this.channel); const channelUrl = (0, util_1.newUrlFromBase)(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery); for (let attemptNumber = 0;; attemptNumber++) { try { return (0, Provider_1.parseUpdateInfo)(await this.httpRequest(channelUrl), channelFile, channelUrl); } catch (e) { if (e instanceof builder_util_runtime_1.HttpError && e.statusCode === 404) { throw (0, builder_util_runtime_1.newError)(`Cannot find channel "${channelFile}" update info: ${e.stack || e.message}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"); } else if (e.code === "ECONNREFUSED") { if (attemptNumber < 3) { await new Promise((resolve, reject) => { try { setTimeout(resolve, 1000 * attemptNumber); } catch (e) { reject(e); } }); continue; } } throw e; } } } resolveFiles(updateInfo) { return (0, Provider_1.resolveFiles)(updateInfo, this.baseUrl); } } exports.GenericProvider = GenericProvider; //# sourceMappingURL=GenericProvider.js.map{"version":3,"file":"GenericProvider.js","sourceRoot":"","sources":["../../src/providers/GenericProvider.ts"],"names":[],"mappings":";;;AAAA,+DAA4F;AAG5F,kCAAwE;AACxE,yCAA4F;AAE5F,MAAa,eAAgB,SAAQ,mBAAoB;IAGvD,YACmB,aAAmC,EACnC,OAAmB,EACpC,cAAsC;QAEtC,KAAK,CAAC,cAA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AM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;4BACpC,IAAI,CAAC;gCACH,UAAU,CAAC,OAAO,EAAE,IAAI,GAAG,aAAa,CAAC,CAAA;4BAC3C,CAAC;4BAAC,OAAO,CAAM,EAAE,CAAC;gCAChB,MAAM,CAAC,CAAC,CAAC,CAAA;4BACX,CAAC;wBACH,CAAC,CAAC,CAAA;wBACF,SAAQ;oBACV,CAAC;gBACH,CAAC;gBACD,MAAM,CAAC,CAAA;YACT,CAAC;QACH,CAAC;IACH,CAAC;IAED,YAAY,CAAC,UAAsB;QACjC,OAAO,IAAA,uBAAY,EAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/C,CAAC;CACF;AA7CD,0CA6CC","sourcesContent":["import { GenericServerOptions, HttpError, newError, UpdateInfo } from \"builder-util-runtime\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"../types\"\nimport { getChannelFilename, newBaseUrl, newUrlFromBase } from \"../util\"\nimport { parseUpdateInfo, Provider, ProviderRuntimeOptions, resolveFiles } from \"./Provider\"\n\nexport class GenericProvider extends Provider {\n private readonly baseUrl = newBaseUrl(this.configuration.url)\n\n constructor(\n private readonly configuration: GenericServerOptions,\n private readonly updater: AppUpdater,\n runtimeOptions: ProviderRuntimeOptions\n ) {\n super(runtimeOptions)\n }\n\n private get channel(): string {\n const result = this.updater.channel || this.configuration.channel\n return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result)\n }\n\n async getLatestVersion(): Promise {\n const channelFile = getChannelFilename(this.channel)\n const channelUrl = newUrlFromBase(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery)\n for (let attemptNumber = 0; ; attemptNumber++) {\n try {\n return parseUpdateInfo(await this.httpRequest(channelUrl), channelFile, channelUrl)\n } catch (e: any) {\n if (e instanceof HttpError && e.statusCode === 404) {\n throw newError(`Cannot find channel \"${channelFile}\" update info: ${e.stack || e.message}`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n } else if (e.code === \"ECONNREFUSED\") {\n if (attemptNumber < 3) {\n await new Promise((resolve, reject) => {\n try {\n setTimeout(resolve, 1000 * attemptNumber)\n } catch (e: any) {\n reject(e)\n }\n })\n continue\n }\n }\n throw e\n }\n }\n }\n\n resolveFiles(updateInfo: UpdateInfo): Array {\n return resolveFiles(updateInfo, this.baseUrl)\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GitHubProvider = exports.BaseGitHubProvider = void 0; exports.computeReleaseNotes = computeReleaseNotes; const builder_util_runtime_1 = require("builder-util-runtime"); const semver = require("semver"); const url_1 = require("url"); const util_1 = require("../util"); const Provider_1 = require("./Provider"); const hrefRegExp = /\/tag\/(v?[^/]+)$/; class BaseGitHubProvider extends Provider_1.Provider { constructor(options, defaultHost, runtimeOptions) { super({ ...runtimeOptions, /* because GitHib uses S3 */ isUseMultipleRangeRequest: false, }); this.options = options; this.baseUrl = (0, util_1.newBaseUrl)((0, builder_util_runtime_1.githubUrl)(options, defaultHost)); const apiHost = defaultHost === "github.com" ? "api.github.com" : defaultHost; this.baseApiUrl = (0, util_1.newBaseUrl)((0, builder_util_runtime_1.githubUrl)(options, apiHost)); } computeGithubBasePath(result) { // https://github.com/electron-userland/electron-builder/issues/1903#issuecomment-320881211 const host = this.options.host; return host && !["github.com", "api.github.com"].includes(host) ? `/api/v3${result}` : result; } } exports.BaseGitHubProvider = BaseGitHubProvider; class GitHubProvider extends BaseGitHubProvider { constructor(options, updater, runtimeOptions) { super(options, "github.com", runtimeOptions); this.options = options; this.updater = updater; } get channel() { const result = this.updater.channel || this.options.channel; return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result); } async getLatestVersion() { var _a, _b, _c, _d, _e; const cancellationToken = new builder_util_runtime_1.CancellationToken(); const feedXml = (await this.httpRequest((0, util_1.newUrlFromBase)(`${this.basePath}.atom`, this.baseUrl), { accept: "application/xml, application/atom+xml, text/xml, */*", }, cancellationToken)); const feed = (0, builder_util_runtime_1.parseXml)(feedXml); // noinspection TypeScriptValidateJSTypes let latestRelease = feed.element("entry", false, `No published versions on GitHub`); let tag = null; try { if (this.updater.allowPrerelease) { const currentChannel = ((_a = this.updater) === null || _a === void 0 ? void 0 : _a.channel) || ((_b = semver.prerelease(this.updater.currentVersion)) === null || _b === void 0 ? void 0 : _b[0]) || null; if (currentChannel === null) { // allowPrerelease=true with no explicit channel and stable current version: // pick the first entry from the Atom feed, which may be a prerelease // noinspection TypeScriptValidateJSTypes tag = hrefRegExp.exec(latestRelease.element("link").attribute("href"))[1]; } else { for (const element of feed.getElements("entry")) { // noinspection TypeScriptValidateJSTypes const hrefElement = hrefRegExp.exec(element.element("link").attribute("href")); // If this is null then something is wrong and skip this release if (hrefElement === null) { continue; } // This Release's Tag const hrefTag = hrefElement[1]; if (!semver.valid(hrefTag)) { continue; } //Get Channel from this release's tag const hrefChannel = ((_c = semver.prerelease(hrefTag)) === null || _c === void 0 ? void 0 : _c[0]) || null; const shouldFetchVersion = !currentChannel || ["alpha", "beta"].includes(currentChannel); const isCustomChannel = hrefChannel !== null && !["alpha", "beta"].includes(String(hrefChannel)); // Allow moving from alpha to beta but not down const channelMismatch = currentChannel === "beta" && hrefChannel === "alpha"; if (shouldFetchVersion && !isCustomChannel && !channelMismatch) { tag = hrefTag; latestRelease = element; break; } const isNextPreRelease = hrefChannel && hrefChannel === currentChannel; if (isNextPreRelease) { tag = hrefTag; latestRelease = element; break; } } } } else { tag = await this.getLatestTagName(cancellationToken); for (const element of feed.getElements("entry")) { // noinspection TypeScriptValidateJSTypes const hrefMatch = hrefRegExp.exec(element.element("link").attribute("href")); if (hrefMatch == null) { continue; } if (hrefMatch[1] === tag) { latestRelease = element; break; } } } } catch (e) { throw (0, builder_util_runtime_1.newError)(`Cannot parse releases feed: ${e.stack || e.message},\nXML:\n${feedXml}`, "ERR_UPDATER_INVALID_RELEASE_FEED"); } if (tag == null) { throw (0, builder_util_runtime_1.newError)(`No published versions on GitHub`, "ERR_UPDATER_NO_PUBLISHED_VERSIONS"); } let rawData; let channelFile = ""; let channelFileUrl = ""; const fetchData = async (channelName) => { channelFile = (0, util_1.getChannelFilename)(channelName); channelFileUrl = (0, util_1.newUrlFromBase)(this.getBaseDownloadPath(String(tag), channelFile), this.baseUrl); const requestOptions = this.createRequestOptions(channelFileUrl); try { return (await this.executor.request(requestOptions, cancellationToken)); } catch (e) { if (e instanceof builder_util_runtime_1.HttpError && e.statusCode === 404) { throw (0, builder_util_runtime_1.newError)(`Cannot find ${channelFile} in the latest release artifacts (${channelFileUrl}): ${e.stack || e.message}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"); } throw e; } }; try { let channel = this.channel; if (this.updater.allowPrerelease && ((_d = semver.prerelease(tag)) === null || _d === void 0 ? void 0 : _d[0])) { channel = this.getCustomChannelName(String((_e = semver.prerelease(tag)) === null || _e === void 0 ? void 0 : _e[0])); } rawData = await fetchData(channel); } catch (e) { if (this.updater.allowPrerelease) { // Allow fallback to `latest.yml` rawData = await fetchData(this.getDefaultChannelName()); } else { throw e; } } const result = (0, Provider_1.parseUpdateInfo)(rawData, channelFile, channelFileUrl); if (result.releaseName == null) { result.releaseName = latestRelease.elementValueOrEmpty("title"); } if (result.releaseNotes == null) { result.releaseNotes = computeReleaseNotes(this.updater.currentVersion, this.updater.fullChangelog, feed, latestRelease); } return { tag: tag, ...result, }; } async getLatestTagName(cancellationToken) { const options = this.options; // do not use API for GitHub to avoid limit, only for custom host or GitHub Enterprise const url = options.host == null || options.host === "github.com" ? (0, util_1.newUrlFromBase)(`${this.basePath}/latest`, this.baseUrl) : new url_1.URL(`${this.computeGithubBasePath(`/repos/${options.owner}/${options.repo}/releases`)}/latest`, this.baseApiUrl); try { const rawData = await this.httpRequest(url, { Accept: "application/json" }, cancellationToken); if (rawData == null) { return null; } const releaseInfo = JSON.parse(rawData); return releaseInfo.tag_name; } catch (e) { throw (0, builder_util_runtime_1.newError)(`Unable to find latest version on GitHub (${url}), please ensure a production release exists: ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"); } } get basePath() { return `/${this.options.owner}/${this.options.repo}/releases`; } resolveFiles(updateInfo) { // still replace space to - due to backward compatibility return (0, Provider_1.resolveFiles)(updateInfo, this.baseUrl, p => this.getBaseDownloadPath(updateInfo.tag, p.replace(/ /g, "-"))); } getBaseDownloadPath(tag, fileName) { return `${this.basePath}/download/${tag}/${fileName}`; } } exports.GitHubProvider = GitHubProvider; function getNoteValue(parent) { const result = parent.elementValueOrEmpty("content"); // GitHub reports empty notes as No content. return result === "No content." ? "" : result; } function computeReleaseNotes(currentVersion, isFullChangelog, feed, latestRelease) { if (!isFullChangelog) { return getNoteValue(latestRelease); } const releaseVersionRegExp = /\/tag\/v?([^/]+)$/; let latestVersion = undefined; try { latestVersion = releaseVersionRegExp.exec(latestRelease.element("link").attribute("href"))[1]; latestVersion = semver.valid(latestVersion) ? latestVersion : undefined; } catch { // If we cannot parse the latest release version, return null — notes cannot be determined } if (latestVersion == null) { return null; } const releaseNotes = []; for (const release of feed.getElements("entry")) { let versionRelease; try { const match = releaseVersionRegExp.exec(release.element("link").attribute("href")); if (!match) { continue; } versionRelease = match[1]; } catch { continue; } // skip non-semver tags (e.g. doc/website releases in monorepos) if (!semver.valid(versionRelease)) { continue; } const isGreaterThanCurrent = semver.gt(versionRelease, currentVersion.raw); const isLessOrEqualThanLatest = semver.lte(versionRelease, latestVersion); if (isGreaterThanCurrent && isLessOrEqualThanLatest) { releaseNotes.push({ version: versionRelease, note: getNoteValue(release), }); } } return releaseNotes.sort((a, b) => semver.rcompare(a.version, b.version)); } //# sourceMappingURL=GitHubProvider.js.map{"version":3,"file":"GitHubProvider.js","sourceRoot":"","sources":["../../src/providers/GitHubProvider.ts"],"names":[],"mappings":";;;AAqOA,kDA8CC;AAnRD,+DAAwJ;AACxJ,iCAAgC;AAChC,6BAAyB;AAGzB,kCAAwE;AACxE,yCAA4F;AAE5F,MA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CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAA;AAC3E,CAAC","sourcesContent":["import { CancellationToken, GithubOptions, githubUrl, HttpError, newError, parseXml, ReleaseNoteInfo, UpdateInfo, XElement } from \"builder-util-runtime\"\nimport * as semver from \"semver\"\nimport { URL } from \"url\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"../types\"\nimport { getChannelFilename, newBaseUrl, newUrlFromBase } from \"../util\"\nimport { parseUpdateInfo, Provider, ProviderRuntimeOptions, resolveFiles } from \"./Provider\"\n\nconst hrefRegExp = /\\/tag\\/(v?[^/]+)$/\n\ninterface GithubUpdateInfo extends UpdateInfo {\n tag: string\n}\nexport abstract class BaseGitHubProvider extends Provider {\n // so, we don't need to parse port (because node http doesn't support host as url does)\n protected readonly baseUrl: URL\n protected readonly baseApiUrl: URL\n\n protected constructor(\n protected readonly options: GithubOptions,\n defaultHost: string,\n runtimeOptions: ProviderRuntimeOptions\n ) {\n super({\n ...runtimeOptions,\n /* because GitHib uses S3 */\n isUseMultipleRangeRequest: false,\n })\n\n this.baseUrl = newBaseUrl(githubUrl(options, defaultHost))\n const apiHost = defaultHost === \"github.com\" ? \"api.github.com\" : defaultHost\n this.baseApiUrl = newBaseUrl(githubUrl(options, apiHost))\n }\n\n protected computeGithubBasePath(result: string): string {\n // https://github.com/electron-userland/electron-builder/issues/1903#issuecomment-320881211\n const host = this.options.host\n return host && ![\"github.com\", \"api.github.com\"].includes(host) ? `/api/v3${result}` : result\n }\n}\n\nexport class GitHubProvider extends BaseGitHubProvider {\n constructor(\n protected readonly options: GithubOptions,\n private readonly updater: AppUpdater,\n runtimeOptions: ProviderRuntimeOptions\n ) {\n super(options, \"github.com\", runtimeOptions)\n }\n\n private get channel(): string {\n const result = this.updater.channel || this.options.channel\n return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result)\n }\n\n async getLatestVersion(): Promise {\n const cancellationToken = new CancellationToken()\n\n const feedXml: string = (await this.httpRequest(\n newUrlFromBase(`${this.basePath}.atom`, this.baseUrl),\n {\n accept: \"application/xml, application/atom+xml, text/xml, */*\",\n },\n cancellationToken\n ))!\n\n const feed = parseXml(feedXml)\n // noinspection TypeScriptValidateJSTypes\n let latestRelease = feed.element(\"entry\", false, `No published versions on GitHub`)\n let tag: string | null = null\n try {\n if (this.updater.allowPrerelease) {\n const currentChannel = this.updater?.channel || (semver.prerelease(this.updater.currentVersion)?.[0] as string) || null\n\n if (currentChannel === null) {\n // allowPrerelease=true with no explicit channel and stable current version:\n // pick the first entry from the Atom feed, which may be a prerelease\n // noinspection TypeScriptValidateJSTypes\n tag = hrefRegExp.exec(latestRelease.element(\"link\").attribute(\"href\"))![1]\n } else {\n for (const element of feed.getElements(\"entry\")) {\n // noinspection TypeScriptValidateJSTypes\n const hrefElement = hrefRegExp.exec(element.element(\"link\").attribute(\"href\"))!\n\n // If this is null then something is wrong and skip this release\n if (hrefElement === null) {\n continue\n }\n\n // This Release's Tag\n const hrefTag = hrefElement[1]\n if (!semver.valid(hrefTag)) {\n continue\n }\n\n //Get Channel from this release's tag\n const hrefChannel = (semver.prerelease(hrefTag)?.[0] as string) || null\n\n const shouldFetchVersion = !currentChannel || [\"alpha\", \"beta\"].includes(currentChannel)\n const isCustomChannel = hrefChannel !== null && ![\"alpha\", \"beta\"].includes(String(hrefChannel))\n // Allow moving from alpha to beta but not down\n const channelMismatch = currentChannel === \"beta\" && hrefChannel === \"alpha\"\n\n if (shouldFetchVersion && !isCustomChannel && !channelMismatch) {\n tag = hrefTag\n latestRelease = element\n break\n }\n\n const isNextPreRelease = hrefChannel && hrefChannel === currentChannel\n if (isNextPreRelease) {\n tag = hrefTag\n latestRelease = element\n break\n }\n }\n }\n } else {\n tag = await this.getLatestTagName(cancellationToken)\n for (const element of feed.getElements(\"entry\")) {\n // noinspection TypeScriptValidateJSTypes\n const hrefMatch = hrefRegExp.exec(element.element(\"link\").attribute(\"href\"))\n if (hrefMatch == null) {\n continue\n }\n if (hrefMatch[1] === tag) {\n latestRelease = element\n break\n }\n }\n }\n } catch (e: any) {\n throw newError(`Cannot parse releases feed: ${e.stack || e.message},\\nXML:\\n${feedXml}`, \"ERR_UPDATER_INVALID_RELEASE_FEED\")\n }\n\n if (tag == null) {\n throw newError(`No published versions on GitHub`, \"ERR_UPDATER_NO_PUBLISHED_VERSIONS\")\n }\n\n let rawData: string\n let channelFile = \"\"\n let channelFileUrl: any = \"\"\n const fetchData = async (channelName: string) => {\n channelFile = getChannelFilename(channelName)\n channelFileUrl = newUrlFromBase(this.getBaseDownloadPath(String(tag), channelFile), this.baseUrl)\n const requestOptions = this.createRequestOptions(channelFileUrl)\n try {\n return (await this.executor.request(requestOptions, cancellationToken))!\n } catch (e: any) {\n if (e instanceof HttpError && e.statusCode === 404) {\n throw newError(`Cannot find ${channelFile} in the latest release artifacts (${channelFileUrl}): ${e.stack || e.message}`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n }\n throw e\n }\n }\n\n try {\n let channel = this.channel\n if (this.updater.allowPrerelease && semver.prerelease(tag)?.[0]) {\n channel = this.getCustomChannelName(String(semver.prerelease(tag)?.[0]))\n }\n rawData = await fetchData(channel)\n } catch (e: any) {\n if (this.updater.allowPrerelease) {\n // Allow fallback to `latest.yml`\n rawData = await fetchData(this.getDefaultChannelName())\n } else {\n throw e\n }\n }\n\n const result = parseUpdateInfo(rawData, channelFile, channelFileUrl)\n if (result.releaseName == null) {\n result.releaseName = latestRelease.elementValueOrEmpty(\"title\")\n }\n\n if (result.releaseNotes == null) {\n result.releaseNotes = computeReleaseNotes(this.updater.currentVersion, this.updater.fullChangelog, feed, latestRelease)\n }\n return {\n tag: tag,\n ...result,\n }\n }\n\n private async getLatestTagName(cancellationToken: CancellationToken): Promise {\n const options = this.options\n // do not use API for GitHub to avoid limit, only for custom host or GitHub Enterprise\n const url =\n options.host == null || options.host === \"github.com\"\n ? newUrlFromBase(`${this.basePath}/latest`, this.baseUrl)\n : new URL(`${this.computeGithubBasePath(`/repos/${options.owner}/${options.repo}/releases`)}/latest`, this.baseApiUrl)\n try {\n const rawData = await this.httpRequest(url, { Accept: \"application/json\" }, cancellationToken)\n if (rawData == null) {\n return null\n }\n\n const releaseInfo: GithubReleaseInfo = JSON.parse(rawData)\n return releaseInfo.tag_name\n } catch (e: any) {\n throw newError(`Unable to find latest version on GitHub (${url}), please ensure a production release exists: ${e.stack || e.message}`, \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\")\n }\n }\n\n private get basePath(): string {\n return `/${this.options.owner}/${this.options.repo}/releases`\n }\n\n resolveFiles(updateInfo: GithubUpdateInfo): Array {\n // still replace space to - due to backward compatibility\n return resolveFiles(updateInfo, this.baseUrl, p => this.getBaseDownloadPath(updateInfo.tag, p.replace(/ /g, \"-\")))\n }\n\n private getBaseDownloadPath(tag: string, fileName: string): string {\n return `${this.basePath}/download/${tag}/${fileName}`\n }\n}\n\ninterface GithubReleaseInfo {\n readonly tag_name: string\n}\n\nfunction getNoteValue(parent: XElement): string {\n const result = parent.elementValueOrEmpty(\"content\")\n // GitHub reports empty notes as No content.\n return result === \"No content.\" ? \"\" : result\n}\n\nexport function computeReleaseNotes(currentVersion: semver.SemVer, isFullChangelog: boolean, feed: XElement, latestRelease: XElement): string | Array | null {\n if (!isFullChangelog) {\n return getNoteValue(latestRelease)\n }\n\n const releaseVersionRegExp = /\\/tag\\/v?([^/]+)$/\n\n let latestVersion: string | undefined = undefined\n try {\n latestVersion = releaseVersionRegExp.exec(latestRelease.element(\"link\").attribute(\"href\"))![1]\n latestVersion = semver.valid(latestVersion) ? latestVersion : undefined\n } catch {\n // If we cannot parse the latest release version, return null — notes cannot be determined\n }\n\n if (latestVersion == null) {\n return null\n }\n\n const releaseNotes: Array = []\n for (const release of feed.getElements(\"entry\")) {\n let versionRelease: string\n try {\n const match = releaseVersionRegExp.exec(release.element(\"link\").attribute(\"href\"))\n if (!match) {\n continue\n }\n versionRelease = match[1]\n } catch {\n continue\n }\n // skip non-semver tags (e.g. doc/website releases in monorepos)\n if (!semver.valid(versionRelease)) {\n continue\n }\n\n const isGreaterThanCurrent = semver.gt(versionRelease, currentVersion.raw)\n const isLessOrEqualThanLatest = semver.lte(versionRelease, latestVersion)\n if (isGreaterThanCurrent && isLessOrEqualThanLatest) {\n releaseNotes.push({\n version: versionRelease,\n note: getNoteValue(release),\n })\n }\n }\n return releaseNotes.sort((a, b) => semver.rcompare(a.version, b.version))\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GitLabProvider = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const url_1 = require("url"); // @ts-ignore const escapeRegExp = require("lodash.escaperegexp"); const util_1 = require("../util"); const Provider_1 = require("./Provider"); class GitLabProvider extends Provider_1.Provider { /** * Normalizes filenames by replacing spaces and underscores with dashes. * * This is a workaround to handle filename formatting differences between tools: * - electron-builder formats filenames like "test file.txt" as "test-file.txt" * - GitLab may provide asset URLs using underscores, such as "test_file.txt" * * Because of this mismatch, we can't reliably extract the correct filename from * the asset path without normalization. This function ensures consistent matching * across different filename formats by converting all spaces and underscores to dashes. * * @param filename The filename to normalize * @returns The normalized filename with spaces and underscores replaced by dashes */ normalizeFilename(filename) { return filename.replace(/ |_/g, "-"); } constructor(options, updater, runtimeOptions) { super({ ...runtimeOptions, // GitLab might not support multiple range requests efficiently isUseMultipleRangeRequest: false, }); this.options = options; this.updater = updater; // Cache the latest version info to avoid unnecessary HTTP requests this.cachedLatestVersion = null; const defaultHost = "gitlab.com"; const host = options.host || defaultHost; this.baseApiUrl = (0, util_1.newBaseUrl)(`https://${host}/api/v4`); } get channel() { const result = this.updater.channel || this.options.channel; return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result); } async getLatestVersion() { const cancellationToken = new builder_util_runtime_1.CancellationToken(); // Get latest release from GitLab API using the permalink/latest endpoint const latestReleaseUrl = (0, util_1.newUrlFromBase)(`projects/${this.options.projectId}/releases/permalink/latest`, this.baseApiUrl); const header = { Accept: "application/json", ...this.setAuthHeaderForToken(this.options.token || null) }; let releaseResponse; try { releaseResponse = await this.httpRequest(latestReleaseUrl, header, cancellationToken); } catch (e) { throw (0, builder_util_runtime_1.newError)(`Unable to find latest release on GitLab (${latestReleaseUrl}): ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"); } if (!releaseResponse) { throw (0, builder_util_runtime_1.newError)("No published releases on GitLab", "ERR_UPDATER_NO_PUBLISHED_VERSIONS"); } let latestRelease; try { latestRelease = JSON.parse(releaseResponse); } catch (e) { throw (0, builder_util_runtime_1.newError)(`Unable to parse latest release response from GitLab (${latestReleaseUrl}): response was not valid JSON: ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"); } if (latestRelease.upcoming_release) { throw (0, builder_util_runtime_1.newError)("Latest GitLab release is scheduled but not yet published", "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"); } const tag = latestRelease.tag_name; // Look for channel file in release assets let rawData = null; let channelFile = ""; let channelFileUrl = null; const fetchChannelData = async (channelName) => { channelFile = (0, util_1.getChannelFilename)(channelName); // Find the channel file in GitLab release assets const channelAsset = latestRelease.assets.links.find(asset => asset.name === channelFile); if (!channelAsset) { throw (0, builder_util_runtime_1.newError)(`Cannot find ${channelFile} in the latest release assets`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"); } channelFileUrl = new url_1.URL(channelAsset.direct_asset_url); const authHeaders = this.setAuthHeaderForToken(this.options.token || null); const headers = Object.keys(authHeaders).length ? authHeaders : undefined; try { const result = await this.httpRequest(channelFileUrl, headers, cancellationToken); if (!result) { throw (0, builder_util_runtime_1.newError)(`Empty response from ${channelFileUrl}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"); } return result; } catch (e) { if (e instanceof builder_util_runtime_1.HttpError && e.statusCode === 404) { throw (0, builder_util_runtime_1.newError)(`Cannot find ${channelFile} in the latest release artifacts (${channelFileUrl}): ${e.stack || e.message}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"); } throw e; } }; try { rawData = await fetchChannelData(this.channel); } catch (e) { // If custom channel fails, try default channel as fallback if (this.channel !== this.getDefaultChannelName()) { rawData = await fetchChannelData(this.getDefaultChannelName()); } else { throw e; } } if (!rawData) { throw (0, builder_util_runtime_1.newError)(`Unable to parse channel data from ${channelFile}`, "ERR_UPDATER_INVALID_UPDATE_INFO"); } const result = (0, Provider_1.parseUpdateInfo)(rawData, channelFile, channelFileUrl); // Set release name from GitLab if not present if (result.releaseName == null) { result.releaseName = latestRelease.name; } // Set release notes from GitLab description if not present if (result.releaseNotes == null) { result.releaseNotes = latestRelease.description || null; } const gitlabUpdateInfo = { tag: tag, assets: this.convertAssetsToMap(latestRelease.assets), ...result, }; // Cache the latest version info this.cachedLatestVersion = gitlabUpdateInfo; return gitlabUpdateInfo; } /** * Utility function to convert GitlabReleaseAsset to Map * Maps asset names to their download URLs */ convertAssetsToMap(assets) { const assetsMap = new Map(); for (const asset of assets.links) { assetsMap.set(this.normalizeFilename(asset.name), asset.direct_asset_url); } return assetsMap; } /** * Find blockmap file URL in assets map for a specific filename */ findBlockMapInAssets(assets, filename) { const possibleBlockMapNames = [`${filename}.blockmap`, `${this.normalizeFilename(filename)}.blockmap`]; for (const blockMapName of possibleBlockMapNames) { const assetUrl = assets.get(blockMapName); if (assetUrl) { return new url_1.URL(assetUrl); } } return null; } async fetchReleaseInfoByVersion(version) { const cancellationToken = new builder_util_runtime_1.CancellationToken(); // Try v-prefixed version first, then fallback to plain version const possibleReleaseIds = [`v${version}`, version]; for (const releaseId of possibleReleaseIds) { const releaseUrl = (0, util_1.newUrlFromBase)(`projects/${this.options.projectId}/releases/${encodeURIComponent(releaseId)}`, this.baseApiUrl); try { const header = { Accept: "application/json", ...this.setAuthHeaderForToken(this.options.token || null) }; const releaseResponse = await this.httpRequest(releaseUrl, header, cancellationToken); if (releaseResponse) { const release = JSON.parse(releaseResponse); return release; } } catch (e) { // If it's a 404 error, try the next release ID format if (e instanceof builder_util_runtime_1.HttpError && e.statusCode === 404) { continue; } // For other errors, throw immediately throw (0, builder_util_runtime_1.newError)(`Unable to find release ${releaseId} on GitLab (${releaseUrl}): ${e.stack || e.message}`, "ERR_UPDATER_RELEASE_NOT_FOUND"); } } // If we get here, none of the release ID formats worked throw (0, builder_util_runtime_1.newError)(`Unable to find release with version ${version} (tried: ${possibleReleaseIds.join(", ")}) on GitLab`, "ERR_UPDATER_RELEASE_NOT_FOUND"); } setAuthHeaderForToken(token) { const headers = {}; if (token != null) { // If the token starts with "Bearer", it is an OAuth application secret // Note that the original gitlab token would not start with "Bearer" // it might start with "gloas-", if so user needs to add "Bearer " prefix to the token if (token.startsWith("Bearer")) { headers.authorization = token; } else { headers["PRIVATE-TOKEN"] = token; } } return headers; } /** * Get version info for blockmap files, using cache when possible */ async getVersionInfoForBlockMap(version) { // Check if we can use cached version info if (this.cachedLatestVersion && this.cachedLatestVersion.version === version) { return this.cachedLatestVersion.assets; } // Fetch version info if not cached or version doesn't match const versionInfo = await this.fetchReleaseInfoByVersion(version); if (versionInfo && versionInfo.assets) { return this.convertAssetsToMap(versionInfo.assets); } return null; } /** * Find blockmap URLs from version assets */ async findBlockMapUrlsFromAssets(oldVersion, newVersion, baseFilename) { let newBlockMapUrl = null; let oldBlockMapUrl = null; // Get new version assets const newVersionAssets = await this.getVersionInfoForBlockMap(newVersion); if (newVersionAssets) { newBlockMapUrl = this.findBlockMapInAssets(newVersionAssets, baseFilename); } // Get old version assets const oldVersionAssets = await this.getVersionInfoForBlockMap(oldVersion); if (oldVersionAssets) { const oldFilename = baseFilename.replace(new RegExp(escapeRegExp(newVersion), "g"), oldVersion); oldBlockMapUrl = this.findBlockMapInAssets(oldVersionAssets, oldFilename); } return [oldBlockMapUrl, newBlockMapUrl]; } async getBlockMapFiles(baseUrl, oldVersion, newVersion, oldBlockMapFileBaseUrl = null) { // If is `project_upload`, find blockmap files from corresponding gitLab assets // Because each asset has an unique path that includes an identified hash code, // e.g. https://gitlab.com/-/project/71361100/uploads/051f27a925eaf679f2ad688105362acc/latest.yml if (this.options.uploadTarget === "project_upload") { // Get the base filename from the URL to find corresponding blockmap files const baseFilename = baseUrl.pathname.split("/").pop() || ""; // Try to find blockmap files in GitLab assets const [oldBlockMapUrl, newBlockMapUrl] = await this.findBlockMapUrlsFromAssets(oldVersion, newVersion, baseFilename); if (!newBlockMapUrl) { throw (0, builder_util_runtime_1.newError)(`Cannot find blockmap file for ${newVersion} in GitLab assets`, "ERR_UPDATER_BLOCKMAP_FILE_NOT_FOUND"); } if (!oldBlockMapUrl) { throw (0, builder_util_runtime_1.newError)(`Cannot find blockmap file for ${oldVersion} in GitLab assets`, "ERR_UPDATER_BLOCKMAP_FILE_NOT_FOUND"); } return [oldBlockMapUrl, newBlockMapUrl]; } else { return super.getBlockMapFiles(baseUrl, oldVersion, newVersion, oldBlockMapFileBaseUrl); } } resolveFiles(updateInfo) { return (0, Provider_1.getFileList)(updateInfo).map((fileInfo) => { // Try both original and normalized filename formats const possibleNames = [ fileInfo.url, // Original filename this.normalizeFilename(fileInfo.url), // Normalized filename (spaces/underscores → dashes) ]; const matchingAssetName = possibleNames.find(name => updateInfo.assets.has(name)); const assetUrl = matchingAssetName ? updateInfo.assets.get(matchingAssetName) : undefined; if (!assetUrl) { throw (0, builder_util_runtime_1.newError)(`Cannot find asset "${fileInfo.url}" in GitLab release assets. Available assets: ${Array.from(updateInfo.assets.keys()).join(", ")}`, "ERR_UPDATER_ASSET_NOT_FOUND"); } return { url: new url_1.URL(assetUrl), info: fileInfo, }; }); } toString() { return `GitLab (projectId: ${this.options.projectId}, channel: ${this.channel})`; } } exports.GitLabProvider = GitLabProvider; //# sourceMappingURL=GitLabProvider.js.map{"version":3,"file":"GitLabProvider.js","sourceRoot":"","sources":["../../src/providers/GitLabProvider.ts"],"names":[],"mappings":";;;AAAA,+DAA+J;AAC/J,6B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AAS,CAAA;YAEzF,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,MAAM,IAAA,+BAAQ,EACZ,sBAAsB,QAAQ,CAAC,GAAG,iDAAiD,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EACpI,6BAA6B,CAC9B,CAAA;YACH,CAAC;YAED,OAAO;gBACL,GAAG,EAAE,IAAI,SAAG,CAAC,QAAQ,CAAC;gBACtB,IAAI,EAAE,QAAQ;aACf,CAAA;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,QAAQ;QACN,OAAO,sBAAsB,IAAI,CAAC,OAAO,CAAC,SAAS,cAAc,IAAI,CAAC,OAAO,GAAG,CAAA;IAClF,CAAC;CACF;AAhUD,wCAgUC","sourcesContent":["import { CancellationToken, GitlabOptions, HttpError, newError, UpdateFileInfo, UpdateInfo, GitlabReleaseInfo, GitlabReleaseAsset } from \"builder-util-runtime\"\nimport { URL } from \"url\"\n// @ts-ignore\nimport * as escapeRegExp from \"lodash.escaperegexp\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"../types\"\nimport { getChannelFilename, newBaseUrl, newUrlFromBase } from \"../util\"\nimport { getFileList, parseUpdateInfo, Provider, ProviderRuntimeOptions } from \"./Provider\"\n\ninterface GitlabUpdateInfo extends UpdateInfo {\n tag: string\n assets: Map // filename -> download URL mapping\n}\n\nexport class GitLabProvider extends Provider {\n private readonly baseApiUrl: URL\n // Cache the latest version info to avoid unnecessary HTTP requests\n private cachedLatestVersion: GitlabUpdateInfo | null = null\n\n /**\n * Normalizes filenames by replacing spaces and underscores with dashes.\n *\n * This is a workaround to handle filename formatting differences between tools:\n * - electron-builder formats filenames like \"test file.txt\" as \"test-file.txt\"\n * - GitLab may provide asset URLs using underscores, such as \"test_file.txt\"\n *\n * Because of this mismatch, we can't reliably extract the correct filename from\n * the asset path without normalization. This function ensures consistent matching\n * across different filename formats by converting all spaces and underscores to dashes.\n *\n * @param filename The filename to normalize\n * @returns The normalized filename with spaces and underscores replaced by dashes\n */\n private normalizeFilename(filename: string): string {\n return filename.replace(/ |_/g, \"-\")\n }\n\n constructor(\n private readonly options: GitlabOptions,\n private readonly updater: AppUpdater,\n runtimeOptions: ProviderRuntimeOptions\n ) {\n super({\n ...runtimeOptions,\n // GitLab might not support multiple range requests efficiently\n isUseMultipleRangeRequest: false,\n })\n\n const defaultHost = \"gitlab.com\"\n const host = options.host || defaultHost\n\n this.baseApiUrl = newBaseUrl(`https://${host}/api/v4`)\n }\n\n private get channel(): string {\n const result = this.updater.channel || this.options.channel\n return result == null ? this.getDefaultChannelName() : this.getCustomChannelName(result)\n }\n\n async getLatestVersion(): Promise {\n const cancellationToken = new CancellationToken()\n\n // Get latest release from GitLab API using the permalink/latest endpoint\n const latestReleaseUrl = newUrlFromBase(`projects/${this.options.projectId}/releases/permalink/latest`, this.baseApiUrl)\n\n const header = { Accept: \"application/json\", ...this.setAuthHeaderForToken(this.options.token || null) }\n let releaseResponse: string | null\n try {\n releaseResponse = await this.httpRequest(latestReleaseUrl, header, cancellationToken)\n } catch (e: any) {\n throw newError(`Unable to find latest release on GitLab (${latestReleaseUrl}): ${e.stack || e.message}`, \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\")\n }\n\n if (!releaseResponse) {\n throw newError(\"No published releases on GitLab\", \"ERR_UPDATER_NO_PUBLISHED_VERSIONS\")\n }\n\n let latestRelease: GitlabReleaseInfo\n try {\n latestRelease = JSON.parse(releaseResponse)\n } catch (e: any) {\n throw newError(\n `Unable to parse latest release response from GitLab (${latestReleaseUrl}): response was not valid JSON: ${e.stack || e.message}`,\n \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\"\n )\n }\n\n if (latestRelease.upcoming_release) {\n throw newError(\"Latest GitLab release is scheduled but not yet published\", \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\")\n }\n\n const tag = latestRelease.tag_name\n\n // Look for channel file in release assets\n let rawData: string | null = null\n let channelFile = \"\"\n let channelFileUrl: URL | null = null\n\n const fetchChannelData = async (channelName: string): Promise => {\n channelFile = getChannelFilename(channelName)\n\n // Find the channel file in GitLab release assets\n const channelAsset = latestRelease.assets.links.find(asset => asset.name === channelFile)\n\n if (!channelAsset) {\n throw newError(`Cannot find ${channelFile} in the latest release assets`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n }\n\n channelFileUrl = new URL(channelAsset.direct_asset_url)\n const authHeaders = this.setAuthHeaderForToken(this.options.token || null)\n const headers = Object.keys(authHeaders).length ? authHeaders : undefined\n\n try {\n const result = await this.httpRequest(channelFileUrl, headers, cancellationToken)\n if (!result) {\n throw newError(`Empty response from ${channelFileUrl}`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n }\n return result\n } catch (e: any) {\n if (e instanceof HttpError && e.statusCode === 404) {\n throw newError(`Cannot find ${channelFile} in the latest release artifacts (${channelFileUrl}): ${e.stack || e.message}`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n }\n throw e\n }\n }\n\n try {\n rawData = await fetchChannelData(this.channel)\n } catch (e: any) {\n // If custom channel fails, try default channel as fallback\n if (this.channel !== this.getDefaultChannelName()) {\n rawData = await fetchChannelData(this.getDefaultChannelName())\n } else {\n throw e\n }\n }\n\n if (!rawData) {\n throw newError(`Unable to parse channel data from ${channelFile}`, \"ERR_UPDATER_INVALID_UPDATE_INFO\")\n }\n\n const result = parseUpdateInfo(rawData, channelFile, channelFileUrl!)\n\n // Set release name from GitLab if not present\n if (result.releaseName == null) {\n result.releaseName = latestRelease.name\n }\n\n // Set release notes from GitLab description if not present\n if (result.releaseNotes == null) {\n result.releaseNotes = latestRelease.description || null\n }\n\n const gitlabUpdateInfo = {\n tag: tag,\n assets: this.convertAssetsToMap(latestRelease.assets),\n ...result,\n }\n\n // Cache the latest version info\n this.cachedLatestVersion = gitlabUpdateInfo\n\n return gitlabUpdateInfo\n }\n\n /**\n * Utility function to convert GitlabReleaseAsset to Map\n * Maps asset names to their download URLs\n */\n private convertAssetsToMap(assets: GitlabReleaseAsset): Map {\n const assetsMap = new Map()\n for (const asset of assets.links) {\n assetsMap.set(this.normalizeFilename(asset.name), asset.direct_asset_url)\n }\n return assetsMap\n }\n\n /**\n * Find blockmap file URL in assets map for a specific filename\n */\n private findBlockMapInAssets(assets: Map, filename: string): URL | null {\n const possibleBlockMapNames = [`${filename}.blockmap`, `${this.normalizeFilename(filename)}.blockmap`]\n\n for (const blockMapName of possibleBlockMapNames) {\n const assetUrl = assets.get(blockMapName)\n if (assetUrl) {\n return new URL(assetUrl)\n }\n }\n return null\n }\n\n private async fetchReleaseInfoByVersion(version: string): Promise {\n const cancellationToken = new CancellationToken()\n\n // Try v-prefixed version first, then fallback to plain version\n const possibleReleaseIds = [`v${version}`, version]\n\n for (const releaseId of possibleReleaseIds) {\n const releaseUrl = newUrlFromBase(`projects/${this.options.projectId}/releases/${encodeURIComponent(releaseId)}`, this.baseApiUrl)\n\n try {\n const header = { Accept: \"application/json\", ...this.setAuthHeaderForToken(this.options.token || null) }\n const releaseResponse = await this.httpRequest(releaseUrl, header, cancellationToken)\n\n if (releaseResponse) {\n const release: GitlabReleaseInfo = JSON.parse(releaseResponse)\n return release\n }\n } catch (e: any) {\n // If it's a 404 error, try the next release ID format\n if (e instanceof HttpError && e.statusCode === 404) {\n continue\n }\n // For other errors, throw immediately\n throw newError(`Unable to find release ${releaseId} on GitLab (${releaseUrl}): ${e.stack || e.message}`, \"ERR_UPDATER_RELEASE_NOT_FOUND\")\n }\n }\n\n // If we get here, none of the release ID formats worked\n throw newError(`Unable to find release with version ${version} (tried: ${possibleReleaseIds.join(\", \")}) on GitLab`, \"ERR_UPDATER_RELEASE_NOT_FOUND\")\n }\n\n private setAuthHeaderForToken(token: string | null): { [key: string]: string } {\n const headers: { [key: string]: string } = {}\n\n if (token != null) {\n // If the token starts with \"Bearer\", it is an OAuth application secret\n // Note that the original gitlab token would not start with \"Bearer\"\n // it might start with \"gloas-\", if so user needs to add \"Bearer \" prefix to the token\n if (token.startsWith(\"Bearer\")) {\n headers.authorization = token\n } else {\n headers[\"PRIVATE-TOKEN\"] = token\n }\n }\n\n return headers\n }\n\n /**\n * Get version info for blockmap files, using cache when possible\n */\n private async getVersionInfoForBlockMap(version: string): Promise | null> {\n // Check if we can use cached version info\n if (this.cachedLatestVersion && this.cachedLatestVersion.version === version) {\n return this.cachedLatestVersion.assets\n }\n\n // Fetch version info if not cached or version doesn't match\n const versionInfo = await this.fetchReleaseInfoByVersion(version)\n if (versionInfo && versionInfo.assets) {\n return this.convertAssetsToMap(versionInfo.assets)\n }\n\n return null\n }\n\n /**\n * Find blockmap URLs from version assets\n */\n private async findBlockMapUrlsFromAssets(oldVersion: string, newVersion: string, baseFilename: string): Promise<[URL | null, URL | null]> {\n let newBlockMapUrl: URL | null = null\n let oldBlockMapUrl: URL | null = null\n\n // Get new version assets\n const newVersionAssets = await this.getVersionInfoForBlockMap(newVersion)\n if (newVersionAssets) {\n newBlockMapUrl = this.findBlockMapInAssets(newVersionAssets, baseFilename)\n }\n\n // Get old version assets\n const oldVersionAssets = await this.getVersionInfoForBlockMap(oldVersion)\n if (oldVersionAssets) {\n const oldFilename = baseFilename.replace(new RegExp(escapeRegExp(newVersion), \"g\"), oldVersion)\n oldBlockMapUrl = this.findBlockMapInAssets(oldVersionAssets, oldFilename)\n }\n\n return [oldBlockMapUrl, newBlockMapUrl]\n }\n\n async getBlockMapFiles(baseUrl: URL, oldVersion: string, newVersion: string, oldBlockMapFileBaseUrl: string | null = null): Promise {\n // If is `project_upload`, find blockmap files from corresponding gitLab assets\n // Because each asset has an unique path that includes an identified hash code,\n // e.g. https://gitlab.com/-/project/71361100/uploads/051f27a925eaf679f2ad688105362acc/latest.yml\n if (this.options.uploadTarget === \"project_upload\") {\n // Get the base filename from the URL to find corresponding blockmap files\n const baseFilename = baseUrl.pathname.split(\"/\").pop() || \"\"\n\n // Try to find blockmap files in GitLab assets\n const [oldBlockMapUrl, newBlockMapUrl] = await this.findBlockMapUrlsFromAssets(oldVersion, newVersion, baseFilename)\n\n if (!newBlockMapUrl) {\n throw newError(`Cannot find blockmap file for ${newVersion} in GitLab assets`, \"ERR_UPDATER_BLOCKMAP_FILE_NOT_FOUND\")\n }\n\n if (!oldBlockMapUrl) {\n throw newError(`Cannot find blockmap file for ${oldVersion} in GitLab assets`, \"ERR_UPDATER_BLOCKMAP_FILE_NOT_FOUND\")\n }\n\n return [oldBlockMapUrl, newBlockMapUrl]\n } else {\n return super.getBlockMapFiles(baseUrl, oldVersion, newVersion, oldBlockMapFileBaseUrl)\n }\n }\n\n resolveFiles(updateInfo: GitlabUpdateInfo): Array {\n return getFileList(updateInfo).map((fileInfo: UpdateFileInfo) => {\n // Try both original and normalized filename formats\n const possibleNames = [\n fileInfo.url, // Original filename\n this.normalizeFilename(fileInfo.url), // Normalized filename (spaces/underscores → dashes)\n ]\n\n const matchingAssetName = possibleNames.find(name => updateInfo.assets.has(name))\n const assetUrl = matchingAssetName ? updateInfo.assets.get(matchingAssetName) : undefined\n\n if (!assetUrl) {\n throw newError(\n `Cannot find asset \"${fileInfo.url}\" in GitLab release assets. Available assets: ${Array.from(updateInfo.assets.keys()).join(\", \")}`,\n \"ERR_UPDATER_ASSET_NOT_FOUND\"\n )\n }\n\n return {\n url: new URL(assetUrl),\n info: fileInfo,\n }\n })\n }\n\n toString(): string {\n return `GitLab (projectId: ${this.options.projectId}, channel: ${this.channel})`\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.KeygenProvider = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const util_1 = require("../util"); const Provider_1 = require("./Provider"); class KeygenProvider extends Provider_1.Provider { constructor(configuration, updater, runtimeOptions) { super({ ...runtimeOptions, isUseMultipleRangeRequest: false, }); this.configuration = configuration; this.updater = updater; this.defaultHostname = "api.keygen.sh"; const host = this.configuration.host || this.defaultHostname; this.baseUrl = (0, util_1.newBaseUrl)(`https://${host}/v1/accounts/${this.configuration.account}/artifacts?product=${this.configuration.product}`); } get channel() { return this.updater.channel || this.configuration.channel || "stable"; } async getLatestVersion() { const cancellationToken = new builder_util_runtime_1.CancellationToken(); const channelFile = (0, util_1.getChannelFilename)(this.getCustomChannelName(this.channel)); const channelUrl = (0, util_1.newUrlFromBase)(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery); try { const updateInfo = await this.httpRequest(channelUrl, { Accept: "application/vnd.api+json", "Keygen-Version": "1.1", }, cancellationToken); return (0, Provider_1.parseUpdateInfo)(updateInfo, channelFile, channelUrl); } catch (e) { throw (0, builder_util_runtime_1.newError)(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"); } } resolveFiles(updateInfo) { return (0, Provider_1.resolveFiles)(updateInfo, this.baseUrl); } toString() { const { account, product, platform } = this.configuration; return `Keygen (account: ${account}, product: ${product}, platform: ${platform}, channel: ${this.channel})`; } } exports.KeygenProvider = KeygenProvider; //# sourceMappingURL=KeygenProvider.js.map{"version":3,"file":"KeygenProvider.js","sourceRoot":"","sources":["../../src/providers/KeygenProvider.ts"],"names":[],"mappings":";;;AAAA,+DAA6F;AAG7F,kCAAwE;AACxE,yCAA4F;AAE5F,MAAa,cAAe,SAAQ,mBAAoB;IAItD,YACmB,aAA4B,EAC5B,OAAmB,EACpC,cAAsC;QAEtC,KAAK,CAAC;YACJ,GAAG,cAAc;YACjB,yBAAyB,EAAE,KAAK;SACjC,CAAC,CAAA;QAPe,kBAAa,GAAb,aAAa,CAAe;QAC5B,YAAO,GAAP,OAAO,CAAY;QALrB,oBAAe,GAAG,eAAe,CAAA;QAYhD,MAAM,IAAI,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,IAAI,IAAI,CAAC,eAAe,CAAA;QAC5D,IAAI,CAAC,OAAO,GAAG,IAAA,iBAAU,EAAC,WAAW,IAAI,gBAAgB,IA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O,eAAe,QAAQ,cAAc,IAAI,CAAC,OAAO,GAAG,CAAA;IAC7G,CAAC;CACF;AAhDD,wCAgDC","sourcesContent":["import { CancellationToken, KeygenOptions, newError, UpdateInfo } from \"builder-util-runtime\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"../types\"\nimport { getChannelFilename, newBaseUrl, newUrlFromBase } from \"../util\"\nimport { parseUpdateInfo, Provider, ProviderRuntimeOptions, resolveFiles } from \"./Provider\"\n\nexport class KeygenProvider extends Provider {\n private readonly defaultHostname = \"api.keygen.sh\"\n private readonly baseUrl: URL\n\n constructor(\n private readonly configuration: KeygenOptions,\n private readonly updater: AppUpdater,\n runtimeOptions: ProviderRuntimeOptions\n ) {\n super({\n ...runtimeOptions,\n isUseMultipleRangeRequest: false,\n })\n const host = this.configuration.host || this.defaultHostname\n this.baseUrl = newBaseUrl(`https://${host}/v1/accounts/${this.configuration.account}/artifacts?product=${this.configuration.product}`)\n }\n\n private get channel(): string {\n return this.updater.channel || this.configuration.channel || \"stable\"\n }\n\n async getLatestVersion(): Promise {\n const cancellationToken = new CancellationToken()\n const channelFile = getChannelFilename(this.getCustomChannelName(this.channel))\n const channelUrl = newUrlFromBase(channelFile, this.baseUrl, this.updater.isAddNoCacheQuery)\n try {\n const updateInfo = await this.httpRequest(\n channelUrl,\n {\n Accept: \"application/vnd.api+json\",\n \"Keygen-Version\": \"1.1\",\n },\n cancellationToken\n )\n return parseUpdateInfo(updateInfo, channelFile, channelUrl)\n } catch (e: any) {\n throw newError(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack || e.message}`, \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\")\n }\n }\n\n resolveFiles(updateInfo: UpdateInfo): Array {\n return resolveFiles(updateInfo, this.baseUrl)\n }\n\n toString() {\n const { account, product, platform } = this.configuration\n return `Keygen (account: ${account}, product: ${product}, platform: ${platform}, channel: ${this.channel})`\n }\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrivateGitHubProvider = void 0; const builder_util_runtime_1 = require("builder-util-runtime"); const js_yaml_1 = require("js-yaml"); const path = require("path"); const url_1 = require("url"); const util_1 = require("../util"); const GitHubProvider_1 = require("./GitHubProvider"); const Provider_1 = require("./Provider"); class PrivateGitHubProvider extends GitHubProvider_1.BaseGitHubProvider { constructor(options, updater, token, runtimeOptions) { super(options, "api.github.com", runtimeOptions); this.updater = updater; this.token = token; } createRequestOptions(url, headers) { const result = super.createRequestOptions(url, headers); result.redirect = "manual"; return result; } async getLatestVersion() { const cancellationToken = new builder_util_runtime_1.CancellationToken(); const channelFile = (0, util_1.getChannelFilename)(this.getDefaultChannelName()); const releaseInfo = await this.getLatestVersionInfo(cancellationToken); const asset = releaseInfo.assets.find(it => it.name === channelFile); if (asset == null) { // html_url must be always, but just to be sure throw (0, builder_util_runtime_1.newError)(`Cannot find ${channelFile} in the release ${releaseInfo.html_url || releaseInfo.name}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"); } const url = new url_1.URL(asset.url); let result; try { result = (0, js_yaml_1.load)((await this.httpRequest(url, this.configureHeaders("application/octet-stream"), cancellationToken))); } catch (e) { if (e instanceof builder_util_runtime_1.HttpError && e.statusCode === 404) { throw (0, builder_util_runtime_1.newError)(`Cannot find ${channelFile} in the latest release artifacts (${url}): ${e.stack || e.message}`, "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"); } throw e; } ; result.assets = releaseInfo.assets; return result; } get fileExtraDownloadHeaders() { return this.configureHeaders("application/octet-stream"); } configureHeaders(accept) { return { accept, authorization: `token ${this.token}`, }; } async getLatestVersionInfo(cancellationToken) { const allowPrerelease = this.updater.allowPrerelease; let basePath = this.basePath; if (!allowPrerelease) { basePath = `${basePath}/latest`; } const url = (0, util_1.newUrlFromBase)(basePath, this.baseUrl); try { const version = JSON.parse((await this.httpRequest(url, this.configureHeaders("application/vnd.github.v3+json"), cancellationToken))); // only `latest` can return a single ReleaseInfo. Otherwise, a list of ReleaseInfo is returned and we need to find the latest one ourselves if (allowPrerelease) { const candidates = version.filter(it => !it.draft); return candidates.find(it => it.prerelease) || candidates[0]; } else { return version; } } catch (e) { throw (0, builder_util_runtime_1.newError)(`Unable to find latest version on GitHub (${url}), please ensure a production release exists: ${e.stack || e.message}`, "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"); } } get basePath() { return this.computeGithubBasePath(`/repos/${this.options.owner}/${this.options.repo}/releases`); } resolveFiles(updateInfo) { return (0, Provider_1.getFileList)(updateInfo).map(it => { const name = path.posix.basename(it.url).replace(/ /g, "-"); const asset = updateInfo.assets.find(it => it != null && it.name === name); if (asset == null) { throw (0, builder_util_runtime_1.newError)(`Cannot find asset "${name}" in: ${JSON.stringify(updateInfo.assets, null, 2)}`, "ERR_UPDATER_ASSET_NOT_FOUND"); } return { url: new url_1.URL(asset.url), info: it, }; }); } } exports.PrivateGitHubProvider = PrivateGitHubProvider; //# sourceMappingURL=PrivateGitHubProvider.js.map{"version":3,"file":"PrivateGitHubProvider.js","sourceRoot":"","sources":["../../src/providers/PrivateGitHubProvider.ts"],"names":[],"mappings":";;;AAAA,+DAAwG;AAExG,qCAA8B;AAC9B,6BAA4B;AAE5B,6BAAyB;AACzB,kCAA4D;AAC5D,qDAAqD;AAErD,yCAAgE;AAMhE,MAAa,qBAAsB,SAAQ,mCAA2C;IACpF,YACE,OAAsB,EACL,OAAmB,EACnB,KAAa,EAC9B,cAAsC;QAEtC,KAAK,CAAC,OAAO,EAAE,gBAAgB,EAAE,cAAc,CAAC,CAAA;QAJ/B,YAAO,GAAP,OAAO,CAAY;QACnB,UAAK,GAAL,KAAK,CAAQ;IAIhC,CAAC;IAES,oBAAoB,CAAC,GAAQ,EAAE,OAAoC;QAC3E,MAAM,MAAM,GAAG,KAAK,CAAC,oBAAoB,CAAC,GAAG,EAAE,OAAO,CAAC,CACtD;QAAC,MAAc,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACpC,OAAO,MAAM,CAAA;IACf,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C,OAAO,EAAE,EAAE,sCAAsC,CAAC,CAAA;QAChL,CAAC;IACH,CAAC;IAED,IAAY,QAAQ;QAClB,OAAO,IAAI,CAAC,qBAAqB,CAAC,UAAU,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,WAAW,CAAC,CAAA;IACjG,CAAC;IAED,YAAY,CAAC,UAAmC;QAC9C,OAAO,IAAA,sBAAW,EAAC,UAAU,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;YACtC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC3D,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,IAAI,KAAK,IAAI,CAAC,CAAA;YAC1E,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;gBAClB,MAAM,IAAA,+BAAQ,EAAC,sBAAsB,IAAI,SAAS,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,6BAA6B,CAAC,CAAA;YAChI,CAAC;YAED,OAAO;gBACL,GAAG,EAAE,IAAI,SAAG,CAAC,KAAK,CAAC,GAAG,CAAC;gBACvB,IAAI,EAAE,EAAE;aACT,CAAA;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA7FD,sDA6FC","sourcesContent":["import { CancellationToken, GithubOptions, HttpError, newError, UpdateInfo } from \"builder-util-runtime\"\nimport { OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { load } from \"js-yaml\"\nimport * as path from \"path\"\nimport { AppUpdater } from \"../AppUpdater\"\nimport { URL } from \"url\"\nimport { getChannelFilename, newUrlFromBase } from \"../util\"\nimport { BaseGitHubProvider } from \"./GitHubProvider\"\nimport { ResolvedUpdateFileInfo } from \"../types\"\nimport { getFileList, ProviderRuntimeOptions } from \"./Provider\"\n\nexport interface PrivateGitHubUpdateInfo extends UpdateInfo {\n assets: Array\n}\n\nexport class PrivateGitHubProvider extends BaseGitHubProvider {\n constructor(\n options: GithubOptions,\n private readonly updater: AppUpdater,\n private readonly token: string,\n runtimeOptions: ProviderRuntimeOptions\n ) {\n super(options, \"api.github.com\", runtimeOptions)\n }\n\n protected createRequestOptions(url: URL, headers?: OutgoingHttpHeaders | null): RequestOptions {\n const result = super.createRequestOptions(url, headers)\n ;(result as any).redirect = \"manual\"\n return result\n }\n\n async getLatestVersion(): Promise {\n const cancellationToken = new CancellationToken()\n const channelFile = getChannelFilename(this.getDefaultChannelName())\n\n const releaseInfo = await this.getLatestVersionInfo(cancellationToken)\n const asset = releaseInfo.assets.find(it => it.name === channelFile)\n if (asset == null) {\n // html_url must be always, but just to be sure\n throw newError(`Cannot find ${channelFile} in the release ${releaseInfo.html_url || releaseInfo.name}`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n }\n\n const url = new URL(asset.url)\n let result: any\n try {\n result = load((await this.httpRequest(url, this.configureHeaders(\"application/octet-stream\"), cancellationToken))!)\n } catch (e: any) {\n if (e instanceof HttpError && e.statusCode === 404) {\n throw newError(`Cannot find ${channelFile} in the latest release artifacts (${url}): ${e.stack || e.message}`, \"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND\")\n }\n throw e\n }\n\n ;(result as PrivateGitHubUpdateInfo).assets = releaseInfo.assets\n return result\n }\n\n get fileExtraDownloadHeaders(): OutgoingHttpHeaders | null {\n return this.configureHeaders(\"application/octet-stream\")\n }\n\n private configureHeaders(accept: string) {\n return {\n accept,\n authorization: `token ${this.token}`,\n }\n }\n\n private async getLatestVersionInfo(cancellationToken: CancellationToken): Promise {\n const allowPrerelease = this.updater.allowPrerelease\n let basePath = this.basePath\n if (!allowPrerelease) {\n basePath = `${basePath}/latest`\n }\n\n const url = newUrlFromBase(basePath, this.baseUrl)\n try {\n const version = JSON.parse((await this.httpRequest(url, this.configureHeaders(\"application/vnd.github.v3+json\"), cancellationToken))!)\n // only `latest` can return a single ReleaseInfo. Otherwise, a list of ReleaseInfo is returned and we need to find the latest one ourselves\n if (allowPrerelease) {\n const candidates = (version as Array).filter(it => !it.draft)\n return candidates.find(it => it.prerelease) || candidates[0]\n } else {\n return version\n }\n } catch (e: any) {\n throw newError(`Unable to find latest version on GitHub (${url}), please ensure a production release exists: ${e.stack || e.message}`, \"ERR_UPDATER_LATEST_VERSION_NOT_FOUND\")\n }\n }\n\n private get basePath(): string {\n return this.computeGithubBasePath(`/repos/${this.options.owner}/${this.options.repo}/releases`)\n }\n\n resolveFiles(updateInfo: PrivateGitHubUpdateInfo): Array {\n return getFileList(updateInfo).map(it => {\n const name = path.posix.basename(it.url).replace(/ /g, \"-\")\n const asset = updateInfo.assets.find(it => it != null && it.name === name)\n if (asset == null) {\n throw newError(`Cannot find asset \"${name}\" in: ${JSON.stringify(updateInfo.assets, null, 2)}`, \"ERR_UPDATER_ASSET_NOT_FOUND\")\n }\n\n return {\n url: new URL(asset.url),\n info: it,\n }\n })\n }\n}\n\ninterface ReleaseInfo {\n name: string\n html_url: string\n draft: boolean\n prerelease: boolean\n assets: Array\n}\n\nexport interface Asset {\n name: string\n url: string\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Provider = void 0; exports.findFile = findFile; exports.parseUpdateInfo = parseUpdateInfo; exports.getFileList = getFileList; exports.resolveFiles = resolveFiles; const builder_util_runtime_1 = require("builder-util-runtime"); const js_yaml_1 = require("js-yaml"); const url_1 = require("url"); const util_1 = require("../util"); // @ts-ignore const escapeRegExp = require("lodash.escaperegexp"); class Provider { constructor(runtimeOptions) { this.runtimeOptions = runtimeOptions; this.requestHeaders = null; this.executor = runtimeOptions.executor; } // By default, the blockmap file is in the same directory as the main file // But some providers may have a different blockmap file, so we need to override this method getBlockMapFiles(baseUrl, oldVersion, newVersion, oldBlockMapFileBaseUrl = null) { const newBlockMapUrl = (0, util_1.newUrlFromBase)(`${baseUrl.pathname}.blockmap`, baseUrl); const oldBlockMapUrl = (0, util_1.newUrlFromBase)(`${baseUrl.pathname.replace(new RegExp(escapeRegExp(newVersion), "g"), oldVersion)}.blockmap`, oldBlockMapFileBaseUrl ? new url_1.URL(oldBlockMapFileBaseUrl) : baseUrl); return [oldBlockMapUrl, newBlockMapUrl]; } get isUseMultipleRangeRequest() { return this.runtimeOptions.isUseMultipleRangeRequest !== false; } getChannelFilePrefix() { if (this.runtimeOptions.platform === "linux") { const arch = process.env["TEST_UPDATER_ARCH"] || process.arch; const archSuffix = arch === "x64" ? "" : `-${arch}`; return "-linux" + archSuffix; } else { return this.runtimeOptions.platform === "darwin" ? "-mac" : ""; } } // due to historical reasons for windows we use channel name without platform specifier getDefaultChannelName() { return this.getCustomChannelName("latest"); } getCustomChannelName(channel) { return `${channel}${this.getChannelFilePrefix()}`; } get fileExtraDownloadHeaders() { return null; } setRequestHeaders(value) { this.requestHeaders = value; } /** * Method to perform API request only to resolve update info, but not to download update. */ httpRequest(url, headers, cancellationToken) { return this.executor.request(this.createRequestOptions(url, headers), cancellationToken); } createRequestOptions(url, headers) { const result = {}; if (this.requestHeaders == null) { if (headers != null) { result.headers = headers; } } else { result.headers = headers == null ? this.requestHeaders : { ...this.requestHeaders, ...headers }; } (0, builder_util_runtime_1.configureRequestUrl)(url, result); return result; } } exports.Provider = Provider; function findFile(files, extension, not) { var _a; if (files.length === 0) { throw (0, builder_util_runtime_1.newError)("No files provided", "ERR_UPDATER_NO_FILES_PROVIDED"); } const filteredFiles = files.filter(it => it.url.pathname.toLowerCase().endsWith(`.${extension.toLowerCase()}`)); const result = (_a = filteredFiles.find(it => [it.url.pathname, it.info.url].some(n => n.includes(process.arch)))) !== null && _a !== void 0 ? _a : filteredFiles.shift(); if (result) { return result; } else if (not == null) { return files[0]; } else { return files.find(fileInfo => !not.some(ext => fileInfo.url.pathname.toLowerCase().endsWith(`.${ext.toLowerCase()}`))); } } function parseUpdateInfo(rawData, channelFile, channelFileUrl) { if (rawData == null) { throw (0, builder_util_runtime_1.newError)(`Cannot parse update info from ${channelFile} in the latest release artifacts (${channelFileUrl}): rawData: null`, "ERR_UPDATER_INVALID_UPDATE_INFO"); } let result; try { result = (0, js_yaml_1.load)(rawData); } catch (e) { throw (0, builder_util_runtime_1.newError)(`Cannot parse update info from ${channelFile} in the latest release artifacts (${channelFileUrl}): ${e.stack || e.message}, rawData: ${rawData}`, "ERR_UPDATER_INVALID_UPDATE_INFO"); } return result; } function getFileList(updateInfo) { const files = updateInfo.files; if (files != null && files.length > 0) { return files; } // noinspection JSDeprecatedSymbols if (updateInfo.path != null) { // noinspection JSDeprecatedSymbols return [ { url: updateInfo.path, sha2: updateInfo.sha2, sha512: updateInfo.sha512, }, ]; } else { throw (0, builder_util_runtime_1.newError)(`No files provided: ${(0, builder_util_runtime_1.safeStringifyJson)(updateInfo)}`, "ERR_UPDATER_NO_FILES_PROVIDED"); } } function resolveFiles(updateInfo, baseUrl, pathTransformer = (p) => p) { const files = getFileList(updateInfo); const result = files.map(fileInfo => { if (fileInfo.sha2 == null && fileInfo.sha512 == null) { throw (0, builder_util_runtime_1.newError)(`Update info doesn't contain nor sha256 neither sha512 checksum: ${(0, builder_util_runtime_1.safeStringifyJson)(fileInfo)}`, "ERR_UPDATER_NO_CHECKSUM"); } return { url: (0, util_1.newUrlFromBase)(pathTransformer(fileInfo.url), baseUrl), info: fileInfo, }; }); const packages = updateInfo.packages; const packageInfo = packages == null ? null : packages[process.arch] || packages.ia32; if (packageInfo != null) { ; result[0].packageInfo = { ...packageInfo, path: (0, util_1.newUrlFromBase)(pathTransformer(packageInfo.path), baseUrl).href, }; } return result; } //# sourceMappingURL=Provider.js.map{"version":3,"file":"Provider.js","sourceRoot":"","sources":["../../src/providers/Provider.ts"],"names":[],"mappings":";;;AAgGA,4BAeC;AAED,0CAeC;AAED,kCAmBC;AAED,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,CAAC,EAAE;QACjE,IAAK,QAAgB,CAAC,IAAI,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,IAAI,IAAI,EAAE,CAAC;YAC9D,MAAM,IAAA,+BAAQ,EAAC,mEAAmE,IAAA,wCAAiB,EAAC,QAAQ,CAAC,EAAE,EAAE,yBAAyB,CAAC,CAAA;QAC7I,CAAC;QACD,OAAO;YACL,GAAG,EAAE,IAAA,qBAAc,EAAC,eAAe,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC;YAC3D,IAAI,EAAE,QAAQ;SACf,CAAA;IACH,CAAC,CAAC,CAAA;IAEF,MAAM,QAAQ,GAAI,UAAgC,CAAC,QAAQ,CAAA;IAC3D,MAAM,WAAW,GAAG,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAA;IACrF,IAAI,WAAW,IAAI,IAAI,EAAE,CAAC;QACxB,CAAC;QAAC,MAAM,CAAC,CAAC,CAAS,CAAC,WAAW,GAAG;YAChC,GAAG,WAAW;YACd,IAAI,EAAE,IAAA,qBAAc,EAAC,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI;SACtE,CAAA;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { CancellationToken, configureRequestUrl, newError, safeStringifyJson, UpdateFileInfo, UpdateInfo, WindowsUpdateInfo } from \"builder-util-runtime\"\nimport { OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { load } from \"js-yaml\"\nimport { URL } from \"url\"\nimport { ElectronHttpExecutor } from \"../electronHttpExecutor\"\nimport { ResolvedUpdateFileInfo } from \"../types\"\nimport { newUrlFromBase } from \"../util\"\n// @ts-ignore\nimport * as escapeRegExp from \"lodash.escaperegexp\"\n\nexport type ProviderPlatform = \"darwin\" | \"linux\" | \"win32\"\n\nexport interface ProviderRuntimeOptions {\n isUseMultipleRangeRequest: boolean\n platform: ProviderPlatform\n\n executor: ElectronHttpExecutor\n}\n\nexport abstract class Provider {\n private requestHeaders: OutgoingHttpHeaders | null = null\n protected readonly executor: ElectronHttpExecutor\n\n protected constructor(private readonly runtimeOptions: ProviderRuntimeOptions) {\n this.executor = runtimeOptions.executor\n }\n\n // By default, the blockmap file is in the same directory as the main file\n // But some providers may have a different blockmap file, so we need to override this method\n getBlockMapFiles(baseUrl: URL, oldVersion: string, newVersion: string, oldBlockMapFileBaseUrl: string | null = null): URL[] | Promise {\n const newBlockMapUrl = newUrlFromBase(`${baseUrl.pathname}.blockmap`, baseUrl)\n const oldBlockMapUrl = newUrlFromBase(\n `${baseUrl.pathname.replace(new RegExp(escapeRegExp(newVersion), \"g\"), oldVersion)}.blockmap`,\n oldBlockMapFileBaseUrl ? new URL(oldBlockMapFileBaseUrl) : baseUrl\n )\n\n return [oldBlockMapUrl, newBlockMapUrl]\n }\n\n get isUseMultipleRangeRequest(): boolean {\n return this.runtimeOptions.isUseMultipleRangeRequest !== false\n }\n\n private getChannelFilePrefix(): string {\n if (this.runtimeOptions.platform === \"linux\") {\n const arch = process.env[\"TEST_UPDATER_ARCH\"] || process.arch\n const archSuffix = arch === \"x64\" ? \"\" : `-${arch}`\n return \"-linux\" + archSuffix\n } else {\n return this.runtimeOptions.platform === \"darwin\" ? \"-mac\" : \"\"\n }\n }\n\n // due to historical reasons for windows we use channel name without platform specifier\n protected getDefaultChannelName(): string {\n return this.getCustomChannelName(\"latest\")\n }\n\n protected getCustomChannelName(channel: string): string {\n return `${channel}${this.getChannelFilePrefix()}`\n }\n\n get fileExtraDownloadHeaders(): OutgoingHttpHeaders | null {\n return null\n }\n\n setRequestHeaders(value: OutgoingHttpHeaders | null): void {\n this.requestHeaders = value\n }\n\n abstract getLatestVersion(): Promise\n\n abstract resolveFiles(updateInfo: T): Array\n\n /**\n * Method to perform API request only to resolve update info, but not to download update.\n */\n protected httpRequest(url: URL, headers?: OutgoingHttpHeaders | null, cancellationToken?: CancellationToken): Promise {\n return this.executor.request(this.createRequestOptions(url, headers), cancellationToken)\n }\n\n protected createRequestOptions(url: URL, headers?: OutgoingHttpHeaders | null): RequestOptions {\n const result: RequestOptions = {}\n if (this.requestHeaders == null) {\n if (headers != null) {\n result.headers = headers\n }\n } else {\n result.headers = headers == null ? this.requestHeaders : { ...this.requestHeaders, ...headers }\n }\n\n configureRequestUrl(url, result)\n return result\n }\n}\n\nexport function findFile(files: Array, extension: string, not?: Array): ResolvedUpdateFileInfo | null | undefined {\n if (files.length === 0) {\n throw newError(\"No files provided\", \"ERR_UPDATER_NO_FILES_PROVIDED\")\n }\n\n const filteredFiles = files.filter(it => it.url.pathname.toLowerCase().endsWith(`.${extension.toLowerCase()}`))\n const result = filteredFiles.find(it => [it.url.pathname, it.info.url].some(n => n.includes(process.arch))) ?? filteredFiles.shift()\n\n if (result) {\n return result\n } else if (not == null) {\n return files[0]\n } else {\n return files.find(fileInfo => !not.some(ext => fileInfo.url.pathname.toLowerCase().endsWith(`.${ext.toLowerCase()}`)))\n }\n}\n\nexport function parseUpdateInfo(rawData: string | null, channelFile: string, channelFileUrl: URL): UpdateInfo {\n if (rawData == null) {\n throw newError(`Cannot parse update info from ${channelFile} in the latest release artifacts (${channelFileUrl}): rawData: null`, \"ERR_UPDATER_INVALID_UPDATE_INFO\")\n }\n\n let result: UpdateInfo\n try {\n result = load(rawData) as UpdateInfo\n } catch (e: any) {\n throw newError(\n `Cannot parse update info from ${channelFile} in the latest release artifacts (${channelFileUrl}): ${e.stack || e.message}, rawData: ${rawData}`,\n \"ERR_UPDATER_INVALID_UPDATE_INFO\"\n )\n }\n return result\n}\n\nexport function getFileList(updateInfo: UpdateInfo): Array {\n const files = updateInfo.files\n if (files != null && files.length > 0) {\n return files\n }\n\n // noinspection JSDeprecatedSymbols\n if (updateInfo.path != null) {\n // noinspection JSDeprecatedSymbols\n return [\n {\n url: updateInfo.path,\n sha2: (updateInfo as any).sha2,\n sha512: updateInfo.sha512,\n } as any,\n ]\n } else {\n throw newError(`No files provided: ${safeStringifyJson(updateInfo)}`, \"ERR_UPDATER_NO_FILES_PROVIDED\")\n }\n}\n\nexport function resolveFiles(updateInfo: UpdateInfo, baseUrl: URL, pathTransformer: (p: string) => string = (p: string): string => p): Array {\n const files = getFileList(updateInfo)\n const result: Array = files.map(fileInfo => {\n if ((fileInfo as any).sha2 == null && fileInfo.sha512 == null) {\n throw newError(`Update info doesn't contain nor sha256 neither sha512 checksum: ${safeStringifyJson(fileInfo)}`, \"ERR_UPDATER_NO_CHECKSUM\")\n }\n return {\n url: newUrlFromBase(pathTransformer(fileInfo.url), baseUrl),\n info: fileInfo,\n }\n })\n\n const packages = (updateInfo as WindowsUpdateInfo).packages\n const packageInfo = packages == null ? null : packages[process.arch] || packages.ia32\n if (packageInfo != null) {\n ;(result[0] as any).packageInfo = {\n ...packageInfo,\n path: newUrlFromBase(pathTransformer(packageInfo.path), baseUrl).href,\n }\n }\n return result\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UpdaterSignal = exports.UPDATE_DOWNLOADED = exports.DOWNLOAD_PROGRESS = exports.CancellationToken = void 0; exports.addHandler = addHandler; const builder_util_runtime_1 = require("builder-util-runtime"); Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return builder_util_runtime_1.CancellationToken; } }); exports.DOWNLOAD_PROGRESS = "download-progress"; exports.UPDATE_DOWNLOADED = "update-downloaded"; class UpdaterSignal { constructor(emitter) { this.emitter = emitter; } /** * Emitted when an authenticating proxy is [asking for user credentials](https://github.com/electron/electron/blob/master/docs/api/client-request.md#event-login). */ login(handler) { addHandler(this.emitter, "login", handler); } progress(handler) { addHandler(this.emitter, exports.DOWNLOAD_PROGRESS, handler); } updateDownloaded(handler) { addHandler(this.emitter, exports.UPDATE_DOWNLOADED, handler); } updateCancelled(handler) { addHandler(this.emitter, "update-cancelled", handler); } } exports.UpdaterSignal = UpdaterSignal; const isLogEvent = false; function addHandler(emitter, event, handler) { if (isLogEvent) { emitter.on(event, (...args) => { console.log("%s %s", event, args); handler(...args); }); } else { emitter.on(event, handler); } } //# sourceMappingURL=types.js.map{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AA6CA,gCASC;AAtDD,+DAAmH;AAK1G,kGALA,wCAAiB,OAKA;AAEb,QAAA,iBAAiB,GAAG,mBAAmB,CAAA;AACvC,QAAA,iBAAiB,GAAG,mBAAmB,CAAA;AAYpD,MAAa,aAAa;IACxB,YAAoB,OAAqB;QAArB,YAAO,GAAP,OAAO,CAAc;IAAG,CAAC;IAE7C;;OAEG;IACH,KAAK,CAAC,OAAqB;QACzB,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;IAC5C,CAAC;IAED,QAAQ,CAAC,OAAqC;QAC5C,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,yBAAiB,EAAE,OAAO,CAAC,CAAA;IACtD,CAAC;IAED,gBAAgB,CAAC,OAA8C;QAC7D,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,yBAAiB,EAAE,OAAO,CAAC,CAAA;IACtD,CAAC;IAED,eAAe,CAAC,OAAmC;QACjD,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,kBAAkB,EAAE,OAAO,CAAC,CAAA;IACvD,CAAC;CACF;AArBD,sCAqBC;AAED,MAAM,UAAU,GAAG,KAAK,CAAA;AAExB,SAAgB,UAAU,CAAC,OAAqB,EAAE,KAAoB,EAAE,OAAsC;IAC5G,IAAI,UAAU,EAAE,CAAC;QACf,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,IAAgB,EAAE,EAAE;YACxC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;YACjC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAA;QAClB,CAAC,CAAC,CAAA;IACJ,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import { CancellationToken, PackageFileInfo, ProgressInfo, UpdateFileInfo, UpdateInfo } from \"builder-util-runtime\"\nimport { EventEmitter } from \"events\"\nimport { URL } from \"url\"\nimport { LoginCallback } from \"./electronHttpExecutor\"\n\nexport { CancellationToken, PackageFileInfo, ProgressInfo, UpdateFileInfo, UpdateInfo }\n\nexport const DOWNLOAD_PROGRESS = \"download-progress\"\nexport const UPDATE_DOWNLOADED = \"update-downloaded\"\n\nexport interface Logger {\n info(message?: any): void\n\n warn(message?: any): void\n\n error(message?: any): void\n\n debug?(message: string): void\n}\n\nexport class UpdaterSignal {\n constructor(private emitter: EventEmitter) {}\n\n /**\n * Emitted when an authenticating proxy is [asking for user credentials](https://github.com/electron/electron/blob/master/docs/api/client-request.md#event-login).\n */\n login(handler: LoginHandler): void {\n addHandler(this.emitter, \"login\", handler)\n }\n\n progress(handler: (info: ProgressInfo) => void): void {\n addHandler(this.emitter, DOWNLOAD_PROGRESS, handler)\n }\n\n updateDownloaded(handler: (info: UpdateDownloadedEvent) => void): void {\n addHandler(this.emitter, UPDATE_DOWNLOADED, handler)\n }\n\n updateCancelled(handler: (info: UpdateInfo) => void): void {\n addHandler(this.emitter, \"update-cancelled\", handler)\n }\n}\n\nconst isLogEvent = false\n\nexport function addHandler(emitter: EventEmitter, event: UpdaterEvents, handler: (...args: Array) => void): void {\n if (isLogEvent) {\n emitter.on(event, (...args: Array) => {\n console.log(\"%s %s\", event, args)\n handler(...args)\n })\n } else {\n emitter.on(event, handler)\n }\n}\n\nexport interface UpdateCheckResult {\n readonly isUpdateAvailable: boolean\n\n readonly updateInfo: UpdateInfo\n\n readonly downloadPromise?: Promise> | null\n\n readonly cancellationToken?: CancellationToken\n\n /** @deprecated */\n readonly versionInfo: UpdateInfo\n}\n\nexport interface UpdateDownloadedEvent extends UpdateInfo {\n downloadedFile: string\n}\n\nexport interface ResolvedUpdateFileInfo {\n readonly url: URL\n readonly info: UpdateFileInfo\n\n packageInfo?: PackageFileInfo\n}\n\nexport type UpdaterEvents = \"login\" | \"checking-for-update\" | \"update-available\" | \"update-not-available\" | \"update-cancelled\" | \"download-progress\" | \"update-downloaded\" | \"error\"\n\nexport type LoginHandler = (authInfo: any, callback: LoginCallback) => void\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.newBaseUrl = newBaseUrl; exports.newUrlFromBase = newUrlFromBase; exports.getChannelFilename = getChannelFilename; // if baseUrl path doesn't ends with /, this path will be not prepended to passed pathname for new URL(input, base) const url_1 = require("url"); /** @internal */ function newBaseUrl(url) { const result = new url_1.URL(url); if (!result.pathname.endsWith("/")) { result.pathname += "/"; } return result; } // addRandomQueryToAvoidCaching is false by default because in most cases URL already contains version number, // so, it makes sense only for Generic Provider for channel files function newUrlFromBase(pathname, baseUrl, addRandomQueryToAvoidCaching = false) { const result = new url_1.URL(pathname, baseUrl); // search is not propagated (search is an empty string if not specified) const search = baseUrl.search; if (search != null && search.length !== 0) { result.search = search; } else if (addRandomQueryToAvoidCaching) { result.search = `noCache=${Date.now().toString(32)}`; } return result; } function getChannelFilename(channel) { return `${channel}.yml`; } //# sourceMappingURL=util.js.map{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAIA,gCAMC;AAID,wCAUC;AAED,gDAEC;AA5BD,mHAAmH;AACnH,6BAAyB;AAEzB,gBAAgB;AAChB,SAAgB,UAAU,CAAC,GAAW;IACpC,MAAM,MAAM,GAAG,IAAI,SAAG,CAAC,GAAG,CAAC,CAAA;IAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,MAAM,CAAC,QAAQ,IAAI,GAAG,CAAA;IACxB,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAED,8GAA8G;AAC9G,iEAAiE;AACjE,SAAgB,cAAc,CAAC,QAAgB,EAAE,OAAY,EAAE,4BAA4B,GAAG,KAAK;IACjG,MAAM,MAAM,GAAG,IAAI,SAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAA;IACzC,wEAAwE;IACxE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;IAC7B,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1C,MAAM,CAAC,MAAM,GAAG,MAAM,CAAA;IACxB,CAAC;SAAM,IAAI,4BAA4B,EAAE,CAAC;QACxC,MAAM,CAAC,MAAM,GAAG,WAAW,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAA;IACtD,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAED,SAAgB,kBAAkB,CAAC,OAAe;IAChD,OAAO,GAAG,OAAO,MAAM,CAAA;AACzB,CAAC","sourcesContent":["// if baseUrl path doesn't ends with /, this path will be not prepended to passed pathname for new URL(input, base)\nimport { URL } from \"url\"\n\n/** @internal */\nexport function newBaseUrl(url: string): URL {\n const result = new URL(url)\n if (!result.pathname.endsWith(\"/\")) {\n result.pathname += \"/\"\n }\n return result\n}\n\n// addRandomQueryToAvoidCaching is false by default because in most cases URL already contains version number,\n// so, it makes sense only for Generic Provider for channel files\nexport function newUrlFromBase(pathname: string, baseUrl: URL, addRandomQueryToAvoidCaching = false): URL {\n const result = new URL(pathname, baseUrl)\n // search is not propagated (search is an empty string if not specified)\n const search = baseUrl.search\n if (search != null && search.length !== 0) {\n result.search = search\n } else if (addRandomQueryToAvoidCaching) {\n result.search = `noCache=${Date.now().toString(32)}`\n }\n return result\n}\n\nexport function getChannelFilename(channel: string): string {\n return `${channel}.yml`\n}\n"]}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySignature = verifySignature; const builder_util_runtime_1 = require("builder-util-runtime"); const child_process_1 = require("child_process"); const os = require("os"); const path = require("path"); function preparePowerShellExec(command, timeout) { // https://github.com/electron-userland/electron-builder/issues/2421 // https://github.com/electron-userland/electron-builder/issues/2535 // Resetting PSModulePath is necessary https://github.com/electron-userland/electron-builder/issues/7127 // semicolon wont terminate the set command and run chcp thus leading to verification errors on certificats with special chars like german umlauts, so rather // join commands using & https://github.com/electron-userland/electron-builder/issues/8162 const executable = `set "PSModulePath=" & chcp 65001 >NUL & powershell.exe`; const args = ["-NoProfile", "-NonInteractive", "-InputFormat", "None", "-Command", command]; const options = { shell: true, timeout, }; return [executable, args, options]; } // $certificateInfo = (Get-AuthenticodeSignature 'xxx\yyy.exe' // | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains("CN=siemens.com")}) // | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 } function verifySignature(publisherNames, unescapedTempUpdateFile, logger) { return new Promise((resolve, reject) => { // Escape quotes and backticks in filenames to prevent user from breaking the // arguments and perform a remote command injection. // // Consider example powershell command: // ```powershell // Get-AuthenticodeSignature 'C:\\path\\my-bad-';calc;'filename.exe' // ``` // The above would work expected and find the file name, however, it will also execute `;calc;` // command and start the calculator app. // // From Powershell quoting rules: // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7 // * Double quotes `"` are treated literally within single-quoted strings; // * Single quotes can be escaped by doubling them: 'don''t' -> don't; // // Also note that at this point the file has already been written to the disk, thus we are // guaranteed that the path will not contain any illegal characters like <>:"/\|?* // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file const tempUpdateFile = unescapedTempUpdateFile.replace(/'/g, "''"); logger.info(`Verifying signature ${tempUpdateFile}`); (0, child_process_1.execFile)(...preparePowerShellExec(`"Get-AuthenticodeSignature -LiteralPath '${tempUpdateFile}' | ConvertTo-Json -Compress"`, 20 * 1000), (error, stdout, stderr) => { var _a; try { if (error != null || stderr) { handleError(logger, error, stderr, reject); resolve(null); return; } const data = parseOut(stdout); if (data.Status === 0) { try { const normlaizedUpdateFilePath = path.normalize(data.Path); const normalizedTempUpdateFile = path.normalize(unescapedTempUpdateFile); logger.info(`LiteralPath: ${normlaizedUpdateFilePath}. Update Path: ${normalizedTempUpdateFile}`); if (normlaizedUpdateFilePath !== normalizedTempUpdateFile) { handleError(logger, new Error(`LiteralPath of ${normlaizedUpdateFilePath} is different than ${normalizedTempUpdateFile}`), stderr, reject); resolve(null); return; } } catch (error) { logger.warn(`Unable to verify LiteralPath of update asset due to missing data.Path. Skipping this step of validation. Message: ${(_a = error.message) !== null && _a !== void 0 ? _a : error.stack}`); } const subject = (0, builder_util_runtime_1.parseDn)(data.SignerCertificate.Subject); let match = false; for (const name of publisherNames) { const dn = (0, builder_util_runtime_1.parseDn)(name); if (dn.size) { // if we have a full DN, compare all values const allKeys = Array.from(dn.keys()); match = allKeys.every(key => { return dn.get(key) === subject.get(key); }); } else if (name === subject.get("CN")) { logger.warn(`Signature validated using only CN ${name}. Please add your full Distinguished Name (DN) to publisherNames configuration`); match = true; } if (match) { resolve(null); return; } } } const result = `publisherNames: ${publisherNames.join(" | ")}, raw info: ` + JSON.stringify(data, (name, value) => (name === "RawData" ? undefined : value), 2); logger.warn(`Sign verification failed, installer signed with incorrect certificate: ${result}`); resolve(result); } catch (e) { handleError(logger, e, null, reject); resolve(null); return; } }); }); } function parseOut(out) { const data = JSON.parse(out); delete data.PrivateKey; delete data.IsOSBinary; delete data.SignatureType; const signerCertificate = data.SignerCertificate; if (signerCertificate != null) { delete signerCertificate.Archived; delete signerCertificate.Extensions; delete signerCertificate.Handle; delete signerCertificate.HasPrivateKey; // duplicates data.SignerCertificate (contains RawData) delete signerCertificate.SubjectName; } return data; } function handleError(logger, error, stderr, reject) { if (isOldWin6()) { logger.warn(`Cannot execute Get-AuthenticodeSignature: ${error || stderr}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`); return; } try { (0, child_process_1.execFileSync)(...preparePowerShellExec("ConvertTo-Json test", 10 * 1000)); } catch (testError) { logger.warn(`Cannot execute ConvertTo-Json: ${testError.message}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`); return; } if (error != null) { reject(error); } if (stderr) { reject(new Error(`Cannot execute Get-AuthenticodeSignature, stderr: ${stderr}. Failing signature validation due to unknown stderr.`)); } } function isOldWin6() { const winVersion = os.release(); return winVersion.startsWith("6.") && !winVersion.startsWith("6.3"); } //# sourceMappingURL=windowsExecutableCodeSignatureVerifier.js.map{"version":3,"file":"windowsExecutableCodeSignatureVerifier.js","sourceRoot":"","sources":["../src/windowsExecutableCodeSignatureVerifier.ts"],"names":[],"mappings":";;AAwBA,0CA2EC;AAnGD,+DAA8C;AAC9C,iDAAuE;AACvE,yBAAwB;AAExB,6BAA4B;AAE5B,SAAS,qBAAqB,CAAC,OAAe,EAAE,OAAgB;IAC9D,oEAAoE;IACpE,oEAAoE;IACpE,wGAAwG;IACxG,6JAA6J;IAC7J,4FAA4F;IAC5F,MAAM,UAAU,GAAG,wDAAwD,CAAA;IAC3E,MAAM,IAAI,GAAG,CAAC,YAAY,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IAC3F,MAAM,OAAO,GAAoB;QAC/B,KAAK,EAAE,IAAI;QACX,OAAO;KACR,CAAA;IACD,OAAO,CAAC,UAAU,EAAE,IAAI,EAAE,OAAO,CAAU,CAAA;AAC7C,CAAC;AAED,8DAA8D;AAC9D,kJAAkJ;AAClJ,kEAAkE;AAClE,SAAgB,eAAe,CAAC,cAA6B,EAAE,uBAA+B,EAAE,MAAc;IAC5G,OAAO,IAAI,OAAO,CAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACpD,6EAA6E;QAC7E,oDAAoD;QACpD,EAAE;QACF,uCAAuC;QACvC,gBAAgB;QAChB,oEAAoE;QACpE,MAAM;QACN,+FAA+F;QAC/F,wCAAwC;QACxC,EAAE;QACF,iCAA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AqB,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC,CAAA;IAC1E,CAAC;IAAC,OAAO,SAAc,EAAE,CAAC;QACxB,MAAM,CAAC,IAAI,CACT,kCAAkC,SAAS,CAAC,OAAO,kHAAkH,CACtK,CAAA;QACD,OAAM;IACR,CAAC;IAED,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;QAClB,MAAM,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;IAED,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,CAAC,IAAI,KAAK,CAAC,qDAAqD,MAAM,uDAAuD,CAAC,CAAC,CAAA;IACvI,CAAC;AACH,CAAC;AAED,SAAS,SAAS;IAChB,MAAM,UAAU,GAAG,EAAE,CAAC,OAAO,EAAE,CAAA;IAC/B,OAAO,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,KAAK,CAAC,CAAA;AACrE,CAAC","sourcesContent":["import { parseDn } from \"builder-util-runtime\"\nimport { execFile, execFileSync, ExecFileOptions } from \"child_process\"\nimport * as os from \"os\"\nimport { Logger } from \"./types\"\nimport * as path from \"path\"\n\nfunction preparePowerShellExec(command: string, timeout?: number) {\n // https://github.com/electron-userland/electron-builder/issues/2421\n // https://github.com/electron-userland/electron-builder/issues/2535\n // Resetting PSModulePath is necessary https://github.com/electron-userland/electron-builder/issues/7127\n // semicolon wont terminate the set command and run chcp thus leading to verification errors on certificats with special chars like german umlauts, so rather\n // join commands using & https://github.com/electron-userland/electron-builder/issues/8162\n const executable = `set \"PSModulePath=\" & chcp 65001 >NUL & powershell.exe`\n const args = [\"-NoProfile\", \"-NonInteractive\", \"-InputFormat\", \"None\", \"-Command\", command]\n const options: ExecFileOptions = {\n shell: true,\n timeout,\n }\n return [executable, args, options] as const\n}\n\n// $certificateInfo = (Get-AuthenticodeSignature 'xxx\\yyy.exe'\n// | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains(\"CN=siemens.com\")})\n// | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }\nexport function verifySignature(publisherNames: Array, unescapedTempUpdateFile: string, logger: Logger): Promise {\n return new Promise((resolve, reject) => {\n // Escape quotes and backticks in filenames to prevent user from breaking the\n // arguments and perform a remote command injection.\n //\n // Consider example powershell command:\n // ```powershell\n // Get-AuthenticodeSignature 'C:\\\\path\\\\my-bad-';calc;'filename.exe'\n // ```\n // The above would work expected and find the file name, however, it will also execute `;calc;`\n // command and start the calculator app.\n //\n // From Powershell quoting rules:\n // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7\n // * Double quotes `\"` are treated literally within single-quoted strings;\n // * Single quotes can be escaped by doubling them: 'don''t' -> don't;\n //\n // Also note that at this point the file has already been written to the disk, thus we are\n // guaranteed that the path will not contain any illegal characters like <>:\"/\\|?*\n // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file\n const tempUpdateFile = unescapedTempUpdateFile.replace(/'/g, \"''\")\n logger.info(`Verifying signature ${tempUpdateFile}`)\n\n execFile(...preparePowerShellExec(`\"Get-AuthenticodeSignature -LiteralPath '${tempUpdateFile}' | ConvertTo-Json -Compress\"`, 20 * 1000), (error, stdout, stderr) => {\n try {\n if (error != null || stderr) {\n handleError(logger, error, stderr, reject)\n resolve(null)\n return\n }\n const data = parseOut(stdout)\n if (data.Status === 0) {\n try {\n const normlaizedUpdateFilePath = path.normalize(data.Path)\n const normalizedTempUpdateFile = path.normalize(unescapedTempUpdateFile)\n logger.info(`LiteralPath: ${normlaizedUpdateFilePath}. Update Path: ${normalizedTempUpdateFile}`)\n if (normlaizedUpdateFilePath !== normalizedTempUpdateFile) {\n handleError(logger, new Error(`LiteralPath of ${normlaizedUpdateFilePath} is different than ${normalizedTempUpdateFile}`), stderr, reject)\n resolve(null)\n return\n }\n } catch (error: any) {\n logger.warn(`Unable to verify LiteralPath of update asset due to missing data.Path. Skipping this step of validation. Message: ${error.message ?? error.stack}`)\n }\n const subject = parseDn(data.SignerCertificate.Subject)\n let match = false\n for (const name of publisherNames) {\n const dn = parseDn(name)\n if (dn.size) {\n // if we have a full DN, compare all values\n const allKeys = Array.from(dn.keys())\n match = allKeys.every(key => {\n return dn.get(key) === subject.get(key)\n })\n } else if (name === subject.get(\"CN\")!) {\n logger.warn(`Signature validated using only CN ${name}. Please add your full Distinguished Name (DN) to publisherNames configuration`)\n match = true\n }\n if (match) {\n resolve(null)\n return\n }\n }\n }\n\n const result = `publisherNames: ${publisherNames.join(\" | \")}, raw info: ` + JSON.stringify(data, (name, value) => (name === \"RawData\" ? undefined : value), 2)\n logger.warn(`Sign verification failed, installer signed with incorrect certificate: ${result}`)\n resolve(result)\n } catch (e: any) {\n handleError(logger, e, null, reject)\n resolve(null)\n return\n }\n })\n })\n}\n\nfunction parseOut(out: string): any {\n const data = JSON.parse(out)\n delete data.PrivateKey\n delete data.IsOSBinary\n delete data.SignatureType\n const signerCertificate = data.SignerCertificate\n if (signerCertificate != null) {\n delete signerCertificate.Archived\n delete signerCertificate.Extensions\n delete signerCertificate.Handle\n delete signerCertificate.HasPrivateKey\n // duplicates data.SignerCertificate (contains RawData)\n delete signerCertificate.SubjectName\n }\n return data\n}\n\nfunction handleError(logger: Logger, error: Error | null, stderr: string | null, reject: (reason: any) => void): void {\n if (isOldWin6()) {\n logger.warn(\n `Cannot execute Get-AuthenticodeSignature: ${error || stderr}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n )\n return\n }\n\n try {\n execFileSync(...preparePowerShellExec(\"ConvertTo-Json test\", 10 * 1000))\n } catch (testError: any) {\n logger.warn(\n `Cannot execute ConvertTo-Json: ${testError.message}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n )\n return\n }\n\n if (error != null) {\n reject(error)\n }\n\n if (stderr) {\n reject(new Error(`Cannot execute Get-AuthenticodeSignature, stderr: ${stderr}. Failing signature validation due to unknown stderr.`))\n }\n}\n\nfunction isOldWin6(): boolean {\n const winVersion = os.release()\n return winVersion.startsWith(\"6.\") && !winVersion.startsWith(\"6.3\")\n}\n"]}{ "name": "electron-updater", "version": "6.8.8", "description": "Cross platform updater for electron applications", "main": "out/main.js", "author": "Vladimir Krivosheev", "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/electron-userland/electron-builder.git", "directory": "packages/electron-updater" }, "homepage": "https://github.com/electron-userland/electron-builder", "files": [ "out" ], "dependencies": { "fs-extra": "^10.1.0", "js-yaml": "^4.1.0", "lazy-val": "^1.0.5", "lodash.escaperegexp": "^4.1.2", "lodash.isequal": "^4.5.0", "semver": "~7.7.3", "tiny-typed-emitter": "^2.1.0", "builder-util-runtime": "9.6.3" }, "devDependencies": { "@types/fs-extra": "9.0.13", "@types/js-yaml": "4.0.3", "@types/lodash.escaperegexp": "4.1.6", "@types/lodash.isequal": "4.5.5", "@types/semver": "7.7.1", "electron": "39.8.5" }, "typings": "./out/main.d.ts", "publishConfig": { "tag": "next" } }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. #!/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. 'use strict' const argv = process.argv.slice(2) let versions = [] const range = [] let inc = null const version = require('../package.json').version let loose = false let includePrerelease = false let coerce = false let rtl = false let identifier let identifierBase const semver = require('../') const parseOptions = require('../internal/parse-options') let reverse = false let options = {} const main = () => { if (!argv.length) { return help() } while (argv.length) { let a = argv.shift() const indexOfEqualSign = a.indexOf('=') if (indexOfEqualSign !== -1) { const value = a.slice(indexOfEqualSign + 1) a = a.slice(0, indexOfEqualSign) argv.unshift(value) } 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': case 'release': 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 '-n': identifierBase = argv.shift() if (identifierBase === 'false') { identifierBase = false } 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 } } options = parseOptions({ loose, includePrerelease, rtl }) versions = versions.map((v) => { return coerce ? (semver.coerce(v, options) || { version: v }).version : v }).filter((v) => { return semver.valid(v, options) }) if (!versions.length) { return fail() } if (inc && (versions.length !== 1 || range.length)) { return failInc() } for (let i = 0, l = range.length; i < l; i++) { versions = versions.filter((v) => { return semver.satisfies(v, range[i], options) }) if (!versions.length) { return fail() } } versions .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) .map(v => semver.clean(v, options)) .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v) .forEach(v => console.log(v)) } const failInc = () => { console.error('--inc can only be used on a single version with no range') fail() } const fail = () => process.exit(1) const help = () => console.log( `SemVer ${version} A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] [ [...]] Prints valid versions sorted by SemVer precedence Options: -r --range Print versions that match the specified range. -i --increment [] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, prerelease, or release. Default level is 'patch'. Only one version may be specified. --preid 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) -n Base number to be used for the prerelease identifier. Can be either 0 or 1, or false to omit the number altogether. Defaults to 0. 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.`) main() 'use strict' const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = require('../internal/parse-options') const { safeRe: re, t } = require('../internal/re') const cmp = require('../functions/cmp') const debug = require('../internal/debug') const SemVer = require('./semver') const Range = require('./range') 'use strict' module.exports = { SemVer: require('./semver.js'), Range: require('./range.js'), Comparator: require('./comparator.js'), } 'use strict' const SPACE_CHARACTERS = /\s+/g // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.formatted = undefined return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.formatted = undefined } get range () { if (this.formatted === undefined) { this.formatted = '' for (let i = 0; i < this.set.length; i++) { if (i > 0) { this.formatted += '||' } const comps = this.set[i] for (let k = 0; k < comps.length; k++) { if (k > 0) { this.formatted += ' ' } this.formatted += comps[k].toString().trim() } } } return this.formatted } format () { return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = require('../internal/lrucache') const cache = new LRU() const parseOptions = require('../internal/parse-options') const Comparator = require('./comparator') const debug = require('../internal/debug') const SemVer = require('./semver') const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = require('../internal/re') const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { comp = comp.replace(re[t.BUILD], '') debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 // TODO build? const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } 'use strict' const debug = require('../internal/debug') const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') const { safeRe: re, t } = require('../internal/re') const parseOptions = require('../internal/parse-options') const { compareIdentifiers } = require('../internal/identifiers') class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } if (this.major < other.major) { return -1 } if (this.major > other.major) { return 1 } if (this.minor < other.minor) { return -1 } if (this.minor > other.minor) { return 1 } if (this.patch < other.patch) { return -1 } if (this.patch > other.patch) { return 1 } return 0 } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('build compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { if (release.startsWith('pre')) { if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } // Avoid an invalid semver results if (identifier) { const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) if (!match || match[1] !== identifier) { throw new Error(`invalid identifier: ${identifier}`) } } } switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'release': if (this.prerelease.length === 0) { throw new Error(`version ${this.raw} is not a prerelease`) } this.prerelease.length = 0 break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer 'use strict' const parse = require('./parse') const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean 'use strict' const eq = require('./eq') const neq = require('./neq') const gt = require('./gt') const gte = require('./gte') const lt = require('./lt') const lte = require('./lte') const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp 'use strict' const SemVer = require('../classes/semver') const parse = require('./parse') const { safeRe: re, t } = require('../internal/re') const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] let next while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state coerceRtlRegex.lastIndex = -1 } if (match === null) { return null } const major = match[2] const minor = match[3] || '0' const patch = match[4] || '0' const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } module.exports = coerce 'use strict' const SemVer = require('../classes/semver') const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild 'use strict' const compare = require('./compare') const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose 'use strict' const SemVer = require('../classes/semver') const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare 'use strict' const parse = require('./parse.js') const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // If the main part has no difference if (lowVersion.compareMain(highVersion) === 0) { if (lowVersion.minor && !lowVersion.patch) { return 'minor' } return 'patch' } } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are prereleases return 'prerelease' } module.exports = diff 'use strict' const compare = require('./compare') const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq 'use strict' const compare = require('./compare') const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt 'use strict' const compare = require('./compare') const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte 'use strict' const SemVer = require('../classes/semver') const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc 'use strict' const compare = require('./compare') const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt 'use strict' const compare = require('./compare') const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte 'use strict' const SemVer = require('../classes/semver') const major = (a, loose) => new SemVer(a, loose).major module.exports = major 'use strict' const SemVer = require('../classes/semver') const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor 'use strict' const compare = require('./compare') const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq 'use strict' const SemVer = require('../classes/semver') const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse 'use strict' const SemVer = require('../classes/semver') const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch 'use strict' const parse = require('./parse') const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease 'use strict' const compare = require('./compare') const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare 'use strict' const compareBuild = require('./compare-build') const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort 'use strict' const Range = require('../classes/range') const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies 'use strict' const compareBuild = require('./compare-build') const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort 'use strict' const parse = require('./parse') const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid 'use strict' // just pre-load all the stuff that index.js lazily exports const internalRe = require('./internal/re') const constants = require('./internal/constants') const SemVer = require('./classes/semver') const identifiers = require('./internal/identifiers') const parse = require('./functions/parse') const valid = require('./functions/valid') const clean = require('./functions/clean') const inc = require('./functions/inc') const diff = require('./functions/diff') const major = require('./functions/major') const minor = require('./functions/minor') const patch = require('./functions/patch') const prerelease = require('./functions/prerelease') const compare = require('./functions/compare') const rcompare = require('./functions/rcompare') const compareLoose = require('./functions/compare-loose') const compareBuild = require('./functions/compare-build') const sort = require('./functions/sort') const rsort = require('./functions/rsort') const gt = require('./functions/gt') const lt = require('./functions/lt') const eq = require('./functions/eq') const neq = require('./functions/neq') const gte = require('./functions/gte') const lte = require('./functions/lte') const cmp = require('./functions/cmp') const coerce = require('./functions/coerce') const Comparator = require('./classes/comparator') const Range = require('./classes/range') const satisfies = require('./functions/satisfies') const toComparators = require('./ranges/to-comparators') const maxSatisfying = require('./ranges/max-satisfying') const minSatisfying = require('./ranges/min-satisfying') const minVersion = require('./ranges/min-version') const validRange = require('./ranges/valid') const outside = require('./ranges/outside') const gtr = require('./ranges/gtr') const ltr = require('./ranges/ltr') const intersects = require('./ranges/intersects') const simplifyRange = require('./ranges/simplify') const subset = require('./ranges/subset') module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } 'use strict' // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } 'use strict' const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug 'use strict' const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { if (typeof a === 'number' && typeof b === 'number') { return a === b ? 0 : a < b ? -1 : 1 } const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } 'use strict' class LRUCache { constructor () { this.max = 1000 this.map = new Map() } get (key) { const value = this.map.get(key) if (value === undefined) { return undefined } else { // Remove the key from the map and add it to the end this.map.delete(key) this.map.set(key, value) return value } } delete (key) { return this.map.delete(key) } set (key, value) { const deleted = this.delete(key) if (!deleted && value !== undefined) { // If cache is full, delete the least recently used item if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value this.delete(firstKey) } this.map.set(key, value) } return this } } module.exports = LRUCache 'use strict' // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions 'use strict' const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = require('./constants') const debug = require('./debug') exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const safeSrc = exports.safeSrc = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value safeSrc[index] = safe re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. // Non-numeric identifiers include numeric identifiers but can be longer. // Therefore non-numeric identifiers must go first. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] }|${src[t.NUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] }|${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCEPLAIN', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) createToken('COERCEFULL', src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) createToken('COERCERTLFULL', src[t.COERCEFULL], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') { "name": "semver", "version": "7.7.4", "description": "The semantic version parser used by npm.", "main": "index.js", "devDependencies": { "@npmcli/eslint-config": "^6.0.0", "@npmcli/template-oss": "4.29.0", "benchmark": "^2.1.4", "tap": "^16.0.0" }, "license": "ISC", "repository": { "type": "git", "url": "git+https://github.com/npm/node-semver.git" }, "bin": { "semver": "bin/semver.js" }, "files": [ "bin/", "lib/", "classes/", "functions/", "internal/", "ranges/", "index.js", "preload.js", "range.bnf" ], "tap": { "timeout": 30, "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "engines": { "node": ">=10" }, "author": "GitHub Inc.", "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.29.0", "engines": ">=10", "distPaths": [ "classes/", "functions/", "internal/", "ranges/", "index.js", "preload.js", "range.bnf" ], "allowPaths": [ "/classes/", "/functions/", "/internal/", "/ranges/", "/index.js", "/preload.js", "/range.bnf", "/benchmarks" ], "publish": "true" } }'use strict' // XXX remove in v8 or beyond module.exports = require('./index.js') 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]+ 'use strict' // Determine if version is greater than all the versions possible in the range. const outside = require('./outside') const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr 'use strict' const Range = require('../classes/range') const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects 'use strict' const outside = require('./outside') // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr 'use strict' const SemVer = require('../classes/semver') const Range = require('../classes/range') const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying 'use strict' const SemVer = require('../classes/semver') const Range = require('../classes/range') const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying 'use strict' const SemVer = require('../classes/semver') const Range = require('../classes/range') const gt = require('../functions/gt') const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion 'use strict' const SemVer = require('../classes/semver') const Comparator = require('../classes/comparator') const { ANY } = Comparator const Range = require('../classes/range') const satisfies = require('../functions/satisfies') const gt = require('../functions/gt') const lt = require('../functions/lt') const lte = require('../functions/lte') const gte = require('../functions/gte') const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside 'use strict' // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = require('../functions/satisfies.js') const compare = require('../functions/compare.js') module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } 'use strict' const Range = require('../classes/range.js') const Comparator = require('../classes/comparator.js') const { ANY } = Comparator const satisfies = require('../functions/satisfies.js') const compare = require('../functions/compare.js') // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If LT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset 'use strict' const Range = require('../classes/range') // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators 'use strict' const Range = require('../classes/range') const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange import path from 'node:path'; import os from 'node:os'; import process from 'node:process'; const homedir = os.homedir(); const tmpdir = os.tmpdir(); const {env} = process; const macos = name => { const library = path.join(homedir, 'Library'); return { data: path.join(library, 'Application Support', name), config: path.join(library, 'Preferences', name), cache: path.join(library, 'Caches', name), log: path.join(library, 'Logs', name), temp: path.join(tmpdir, name), }; }; const windows = name => { const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming'); const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local'); return { // Data/config/cache/log are invented by me as Windows isn't opinionated about this data: path.join(localAppData, name, 'Data'), config: path.join(appData, name, 'Config'), cache: path.join(localAppData, name, 'Cache'), log: path.join(localAppData, name, 'Log'), temp: path.join(tmpdir, name), }; }; // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html const linux = name => { const username = path.basename(homedir); return { data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name), config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name), cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name), // https://wiki.debian.org/XDGBaseDirectorySpecification#state log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name), temp: path.join(tmpdir, username, name), }; }; export default function envPaths(name, {suffix = 'nodejs'} = {}) { if (typeof name !== 'string') { throw new TypeError(`Expected a string, got ${typeof name}`); } if (suffix) { // Add suffix to prevent possible conflict with native apps name += `-${suffix}`; } if (process.platform === 'darwin') { return macos(name); } if (process.platform === 'win32') { return windows(name); } return linux(name); } MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "env-paths", "version": "3.0.0", "description": "Get paths for storing things like data, config, cache, etc", "license": "MIT", "repository": "sindresorhus/env-paths", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "files": [ "index.js", "index.d.ts" ], "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" } }MIT License Copyright (c) 2017 Evgeny Poberezkin 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. 'use strict'; // do not edit .js files directly - edit src/index.jst var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if ((a instanceof Map) && (b instanceof Map)) { if (a.size !== b.size) return false; for (i of a.entries()) if (!b.has(i[0])) return false; for (i of a.entries()) if (!equal(i[1], b.get(i[0]))) return false; return true; } if ((a instanceof Set) && (b instanceof Set)) { if (a.size !== b.size) return false; for (i of a.entries()) if (!b.has(i[0])) return false; return true; } if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (a[i] !== b[i]) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; }; 'use strict'; // do not edit .js files directly - edit src/index.jst var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if ((a instanceof Map) && (b instanceof Map)) { if (a.size !== b.size) return false; for (i of a.entries()) if (!b.has(i[0])) return false; for (i of a.entries()) if (!equal(i[1], b.get(i[0]))) return false; return true; } if ((a instanceof Set) && (b instanceof Set)) { if (a.size !== b.size) return false; for (i of a.entries()) if (!b.has(i[0])) return false; return true; } if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (a[i] !== b[i]) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (key === '_owner' && a.$$typeof) { // React-specific: avoid traversing React elements' _owner. // _owner contains circular references // and is not needed when comparing the actual elements (and not their owners) continue; } if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; }; 'use strict'; // do not edit .js files directly - edit src/index.jst module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; }; { "name": "fast-deep-equal", "version": "3.1.3", "description": "Fast deep equal", "main": "index.js", "repository": { "type": "git", "url": "git+https://github.com/epoberezkin/fast-deep-equal.git" }, "author": "Evgeny Poberezkin", "license": "MIT", "homepage": "https://github.com/epoberezkin/fast-deep-equal#readme", "devDependencies": { "coveralls": "^3.1.0", "dot": "^1.1.2", "eslint": "^7.2.0", "mocha": "^7.2.0", "nyc": "^15.1.0", "pre-commit": "^1.2.2", "react": "^16.12.0", "react-test-renderer": "^16.12.0", "sinon": "^9.0.2", "typescript": "^3.9.5" }, "files": [ "index.js", "index.d.ts", "react.js", "react.d.ts", "es6/" ], "types": "index.d.ts" }'use strict'; // do not edit .js files directly - edit src/index.jst module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (key === '_owner' && a.$$typeof) { // React-specific: avoid traversing React elements' _owner. // _owner contains circular references // and is not needed when comparing the actual elements (and not their owners) continue; } if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; }; Copyright (c) 2011-2021, Gary Court until https://github.com/garycourt/uri-js/commit/a1acf730b4bba3f1097c9f52e7d9d3aba8cdcaae Copyright (c) 2021-present The Fastify team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * The complete list of contributors can be found at: - https://github.com/garycourt/uri-js/graphs/contributorsimport { Bench } from 'tinybench' import { fastUri } from '../index.js' import { parse as uriJsParse, serialize as uriJsSerialize, resolve as uriJsResolve, equal as uriJsEqual } from 'uri-js' const base = 'uri://a/b/c/d;p?q' const domain = 'https://example.com/foo#bar$fiz' const ipv4 = '//10.10.10.10' const ipv6 = '//[2001:db8::7]' const urn = 'urn:foo:a123,456' const urnuuid = 'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6' const urnuuidComponent = { scheme: 'urn', nid: 'uuid', uuid: 'f81d4fae-7dec-11d0-a765-00a0c91e6bf6' } const { parse: fastUriParse, serialize: fastUriSerialize, resolve: fastUriResolve, equal: fastUriEqual, } = fastUri // Initialization as there is a lot to parse at first // eg: regexes fastUriParse(domain) uriJsParse(domain) const benchFastUri = new Bench({ name: 'fast-uri benchmark' }) const benchUriJs = new Bench({ name: 'uri-js benchmark' }) const benchWHATWG = new Bench({ name: 'WHATWG URL benchmark' }) benchFastUri.add('fast-uri: parse domain', function () { fastUriParse(domain) }) benchUriJs.add('urijs: parse domain', function () { uriJsParse(domain) }) benchWHATWG.add('WHATWG URL: parse domain', function () { // eslint-disable-next-line new URL(domain) }) benchFastUri.add('fast-uri: parse IPv4', function () { fastUriParse(ipv4) }) benchUriJs.add('urijs: parse IPv4', function () { uriJsParse(ipv4) }) benchFastUri.add('fast-uri: parse IPv6', function () { fastUriParse(ipv6) }) benchUriJs.add('urijs: parse IPv6', function () { uriJsParse(ipv6) }) benchFastUri.add('fast-uri: parse URN', function () { fastUriParse(urn) }) benchUriJs.add('urijs: parse URN', function () { uriJsParse(urn) }) benchWHATWG.add('WHATWG URL: parse URN', function () { // eslint-disable-next-line new URL(urn) }) benchFastUri.add('fast-uri: parse URN uuid', function () { fastUriParse(urnuuid) }) benchUriJs.add('urijs: parse URN uuid', function () { uriJsParse(urnuuid) }) benchFastUri.add('fast-uri: serialize URN uuid', function () { fastUriSerialize(urnuuidComponent) }) benchUriJs.add('uri-js: serialize URN uuid', function () { uriJsSerialize(urnuuidComponent) }) benchFastUri.add('fast-uri: serialize uri', function () { fastUriSerialize({ scheme: 'uri', userinfo: 'foo:bar', host: 'example.com', port: 1, path: 'path', query: 'query', fragment: 'fragment' }) }) benchUriJs.add('urijs: serialize uri', function () { uriJsSerialize({ scheme: 'uri', userinfo: 'foo:bar', host: 'example.com', port: 1, path: 'path', query: 'query', fragment: 'fragment' }) }) benchFastUri.add('fast-uri: serialize long uri with dots', function () { fastUriSerialize({ scheme: 'uri', userinfo: 'foo:bar', host: 'example.com', port: 1, path: './a/./b/c/../.././d/../e/f/.././/', query: 'query', fragment: 'fragment' }) }) benchUriJs.add('urijs: serialize long uri with dots', function () { uriJsSerialize({ scheme: 'uri', userinfo: 'foo:bar', host: 'example.com', port: 1, path: './a/./b/c/../.././d/../e/f/.././/', query: 'query', fragment: 'fragment' }) }) benchFastUri.add('fast-uri: serialize IPv6', function () { fastUriSerialize({ host: '2606:2800:220:1:248:1893:25c8:1946' }) }) benchUriJs.add('urijs: serialize IPv6', function () { uriJsSerialize({ host: '2606:2800:220:1:248:1893:25c8:1946' }) }) benchFastUri.add('fast-uri: serialize ws', function () { fastUriSerialize({ scheme: 'ws', host: 'example.com', resourceName: '/foo?bar', secure: true }) }) benchUriJs.add('urijs: serialize ws', function () { uriJsSerialize({ scheme: 'ws', host: 'example.com', resourceName: '/foo?bar', secure: true }) }) benchFastUri.add('fast-uri: resolve', function () { fastUriResolve(base, '../../../g') }) benchUriJs.add('urijs: resolve', function () { uriJsResolve(base, '../../../g') }) benchFastUri.add('fast-uri: equal', function () { fastUriEqual('example://a/b/c/%7Bfoo%7D', 'eXAMPLE://a/./b/../b/%63/%7bfoo%7d') }) benchUriJs.add('urijs: equal', function () { uriJsEqual('example://a/b/c/%7Bfoo%7D', 'eXAMPLE://a/./b/../b/%63/%7bfoo%7d') }) await benchFastUri.run() console.log(benchFastUri.name) console.table(benchFastUri.table()) await benchUriJs.run() console.log(benchUriJs.name) console.table(benchUriJs.table()) await benchWHATWG.run() console.log(benchWHATWG.name) console.table(benchWHATWG.table()) import { Bench } from 'tinybench' import { fastUri } from '../index.js' const { equal: fastUriEqual, parse: fastUriParse, } = fastUri const stringA = 'example://a/b/c/%7Bfoo%7D' const stringB = 'eXAMPLE://a/./b/../b/%63/%7bfoo%7d' const componentA = fastUriParse(stringA) const componentB = fastUriParse(stringB) const benchFastUri = new Bench({ name: 'fast-uri equal' }) benchFastUri.add('equal string with string', function () { fastUriEqual(stringA, stringA) }) benchFastUri.add('equal component with component', function () { fastUriEqual(componentA, componentA) }) benchFastUri.add('equal component with string', function () { fastUriEqual(componentA, stringA) }) benchFastUri.add('equal string with component', function () { fastUriEqual(stringA, componentA) }) benchFastUri.add('not equal string with string', function () { fastUriEqual(stringA, stringB) }) benchFastUri.add('not equal component with component', function () { fastUriEqual(componentA, componentB) }) benchFastUri.add('not equal component with string', function () { fastUriEqual(componentA, stringB) }) benchFastUri.add('not equal string with component', function () { fastUriEqual(stringA, componentB) }) await benchFastUri.run() console.log(benchFastUri.name) console.table(benchFastUri.table()) import { Bench } from 'tinybench' import { nonSimpleDomain } from '../lib/utils.js' const benchNonSimpleDomain = new Bench({ name: 'nonSimpleDomain' }) const exampleCom = 'example.com' const exaumlmpleCom = 'exämple.com' const longDomain = 'abc'.repeat(100) + '.com' console.assert(nonSimpleDomain(exampleCom) === false, 'example.com should be a simple domain') console.assert(nonSimpleDomain(exaumlmpleCom) === true, 'exämple.com should not be a simple domain') console.assert(nonSimpleDomain(longDomain) === false, `${longDomain} should be a simple domain?`) benchNonSimpleDomain.add('nonSimpleDomain', function () { nonSimpleDomain(exampleCom) nonSimpleDomain(exaumlmpleCom) nonSimpleDomain(longDomain) }) await benchNonSimpleDomain.run() console.log(benchNonSimpleDomain.name) console.table(benchNonSimpleDomain.table()) { "name": "benchmark", "version": "1.0.0", "description": "", "main": "index.js", "private": true, "author": "", "license": "ISC", "dependencies": { "tinybench": "^5.0.0", "uri-js": "^4.4.1" } }import { Bench } from 'tinybench' import { stringArrayToHexStripped } from '../lib/utils.js' const benchStringArrayToHexStripped = new Bench({ name: 'stringArrayToHexStripped' }) const case1 = ['0', '0', '0', '0'] const case2 = ['0', '0', '0', '1'] const case3 = ['0', '0', '1', '0'] const case4 = ['0', '1', '0', '0'] const case5 = ['1', '0', '0', '0'] const case6 = ['1', '0', '0', '1'] benchStringArrayToHexStripped.add('stringArrayToHexStripped', function () { stringArrayToHexStripped(case1) stringArrayToHexStripped(case2) stringArrayToHexStripped(case3) stringArrayToHexStripped(case4) stringArrayToHexStripped(case5) stringArrayToHexStripped(case6) }) await benchStringArrayToHexStripped.run() console.log(benchStringArrayToHexStripped.name) console.table(benchStringArrayToHexStripped.table()) import { Bench } from 'tinybench' import { wsIsSecure } from '../lib/schemes.js' const benchWsIsSecure = new Bench({ name: 'wsIsSecure' }) const wsComponentAttributeSecureTrue = { scheme: 'ws', secure: true, } const wsComponentAttributeSecureFalse = { scheme: 'ws', secure: false, } const wssComponent = { scheme: 'wss', } const wssComponentMixedCase = { scheme: 'Wss', } const wssComponentUpperCase = { scheme: 'WSS', } const httpComponent = { scheme: 'http', } console.assert(wsIsSecure(wsComponentAttributeSecureTrue) === true, 'wsComponentAttributeSecureTrue should be secure') console.assert(wsIsSecure(wsComponentAttributeSecureFalse) === false, 'wsComponentAttributeSecureFalse should not be secure') console.assert(wsIsSecure(wssComponent) === true, 'wssComponent should be secure') console.assert(wsIsSecure(wssComponentMixedCase) === true, 'wssComponentMixedCase should be secure') console.assert(wsIsSecure(wssComponentUpperCase) === true, 'wssComponentUpperCase should be secure') console.assert(wsIsSecure(httpComponent) === false, 'httpComponent should not be secure') benchWsIsSecure.add(JSON.stringify(wsComponentAttributeSecureFalse), function () { wsIsSecure(wsComponentAttributeSecureFalse) }) benchWsIsSecure.add(JSON.stringify(wsComponentAttributeSecureTrue), function () { wsIsSecure(wsComponentAttributeSecureTrue) }) benchWsIsSecure.add(JSON.stringify(wssComponent), function () { wsIsSecure(wssComponent) }) benchWsIsSecure.add(JSON.stringify(wssComponentMixedCase), function () { wsIsSecure(wssComponentMixedCase) }) benchWsIsSecure.add(JSON.stringify(wssComponentUpperCase), function () { wsIsSecure(wssComponentUpperCase) }) benchWsIsSecure.add(JSON.stringify(httpComponent), function () { wsIsSecure(httpComponent) }) await benchWsIsSecure.run() console.log(benchWsIsSecure.name) console.table(benchWsIsSecure.table()) 'use strict' module.exports = require('neostandard')({ ignores: require('neostandard').resolveIgnoresFromGitignore(), ts: true }) 'use strict' const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils') const { SCHEMES, getSchemeHandler } = require('./lib/schemes') /** * @template {import('./types/index').URIComponent|string} T * @param {T} uri * @param {import('./types/index').Options} [options] * @returns {T} */ function normalize (uri, options) { if (typeof uri === 'string') { uri = /** @type {T} */ (normalizeString(uri, options)) } else if (typeof uri === 'object') { uri = /** @type {T} */ (parse(serialize(uri, options), options)) } return uri } /** * @param {string} baseURI * @param {string} relativeURI * @param {import('./types/index').Options} [options] * @returns {string} */ function resolve (baseURI, relativeURI, options) { const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' } const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true) schemelessOptions.skipEscape = true return serialize(resolved, schemelessOptions) } /** * @param {import ('./types/index').URIComponent} base * @param {import ('./types/index').URIComponent} relative * @param {import('./types/index').Options} [options] * @param {boolean} [skipNormalization=false] * @returns {import ('./types/index').URIComponent} */ function resolveComponent (base, relative, options, skipNormalization) { /** @type {import('./types/index').URIComponent} */ const target = {} if (!skipNormalization) { base = parse(serialize(base, options), options) // normalize base component relative = parse(serialize(relative, options), options) // normalize relative component } options = options || {} if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme // target.authority = relative.authority; target.userinfo = relative.userinfo target.host = relative.host target.port = relative.port target.path = removeDotSegments(relative.path || '') target.query = relative.query } else { if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { // target.authority = relative.authority; target.userinfo = relative.userinfo target.host = relative.host target.port = relative.port target.path = removeDotSegments(relative.path || '') target.query = relative.query } else { if (!relative.path) { target.path = base.path if (relative.query !== undefined) { target.query = relative.query } else { target.query = base.query } } else { if (relative.path[0] === '/') { target.path = removeDotSegments(relative.path) } else { if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { target.path = '/' + relative.path } else if (!base.path) { target.path = relative.path } else { target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path } target.path = removeDotSegments(target.path) } target.query = relative.query } // target.authority = base.authority; target.userinfo = base.userinfo target.host = base.host target.port = base.port } target.scheme = base.scheme } target.fragment = relative.fragment return target } /** * @param {import ('./types/index').URIComponent|string} uriA * @param {import ('./types/index').URIComponent|string} uriB * @param {import ('./types/index').Options} options * @returns {boolean} */ function equal (uriA, uriB, options) { const normalizedA = normalizeComparableURI(uriA, options) const normalizedB = normalizeComparableURI(uriB, options) return normalizedA !== undefined && normalizedB !== undefined && normalizedA.toLowerCase() === normalizedB.toLowerCase() } /** * @param {Readonly} cmpts * @param {import('./types/index').Options} [opts] * @returns {string} */ function serialize (cmpts, opts) { const component = { host: cmpts.host, scheme: cmpts.scheme, userinfo: cmpts.userinfo, port: cmpts.port, path: cmpts.path, query: cmpts.query, nid: cmpts.nid, nss: cmpts.nss, uuid: cmpts.uuid, fragment: cmpts.fragment, reference: cmpts.reference, resourceName: cmpts.resourceName, secure: cmpts.secure, error: '' } const options = Object.assign({}, opts) const uriTokens = [] // find scheme handler const schemeHandler = getSchemeHandler(options.scheme || component.scheme) // perform scheme specific serialization if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options) if (component.path !== undefined) { if (!options.skipEscape) { component.path = escapePreservingEscapes(component.path) if (component.scheme !== undefined) { component.path = component.path.split('%3A').join(':') } } else { component.path = normalizePercentEncoding(component.path) } } if (options.reference !== 'suffix' && component.scheme) { uriTokens.push(component.scheme, ':') } const authority = recomposeAuthority(component) if (authority !== undefined) { if (options.reference !== 'suffix') { uriTokens.push('//') } uriTokens.push(authority) if (component.path && component.path[0] !== '/') { uriTokens.push('/') } } if (component.path !== undefined) { let s = component.path if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { s = removeDotSegments(s) } if ( authority === undefined && s[0] === '/' && s[1] === '/' ) { // don't allow the path to start with "//" s = '/%2F' + s.slice(2) } uriTokens.push(s) } if (component.query !== undefined) { uriTokens.push('?', component.query) } if (component.fragment !== undefined) { uriTokens.push('#', component.fragment) } return uriTokens.join('') } const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u /** * @param {import('./types/index').URIComponent} parsed * @param {RegExpMatchArray} matches * @returns {string|undefined} */ function getParseError (parsed, matches) { if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') { return 'URI path must start with "/" when authority is present.' } if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) { return 'URI port is malformed.' } return undefined } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean }} */ function parseWithStatus (uri, opts) { const options = Object.assign({}, opts) /** @type {import('./types/index').URIComponent} */ const parsed = { scheme: undefined, userinfo: undefined, host: '', port: undefined, path: '', query: undefined, fragment: undefined } let malformedAuthorityOrPort = false let isIP = false if (options.reference === 'suffix') { if (options.scheme) { uri = options.scheme + ':' + uri } else { uri = '//' + uri } } const matches = uri.match(URI_PARSE) if (matches) { // store each component parsed.scheme = matches[1] parsed.userinfo = matches[3] parsed.host = matches[4] parsed.port = parseInt(matches[5], 10) parsed.path = matches[6] || '' parsed.query = matches[7] parsed.fragment = matches[8] // fix port number if (isNaN(parsed.port)) { parsed.port = matches[5] } const parseError = getParseError(parsed, matches) if (parseError !== undefined) { parsed.error = parsed.error || parseError malformedAuthorityOrPort = true } if (parsed.host) { const ipv4result = isIPv4(parsed.host) if (ipv4result === false) { const ipv6result = normalizeIPv6(parsed.host) parsed.host = ipv6result.host.toLowerCase() isIP = ipv6result.isIPV6 } else { isIP = true } } if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) { parsed.reference = 'same-document' } else if (parsed.scheme === undefined) { parsed.reference = 'relative' } else if (parsed.fragment === undefined) { parsed.reference = 'absolute' } else { parsed.reference = 'uri' } // check for reference errors if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) { parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.' } // find scheme handler const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme) // check if scheme can't handle IRIs if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { // if host component is a domain name if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) { // convert Unicode IDN -> ASCII IDN try { parsed.host = URL.domainToASCII(parsed.host.toLowerCase()) } catch (e) { parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e } } // convert IRI -> URI } if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) { if (uri.indexOf('%') !== -1) { if (parsed.scheme !== undefined) { parsed.scheme = unescape(parsed.scheme) } if (parsed.host !== undefined) { parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP) } } if (parsed.path) { parsed.path = normalizePathEncoding(parsed.path) } if (parsed.fragment) { try { parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)) } catch { parsed.error = parsed.error || 'URI malformed' } } } // perform scheme specific parsing if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(parsed, options) } } else { parsed.error = parsed.error || 'URI can not be parsed.' } return { parsed, malformedAuthorityOrPort } } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns */ function parse (uri, opts) { return parseWithStatus(uri, opts).parsed } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns {string} */ function normalizeString (uri, opts) { return normalizeStringWithStatus(uri, opts).normalized } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns {{ normalized: string, malformedAuthorityOrPort: boolean }} */ function normalizeStringWithStatus (uri, opts) { const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts) return { normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts), malformedAuthorityOrPort } } /** * @param {import ('./types/index').URIComponent|string} uri * @param {import('./types/index').Options} [opts] * @returns {string|undefined} */ function normalizeComparableURI (uri, opts) { if (typeof uri === 'string') { const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts) return malformedAuthorityOrPort ? undefined : normalized } if (typeof uri === 'object') { return serialize(uri, opts) } } const fastUri = { SCHEMES, normalize, resolve, resolveComponent, equal, serialize, parse } module.exports = fastUri module.exports.default = fastUri module.exports.fastUri = fastUri 'use strict' const { isUUID } = require('./utils') const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu const supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws', 'wss', 'urn', 'urn:uuid']) /** @typedef {supportedSchemeNames[number]} SchemeName */ /** * @param {string} name * @returns {name is SchemeName} */ function isValidSchemeName (name) { return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1 } /** * @callback SchemeFn * @param {import('../types/index').URIComponent} component * @param {import('../types/index').Options} options * @returns {import('../types/index').URIComponent} */ /** * @typedef {Object} SchemeHandler * @property {SchemeName} scheme - The scheme name. * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. * @property {SchemeFn} parse - Function to parse the URI component for this scheme. * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. */ /** * @param {import('../types/index').URIComponent} wsComponent * @returns {boolean} */ function wsIsSecure (wsComponent) { if (wsComponent.secure === true) { return true } else if (wsComponent.secure === false) { return false } else if (wsComponent.scheme) { return ( wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') && (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') && (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S') ) } else { return false } } /** @type {SchemeFn} */ function httpParse (component) { if (!component.host) { component.error = component.error || 'HTTP URIs must have a host.' } return component } /** @type {SchemeFn} */ function httpSerialize (component) { const secure = String(component.scheme).toLowerCase() === 'https' // normalize the default port if (component.port === (secure ? 443 : 80) || component.port === '') { component.port = undefined } // normalize the empty path if (!component.path) { component.path = '/' } // NOTE: We do not parse query strings for HTTP URIs // as WWW Form Url Encoded query strings are part of the HTML4+ spec, // and not the HTTP spec. return component } /** @type {SchemeFn} */ function wsParse (wsComponent) { // indicate if the secure flag is set wsComponent.secure = wsIsSecure(wsComponent) // construct resouce name wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '') wsComponent.path = undefined wsComponent.query = undefined return wsComponent } /** @type {SchemeFn} */ function wsSerialize (wsComponent) { // normalize the default port if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') { wsComponent.port = undefined } // ensure scheme matches secure flag if (typeof wsComponent.secure === 'boolean') { wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws') wsComponent.secure = undefined } // reconstruct path from resource name if (wsComponent.resourceName) { const [path, query] = wsComponent.resourceName.split('?') wsComponent.path = (path && path !== '/' ? path : undefined) wsComponent.query = query wsComponent.resourceName = undefined } // forbid fragment component wsComponent.fragment = undefined return wsComponent } /** @type {SchemeFn} */ function urnParse (urnComponent, options) { if (!urnComponent.path) { urnComponent.error = 'URN can not be parsed' return urnComponent } const matches = urnComponent.path.match(URN_REG) if (matches) { const scheme = options.scheme || urnComponent.scheme || 'urn' urnComponent.nid = matches[1].toLowerCase() urnComponent.nss = matches[2] const urnScheme = `${scheme}:${options.nid || urnComponent.nid}` const schemeHandler = getSchemeHandler(urnScheme) urnComponent.path = undefined if (schemeHandler) { urnComponent = schemeHandler.parse(urnComponent, options) } } else { urnComponent.error = urnComponent.error || 'URN can not be parsed.' } return urnComponent } /** @type {SchemeFn} */ function urnSerialize (urnComponent, options) { if (urnComponent.nid === undefined) { throw new Error('URN without nid cannot be serialized') } const scheme = options.scheme || urnComponent.scheme || 'urn' const nid = urnComponent.nid.toLowerCase() const urnScheme = `${scheme}:${options.nid || nid}` const schemeHandler = getSchemeHandler(urnScheme) if (schemeHandler) { urnComponent = schemeHandler.serialize(urnComponent, options) } const uriComponent = urnComponent const nss = urnComponent.nss uriComponent.path = `${nid || options.nid}:${nss}` options.skipEscape = true return uriComponent } /** @type {SchemeFn} */ function urnuuidParse (urnComponent, options) { const uuidComponent = urnComponent uuidComponent.uuid = uuidComponent.nss uuidComponent.nss = undefined if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { uuidComponent.error = uuidComponent.error || 'UUID is not valid.' } return uuidComponent } /** @type {SchemeFn} */ function urnuuidSerialize (uuidComponent) { const urnComponent = uuidComponent // normalize UUID urnComponent.nss = (uuidComponent.uuid || '').toLowerCase() return urnComponent } const http = /** @type {SchemeHandler} */ ({ scheme: 'http', domainHost: true, parse: httpParse, serialize: httpSerialize }) const https = /** @type {SchemeHandler} */ ({ scheme: 'https', domainHost: http.domainHost, parse: httpParse, serialize: httpSerialize }) const ws = /** @type {SchemeHandler} */ ({ scheme: 'ws', domainHost: true, parse: wsParse, serialize: wsSerialize }) const wss = /** @type {SchemeHandler} */ ({ scheme: 'wss', domainHost: ws.domainHost, parse: ws.parse, serialize: ws.serialize }) const urn = /** @type {SchemeHandler} */ ({ scheme: 'urn', parse: urnParse, serialize: urnSerialize, skipNormalize: true }) const urnuuid = /** @type {SchemeHandler} */ ({ scheme: 'urn:uuid', parse: urnuuidParse, serialize: urnuuidSerialize, skipNormalize: true }) const SCHEMES = /** @type {Record} */ ({ http, https, ws, wss, urn, 'urn:uuid': urnuuid }) Object.setPrototypeOf(SCHEMES, null) /** * @param {string|undefined} scheme * @returns {SchemeHandler|undefined} */ function getSchemeHandler (scheme) { return ( scheme && ( SCHEMES[/** @type {SchemeName} */ (scheme)] || SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())]) ) || undefined } module.exports = { wsIsSecure, SCHEMES, isValidSchemeName, getSchemeHandler, } 'use strict' /** @type {(value: string) => boolean} */ const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu) /** @type {(value: string) => boolean} */ const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u) /** @type {(value: string) => boolean} */ const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu) /** @type {(value: string) => boolean} */ const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu) /** @type {(value: string) => boolean} */ const isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu) /** * @param {Array} input * @returns {string} */ function stringArrayToHexStripped (input) { let acc = '' let code = 0 let i = 0 for (i = 0; i < input.length; i++) { code = input[i].charCodeAt(0) if (code === 48) { continue } if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) { return '' } acc += input[i] break } for (i += 1; i < input.length; i++) { code = input[i].charCodeAt(0) if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) { return '' } acc += input[i] } return acc } /** * @typedef {Object} GetIPV6Result * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. * @property {string} address - The parsed IPv6 address. * @property {string} [zone] - The zone identifier, if present. */ /** * @param {string} value * @returns {boolean} */ const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u) /** * @param {Array} buffer * @returns {boolean} */ function consumeIsZone (buffer) { buffer.length = 0 return true } /** * @param {Array} buffer * @param {Array} address * @param {GetIPV6Result} output * @returns {boolean} */ function consumeHextets (buffer, address, output) { if (buffer.length) { const hex = stringArrayToHexStripped(buffer) if (hex !== '') { address.push(hex) } else { output.error = true return false } buffer.length = 0 } return true } /** * @param {string} input * @returns {GetIPV6Result} */ function getIPV6 (input) { let tokenCount = 0 const output = { error: false, address: '', zone: '' } /** @type {Array} */ const address = [] /** @type {Array} */ const buffer = [] let endipv6Encountered = false let endIpv6 = false let consume = consumeHextets for (let i = 0; i < input.length; i++) { const cursor = input[i] if (cursor === '[' || cursor === ']') { continue } if (cursor === ':') { if (endipv6Encountered === true) { endIpv6 = true } if (!consume(buffer, address, output)) { break } if (++tokenCount > 7) { // not valid output.error = true break } if (i > 0 && input[i - 1] === ':') { endipv6Encountered = true } address.push(':') continue } else if (cursor === '%') { if (!consume(buffer, address, output)) { break } // switch to zone detection consume = consumeIsZone } else { buffer.push(cursor) continue } } if (buffer.length) { if (consume === consumeIsZone) { output.zone = buffer.join('') } else if (endIpv6) { address.push(buffer.join('')) } else { address.push(stringArrayToHexStripped(buffer)) } } output.address = address.join('') return output } /** * @typedef {Object} NormalizeIPv6Result * @property {string} host - The normalized host. * @property {string} [escapedHost] - The escaped host. * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. */ /** * @param {string} host * @returns {NormalizeIPv6Result} */ function normalizeIPv6 (host) { if (findToken(host, ':') < 2) { return { host, isIPV6: false } } const ipv6 = getIPV6(host) if (!ipv6.error) { let newHost = ipv6.address let escapedHost = ipv6.address if (ipv6.zone) { newHost += '%' + ipv6.zone escapedHost += '%25' + ipv6.zone } return { host: newHost, isIPV6: true, escapedHost } } else { return { host, isIPV6: false } } } /** * @param {string} str * @param {string} token * @returns {number} */ function findToken (str, token) { let ind = 0 for (let i = 0; i < str.length; i++) { if (str[i] === token) ind++ } return ind } /** * @param {string} path * @returns {string} * * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 */ function removeDotSegments (path) { let input = path const output = [] let nextSlash = -1 let len = 0 // eslint-disable-next-line no-cond-assign while (len = input.length) { if (len === 1) { if (input === '.') { break } else if (input === '/') { output.push('/') break } else { output.push(input) break } } else if (len === 2) { if (input[0] === '.') { if (input[1] === '.') { break } else if (input[1] === '/') { input = input.slice(2) continue } } else if (input[0] === '/') { if (input[1] === '.' || input[1] === '/') { output.push('/') break } } } else if (len === 3) { if (input === '/..') { if (output.length !== 0) { output.pop() } output.push('/') break } } if (input[0] === '.') { if (input[1] === '.') { if (input[2] === '/') { input = input.slice(3) continue } } else if (input[1] === '/') { input = input.slice(2) continue } } else if (input[0] === '/') { if (input[1] === '.') { if (input[2] === '/') { input = input.slice(2) continue } else if (input[2] === '.') { if (input[3] === '/') { input = input.slice(3) if (output.length !== 0) { output.pop() } continue } } } } // Rule 2E: Move normal path segment to output if ((nextSlash = input.indexOf('/', 1)) === -1) { output.push(input) break } else { output.push(input.slice(0, nextSlash)) input = input.slice(nextSlash) } } return output.join('') } /** * Re-escape RFC 3986 gen-delims that must not appear literally in the host. * After the URI regex parses, these characters cannot be literal in the host * field, so any that appear after decoding came from percent-encoding and * must be restored to prevent authority structure changes. * * @param {string} host * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping) * @returns {string} */ const HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' } const HOST_DELIM_RE = /[@/?#:]/g const HOST_DELIM_NO_COLON_RE = /[@/?#]/g function reescapeHostDelimiters (host, isIP) { const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE re.lastIndex = 0 return host.replace(re, (ch) => HOST_DELIMS[ch]) } /** * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes. * Reserved delimiters such as `%2F` and `%2E` stay escaped. * * @param {string} input * @param {boolean} [decodeUnreserved=false] * @returns {string} */ function normalizePercentEncoding (input, decodeUnreserved = false) { if (input.indexOf('%') === -1) { return input } let output = '' for (let i = 0; i < input.length; i++) { if (input[i] === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { const normalizedHex = hex.toUpperCase() const decoded = String.fromCharCode(parseInt(normalizedHex, 16)) if (decodeUnreserved && isUnreserved(decoded)) { output += decoded } else { output += '%' + normalizedHex } i += 2 continue } } output += input[i] } return output } /** * Normalizes path data without turning reserved escapes into live path syntax. * Valid escapes are uppercased, raw unsafe characters are escaped, and only * unreserved bytes that are not `.` are decoded. * * @param {string} input * @returns {string} */ function normalizePathEncoding (input) { let output = '' for (let i = 0; i < input.length; i++) { if (input[i] === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { const normalizedHex = hex.toUpperCase() const decoded = String.fromCharCode(parseInt(normalizedHex, 16)) if (decoded !== '.' && isUnreserved(decoded)) { output += decoded } else { output += '%' + normalizedHex } i += 2 continue } } if (isPathCharacter(input[i])) { output += input[i] } else { output += escape(input[i]) } } return output } /** * Escapes a component while preserving existing valid percent escapes. * * @param {string} input * @returns {string} */ function escapePreservingEscapes (input) { let output = '' for (let i = 0; i < input.length; i++) { if (input[i] === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { output += '%' + hex.toUpperCase() i += 2 continue } } output += escape(input[i]) } return output } /** * @param {import('../types/index').URIComponent} component * @returns {string|undefined} */ function recomposeAuthority (component) { const uriTokens = [] if (component.userinfo !== undefined) { uriTokens.push(component.userinfo) uriTokens.push('@') } if (component.host !== undefined) { let host = unescape(component.host) if (!isIPv4(host)) { const ipV6res = normalizeIPv6(host) if (ipV6res.isIPV6 === true) { host = `[${ipV6res.escapedHost}]` } else { host = reescapeHostDelimiters(host, false) } } uriTokens.push(host) } if (typeof component.port === 'number' || typeof component.port === 'string') { uriTokens.push(':') uriTokens.push(String(component.port)) } return uriTokens.length ? uriTokens.join('') : undefined }; module.exports = { nonSimpleDomain, recomposeAuthority, reescapeHostDelimiters, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, removeDotSegments, isIPv4, isUUID, normalizeIPv6, stringArrayToHexStripped } { "name": "fast-uri", "description": "Dependency-free RFC 3986 URI toolbox", "version": "3.1.2", "main": "index.js", "type": "commonjs", "types": "types/index.d.ts", "license": "BSD-3-Clause", "author": "Vincent Le Goff (https://github.com/zekth)", "repository": { "type": "git", "url": "git+https://github.com/fastify/fast-uri.git" }, "homepage": "https://github.com/fastify/fast-uri", "funding": [ { "type": "github", "url": "https://github.com/sponsors/fastify" }, { "type": "opencollective", "url": "https://opencollective.com/fastify" } ], "devDependencies": { "ajv": "^8.16.0", "eslint": "^9.17.0", "neostandard": "^0.13.0", "playwright-test": "^14.1.12", "tape": "^5.8.1", "tsd": "^0.33.0" } }{ "compilerOptions": { "allowJs": true, "checkJs": true, "strict": true, "noImplicitAny": true, "target": "es2015" } }import uri, { URIComponents, URIComponent, Options, options } from '..' import { expectDeprecated, expectType } from 'tsd' const parsed = uri.parse('foo') expectType(parsed) const parsed2 = uri.parse('foo', { domainHost: true, scheme: 'https', unicodeSupport: false }) expectType(parsed2) expectType({} as URIComponents) expectDeprecated({} as URIComponents) expectType({} as options) expectDeprecated({} as options) (The MIT License) Copyright (c) 2011-2017 JP Richardson 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. 'use strict' const fs = require('graceful-fs') const path = require('path') const mkdirsSync = require('../mkdirs').mkdirsSync const utimesMillisSync = require('../util/utimes').utimesMillisSync const stat = require('../util/stat') function copySync (src, dest, opts) { if (typeof opts === 'function') { opts = { filter: opts } } opts = opts || {} opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { process.emitWarning( 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', 'Warning', 'fs-extra-WARN0002' ) } const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts) stat.checkParentPathsSync(src, srcStat, dest, 'copy') return handleFilterAndCopy(destStat, src, dest, opts) } function handleFilterAndCopy (destStat, src, dest, opts) { if (opts.filter && !opts.filter(src, dest)) return const destParent = path.dirname(dest) if (!fs.existsSync(destParent)) mkdirsSync(destParent) return getStats(destStat, src, dest, opts) } function startCopy (destStat, src, dest, opts) { if (opts.filter && !opts.filter(src, dest)) return return getStats(destStat, src, dest, opts) } function getStats (destStat, src, dest, opts) { const statSync = opts.dereference ? fs.statSync : fs.lstatSync const srcStat = statSync(src) if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) throw new Error(`Unknown file: ${src}`) } function onFile (srcStat, destStat, src, dest, opts) { if (!destStat) return copyFile(srcStat, src, dest, opts) return mayCopyFile(srcStat, src, dest, opts) } function mayCopyFile (srcStat, src, dest, opts) { if (opts.overwrite) { fs.unlinkSync(dest) return copyFile(srcStat, src, dest, opts) } else if (opts.errorOnExist) { throw new Error(`'${dest}' already exists`) } } function copyFile (srcStat, src, dest, opts) { fs.copyFileSync(src, dest) if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) return setDestMode(dest, srcStat.mode) } function handleTimestamps (srcMode, src, dest) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) return setDestTimestamps(src, dest) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode) { return setDestMode(dest, srcMode | 0o200) } function setDestMode (dest, srcMode) { return fs.chmodSync(dest, srcMode) } function setDestTimestamps (src, dest) { // The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) const updatedSrcStat = fs.statSync(src) return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) } function onDir (srcStat, destStat, src, dest, opts) { if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) return copyDir(src, dest, opts) } function mkDirAndCopy (srcMode, src, dest, opts) { fs.mkdirSync(dest) copyDir(src, dest, opts) return setDestMode(dest, srcMode) } function copyDir (src, dest, opts) { fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) } function copyDirItem (item, src, dest, opts) { const srcItem = path.join(src, item) const destItem = path.join(dest, item) const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts) return startCopy(destStat, srcItem, destItem, opts) } function onLink (destStat, src, dest, opts) { let resolvedSrc = fs.readlinkSync(src) if (opts.dereference) { resolvedSrc = path.resolve(process.cwd(), resolvedSrc) } if (!destStat) { return fs.symlinkSync(resolvedSrc, dest) } else { let resolvedDest try { resolvedDest = fs.readlinkSync(dest) } catch (err) { // dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) throw err } if (opts.dereference) { resolvedDest = path.resolve(process.cwd(), resolvedDest) } if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) } // prevent copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) } return copyLink(resolvedSrc, dest) } } function copyLink (resolvedSrc, dest) { fs.unlinkSync(dest) return fs.symlinkSync(resolvedSrc, dest) } module.exports = copySync 'use strict' const fs = require('graceful-fs') const path = require('path') const mkdirs = require('../mkdirs').mkdirs const pathExists = require('../path-exists').pathExists const utimesMillis = require('../util/utimes').utimesMillis const stat = require('../util/stat') function copy (src, dest, opts, cb) { if (typeof opts === 'function' && !cb) { cb = opts opts = {} } else if (typeof opts === 'function') { opts = { filter: opts } } cb = cb || function () {} opts = opts || {} opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { process.emitWarning( 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', 'Warning', 'fs-extra-WARN0001' ) } stat.checkPaths(src, dest, 'copy', opts, (err, stats) => { if (err) return cb(err) const { srcStat, destStat } = stats stat.checkParentPaths(src, srcStat, dest, 'copy', err => { if (err) return cb(err) if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) return checkParentDir(destStat, src, dest, opts, cb) }) }) } function checkParentDir (destStat, src, dest, opts, cb) { const destParent = path.dirname(dest) pathExists(destParent, (err, dirExists) => { if (err) return cb(err) if (dirExists) return getStats(destStat, src, dest, opts, cb) mkdirs(destParent, err => { if (err) return cb(err) return getStats(destStat, src, dest, opts, cb) }) }) } function handleFilter (onInclude, destStat, src, dest, opts, cb) { Promise.resolve(opts.filter(src, dest)).then(include => { if (include) return onInclude(destStat, src, dest, opts, cb) return cb() }, error => cb(error)) } function startCopy (destStat, src, dest, opts, cb) { if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) return getStats(destStat, src, dest, opts, cb) } function getStats (destStat, src, dest, opts, cb) { const stat = opts.dereference ? fs.stat : fs.lstat stat(src, (err, srcStat) => { if (err) return cb(err) if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) else if (srcStat.isSocket()) return cb(new Error(`Cannot copy a socket file: ${src}`)) else if (srcStat.isFIFO()) return cb(new Error(`Cannot copy a FIFO pipe: ${src}`)) return cb(new Error(`Unknown file: ${src}`)) }) } function onFile (srcStat, destStat, src, dest, opts, cb) { if (!destStat) return copyFile(srcStat, src, dest, opts, cb) return mayCopyFile(srcStat, src, dest, opts, cb) } function mayCopyFile (srcStat, src, dest, opts, cb) { if (opts.overwrite) { fs.unlink(dest, err => { if (err) return cb(err) return copyFile(srcStat, src, dest, opts, cb) }) } else if (opts.errorOnExist) { return cb(new Error(`'${dest}' already exists`)) } else return cb() } function copyFile (srcStat, src, dest, opts, cb) { fs.copyFile(src, dest, err => { if (err) return cb(err) if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) return setDestMode(dest, srcStat.mode, cb) }) } function handleTimestampsAndMode (srcMode, src, dest, cb) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) { return makeFileWritable(dest, srcMode, err => { if (err) return cb(err) return setDestTimestampsAndMode(srcMode, src, dest, cb) }) } return setDestTimestampsAndMode(srcMode, src, dest, cb) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode, cb) { return setDestMode(dest, srcMode | 0o200, cb) } function setDestTimestampsAndMode (srcMode, src, dest, cb) { setDestTimestamps(src, dest, err => { if (err) return cb(err) return setDestMode(dest, srcMode, cb) }) } function setDestMode (dest, srcMode, cb) { return fs.chmod(dest, srcMode, cb) } function setDestTimestamps (src, dest, cb) { // The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) fs.stat(src, (err, updatedSrcStat) => { if (err) return cb(err) return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) }) } function onDir (srcStat, destStat, src, dest, opts, cb) { if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) return copyDir(src, dest, opts, cb) } function mkDirAndCopy (srcMode, src, dest, opts, cb) { fs.mkdir(dest, err => { if (err) return cb(err) copyDir(src, dest, opts, err => { if (err) return cb(err) return setDestMode(dest, srcMode, cb) }) }) } function copyDir (src, dest, opts, cb) { fs.readdir(src, (err, items) => { if (err) return cb(err) return copyDirItems(items, src, dest, opts, cb) }) } function copyDirItems (items, src, dest, opts, cb) { const item = items.pop() if (!item) return cb() return copyDirItem(items, item, src, dest, opts, cb) } function copyDirItem (items, item, src, dest, opts, cb) { const srcItem = path.join(src, item) const destItem = path.join(dest, item) stat.checkPaths(srcItem, destItem, 'copy', opts, (err, stats) => { if (err) return cb(err) const { destStat } = stats startCopy(destStat, srcItem, destItem, opts, err => { if (err) return cb(err) return copyDirItems(items, src, dest, opts, cb) }) }) } function onLink (destStat, src, dest, opts, cb) { fs.readlink(src, (err, resolvedSrc) => { if (err) return cb(err) if (opts.dereference) { resolvedSrc = path.resolve(process.cwd(), resolvedSrc) } if (!destStat) { return fs.symlink(resolvedSrc, dest, cb) } else { fs.readlink(dest, (err, resolvedDest) => { if (err) { // dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) return cb(err) } if (opts.dereference) { resolvedDest = path.resolve(process.cwd(), resolvedDest) } if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) } // do not copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) } return copyLink(resolvedSrc, dest, cb) }) } }) } function copyLink (resolvedSrc, dest, cb) { fs.unlink(dest, err => { if (err) return cb(err) return fs.symlink(resolvedSrc, dest, cb) }) } module.exports = copy 'use strict' const u = require('universalify').fromCallback module.exports = { copy: u(require('./copy')), copySync: require('./copy-sync') } 'use strict' const u = require('universalify').fromPromise const fs = require('../fs') const path = require('path') const mkdir = require('../mkdirs') const remove = require('../remove') const emptyDir = u(async function emptyDir (dir) { let items try { items = await fs.readdir(dir) } catch { return mkdir.mkdirs(dir) } return Promise.all(items.map(item => remove.remove(path.join(dir, item)))) }) function emptyDirSync (dir) { let items try { items = fs.readdirSync(dir) } catch { return mkdir.mkdirsSync(dir) } items.forEach(item => { item = path.join(dir, item) remove.removeSync(item) }) } module.exports = { emptyDirSync, emptydirSync: emptyDirSync, emptyDir, emptydir: emptyDir } 'use strict' const u = require('universalify').fromCallback const path = require('path') const fs = require('graceful-fs') const mkdir = require('../mkdirs') function createFile (file, callback) { function makeFile () { fs.writeFile(file, '', err => { if (err) return callback(err) callback() }) } fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err if (!err && stats.isFile()) return callback() const dir = path.dirname(file) fs.stat(dir, (err, stats) => { if (err) { // if the directory doesn't exist, make it if (err.code === 'ENOENT') { return mkdir.mkdirs(dir, err => { if (err) return callback(err) makeFile() }) } return callback(err) } if (stats.isDirectory()) makeFile() else { // parent is not a directory // This is just to cause an internal ENOTDIR error to be thrown fs.readdir(dir, err => { if (err) return callback(err) }) } }) }) } function createFileSync (file) { let stats try { stats = fs.statSync(file) } catch {} if (stats && stats.isFile()) return const dir = path.dirname(file) try { if (!fs.statSync(dir).isDirectory()) { // parent is not a directory // This is just to cause an internal ENOTDIR error to be thrown fs.readdirSync(dir) } } catch (err) { // If the stat call above failed because the directory doesn't exist, create it if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) else throw err } fs.writeFileSync(file, '') } module.exports = { createFile: u(createFile), createFileSync } 'use strict' const { createFile, createFileSync } = require('./file') const { createLink, createLinkSync } = require('./link') const { createSymlink, createSymlinkSync } = require('./symlink') module.exports = { // file createFile, createFileSync, ensureFile: createFile, ensureFileSync: createFileSync, // link createLink, createLinkSync, ensureLink: createLink, ensureLinkSync: createLinkSync, // symlink createSymlink, createSymlinkSync, ensureSymlink: createSymlink, ensureSymlinkSync: createSymlinkSync } 'use strict' const u = require('universalify').fromCallback const path = require('path') const fs = require('graceful-fs') const mkdir = require('../mkdirs') const pathExists = require('../path-exists').pathExists const { areIdentical } = require('../util/stat') function createLink (srcpath, dstpath, callback) { function makeLink (srcpath, dstpath) { fs.link(srcpath, dstpath, err => { if (err) return callback(err) callback(null) }) } fs.lstat(dstpath, (_, dstStat) => { fs.lstat(srcpath, (err, srcStat) => { if (err) { err.message = err.message.replace('lstat', 'ensureLink') return callback(err) } if (dstStat && areIdentical(srcStat, dstStat)) return callback(null) const dir = path.dirname(dstpath) pathExists(dir, (err, dirExists) => { if (err) return callback(err) if (dirExists) return makeLink(srcpath, dstpath) mkdir.mkdirs(dir, err => { if (err) return callback(err) makeLink(srcpath, dstpath) }) }) }) }) } function createLinkSync (srcpath, dstpath) { let dstStat try { dstStat = fs.lstatSync(dstpath) } catch {} try { const srcStat = fs.lstatSync(srcpath) if (dstStat && areIdentical(srcStat, dstStat)) return } catch (err) { err.message = err.message.replace('lstat', 'ensureLink') throw err } const dir = path.dirname(dstpath) const dirExists = fs.existsSync(dir) if (dirExists) return fs.linkSync(srcpath, dstpath) mkdir.mkdirsSync(dir) return fs.linkSync(srcpath, dstpath) } module.exports = { createLink: u(createLink), createLinkSync } 'use strict' const path = require('path') const fs = require('graceful-fs') const pathExists = require('../path-exists').pathExists /** * Function that returns two types of paths, one relative to symlink, and one * relative to the current working directory. Checks if path is absolute or * relative. If the path is relative, this function checks if the path is * relative to symlink or relative to current working directory. This is an * initiative to find a smarter `srcpath` to supply when building symlinks. * This allows you to determine which path to use out of one of three possible * types of source paths. The first is an absolute path. This is detected by * `path.isAbsolute()`. When an absolute path is provided, it is checked to * see if it exists. If it does it's used, if not an error is returned * (callback)/ thrown (sync). The other two options for `srcpath` are a * relative url. By default Node's `fs.symlink` works by creating a symlink * using `dstpath` and expects the `srcpath` to be relative to the newly * created symlink. If you provide a `srcpath` that does not exist on the file * system it results in a broken symlink. To minimize this, the function * checks to see if the 'relative to symlink' source file exists, and if it * does it will use it. If it does not, it checks if there's a file that * exists that is relative to the current working directory, if does its used. * This preserves the expectations of the original fs.symlink spec and adds * the ability to pass in `relative to current working direcotry` paths. */ function symlinkPaths (srcpath, dstpath, callback) { if (path.isAbsolute(srcpath)) { return fs.lstat(srcpath, (err) => { if (err) { err.message = err.message.replace('lstat', 'ensureSymlink') return callback(err) } return callback(null, { toCwd: srcpath, toDst: srcpath }) }) } else { const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) return pathExists(relativeToDst, (err, exists) => { if (err) return callback(err) if (exists) { return callback(null, { toCwd: relativeToDst, toDst: srcpath }) } else { return fs.lstat(srcpath, (err) => { if (err) { err.message = err.message.replace('lstat', 'ensureSymlink') return callback(err) } return callback(null, { toCwd: srcpath, toDst: path.relative(dstdir, srcpath) }) }) } }) } } function symlinkPathsSync (srcpath, dstpath) { let exists if (path.isAbsolute(srcpath)) { exists = fs.existsSync(srcpath) if (!exists) throw new Error('absolute srcpath does not exist') return { toCwd: srcpath, toDst: srcpath } } else { const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) exists = fs.existsSync(relativeToDst) if (exists) { return { toCwd: relativeToDst, toDst: srcpath } } else { exists = fs.existsSync(srcpath) if (!exists) throw new Error('relative srcpath does not exist') return { toCwd: srcpath, toDst: path.relative(dstdir, srcpath) } } } } module.exports = { symlinkPaths, symlinkPathsSync } 'use strict' const fs = require('graceful-fs') function symlinkType (srcpath, type, callback) { callback = (typeof type === 'function') ? type : callback type = (typeof type === 'function') ? false : type if (type) return callback(null, type) fs.lstat(srcpath, (err, stats) => { if (err) return callback(null, 'file') type = (stats && stats.isDirectory()) ? 'dir' : 'file' callback(null, type) }) } function symlinkTypeSync (srcpath, type) { let stats if (type) return type try { stats = fs.lstatSync(srcpath) } catch { return 'file' } return (stats && stats.isDirectory()) ? 'dir' : 'file' } module.exports = { symlinkType, symlinkTypeSync } 'use strict' const u = require('universalify').fromCallback const path = require('path') const fs = require('../fs') const _mkdirs = require('../mkdirs') const mkdirs = _mkdirs.mkdirs const mkdirsSync = _mkdirs.mkdirsSync const _symlinkPaths = require('./symlink-paths') const symlinkPaths = _symlinkPaths.symlinkPaths const symlinkPathsSync = _symlinkPaths.symlinkPathsSync const _symlinkType = require('./symlink-type') const symlinkType = _symlinkType.symlinkType const symlinkTypeSync = _symlinkType.symlinkTypeSync const pathExists = require('../path-exists').pathExists const { areIdentical } = require('../util/stat') function createSymlink (srcpath, dstpath, type, callback) { callback = (typeof type === 'function') ? type : callback type = (typeof type === 'function') ? false : type fs.lstat(dstpath, (err, stats) => { if (!err && stats.isSymbolicLink()) { Promise.all([ fs.stat(srcpath), fs.stat(dstpath) ]).then(([srcStat, dstStat]) => { if (areIdentical(srcStat, dstStat)) return callback(null) _createSymlink(srcpath, dstpath, type, callback) }) } else _createSymlink(srcpath, dstpath, type, callback) }) } function _createSymlink (srcpath, dstpath, type, callback) { symlinkPaths(srcpath, dstpath, (err, relative) => { if (err) return callback(err) srcpath = relative.toDst symlinkType(relative.toCwd, type, (err, type) => { if (err) return callback(err) const dir = path.dirname(dstpath) pathExists(dir, (err, dirExists) => { if (err) return callback(err) if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) mkdirs(dir, err => { if (err) return callback(err) fs.symlink(srcpath, dstpath, type, callback) }) }) }) }) } function createSymlinkSync (srcpath, dstpath, type) { let stats try { stats = fs.lstatSync(dstpath) } catch {} if (stats && stats.isSymbolicLink()) { const srcStat = fs.statSync(srcpath) const dstStat = fs.statSync(dstpath) if (areIdentical(srcStat, dstStat)) return } const relative = symlinkPathsSync(srcpath, dstpath) srcpath = relative.toDst type = symlinkTypeSync(relative.toCwd, type) const dir = path.dirname(dstpath) const exists = fs.existsSync(dir) if (exists) return fs.symlinkSync(srcpath, dstpath, type) mkdirsSync(dir) return fs.symlinkSync(srcpath, dstpath, type) } module.exports = { createSymlink: u(createSymlink), createSymlinkSync } 'use strict' // This is adapted from https://github.com/normalize/mz // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors const u = require('universalify').fromCallback const fs = require('graceful-fs') const api = [ 'access', 'appendFile', 'chmod', 'chown', 'close', 'copyFile', 'fchmod', 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod', 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'opendir', 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rm', 'rmdir', 'stat', 'symlink', 'truncate', 'unlink', 'utimes', 'writeFile' ].filter(key => { // Some commands are not available on some systems. Ex: // fs.opendir was added in Node.js v12.12.0 // fs.rm was added in Node.js v14.14.0 // fs.lchown is not available on at least some Linux return typeof fs[key] === 'function' }) // Export cloned fs: Object.assign(exports, fs) // Universalify async methods: api.forEach(method => { exports[method] = u(fs[method]) }) // We differ from mz/fs in that we still ship the old, broken, fs.exists() // since we are a drop-in replacement for the native module exports.exists = function (filename, callback) { if (typeof callback === 'function') { return fs.exists(filename, callback) } return new Promise(resolve => { return fs.exists(filename, resolve) }) } // fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args exports.read = function (fd, buffer, offset, length, position, callback) { if (typeof callback === 'function') { return fs.read(fd, buffer, offset, length, position, callback) } return new Promise((resolve, reject) => { fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { if (err) return reject(err) resolve({ bytesRead, buffer }) }) }) } // Function signature can be // fs.write(fd, buffer[, offset[, length[, position]]], callback) // OR // fs.write(fd, string[, position[, encoding]], callback) // We need to handle both cases, so we use ...args exports.write = function (fd, buffer, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.write(fd, buffer, ...args) } return new Promise((resolve, reject) => { fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { if (err) return reject(err) resolve({ bytesWritten, buffer }) }) }) } // fs.writev only available in Node v12.9.0+ if (typeof fs.writev === 'function') { // Function signature is // s.writev(fd, buffers[, position], callback) // We need to handle the optional arg, so we use ...args exports.writev = function (fd, buffers, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.writev(fd, buffers, ...args) } return new Promise((resolve, reject) => { fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { if (err) return reject(err) resolve({ bytesWritten, buffers }) }) }) } } // fs.realpath.native sometimes not available if fs is monkey-patched if (typeof fs.realpath.native === 'function') { exports.realpath.native = u(fs.realpath.native) } else { process.emitWarning( 'fs.realpath.native is not a function. Is fs being monkey-patched?', 'Warning', 'fs-extra-WARN0003' ) } 'use strict' module.exports = { // Export promiseified graceful-fs: ...require('./fs'), // Export extra methods: ...require('./copy'), ...require('./empty'), ...require('./ensure'), ...require('./json'), ...require('./mkdirs'), ...require('./move'), ...require('./output-file'), ...require('./path-exists'), ...require('./remove') } 'use strict' const u = require('universalify').fromPromise const jsonFile = require('./jsonfile') jsonFile.outputJson = u(require('./output-json')) jsonFile.outputJsonSync = require('./output-json-sync') // aliases jsonFile.outputJSON = jsonFile.outputJson jsonFile.outputJSONSync = jsonFile.outputJsonSync jsonFile.writeJSON = jsonFile.writeJson jsonFile.writeJSONSync = jsonFile.writeJsonSync jsonFile.readJSON = jsonFile.readJson jsonFile.readJSONSync = jsonFile.readJsonSync module.exports = jsonFile 'use strict' const jsonFile = require('jsonfile') module.exports = { // jsonfile exports readJson: jsonFile.readFile, readJsonSync: jsonFile.readFileSync, writeJson: jsonFile.writeFile, writeJsonSync: jsonFile.writeFileSync } 'use strict' const { stringify } = require('jsonfile/utils') const { outputFileSync } = require('../output-file') function outputJsonSync (file, data, options) { const str = stringify(data, options) outputFileSync(file, str, options) } module.exports = outputJsonSync 'use strict' const { stringify } = require('jsonfile/utils') const { outputFile } = require('../output-file') async function outputJson (file, data, options = {}) { const str = stringify(data, options) await outputFile(file, str, options) } module.exports = outputJson 'use strict' const u = require('universalify').fromPromise const { makeDir: _makeDir, makeDirSync } = require('./make-dir') const makeDir = u(_makeDir) module.exports = { mkdirs: makeDir, mkdirsSync: makeDirSync, // alias mkdirp: makeDir, mkdirpSync: makeDirSync, ensureDir: makeDir, ensureDirSync: makeDirSync } 'use strict' const fs = require('../fs') const { checkPath } = require('./utils') const getMode = options => { const defaults = { mode: 0o777 } if (typeof options === 'number') return options return ({ ...defaults, ...options }).mode } module.exports.makeDir = async (dir, options) => { checkPath(dir) return fs.mkdir(dir, { mode: getMode(options), recursive: true }) } module.exports.makeDirSync = (dir, options) => { checkPath(dir) return fs.mkdirSync(dir, { mode: getMode(options), recursive: true }) } // Adapted from https://github.com/sindresorhus/make-dir // Copyright (c) Sindre Sorhus (sindresorhus.com) // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict' const path = require('path') // https://github.com/nodejs/node/issues/8987 // https://github.com/libuv/libuv/pull/1088 module.exports.checkPath = function checkPath (pth) { if (process.platform === 'win32') { const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) if (pathHasInvalidWinCharacters) { const error = new Error(`Path contains invalid characters: ${pth}`) error.code = 'EINVAL' throw error } } } 'use strict' const u = require('universalify').fromCallback module.exports = { move: u(require('./move')), moveSync: require('./move-sync') } 'use strict' const fs = require('graceful-fs') const path = require('path') const copySync = require('../copy').copySync const removeSync = require('../remove').removeSync const mkdirpSync = require('../mkdirs').mkdirpSync const stat = require('../util/stat') function moveSync (src, dest, opts) { opts = opts || {} const overwrite = opts.overwrite || opts.clobber || false const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts) stat.checkParentPathsSync(src, srcStat, dest, 'move') if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest)) return doRename(src, dest, overwrite, isChangingCase) } function isParentRoot (dest) { const parent = path.dirname(dest) const parsedPath = path.parse(parent) return parsedPath.root === parent } function doRename (src, dest, overwrite, isChangingCase) { if (isChangingCase) return rename(src, dest, overwrite) if (overwrite) { removeSync(dest) return rename(src, dest, overwrite) } if (fs.existsSync(dest)) throw new Error('dest already exists.') return rename(src, dest, overwrite) } function rename (src, dest, overwrite) { try { fs.renameSync(src, dest) } catch (err) { if (err.code !== 'EXDEV') throw err return moveAcrossDevice(src, dest, overwrite) } } function moveAcrossDevice (src, dest, overwrite) { const opts = { overwrite, errorOnExist: true } copySync(src, dest, opts) return removeSync(src) } module.exports = moveSync 'use strict' const fs = require('graceful-fs') const path = require('path') const copy = require('../copy').copy const remove = require('../remove').remove const mkdirp = require('../mkdirs').mkdirp const pathExists = require('../path-exists').pathExists const stat = require('../util/stat') function move (src, dest, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } opts = opts || {} const overwrite = opts.overwrite || opts.clobber || false stat.checkPaths(src, dest, 'move', opts, (err, stats) => { if (err) return cb(err) const { srcStat, isChangingCase = false } = stats stat.checkParentPaths(src, srcStat, dest, 'move', err => { if (err) return cb(err) if (isParentRoot(dest)) return doRename(src, dest, overwrite, isChangingCase, cb) mkdirp(path.dirname(dest), err => { if (err) return cb(err) return doRename(src, dest, overwrite, isChangingCase, cb) }) }) }) } function isParentRoot (dest) { const parent = path.dirname(dest) const parsedPath = path.parse(parent) return parsedPath.root === parent } function doRename (src, dest, overwrite, isChangingCase, cb) { if (isChangingCase) return rename(src, dest, overwrite, cb) if (overwrite) { return remove(dest, err => { if (err) return cb(err) return rename(src, dest, overwrite, cb) }) } pathExists(dest, (err, destExists) => { if (err) return cb(err) if (destExists) return cb(new Error('dest already exists.')) return rename(src, dest, overwrite, cb) }) } function rename (src, dest, overwrite, cb) { fs.rename(src, dest, err => { if (!err) return cb() if (err.code !== 'EXDEV') return cb(err) return moveAcrossDevice(src, dest, overwrite, cb) }) } function moveAcrossDevice (src, dest, overwrite, cb) { const opts = { overwrite, errorOnExist: true } copy(src, dest, opts, err => { if (err) return cb(err) return remove(src, cb) }) } module.exports = move 'use strict' const u = require('universalify').fromCallback const fs = require('graceful-fs') const path = require('path') const mkdir = require('../mkdirs') const pathExists = require('../path-exists').pathExists function outputFile (file, data, encoding, callback) { if (typeof encoding === 'function') { callback = encoding encoding = 'utf8' } const dir = path.dirname(file) pathExists(dir, (err, itDoes) => { if (err) return callback(err) if (itDoes) return fs.writeFile(file, data, encoding, callback) mkdir.mkdirs(dir, err => { if (err) return callback(err) fs.writeFile(file, data, encoding, callback) }) }) } function outputFileSync (file, ...args) { const dir = path.dirname(file) if (fs.existsSync(dir)) { return fs.writeFileSync(file, ...args) } mkdir.mkdirsSync(dir) fs.writeFileSync(file, ...args) } module.exports = { outputFile: u(outputFile), outputFileSync } 'use strict' const u = require('universalify').fromPromise const fs = require('../fs') function pathExists (path) { return fs.access(path).then(() => true).catch(() => false) } module.exports = { pathExists: u(pathExists), pathExistsSync: fs.existsSync } 'use strict' const fs = require('graceful-fs') const u = require('universalify').fromCallback const rimraf = require('./rimraf') function remove (path, callback) { // Node 14.14.0+ if (fs.rm) return fs.rm(path, { recursive: true, force: true }, callback) rimraf(path, callback) } function removeSync (path) { // Node 14.14.0+ if (fs.rmSync) return fs.rmSync(path, { recursive: true, force: true }) rimraf.sync(path) } module.exports = { remove: u(remove), removeSync } 'use strict' const fs = require('graceful-fs') const path = require('path') const assert = require('assert') const isWindows = (process.platform === 'win32') function defaults (options) { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(m => { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 } function rimraf (p, options, cb) { let busyTries = 0 if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') defaults(options) rimraf_(p, options, function CB (er) { if (er) { if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && busyTries < options.maxBusyTries) { busyTries++ const time = busyTries * 100 // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), time) } // already gone if (er.code === 'ENOENT') er = null } cb(er) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === 'ENOENT') { return cb(null) } // Windows can EPERM on stat. Life is suffering. if (er && er.code === 'EPERM' && isWindows) { return fixWinEPERM(p, options, er, cb) } if (st && st.isDirectory()) { return rmdir(p, options, er, cb) } options.unlink(p, er => { if (er) { if (er.code === 'ENOENT') { return cb(null) } if (er.code === 'EPERM') { return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) } if (er.code === 'EISDIR') { return rmdir(p, options, er, cb) } } return cb(er) }) }) } function fixWinEPERM (p, options, er, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.chmod(p, 0o666, er2 => { if (er2) { cb(er2.code === 'ENOENT' ? null : er) } else { options.stat(p, (er3, stats) => { if (er3) { cb(er3.code === 'ENOENT' ? null : er) } else if (stats.isDirectory()) { rmdir(p, options, er, cb) } else { options.unlink(p, cb) } }) } }) } function fixWinEPERMSync (p, options, er) { let stats assert(p) assert(options) try { options.chmodSync(p, 0o666) } catch (er2) { if (er2.code === 'ENOENT') { return } else { throw er } } try { stats = options.statSync(p) } catch (er3) { if (er3.code === 'ENOENT') { return } else { throw er } } if (stats.isDirectory()) { rmdirSync(p, options, er) } else { options.unlinkSync(p) } } function rmdir (p, options, originalEr, cb) { assert(p) assert(options) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { rmkids(p, options, cb) } else if (er && er.code === 'ENOTDIR') { cb(originalEr) } else { cb(er) } }) } function rmkids (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length let errState if (n === 0) return options.rmdir(p, cb) files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) { return } if (er) return cb(errState = er) if (--n === 0) { options.rmdir(p, cb) } }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. function rimrafSync (p, options) { let st options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') try { st = options.lstatSync(p) } catch (er) { if (er.code === 'ENOENT') { return } // Windows can EPERM on stat. Life is suffering. if (er.code === 'EPERM' && isWindows) { fixWinEPERMSync(p, options, er) } } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) { rmdirSync(p, options, null) } else { options.unlinkSync(p) } } catch (er) { if (er.code === 'ENOENT') { return } else if (er.code === 'EPERM') { return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) } else if (er.code !== 'EISDIR') { throw er } rmdirSync(p, options, er) } } function rmdirSync (p, options, originalEr) { assert(p) assert(options) try { options.rmdirSync(p) } catch (er) { if (er.code === 'ENOTDIR') { throw originalEr } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { rmkidsSync(p, options) } else if (er.code !== 'ENOENT') { throw er } } } function rmkidsSync (p, options) { assert(p) assert(options) options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) if (isWindows) { // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const startTime = Date.now() do { try { const ret = options.rmdirSync(p, options) return ret } catch {} } while (Date.now() - startTime < 500) // give up after 500ms } else { const ret = options.rmdirSync(p, options) return ret } } module.exports = rimraf rimraf.sync = rimrafSync 'use strict' const fs = require('../fs') const path = require('path') const util = require('util') function getStats (src, dest, opts) { const statFunc = opts.dereference ? (file) => fs.stat(file, { bigint: true }) : (file) => fs.lstat(file, { bigint: true }) return Promise.all([ statFunc(src), statFunc(dest).catch(err => { if (err.code === 'ENOENT') return null throw err }) ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) } function getStatsSync (src, dest, opts) { let destStat const statFunc = opts.dereference ? (file) => fs.statSync(file, { bigint: true }) : (file) => fs.lstatSync(file, { bigint: true }) const srcStat = statFunc(src) try { destStat = statFunc(dest) } catch (err) { if (err.code === 'ENOENT') return { srcStat, destStat: null } throw err } return { srcStat, destStat } } function checkPaths (src, dest, funcName, opts, cb) { util.callbackify(getStats)(src, dest, opts, (err, stats) => { if (err) return cb(err) const { srcStat, destStat } = stats if (destStat) { if (areIdentical(srcStat, destStat)) { const srcBaseName = path.basename(src) const destBaseName = path.basename(dest) if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return cb(null, { srcStat, destStat, isChangingCase: true }) } return cb(new Error('Source and destination must not be the same.')) } if (srcStat.isDirectory() && !destStat.isDirectory()) { return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) } if (!srcStat.isDirectory() && destStat.isDirectory()) { return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { return cb(new Error(errMsg(src, dest, funcName))) } return cb(null, { srcStat, destStat }) }) } function checkPathsSync (src, dest, funcName, opts) { const { srcStat, destStat } = getStatsSync(src, dest, opts) if (destStat) { if (areIdentical(srcStat, destStat)) { const srcBaseName = path.basename(src) const destBaseName = path.basename(dest) if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return { srcStat, destStat, isChangingCase: true } } throw new Error('Source and destination must not be the same.') } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new Error(errMsg(src, dest, funcName)) } return { srcStat, destStat } } // recursively check if dest parent is a subdirectory of src. // It works for all file types including symlinks since it // checks the src and dest inodes. It starts from the deepest // parent and stops once it reaches the src parent or the root path. function checkParentPaths (src, srcStat, dest, funcName, cb) { const srcParent = path.resolve(path.dirname(src)) const destParent = path.resolve(path.dirname(dest)) if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() fs.stat(destParent, { bigint: true }, (err, destStat) => { if (err) { if (err.code === 'ENOENT') return cb() return cb(err) } if (areIdentical(srcStat, destStat)) { return cb(new Error(errMsg(src, dest, funcName))) } return checkParentPaths(src, srcStat, destParent, funcName, cb) }) } function checkParentPathsSync (src, srcStat, dest, funcName) { const srcParent = path.resolve(path.dirname(src)) const destParent = path.resolve(path.dirname(dest)) if (destParent === srcParent || destParent === path.parse(destParent).root) return let destStat try { destStat = fs.statSync(destParent, { bigint: true }) } catch (err) { if (err.code === 'ENOENT') return throw err } if (areIdentical(srcStat, destStat)) { throw new Error(errMsg(src, dest, funcName)) } return checkParentPathsSync(src, srcStat, destParent, funcName) } function areIdentical (srcStat, destStat) { return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } // return true if dest is a subdir of src, otherwise false. // It only checks the path strings. function isSrcSubdir (src, dest) { const srcArr = path.resolve(src).split(path.sep).filter(i => i) const destArr = path.resolve(dest).split(path.sep).filter(i => i) return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) } function errMsg (src, dest, funcName) { return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` } module.exports = { checkPaths, checkPathsSync, checkParentPaths, checkParentPathsSync, isSrcSubdir, areIdentical } 'use strict' const fs = require('graceful-fs') function utimesMillis (path, atime, mtime, callback) { // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) fs.open(path, 'r+', (err, fd) => { if (err) return callback(err) fs.futimes(fd, atime, mtime, futimesErr => { fs.close(fd, closeErr => { if (callback) callback(futimesErr || closeErr) }) }) }) } function utimesMillisSync (path, atime, mtime) { const fd = fs.openSync(path, 'r+') fs.futimesSync(fd, atime, mtime) return fs.closeSync(fd) } module.exports = { utimesMillis, utimesMillisSync } { "name": "fs-extra", "version": "10.1.0", "description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as recursive mkdir, copy, and remove.", "engines": { "node": ">=12" }, "homepage": "https://github.com/jprichardson/node-fs-extra", "repository": { "type": "git", "url": "https://github.com/jprichardson/node-fs-extra" }, "author": "JP Richardson ", "license": "MIT", "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" }, "devDependencies": { "at-least-node": "^1.0.0", "klaw": "^2.1.1", "klaw-sync": "^3.0.2", "minimist": "^1.1.1", "mocha": "^5.0.5", "nyc": "^15.0.0", "proxyquire": "^2.0.1", "read-dir-files": "^0.1.1", "standard": "^16.0.3" }, "main": "./lib/index.js", "files": [ "lib/", "!lib/**/__tests__/" ], "sideEffects": false }The ISC License Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, 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. 'use strict' module.exports = clone var getPrototypeOf = Object.getPrototypeOf || function (obj) { return obj.__proto__ } function clone (obj) { if (obj === null || typeof obj !== 'object') return obj if (obj instanceof Object) var copy = { __proto__: getPrototypeOf(obj) } else var copy = Object.create(null) Object.getOwnPropertyNames(obj).forEach(function (key) { Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) }) return copy } var fs = require('fs') var polyfills = require('./polyfills.js') var legacy = require('./legacy-streams.js') var clone = require('./clone.js') var util = require('util') /* istanbul ignore next - node 0.x polyfill */ var gracefulQueue var previousSymbol /* istanbul ignore else - node 0.x polyfill */ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { gracefulQueue = Symbol.for('graceful-fs.queue') // This is used in testing by future versions previousSymbol = Symbol.for('graceful-fs.previous') } else { gracefulQueue = '___graceful-fs.queue' previousSymbol = '___graceful-fs.previous' } function noop () {} function publishQueue(context, queue) { Object.defineProperty(context, gracefulQueue, { get: function() { return queue } }) } var debug = noop if (util.debuglog) debug = util.debuglog('gfs4') else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) debug = function() { var m = util.format.apply(util, arguments) m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') console.error(m) } // Once time initialization if (!fs[gracefulQueue]) { // This queue can be shared by multiple loaded instances var queue = global[gracefulQueue] || [] publishQueue(fs, queue) // Patch fs.close/closeSync to shared queue version, because we need // to retry() whenever a close happens *anywhere* in the program. // This is essential when multiple graceful-fs instances are // in play at the same time. fs.close = (function (fs$close) { function close (fd, cb) { return fs$close.call(fs, fd, function (err) { // This function uses the graceful-fs shared queue if (!err) { resetQueue() } if (typeof cb === 'function') cb.apply(this, arguments) }) } Object.defineProperty(close, previousSymbol, { value: fs$close }) return close })(fs.close) fs.closeSync = (function (fs$closeSync) { function closeSync (fd) { // This function uses the graceful-fs shared queue fs$closeSync.apply(fs, arguments) resetQueue() } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }) return closeSync })(fs.closeSync) if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug(fs[gracefulQueue]) require('assert').equal(fs[gracefulQueue].length, 0) }) } } if (!global[gracefulQueue]) { publishQueue(global, fs[gracefulQueue]); } module.exports = patch(clone(fs)) if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { module.exports = patch(fs) fs.__patched = true; } function patch (fs) { // Everything that references the open() function needs to be in here polyfills(fs) fs.gracefulify = patch fs.createReadStream = createReadStream fs.createWriteStream = createWriteStream var fs$readFile = fs.readFile fs.readFile = readFile function readFile (path, options, cb) { if (typeof options === 'function') cb = options, options = null return go$readFile(path, options, cb) function go$readFile (path, options, cb, startTime) { return fs$readFile(path, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$writeFile = fs.writeFile fs.writeFile = writeFile function writeFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$writeFile(path, data, options, cb) function go$writeFile (path, data, options, cb, startTime) { return fs$writeFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$appendFile = fs.appendFile if (fs$appendFile) fs.appendFile = appendFile function appendFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null return go$appendFile(path, data, options, cb) function go$appendFile (path, data, options, cb, startTime) { return fs$appendFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$copyFile = fs.copyFile if (fs$copyFile) fs.copyFile = copyFile function copyFile (src, dest, flags, cb) { if (typeof flags === 'function') { cb = flags flags = 0 } return go$copyFile(src, dest, flags, cb) function go$copyFile (src, dest, flags, cb, startTime) { return fs$copyFile(src, dest, flags, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } var fs$readdir = fs.readdir fs.readdir = readdir var noReaddirOptionVersions = /^v[0-5]\./ function readdir (path, options, cb) { if (typeof options === 'function') cb = options, options = null var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir (path, options, cb, startTime) { return fs$readdir(path, fs$readdirCallback( path, options, cb, startTime )) } : function go$readdir (path, options, cb, startTime) { return fs$readdir(path, options, fs$readdirCallback( path, options, cb, startTime )) } return go$readdir(path, options, cb) function fs$readdirCallback (path, options, cb, startTime) { return function (err, files) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([ go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now() ]) else { if (files && files.sort) files.sort() if (typeof cb === 'function') cb.call(this, err, files) } } } } if (process.version.substr(0, 4) === 'v0.8') { var legStreams = legacy(fs) ReadStream = legStreams.ReadStream WriteStream = legStreams.WriteStream } var fs$ReadStream = fs.ReadStream if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype) ReadStream.prototype.open = ReadStream$open } var fs$WriteStream = fs.WriteStream if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype) WriteStream.prototype.open = WriteStream$open } Object.defineProperty(fs, 'ReadStream', { get: function () { return ReadStream }, set: function (val) { ReadStream = val }, enumerable: true, configurable: true }) Object.defineProperty(fs, 'WriteStream', { get: function () { return WriteStream }, set: function (val) { WriteStream = val }, enumerable: true, configurable: true }) // legacy names var FileReadStream = ReadStream Object.defineProperty(fs, 'FileReadStream', { get: function () { return FileReadStream }, set: function (val) { FileReadStream = val }, enumerable: true, configurable: true }) var FileWriteStream = WriteStream Object.defineProperty(fs, 'FileWriteStream', { get: function () { return FileWriteStream }, set: function (val) { FileWriteStream = val }, enumerable: true, configurable: true }) function ReadStream (path, options) { if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this else return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } function ReadStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { if (that.autoClose) that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) that.read() } }) } function WriteStream (path, options) { if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this else return WriteStream.apply(Object.create(WriteStream.prototype), arguments) } function WriteStream$open () { var that = this open(that.path, that.flags, that.mode, function (err, fd) { if (err) { that.destroy() that.emit('error', err) } else { that.fd = fd that.emit('open', fd) } }) } function createReadStream (path, options) { return new fs.ReadStream(path, options) } function createWriteStream (path, options) { return new fs.WriteStream(path, options) } var fs$open = fs.open fs.open = open function open (path, flags, mode, cb) { if (typeof mode === 'function') cb = mode, mode = null return go$open(path, flags, mode, cb) function go$open (path, flags, mode, cb, startTime) { return fs$open(path, flags, mode, function (err, fd) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) else { if (typeof cb === 'function') cb.apply(this, arguments) } }) } } return fs } function enqueue (elem) { debug('ENQUEUE', elem[0].name, elem[1]) fs[gracefulQueue].push(elem) retry() } // keep track of the timeout between retry() calls var retryTimer // reset the startTime and lastTime to now // this resets the start of the 60 second overall timeout as well as the // delay between attempts so that we'll retry these jobs sooner function resetQueue () { var now = Date.now() for (var i = 0; i < fs[gracefulQueue].length; ++i) { // entries that are only a length of 2 are from an older version, don't // bother modifying those since they'll be retried anyway. if (fs[gracefulQueue][i].length > 2) { fs[gracefulQueue][i][3] = now // startTime fs[gracefulQueue][i][4] = now // lastTime } } // call retry to make sure we're actively processing the queue retry() } function retry () { // clear the timer and remove it to help prevent unintended concurrency clearTimeout(retryTimer) retryTimer = undefined if (fs[gracefulQueue].length === 0) return var elem = fs[gracefulQueue].shift() var fn = elem[0] var args = elem[1] // these items may be unset if they were added by an older graceful-fs var err = elem[2] var startTime = elem[3] var lastTime = elem[4] // if we don't have a startTime we have no way of knowing if we've waited // long enough, so go ahead and retry this item now if (startTime === undefined) { debug('RETRY', fn.name, args) fn.apply(null, args) } else if (Date.now() - startTime >= 60000) { // it's been more than 60 seconds total, bail now debug('TIMEOUT', fn.name, args) var cb = args.pop() if (typeof cb === 'function') cb.call(null, err) } else { // the amount of time between the last attempt and right now var sinceAttempt = Date.now() - lastTime // the amount of time between when we first tried, and when we last tried // rounded up to at least 1 var sinceStart = Math.max(lastTime - startTime, 1) // backoff. wait longer than the total time we've been retrying, but only // up to a maximum of 100ms var desiredDelay = Math.min(sinceStart * 1.2, 100) // it's been long enough since the last retry, do it again if (sinceAttempt >= desiredDelay) { debug('RETRY', fn.name, args) fn.apply(null, args.concat([startTime])) } else { // if we can't do this job yet, push it to the end of the queue // and let the next iteration check again fs[gracefulQueue].push(elem) } } // schedule our next run if one isn't already scheduled if (retryTimer === undefined) { retryTimer = setTimeout(retry, 0) } } var Stream = require('stream').Stream module.exports = legacy function legacy (fs) { return { ReadStream: ReadStream, WriteStream: WriteStream } function ReadStream (path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); Stream.call(this); var self = this; this.path = path; this.fd = null; this.readable = true; this.paused = false; this.flags = 'r'; this.mode = 438; /*=0666*/ this.bufferSize = 64 * 1024; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.encoding) this.setEncoding(this.encoding); if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.end === undefined) { this.end = Infinity; } else if ('number' !== typeof this.end) { throw TypeError('end must be a Number'); } if (this.start > this.end) { throw new Error('start must be <= end'); } this.pos = this.start; } if (this.fd !== null) { process.nextTick(function() { self._read(); }); return; } fs.open(this.path, this.flags, this.mode, function (err, fd) { if (err) { self.emit('error', err); self.readable = false; return; } self.fd = fd; self.emit('open', fd); self._read(); }) } function WriteStream (path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); Stream.call(this); this.path = path; this.fd = null; this.writable = true; this.flags = 'w'; this.encoding = 'binary'; this.mode = 438; /*=0666*/ this.bytesWritten = 0; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } this.busy = false; this._queue = []; if (this.fd === null) { this._open = fs.open; this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); this.flush(); } } } { "name": "graceful-fs", "description": "A drop-in replacement for fs, making various improvements.", "version": "4.2.11", "repository": { "type": "git", "url": "https://github.com/isaacs/node-graceful-fs" }, "main": "graceful-fs.js", "directories": { "test": "test" }, "license": "ISC", "devDependencies": { "import-fresh": "^2.0.0", "mkdirp": "^0.5.0", "rimraf": "^2.2.8", "tap": "^16.3.4" }, "files": [ "fs.js", "graceful-fs.js", "legacy-streams.js", "polyfills.js", "clone.js" ], "tap": { "reporter": "classic" } }var constants = require('constants') var origCwd = process.cwd var cwd = null var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform process.cwd = function() { if (!cwd) cwd = origCwd.call(process) return cwd } try { process.cwd() } catch (er) {} // This check is needed until node.js 12 is required if (typeof process.chdir === 'function') { var chdir = process.chdir process.chdir = function (d) { cwd = null chdir.call(process, d) } if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } module.exports = patch function patch (fs) { // (re-)implement some things that are known busted or missing. // lchmod, broken prior to 0.6.2 // back-port the fix here. if (constants.hasOwnProperty('O_SYMLINK') && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { patchLchmod(fs) } // lutimes implementation, or no-op if (!fs.lutimes) { patchLutimes(fs) } // https://github.com/isaacs/node-graceful-fs/issues/4 // Chown should not fail on einval or eperm if non-root. // It should not fail on enosys ever, as this just indicates // that a fs doesn't support the intended operation. fs.chown = chownFix(fs.chown) fs.fchown = chownFix(fs.fchown) fs.lchown = chownFix(fs.lchown) fs.chmod = chmodFix(fs.chmod) fs.fchmod = chmodFix(fs.fchmod) fs.lchmod = chmodFix(fs.lchmod) fs.chownSync = chownFixSync(fs.chownSync) fs.fchownSync = chownFixSync(fs.fchownSync) fs.lchownSync = chownFixSync(fs.lchownSync) fs.chmodSync = chmodFixSync(fs.chmodSync) fs.fchmodSync = chmodFixSync(fs.fchmodSync) fs.lchmodSync = chmodFixSync(fs.lchmodSync) fs.stat = statFix(fs.stat) fs.fstat = statFix(fs.fstat) fs.lstat = statFix(fs.lstat) fs.statSync = statFixSync(fs.statSync) fs.fstatSync = statFixSync(fs.fstatSync) fs.lstatSync = statFixSync(fs.lstatSync) // if lchmod/lchown do not exist, then make them no-ops if (fs.chmod && !fs.lchmod) { fs.lchmod = function (path, mode, cb) { if (cb) process.nextTick(cb) } fs.lchmodSync = function () {} } if (fs.chown && !fs.lchown) { fs.lchown = function (path, uid, gid, cb) { if (cb) process.nextTick(cb) } fs.lchownSync = function () {} } // on Windows, A/V software can lock the directory, causing this // to fail with an EACCES or EPERM if the directory contains newly // created files. Try again on failure, for up to 60 seconds. // Set the timeout this long because some Windows Anti-Virus, such as Parity // bit9, may lock files for up to a minute, causing npm package install // failures. Also, take care to yield the scheduler. Windows scheduling gives // CPU to a busy looping process, which can cause the program causing the lock // contention to be starved of CPU by node, so the contention doesn't resolve. if (platform === "win32") { fs.rename = typeof fs.rename !== 'function' ? fs.rename : (function (fs$rename) { function rename (from, to, cb) { var start = Date.now() var backoff = 0; fs$rename(from, to, function CB (er) { if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) { setTimeout(function() { fs.stat(to, function (stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else cb(er) }) }, backoff) if (backoff < 100) backoff += 10; return; } if (cb) cb(er) }) } if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) return rename })(fs.rename) } // if read() returns EAGAIN, then just try it again. fs.read = typeof fs.read !== 'function' ? fs.read : (function (fs$read) { function read (fd, buffer, offset, length, position, callback_) { var callback if (callback_ && typeof callback_ === 'function') { var eagCounter = 0 callback = function (er, _, __) { if (er && er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ return fs$read.call(fs, fd, buffer, offset, length, position, callback) } callback_.apply(this, arguments) } } return fs$read.call(fs, fd, buffer, offset, length, position, callback) } // This ensures `util.promisify` works as it does for native `fs.read`. if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) return read })(fs.read) fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { var eagCounter = 0 while (true) { try { return fs$readSync.call(fs, fd, buffer, offset, length, position) } catch (er) { if (er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++ continue } throw er } } }})(fs.readSync) function patchLchmod (fs) { fs.lchmod = function (path, mode, callback) { fs.open( path , constants.O_WRONLY | constants.O_SYMLINK , mode , function (err, fd) { if (err) { if (callback) callback(err) return } // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. fs.fchmod(fd, mode, function (err) { fs.close(fd, function(err2) { if (callback) callback(err || err2) }) }) }) } fs.lchmodSync = function (path, mode) { var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. var threw = true var ret try { ret = fs.fchmodSync(fd, mode) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } function patchLutimes (fs) { if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { fs.lutimes = function (path, at, mt, cb) { fs.open(path, constants.O_SYMLINK, function (er, fd) { if (er) { if (cb) cb(er) return } fs.futimes(fd, at, mt, function (er) { fs.close(fd, function (er2) { if (cb) cb(er || er2) }) }) }) } fs.lutimesSync = function (path, at, mt) { var fd = fs.openSync(path, constants.O_SYMLINK) var ret var threw = true try { ret = fs.futimesSync(fd, at, mt) threw = false } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } else { fs.closeSync(fd) } } return ret } } else if (fs.futimes) { fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } fs.lutimesSync = function () {} } } function chmodFix (orig) { if (!orig) return orig return function (target, mode, cb) { return orig.call(fs, target, mode, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chmodFixSync (orig) { if (!orig) return orig return function (target, mode) { try { return orig.call(fs, target, mode) } catch (er) { if (!chownErOk(er)) throw er } } } function chownFix (orig) { if (!orig) return orig return function (target, uid, gid, cb) { return orig.call(fs, target, uid, gid, function (er) { if (chownErOk(er)) er = null if (cb) cb.apply(this, arguments) }) } } function chownFixSync (orig) { if (!orig) return orig return function (target, uid, gid) { try { return orig.call(fs, target, uid, gid) } catch (er) { if (!chownErOk(er)) throw er } } } function statFix (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options, cb) { if (typeof options === 'function') { cb = options options = null } function callback (er, stats) { if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } if (cb) cb.apply(this, arguments) } return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback) } } function statFixSync (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options) { var stats = options ? orig.call(fs, target, options) : orig.call(fs, target) if (stats) { if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 } return stats; } } // ENOSYS means that the fs doesn't support the op. Just ignore // that, because it doesn't matter. // // if there's no getuid, or if getuid() is something other // than 0, and the error is EINVAL or EPERM, then just ignore // it. // // This specific case is a silent failure in cp, install, tar, // and most other unix tools that manage permissions. // // When running as root, or if other types of errors are // encountered, then it's strict. function chownErOk (er) { if (!er) return true if (er.code === "ENOSYS") return true var nonroot = !process.getuid || process.getuid() !== 0 if (nonroot) { if (er.code === "EINVAL" || er.code === "EPERM") return true } return false } } (The MIT License) Copyright (C) 2011-2015 by Vitaly Puzrin 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. #!/usr/bin/env node 'use strict' const fs = require('fs') const argparse = require('argparse') const yaml = require('..') /// ///////////////////////////////////////////////////////////////////////////// const cli = new argparse.ArgumentParser({ prog: 'js-yaml', add_help: true }) cli.add_argument('-v', '--version', { action: 'version', version: require('../package.json').version }) cli.add_argument('-c', '--compact', { help: 'Display errors in compact mode', action: 'store_true' }) // deprecated (not needed after we removed output colors) // option suppressed, but not completely removed for compatibility cli.add_argument('-j', '--to-json', { help: argparse.SUPPRESS, dest: 'json', action: 'store_true' }) cli.add_argument('-t', '--trace', { help: 'Show stack trace on error', action: 'store_true' }) cli.add_argument('file', { help: 'File to read, utf-8 encoded without BOM', nargs: '?', default: '-' }) /// ///////////////////////////////////////////////////////////////////////////// const options = cli.parse_args() /// ///////////////////////////////////////////////////////////////////////////// function readFile (filename, encoding, callback) { if (options.file === '-') { // read from stdin const chunks = [] process.stdin.on('data', function (chunk) { chunks.push(chunk) }) process.stdin.on('end', function () { return callback(null, Buffer.concat(chunks).toString(encoding)) }) } else { fs.readFile(filename, encoding, callback) } } readFile(options.file, 'utf8', function (error, input) { let output let isYaml if (error) { if (error.code === 'ENOENT') { console.error('File not found: ' + options.file) process.exit(2) } console.error( (options.trace && error.stack) || error.message || String(error)) process.exit(1) } try { output = JSON.parse(input) isYaml = false } catch (err) { if (err instanceof SyntaxError) { try { output = [] yaml.loadAll(input, function (doc) { output.push(doc) }, {}) isYaml = true if (output.length === 0) output = null else if (output.length === 1) output = output[0] } catch (e) { if (options.trace && err.stack) console.error(e.stack) else console.error(e.toString(options.compact)) process.exit(1) } } else { console.error( (options.trace && err.stack) || err.message || String(err)) process.exit(1) } } if (isYaml) console.log(JSON.stringify(output, null, ' ')) else console.log(yaml.dump(output)) }) /*! js-yaml 4.2.0 https://github.com/nodeca/js-yaml @license MIT */ (function(global, factory) { typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.jsyaml = {})); })(this, function(exports) { Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); //#region \0rolldown/runtime.js var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports); var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion //#region lib/common.js var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => { function isNothing(subject) { return typeof subject === "undefined" || subject === null; } function isObject(subject) { return typeof subject === "object" && subject !== null; } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [sequence]; } function extend(target, source) { if (source) { const sourceKeys = Object.keys(source); for (let index = 0, length = sourceKeys.length; index < length; index += 1) { const key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { let result = ""; for (let cycle = 0; cycle < count; cycle += 1) result += string; return result; } function isNegativeZero(number) { return number === 0 && Number.NEGATIVE_INFINITY === 1 / number; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.toArray = toArray; module.exports.repeat = repeat; module.exports.isNegativeZero = isNegativeZero; module.exports.extend = extend; })); //#endregion //#region lib/exception.js var require_exception = /* @__PURE__ */ __commonJSMin(((exports, module) => { function formatError(exception, compact) { let where = ""; const message = exception.reason || "(unknown reason)"; if (!exception.mark) return message; if (exception.mark.name) where += "in \"" + exception.mark.name + "\" "; where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")"; if (!compact && exception.mark.snippet) where += "\n\n" + exception.mark.snippet; return message + " " + where; } function YAMLException(reason, mark) { Error.call(this); this.name = "YAMLException"; this.reason = reason; this.mark = mark; this.message = formatError(this, false); if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); else this.stack = (/* @__PURE__ */ new Error()).stack || ""; } YAMLException.prototype = Object.create(Error.prototype); YAMLException.prototype.constructor = YAMLException; YAMLException.prototype.toString = function toString(compact) { return this.name + ": " + formatError(this, compact); }; module.exports = YAMLException; })); //#endregion //#region lib/snippet.js var require_snippet = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { let head = ""; let tail = ""; const maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = " ... "; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = " ..."; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail, pos: position - lineStart + head.length }; } function padStart(string, max) { return common.repeat(" ", max - string.length) + string; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== "number") options.indent = 1; if (typeof options.linesBefore !== "number") options.linesBefore = 3; if (typeof options.linesAfter !== "number") options.linesAfter = 2; const re = /\r?\n|\r|\0/g; const lineStarts = [0]; const lineEnds = []; let match; let foundLineNo = -1; while (match = re.exec(mark.buffer)) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2; } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; let result = ""; const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (let i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; const line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength); result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; } const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; for (let i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; const line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength); result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n"; } return result.replace(/\n$/, ""); } module.exports = makeSnippet; })); //#endregion //#region lib/type.js var require_type = /* @__PURE__ */ __commonJSMin(((exports, module) => { var YAMLException = require_exception(); var TYPE_CONSTRUCTOR_OPTIONS = [ "kind", "multi", "resolve", "construct", "instanceOf", "predicate", "represent", "representName", "defaultStyle", "styleAliases" ]; var YAML_NODE_KINDS = [ "scalar", "sequence", "mapping" ]; function compileStyleAliases(map) { const result = {}; if (map !== null) Object.keys(map).forEach(function(style) { map[style].forEach(function(alias) { result[String(alias)] = style; }); }); return result; } function Type(tag, options) { options = options || {}; Object.keys(options).forEach(function(name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) throw new YAMLException("Unknown option \"" + name + "\" is met in definition of \"" + tag + "\" YAML type."); }); this.options = options; this.tag = tag; this.kind = options["kind"] || null; this.resolve = options["resolve"] || function() { return true; }; this.construct = options["construct"] || function(data) { return data; }; this.instanceOf = options["instanceOf"] || null; this.predicate = options["predicate"] || null; this.represent = options["represent"] || null; this.representName = options["representName"] || null; this.defaultStyle = options["defaultStyle"] || null; this.multi = options["multi"] || false; this.styleAliases = compileStyleAliases(options["styleAliases"] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) throw new YAMLException("Unknown kind \"" + this.kind + "\" is specified for \"" + tag + "\" YAML type."); } module.exports = Type; })); //#endregion //#region lib/schema.js var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { var YAMLException = require_exception(); var Type = require_type(); function compileList(schema, name) { const result = []; schema[name].forEach(function(currentType) { let newIndex = result.length; result.forEach(function(previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) newIndex = previousIndex; }); result[newIndex] = currentType; }); return result; } function compileMap() { const result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }; function collectType(type) { if (type.multi) { result.multi[type.kind].push(type); result.multi["fallback"].push(type); } else result[type.kind][type.tag] = result["fallback"][type.tag] = type; } for (let index = 0, length = arguments.length; index < length; index += 1) arguments[index].forEach(collectType); return result; } function Schema(definition) { return this.extend(definition); } Schema.prototype.extend = function extend(definition) { let implicit = []; let explicit = []; if (definition instanceof Type) explicit.push(definition); else if (Array.isArray(definition)) explicit = explicit.concat(definition); else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else throw new YAMLException("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); implicit.forEach(function(type) { if (!(type instanceof Type)) throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object."); if (type.loadKind && type.loadKind !== "scalar") throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); if (type.multi) throw new YAMLException("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); }); explicit.forEach(function(type) { if (!(type instanceof Type)) throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object."); }); const result = Object.create(Schema.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, "implicit"); result.compiledExplicit = compileList(result, "explicit"); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; module.exports = Schema; })); //#endregion //#region lib/type/str.js var require_str = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_type())("tag:yaml.org,2002:str", { kind: "scalar", construct: function(data) { return data !== null ? data : ""; } }); })); //#endregion //#region lib/type/seq.js var require_seq = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_type())("tag:yaml.org,2002:seq", { kind: "sequence", construct: function(data) { return data !== null ? data : []; } }); })); //#endregion //#region lib/type/map.js var require_map = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_type())("tag:yaml.org,2002:map", { kind: "mapping", construct: function(data) { return data !== null ? data : {}; } }); })); //#endregion //#region lib/schema/failsafe.js var require_failsafe = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_schema())({ explicit: [ require_str(), require_seq(), require_map() ] }); })); //#endregion //#region lib/type/null.js var require_null = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); function resolveYamlNull(data) { if (data === null) return true; const max = data.length; return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL"); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } module.exports = new Type("tag:yaml.org,2002:null", { kind: "scalar", resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function() { return "~"; }, lowercase: function() { return "null"; }, uppercase: function() { return "NULL"; }, camelcase: function() { return "Null"; }, empty: function() { return ""; } }, defaultStyle: "lowercase" }); })); //#endregion //#region lib/type/bool.js var require_bool = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); function resolveYamlBoolean(data) { if (data === null) return false; const max = data.length; return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE"); } function constructYamlBoolean(data) { return data === "true" || data === "True" || data === "TRUE"; } function isBoolean(object) { return Object.prototype.toString.call(object) === "[object Boolean]"; } module.exports = new Type("tag:yaml.org,2002:bool", { kind: "scalar", resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function(object) { return object ? "true" : "false"; }, uppercase: function(object) { return object ? "TRUE" : "FALSE"; }, camelcase: function(object) { return object ? "True" : "False"; } }, defaultStyle: "lowercase" }); })); //#endregion //#region lib/type/int.js var require_int = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var Type = require_type(); function isHexCode(c) { return c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102; } function isOctCode(c) { return c >= 48 && c <= 55; } function isDecCode(c) { return c >= 48 && c <= 57; } function resolveYamlInteger(data) { if (data === null) return false; const max = data.length; let index = 0; let hasDigits = false; if (!max) return false; let ch = data[index]; if (ch === "-" || ch === "+") ch = data[++index]; if (ch === "0") { if (index + 1 === max) return true; ch = data[++index]; if (ch === "b") { index++; for (; index < max; index++) { ch = data[index]; if (ch !== "0" && ch !== "1") return false; hasDigits = true; } return hasDigits && Number.isFinite(parseYamlInteger(data)); } if (ch === "x") { index++; for (; index < max; index++) { if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && Number.isFinite(parseYamlInteger(data)); } if (ch === "o") { index++; for (; index < max; index++) { if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && Number.isFinite(parseYamlInteger(data)); } } for (; index < max; index++) { if (!isDecCode(data.charCodeAt(index))) return false; hasDigits = true; } if (!hasDigits) return false; return Number.isFinite(parseYamlInteger(data)); } function parseYamlInteger(data) { let value = data; let sign = 1; let ch = value[0]; if (ch === "-" || ch === "+") { if (ch === "-") sign = -1; value = value.slice(1); ch = value[0]; } if (value === "0") return 0; if (ch === "0") { if (value[1] === "b") return sign * parseInt(value.slice(2), 2); if (value[1] === "x") return sign * parseInt(value.slice(2), 16); if (value[1] === "o") return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function constructYamlInteger(data) { return parseYamlInteger(data); } function isInteger(object) { return Object.prototype.toString.call(object) === "[object Number]" && object % 1 === 0 && !common.isNegativeZero(object); } module.exports = new Type("tag:yaml.org,2002:int", { kind: "scalar", resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function(obj) { return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1); }, octal: function(obj) { return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1); }, decimal: function(obj) { return obj.toString(10); }, hexadecimal: function(obj) { return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: "decimal", styleAliases: { binary: [2, "bin"], octal: [8, "oct"], decimal: [10, "dec"], hexadecimal: [16, "hex"] } }); })); //#endregion //#region lib/type/float.js var require_float = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var Type = require_type(); var YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); var YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data)) return false; if (Number.isFinite(parseFloat(data, 10))) return true; return YAML_FLOAT_SPECIAL_PATTERN.test(data); } function constructYamlFloat(data) { let value = data.toLowerCase(); const sign = value[0] === "-" ? -1 : 1; if ("+-".indexOf(value[0]) >= 0) value = value.slice(1); if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; else if (value === ".nan") return NaN; return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { if (isNaN(object)) switch (style) { case "lowercase": return ".nan"; case "uppercase": return ".NAN"; case "camelcase": return ".NaN"; } else if (Number.POSITIVE_INFINITY === object) switch (style) { case "lowercase": return ".inf"; case "uppercase": return ".INF"; case "camelcase": return ".Inf"; } else if (Number.NEGATIVE_INFINITY === object) switch (style) { case "lowercase": return "-.inf"; case "uppercase": return "-.INF"; case "camelcase": return "-.Inf"; } else if (common.isNegativeZero(object)) return "-0.0"; const res = object.toString(10); return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; } function isFloat(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object)); } module.exports = new Type("tag:yaml.org,2002:float", { kind: "scalar", resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: "lowercase" }); })); //#endregion //#region lib/schema/json.js var require_json = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = require_failsafe().extend({ implicit: [ require_null(), require_bool(), require_int(), require_float() ] }); })); //#endregion //#region lib/schema/core.js var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = require_json(); })); //#endregion //#region lib/type/timestamp.js var require_timestamp = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"); var YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"); function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { let fraction = 0; let delta = null; let match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error("Date resolve error"); const year = +match[1]; const month = +match[2] - 1; const day = +match[3]; if (!match[4]) return new Date(Date.UTC(year, month, day)); const hour = +match[4]; const minute = +match[5]; const second = +match[6]; if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) fraction += "0"; fraction = +fraction; } if (match[9]) { const tzHour = +match[10]; const tzMinute = +(match[11] || 0); delta = (tzHour * 60 + tzMinute) * 6e4; if (match[9] === "-") delta = -delta; } const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object) { return object.toISOString(); } module.exports = new Type("tag:yaml.org,2002:timestamp", { kind: "scalar", resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); })); //#endregion //#region lib/type/merge.js var require_merge = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); function resolveYamlMerge(data) { return data === "<<" || data === null; } module.exports = new Type("tag:yaml.org,2002:merge", { kind: "scalar", resolve: resolveYamlMerge }); })); //#endregion //#region lib/type/binary.js var require_binary = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; function resolveYamlBinary(data) { if (data === null) return false; let bitlen = 0; const max = data.length; const map = BASE64_MAP; for (let idx = 0; idx < max; idx++) { const code = map.indexOf(data.charAt(idx)); if (code > 64) continue; if (code < 0) return false; bitlen += 6; } return bitlen % 8 === 0; } function constructYamlBinary(data) { const input = data.replace(/[\r\n=]/g, ""); const max = input.length; const map = BASE64_MAP; let bits = 0; const result = []; for (let idx = 0; idx < max; idx++) { if (idx % 4 === 0 && idx) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } bits = bits << 6 | map.indexOf(input.charAt(idx)); } const tailbits = max % 4 * 6; if (tailbits === 0) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } else if (tailbits === 18) { result.push(bits >> 10 & 255); result.push(bits >> 2 & 255); } else if (tailbits === 12) result.push(bits >> 4 & 255); return new Uint8Array(result); } function representYamlBinary(object) { let result = ""; let bits = 0; const max = object.length; const map = BASE64_MAP; for (let idx = 0; idx < max; idx++) { if (idx % 3 === 0 && idx) { result += map[bits >> 18 & 63]; result += map[bits >> 12 & 63]; result += map[bits >> 6 & 63]; result += map[bits & 63]; } bits = (bits << 8) + object[idx]; } const tail = max % 3; if (tail === 0) { result += map[bits >> 18 & 63]; result += map[bits >> 12 & 63]; result += map[bits >> 6 & 63]; result += map[bits & 63]; } else if (tail === 2) { result += map[bits >> 10 & 63]; result += map[bits >> 4 & 63]; result += map[bits << 2 & 63]; result += map[64]; } else if (tail === 1) { result += map[bits >> 2 & 63]; result += map[bits << 4 & 63]; result += map[64]; result += map[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === "[object Uint8Array]"; } module.exports = new Type("tag:yaml.org,2002:binary", { kind: "scalar", resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); })); //#endregion //#region lib/type/omap.js var require_omap = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var _hasOwnProperty = Object.prototype.hasOwnProperty; var _toString = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; const objectKeys = []; const object = data; for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index]; let pairHasKey = false; if (_toString.call(pair) !== "[object Object]") return false; let pairKey; for (pairKey in pair) if (_hasOwnProperty.call(pair, pairKey)) if (!pairHasKey) pairHasKey = true; else return false; if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } module.exports = new Type("tag:yaml.org,2002:omap", { kind: "sequence", resolve: resolveYamlOmap, construct: constructYamlOmap }); })); //#endregion //#region lib/type/pairs.js var require_pairs = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var _toString = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; const object = data; const result = new Array(object.length); for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index]; if (_toString.call(pair) !== "[object Object]") return false; const keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [keys[0], pair[keys[0]]]; } return true; } function constructYamlPairs(data) { if (data === null) return []; const object = data; const result = new Array(object.length); for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index]; const keys = Object.keys(pair); result[index] = [keys[0], pair[keys[0]]]; } return result; } module.exports = new Type("tag:yaml.org,2002:pairs", { kind: "sequence", resolve: resolveYamlPairs, construct: constructYamlPairs }); })); //#endregion //#region lib/type/set.js var require_set = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var _hasOwnProperty = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; const object = data; for (const key in object) if (_hasOwnProperty.call(object, key)) { if (object[key] !== null) return false; } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } module.exports = new Type("tag:yaml.org,2002:set", { kind: "mapping", resolve: resolveYamlSet, construct: constructYamlSet }); })); //#endregion //#region lib/schema/default.js var require_default = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = require_core().extend({ implicit: [require_timestamp(), require_merge()], explicit: [ require_binary(), require_omap(), require_pairs(), require_set() ] }); })); //#endregion //#region lib/loader.js var require_loader = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var YAMLException = require_exception(); var makeSnippet = require_snippet(); var DEFAULT_SCHEMA = require_default(); var _hasOwnProperty = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]{}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/; var PATTERN_TAG_URI = /^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function isEol(c) { return c === 10 || c === 13; } function isWhiteSpace(c) { return c === 9 || c === 32; } function isWsOrEol(c) { return c === 9 || c === 32 || c === 10 || c === 13; } function isFlowIndicator(c) { return c === 44 || c === 91 || c === 93 || c === 123 || c === 125; } function fromHexCode(c) { if (c >= 48 && c <= 57) return c - 48; const lc = c | 32; if (lc >= 97 && lc <= 102) return lc - 97 + 10; return -1; } function escapedHexLen(c) { if (c === 120) return 2; if (c === 117) return 4; if (c === 85) return 8; return 0; } function fromDecimalCode(c) { if (c >= 48 && c <= 57) return c - 48; return -1; } function simpleEscapeSequence(c) { switch (c) { case 48: return "\0"; case 97: return "\x07"; case 98: return "\b"; case 116: return " "; case 9: return " "; case 110: return "\n"; case 118: return "\v"; case 102: return "\f"; case 114: return "\r"; case 101: return "\x1B"; case 32: return " "; case 34: return "\""; case 47: return "/"; case 92: return "\\"; case 78: return "…"; case 95: return "\xA0"; case 76: return "\u2028"; case 80: return "\u2029"; default: return ""; } } function charFromCodepoint(c) { if (c <= 65535) return String.fromCharCode(c); return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320); } function setProperty(object, key, value) { if (key === "__proto__") Object.defineProperty(object, key, { configurable: true, enumerable: true, writable: true, value }); else object[key] = value; } var simpleEscapeCheck = new Array(256); var simpleEscapeMap = new Array(256); for (let i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } function State(input, options) { this.input = input; this.filename = options["filename"] || null; this.schema = options["schema"] || DEFAULT_SCHEMA; this.onWarning = options["onWarning"] || null; this.legacy = options["legacy"] || false; this.json = options["json"] || false; this.listener = options["listener"] || null; this.maxDepth = typeof options["maxDepth"] === "number" ? options["maxDepth"] : 100; this.maxMergeSeqLength = typeof options["maxMergeSeqLength"] === "number" ? options["maxMergeSeqLength"] : 20; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; this.depth = 0; this.firstTabInLine = -1; this.documents = []; this.anchorMapTransactions = []; } function generateError(state, message) { const mark = { name: state.filename, buffer: state.input.slice(0, -1), position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = makeSnippet(mark); return new YAMLException(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) state.onWarning.call(null, generateError(state, message)); } function storeAnchor(state, name, value) { const transactions = state.anchorMapTransactions; if (transactions.length !== 0) { const transaction = transactions[transactions.length - 1]; if (!_hasOwnProperty.call(transaction, name)) transaction[name] = { existed: _hasOwnProperty.call(state.anchorMap, name), value: state.anchorMap[name] }; } state.anchorMap[name] = value; } function beginAnchorTransaction(state) { state.anchorMapTransactions.push(Object.create(null)); } function commitAnchorTransaction(state) { const transaction = state.anchorMapTransactions.pop(); const transactions = state.anchorMapTransactions; if (transactions.length === 0) return; const parent = transactions[transactions.length - 1]; const names = Object.keys(transaction); for (let index = 0, length = names.length; index < length; index += 1) { const name = names[index]; if (!_hasOwnProperty.call(parent, name)) parent[name] = transaction[name]; } } function rollbackAnchorTransaction(state) { const transaction = state.anchorMapTransactions.pop(); const names = Object.keys(transaction); for (let index = names.length - 1; index >= 0; index -= 1) { const entry = transaction[names[index]]; if (entry.existed) state.anchorMap[names[index]] = entry.value; else delete state.anchorMap[names[index]]; } } function snapshotState(state) { return { position: state.position, line: state.line, lineStart: state.lineStart, lineIndent: state.lineIndent, firstTabInLine: state.firstTabInLine, tag: state.tag, anchor: state.anchor, kind: state.kind, result: state.result }; } function restoreState(state, snapshot) { state.position = snapshot.position; state.line = snapshot.line; state.lineStart = snapshot.lineStart; state.lineIndent = snapshot.lineIndent; state.firstTabInLine = snapshot.firstTabInLine; state.tag = snapshot.tag; state.anchor = snapshot.anchor; state.kind = snapshot.kind; state.result = snapshot.result; } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { if (state.version !== null) throwError(state, "duplication of %YAML directive"); if (args.length !== 1) throwError(state, "YAML directive accepts exactly one argument"); const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) throwError(state, "ill-formed argument of the YAML directive"); const major = parseInt(match[1], 10); const minor = parseInt(match[2], 10); if (major !== 1) throwError(state, "unacceptable YAML version of the document"); state.version = args[0]; state.checkLineBreaks = minor < 2; if (minor !== 1 && minor !== 2) throwWarning(state, "unsupported YAML version of the document"); }, TAG: function handleTagDirective(state, name, args) { let prefix; if (args.length !== 2) throwError(state, "TAG directive accepts exactly two arguments"); const handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); if (_hasOwnProperty.call(state.tagMap, handle)) throwError(state, "there is a previously declared suffix for \"" + handle + "\" tag handle"); if (!PATTERN_TAG_URI.test(prefix)) throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, "tag prefix is malformed: " + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { if (start < end) { const _result = state.input.slice(start, end); if (checkJson) for (let _position = 0, _length = _result.length; _position < _length; _position += 1) { const _character = _result.charCodeAt(_position); if (!(_character === 9 || _character >= 32 && _character <= 1114111)) throwError(state, "expected valid JSON character"); } else if (PATTERN_NON_PRINTABLE.test(_result)) throwError(state, "the stream contains non-printable characters"); state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { if (!common.isObject(source)) throwError(state, "cannot merge mappings; the provided source object is unacceptable"); const sourceKeys = Object.keys(source); for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { const key = sourceKeys[index]; if (!_hasOwnProperty.call(destination, key)) { setProperty(destination, key, source[key]); overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) throwError(state, "nested arrays are not supported inside keys"); if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") keyNode[index] = "[object Object]"; } } if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") keyNode = "[object Object]"; keyNode = String(keyNode); if (_result === null) _result = {}; if (keyTag === "tag:yaml.org,2002:merge") if (Array.isArray(valueNode)) { if (valueNode.length > state.maxMergeSeqLength) throwError(state, "merge sequence length exceeded maxMergeSeqLength (" + state.maxMergeSeqLength + ")"); const seen = /* @__PURE__ */ new Set(); for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) { const src = valueNode[index]; if (seen.has(src)) continue; seen.add(src); mergeMappings(state, _result, src, overridableKeys); } } else mergeMappings(state, _result, valueNode, overridableKeys); else { if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, "duplicated mapping key"); } setProperty(_result, keyNode, valueNode); delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { const ch = state.input.charCodeAt(state.position); if (ch === 10) state.position++; else if (ch === 13) { state.position++; if (state.input.charCodeAt(state.position) === 10) state.position++; } else throwError(state, "a line break is expected"); state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { let lineBreaks = 0; let ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (isWhiteSpace(ch)) { if (ch === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position; ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 35) do ch = state.input.charCodeAt(++state.position); while (ch !== 10 && ch !== 13 && ch !== 0); if (isEol(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else break; } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) throwWarning(state, "deficient indentation"); return lineBreaks; } function testDocumentSeparator(state) { let _position = state.position; let ch = state.input.charCodeAt(_position); if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || isWsOrEol(ch)) return true; } return false; } function writeFoldedLines(state, count) { if (count === 1) state.result += " "; else if (count > 1) state.result += common.repeat("\n", count - 1); } function readPlainScalar(state, nodeIndent, withinFlowCollection) { let captureStart; let captureEnd; let hasPendingContent; let _line; let _lineStart; let _lineIndent; const _kind = state.kind; const _result = state.result; let ch = state.input.charCodeAt(state.position); if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) return false; if (ch === 63 || ch === 45) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) return false; } state.kind = "scalar"; state.result = ""; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 58) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) break; } else if (ch === 35) { if (isWsOrEol(state.input.charCodeAt(state.position - 1))) break; } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && isFlowIndicator(ch)) break; else if (isEol(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!isWhiteSpace(ch)) captureEnd = state.position + 1; ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) return true; state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { let captureStart; let captureEnd; let ch = state.input.charCodeAt(state.position); if (ch !== 39) return false; state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) if (ch === 39) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 39) { captureStart = state.position; state.position++; captureEnd = state.position; } else return true; } else if (isEol(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a single quoted scalar"); else { state.position++; if (!isWhiteSpace(ch)) captureEnd = state.position; } throwError(state, "unexpected end of the stream within a single quoted scalar"); } function readDoubleQuotedScalar(state, nodeIndent) { let captureStart; let captureEnd; let tmp; let ch = state.input.charCodeAt(state.position); if (ch !== 34) return false; state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) if (ch === 34) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 92) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (isEol(ch)) skipSeparationSpace(state, false, nodeIndent); else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { let hexLength = tmp; let hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) hexResult = (hexResult << 4) + tmp; else throwError(state, "expected hexadecimal character"); } state.result += charFromCodepoint(hexResult); state.position++; } else throwError(state, "unknown escape sequence"); captureStart = captureEnd = state.position; } else if (isEol(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a double quoted scalar"); else { state.position++; if (!isWhiteSpace(ch)) captureEnd = state.position; } throwError(state, "unexpected end of the stream within a double quoted scalar"); } function readFlowCollection(state, nodeIndent) { let readNext = true; let _line; let _lineStart; let _pos; const _tag = state.tag; let _result; const _anchor = state.anchor; let terminator; let isPair; let isExplicitPair; let isMapping; const overridableKeys = Object.create(null); let keyNode; let keyTag; let valueNode; let ch = state.input.charCodeAt(state.position); if (ch === 91) { terminator = 93; isMapping = false; _result = []; } else if (ch === 123) { terminator = 125; isMapping = true; _result = {}; } else return false; if (state.anchor !== null) storeAnchor(state, state.anchor, _result); ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? "mapping" : "sequence"; state.result = _result; return true; } else if (!readNext) throwError(state, "missed comma between flow collection entries"); else if (ch === 44) throwError(state, "expected the node content, but found ','"); keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 63) { if (isWsOrEol(state.input.charCodeAt(state.position + 1))) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 58) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); else if (isPair) _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); else _result.push(keyNode); skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 44) { readNext = true; ch = state.input.charCodeAt(++state.position); } else readNext = false; } throwError(state, "unexpected end of the stream within a flow collection"); } function readBlockScalar(state, nodeIndent) { let folding; let chomping = CHOMPING_CLIP; let didReadContent = false; let detectedIndent = false; let textIndent = nodeIndent; let emptyLines = 0; let atMoreIndented = false; let tmp; let ch = state.input.charCodeAt(state.position); if (ch === 124) folding = false; else if (ch === 62) folding = true; else return false; state.kind = "scalar"; state.result = ""; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 43 || ch === 45) if (CHOMPING_CLIP === chomping) chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP; else throwError(state, "repeat of a chomping mode identifier"); else if ((tmp = fromDecimalCode(ch)) >= 0) if (tmp === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else throwError(state, "repeat of an indentation width identifier"); else break; } if (isWhiteSpace(ch)) { do ch = state.input.charCodeAt(++state.position); while (isWhiteSpace(ch)); if (ch === 35) do ch = state.input.charCodeAt(++state.position); while (!isEol(ch) && ch !== 0); } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) textIndent = state.lineIndent; if (isEol(ch)) { emptyLines++; continue; } if (!detectedIndent && textIndent === 0) throwError(state, "missing indentation for block scalar"); if (state.lineIndent < textIndent) { if (chomping === CHOMPING_KEEP) state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); else if (chomping === CHOMPING_CLIP) { if (didReadContent) state.result += "\n"; } break; } if (folding) if (isWhiteSpace(ch)) { atMoreIndented = true; state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat("\n", emptyLines + 1); } else if (emptyLines === 0) { if (didReadContent) state.result += " "; } else state.result += common.repeat("\n", emptyLines); else state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); didReadContent = true; detectedIndent = true; emptyLines = 0; const captureStart = state.position; while (!isEol(ch) && ch !== 0) ch = state.input.charCodeAt(++state.position); captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { const _tag = state.tag; const _anchor = state.anchor; const _result = []; let detected = false; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) storeAnchor(state, state.anchor, _result); let ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } if (ch !== 45) break; if (!isWsOrEol(state.input.charCodeAt(state.position + 1))) break; detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } const _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a sequence entry"); else if (state.lineIndent < nodeIndent) break; } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "sequence"; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { let allowCompact; let _keyLine; let _keyLineStart; let _keyPos; const _tag = state.tag; const _anchor = state.anchor; const _result = {}; const overridableKeys = Object.create(null); let keyTag = null; let keyNode = null; let valueNode = null; let atExplicitKey = false; let detected = false; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) storeAnchor(state, state.anchor, _result); let ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } const following = state.input.charCodeAt(state.position + 1); const _line = state.line; if ((ch === 63 || ch === 58) && isWsOrEol(following)) { if (ch === 63) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { atExplicitKey = false; allowCompact = true; } else throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"); state.position += 1; ch = following; } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break; if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position); if (ch === 58) { ch = state.input.charCodeAt(++state.position); if (!isWsOrEol(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) throwError(state, "can not read an implicit mapping pair; a colon is missed"); else { state.tag = _tag; state.anchor = _anchor; return true; } } else if (detected) throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); else { state.tag = _tag; state.anchor = _anchor; return true; } } if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) if (atExplicitKey) keyNode = state.result; else valueNode = state.result; if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a mapping entry"); else if (state.lineIndent < nodeIndent) break; } if (atExplicitKey) storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "mapping"; state.result = _result; } return detected; } function readTagProperty(state) { let isVerbatim = false; let isNamed = false; let tagHandle; let tagName; let ch = state.input.charCodeAt(state.position); if (ch !== 33) return false; if (state.tag !== null) throwError(state, "duplication of a tag property"); ch = state.input.charCodeAt(++state.position); if (ch === 60) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 33) { isNamed = true; tagHandle = "!!"; ch = state.input.charCodeAt(++state.position); } else tagHandle = "!"; let _position = state.position; if (isVerbatim) { do ch = state.input.charCodeAt(++state.position); while (ch !== 0 && ch !== 62); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else throwError(state, "unexpected end of the stream within a verbatim tag"); } else { while (ch !== 0 && !isWsOrEol(ch)) { if (ch === 33) if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters"); isNamed = true; _position = state.position + 1; } else throwError(state, "tag suffix cannot contain exclamation marks"); ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, "tag suffix cannot contain flow indicator characters"); } if (tagName && !PATTERN_TAG_URI.test(tagName)) throwError(state, "tag name cannot contain such characters: " + tagName); try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, "tag name is malformed: " + tagName); } if (isVerbatim) state.tag = tagName; else if (_hasOwnProperty.call(state.tagMap, tagHandle)) state.tag = state.tagMap[tagHandle] + tagName; else if (tagHandle === "!") state.tag = "!" + tagName; else if (tagHandle === "!!") state.tag = "tag:yaml.org,2002:" + tagName; else throwError(state, "undeclared tag handle \"" + tagHandle + "\""); return true; } function readAnchorProperty(state) { let ch = state.input.charCodeAt(state.position); if (ch !== 38) return false; if (state.anchor !== null) throwError(state, "duplication of an anchor property"); ch = state.input.charCodeAt(++state.position); const _position = state.position; while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) ch = state.input.charCodeAt(++state.position); if (state.position === _position) throwError(state, "name of an anchor node must contain at least one character"); state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { let ch = state.input.charCodeAt(state.position); if (ch !== 42) return false; ch = state.input.charCodeAt(++state.position); const _position = state.position; while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) ch = state.input.charCodeAt(++state.position); if (state.position === _position) throwError(state, "name of an alias node must contain at least one character"); const alias = state.input.slice(_position, state.position); if (!_hasOwnProperty.call(state.anchorMap, alias)) throwError(state, "unidentified alias \"" + alias + "\""); state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function tryReadBlockMappingFromProperty(state, propertyStart, nodeIndent, flowIndent) { const fallbackState = snapshotState(state); beginAnchorTransaction(state); restoreState(state, propertyStart); state.tag = null; state.anchor = null; state.kind = null; state.result = null; if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === "mapping") { commitAnchorTransaction(state); return true; } rollbackAnchorTransaction(state); restoreState(state, fallbackState); return false; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { let allowBlockScalars; let allowBlockCollections; let indentStatus = 1; let atNewLine = false; let hasContent = false; let propertyStart = null; let type; let flowIndent; let blockIndent; if (state.depth >= state.maxDepth) throwError(state, "nesting exceeded maxDepth (" + state.maxDepth + ")"); state.depth += 1; if (state.listener !== null) state.listener("open", state); state.tag = null; state.anchor = null; state.kind = null; state.result = null; const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext; if (allowToSeek) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; if (state.lineIndent > parentIndent) indentStatus = 1; else if (state.lineIndent === parentIndent) indentStatus = 0; else if (state.lineIndent < parentIndent) indentStatus = -1; } } if (indentStatus === 1) while (true) { const ch = state.input.charCodeAt(state.position); const propertyState = snapshotState(state); if (atNewLine && (ch === 33 && state.tag !== null || ch === 38 && state.anchor !== null)) break; if (!readTagProperty(state) && !readAnchorProperty(state)) break; if (propertyStart === null) propertyStart = propertyState; if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) indentStatus = 1; else if (state.lineIndent === parentIndent) indentStatus = 0; else if (state.lineIndent < parentIndent) indentStatus = -1; } else allowBlockCollections = false; } if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact; if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) flowIndent = parentIndent; else flowIndent = parentIndent + 1; blockIndent = state.position - state.lineStart; if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) hasContent = true; else { const ch = state.input.charCodeAt(state.position); if (propertyStart !== null && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62 && tryReadBlockMappingFromProperty(state, propertyStart, propertyStart.position - propertyStart.lineStart, flowIndent)) hasContent = true; else if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) hasContent = true; else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) throwError(state, "alias node should not have any properties"); } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) state.tag = "?"; } if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); } else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } if (state.tag === null) { if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); } else if (state.tag === "?") { if (state.result !== null && state.kind !== "scalar") throwError(state, "unacceptable node kind for ! tag; it should be \"scalar\", not \"" + state.kind + "\""); for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); break; } } } else if (state.tag !== "!") { if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) type = state.typeMap[state.kind || "fallback"][state.tag]; else { type = null; const typeList = state.typeMap.multi[state.kind || "fallback"]; for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex]; break; } } if (!type) throwError(state, "unknown tag !<" + state.tag + ">"); if (state.result !== null && type.kind !== state.kind) throwError(state, "unacceptable node kind for !<" + state.tag + "> tag; it should be \"" + type.kind + "\", not \"" + state.kind + "\""); if (!type.resolve(state.result, state.tag)) throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag"); else { state.result = type.construct(state.result, state.tag); if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); } } if (state.listener !== null) state.listener("close", state); state.depth -= 1; return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { const documentStart = state.position; let hasDirectives = false; let ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = Object.create(null); state.anchorMap = Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 37) break; hasDirectives = true; ch = state.input.charCodeAt(++state.position); let _position = state.position; while (ch !== 0 && !isWsOrEol(ch)) ch = state.input.charCodeAt(++state.position); const directiveName = state.input.slice(_position, state.position); const directiveArgs = []; if (directiveName.length < 1) throwError(state, "directive name must not be less than one character in length"); while (ch !== 0) { while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position); if (ch === 35) { do ch = state.input.charCodeAt(++state.position); while (ch !== 0 && !isEol(ch)); break; } if (isEol(ch)) break; _position = state.position; while (ch !== 0 && !isWsOrEol(ch)) ch = state.input.charCodeAt(++state.position); directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty.call(directiveHandlers, directiveName)) directiveHandlers[directiveName](state, directiveName, directiveArgs); else throwWarning(state, "unknown document directive \"" + directiveName + "\""); } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) throwError(state, "directives end mark is expected"); composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) throwWarning(state, "non-ASCII line breaks are interpreted as content"); state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 46) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < state.length - 1) throwError(state, "end of the stream or a document separator is expected"); } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) input += "\n"; if (input.charCodeAt(0) === 65279) input = input.slice(1); } const state = new State(input, options); const nullpos = input.indexOf("\0"); if (nullpos !== -1) { state.position = nullpos; throwError(state, "null byte is not allowed in input"); } state.input += "\0"; while (state.input.charCodeAt(state.position) === 32) { state.lineIndent += 1; state.position += 1; } while (state.position < state.length - 1) readDocument(state); return state.documents; } function loadAll(input, iterator, options) { if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") { options = iterator; iterator = null; } const documents = loadDocuments(input, options); if (typeof iterator !== "function") return documents; for (let index = 0, length = documents.length; index < length; index += 1) iterator(documents[index]); } function load(input, options) { const documents = loadDocuments(input, options); if (documents.length === 0) return; else if (documents.length === 1) return documents[0]; throw new YAMLException("expected a single document in the stream, but found more"); } module.exports.loadAll = loadAll; module.exports.load = load; })); //#endregion //#region lib/dumper.js var require_dumper = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var YAMLException = require_exception(); var DEFAULT_SCHEMA = require_default(); var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 65279; var CHAR_TAB = 9; var CHAR_LINE_FEED = 10; var CHAR_CARRIAGE_RETURN = 13; var CHAR_SPACE = 32; var CHAR_EXCLAMATION = 33; var CHAR_DOUBLE_QUOTE = 34; var CHAR_SHARP = 35; var CHAR_PERCENT = 37; var CHAR_AMPERSAND = 38; var CHAR_SINGLE_QUOTE = 39; var CHAR_ASTERISK = 42; var CHAR_COMMA = 44; var CHAR_MINUS = 45; var CHAR_COLON = 58; var CHAR_EQUALS = 61; var CHAR_GREATER_THAN = 62; var CHAR_QUESTION = 63; var CHAR_COMMERCIAL_AT = 64; var CHAR_LEFT_SQUARE_BRACKET = 91; var CHAR_RIGHT_SQUARE_BRACKET = 93; var CHAR_GRAVE_ACCENT = 96; var CHAR_LEFT_CURLY_BRACKET = 123; var CHAR_VERTICAL_LINE = 124; var CHAR_RIGHT_CURLY_BRACKET = 125; var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0] = "\\0"; ESCAPE_SEQUENCES[7] = "\\a"; ESCAPE_SEQUENCES[8] = "\\b"; ESCAPE_SEQUENCES[9] = "\\t"; ESCAPE_SEQUENCES[10] = "\\n"; ESCAPE_SEQUENCES[11] = "\\v"; ESCAPE_SEQUENCES[12] = "\\f"; ESCAPE_SEQUENCES[13] = "\\r"; ESCAPE_SEQUENCES[27] = "\\e"; ESCAPE_SEQUENCES[34] = "\\\""; ESCAPE_SEQUENCES[92] = "\\\\"; ESCAPE_SEQUENCES[133] = "\\N"; ESCAPE_SEQUENCES[160] = "\\_"; ESCAPE_SEQUENCES[8232] = "\\L"; ESCAPE_SEQUENCES[8233] = "\\P"; var DEPRECATED_BOOLEANS_SYNTAX = [ "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", "n", "N", "no", "No", "NO", "off", "Off", "OFF" ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema, map) { if (map === null) return {}; const result = {}; const keys = Object.keys(map); for (let index = 0, length = keys.length; index < length; index += 1) { let tag = keys[index]; let style = String(map[tag]); if (tag.slice(0, 2) === "!!") tag = "tag:yaml.org,2002:" + tag.slice(2); const type = schema.compiledTypeMap["fallback"][tag]; if (type && _hasOwnProperty.call(type.styleAliases, style)) style = type.styleAliases[style]; result[tag] = style; } return result; } function encodeHex(character) { let handle; let length; const string = character.toString(16).toUpperCase(); if (character <= 255) { handle = "x"; length = 2; } else if (character <= 65535) { handle = "u"; length = 4; } else if (character <= 4294967295) { handle = "U"; length = 8; } else throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF"); return "\\" + handle + common.repeat("0", length - string.length) + string; } var QUOTING_TYPE_SINGLE = 1; var QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options["schema"] || DEFAULT_SCHEMA; this.indent = Math.max(1, options["indent"] || 2); this.noArrayIndent = options["noArrayIndent"] || false; this.skipInvalid = options["skipInvalid"] || false; this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"]; this.styleMap = compileStyleMap(this.schema, options["styles"] || null); this.sortKeys = options["sortKeys"] || false; this.lineWidth = options["lineWidth"] || 80; this.noRefs = options["noRefs"] || false; this.noCompatMode = options["noCompatMode"] || false; this.condenseFlow = options["condenseFlow"] || false; this.quotingType = options["quotingType"] === "\"" ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options["forceQuotes"] || false; this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ""; this.duplicates = []; this.usedDuplicates = null; } function indentString(string, spaces) { const ind = common.repeat(" ", spaces); let position = 0; let result = ""; const length = string.length; while (position < length) { let line; const next = string.indexOf("\n", position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== "\n") result += ind; result += line; } return result; } function generateNextLine(state, level) { return "\n" + common.repeat(" ", state.indent * level); } function testImplicitResolving(state, str) { for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) if (state.implicitTypes[index].resolve(str)) return true; return false; } function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } function isPrintable(c) { return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111; } function isNsCharOrWhitespace(c) { return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } function isPlainSafe(c, prev, inblock) { const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar; } function isPlainSafeFirst(c) { return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } function isPlainSafeLast(c) { return !isWhitespace(c) && c !== CHAR_COLON; } function codePointAt(string, pos) { const first = string.charCodeAt(pos); let second; if (first >= 55296 && first <= 56319 && pos + 1 < string.length) { second = string.charCodeAt(pos + 1); if (second >= 56320 && second <= 57343) return (first - 55296) * 1024 + second - 56320 + 65536; } return first; } function needIndentIndicator(string) { return /^\n* /.test(string); } var STYLE_PLAIN = 1; var STYLE_SINGLE = 2; var STYLE_LITERAL = 3; var STYLE_FOLDED = 4; var STYLE_DOUBLE = 5; function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { let i; let char = 0; let prevChar = null; let hasLineBreak = false; let hasFoldableLine = false; const shouldTrackWidth = lineWidth !== -1; let previousLineBreak = -1; let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1)); if (singleLineOnly || forceQuotes) for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string, i); if (!isPrintable(char)) return STYLE_DOUBLE; plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } else { for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string, i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " "; previousLineBreak = i; } } else if (!isPrintable(char)) return STYLE_DOUBLE; plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " "; } if (!hasLineBreak && !hasFoldableLine) { if (plain && !forceQuotes && !testAmbiguousType(string)) return STYLE_PLAIN; return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } if (indentPerLevel > 9 && needIndentIndicator(string)) return STYLE_DOUBLE; if (!forceQuotes) return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } function writeScalar(state, string, level, iskey, inblock) { state.dump = function() { if (string.length === 0) return state.quotingType === QUOTING_TYPE_DOUBLE ? "\"\"" : "''"; if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) return state.quotingType === QUOTING_TYPE_DOUBLE ? "\"" + string + "\"" : "'" + string + "'"; } const indent = state.indent * Math.max(1, level); const lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); const singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel; function testAmbiguity(string) { return testImplicitResolving(state, string); } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { case STYLE_PLAIN: return string; case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)); case STYLE_FOLDED: return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); case STYLE_DOUBLE: return "\"" + escapeString(string, lineWidth) + "\""; default: throw new YAMLException("impossible error: invalid scalar style"); } }(); } function blockHeader(string, indentPerLevel) { const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ""; const clip = string[string.length - 1] === "\n"; return indentIndicator + (clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-") + "\n"; } function dropEndingNewline(string) { return string[string.length - 1] === "\n" ? string.slice(0, -1) : string; } function foldString(string, width) { const lineRe = /(\n+)([^\n]*)/g; let result = function() { let nextLF = string.indexOf("\n"); nextLF = nextLF !== -1 ? nextLF : string.length; lineRe.lastIndex = nextLF; return foldLine(string.slice(0, nextLF), width); }(); let prevMoreIndented = string[0] === "\n" || string[0] === " "; let moreIndented; let match; while (match = lineRe.exec(string)) { const prefix = match[1]; const line = match[2]; moreIndented = line[0] === " "; result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } function foldLine(line, width) { if (line === "" || line[0] === " ") return line; const breakRe = / [^ ]/g; let match; let start = 0; let end; let curr = 0; let next = 0; let result = ""; while (match = breakRe.exec(line)) { next = match.index; if (next - start > width) { end = curr > start ? curr : next; result += "\n" + line.slice(start, end); start = end + 1; } curr = next; } result += "\n"; if (line.length - start > width && curr > start) result += line.slice(start, curr) + "\n" + line.slice(curr + 1); else result += line.slice(start); return result.slice(1); } function escapeString(string) { let result = ""; let char = 0; for (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string, i); const escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string[i]; if (char >= 65536) result += string[i + 1]; } else result += escapeSeq || encodeHex(char); } return result; } function writeFlowSequence(state, level, object) { let _result = ""; const _tag = state.tag; for (let index = 0, length = object.length; index < length; index += 1) { let value = object[index]; if (state.replacer) value = state.replacer.call(object, String(index), value); if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) { if (_result !== "") _result += "," + (!state.condenseFlow ? " " : ""); _result += state.dump; } } state.tag = _tag; state.dump = "[" + _result + "]"; } function writeBlockSequence(state, level, object, compact) { let _result = ""; const _tag = state.tag; for (let index = 0, length = object.length; index < length; index += 1) { let value = object[index]; if (state.replacer) value = state.replacer.call(object, String(index), value); if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) { if (!compact || _result !== "") _result += generateNextLine(state, level); if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) _result += "-"; else _result += "- "; _result += state.dump; } } state.tag = _tag; state.dump = _result || "[]"; } function writeFlowMapping(state, level, object) { let _result = ""; const _tag = state.tag; const objectKeyList = Object.keys(object); for (let index = 0, length = objectKeyList.length; index < length; index += 1) { let pairBuffer = ""; if (_result !== "") pairBuffer += ", "; if (state.condenseFlow) pairBuffer += "\""; const objectKey = objectKeyList[index]; let objectValue = object[objectKey]; if (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue); if (!writeNode(state, level, objectKey, false, false)) continue; if (state.dump.length > 1024) pairBuffer += "? "; pairBuffer += state.dump + (state.condenseFlow ? "\"" : "") + ":" + (state.condenseFlow ? "" : " "); if (!writeNode(state, level, objectValue, false, false)) continue; pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = "{" + _result + "}"; } function writeBlockMapping(state, level, object, compact) { let _result = ""; const _tag = state.tag; const objectKeyList = Object.keys(object); if (state.sortKeys === true) objectKeyList.sort(); else if (typeof state.sortKeys === "function") objectKeyList.sort(state.sortKeys); else if (state.sortKeys) throw new YAMLException("sortKeys must be a boolean or a function"); for (let index = 0, length = objectKeyList.length; index < length; index += 1) { let pairBuffer = ""; if (!compact || _result !== "") pairBuffer += generateNextLine(state, level); const objectKey = objectKeyList[index]; let objectValue = object[objectKey]; if (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue); if (!writeNode(state, level + 1, objectKey, true, true, true)) continue; const explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024; if (explicitPair) if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) pairBuffer += "?"; else pairBuffer += "? "; pairBuffer += state.dump; if (explicitPair) pairBuffer += generateNextLine(state, level); if (!writeNode(state, level + 1, objectValue, true, explicitPair)) continue; if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) pairBuffer += ":"; else pairBuffer += ": "; pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = _result || "{}"; } function detectType(state, object, explicit) { const typeList = explicit ? state.explicitTypes : state.implicitTypes; for (let index = 0, length = typeList.length; index < length; index += 1) { const type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) { if (explicit) if (type.multi && type.representName) state.tag = type.representName(object); else state.tag = type.tag; else state.tag = "?"; if (type.represent) { const style = state.styleMap[type.tag] || type.defaultStyle; let _result; if (_toString.call(type.represent) === "[object Function]") _result = type.represent(object, style); else if (_hasOwnProperty.call(type.represent, style)) _result = type.represent[style](object, style); else throw new YAMLException("!<" + type.tag + "> tag resolver accepts not \"" + style + "\" style"); state.dump = _result; } return true; } } return false; } function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) detectType(state, object, true); const type = _toString.call(state.dump); const inblock = block; if (block) block = state.flowLevel < 0 || state.flowLevel > level; const objectOrArray = type === "[object Object]" || type === "[object Array]"; let duplicateIndex; let duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) compact = false; if (duplicate && state.usedDuplicates[duplicateIndex]) state.dump = "*ref_" + duplicateIndex; else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) state.usedDuplicates[duplicateIndex] = true; if (type === "[object Object]") if (block && Object.keys(state.dump).length !== 0) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) state.dump = "&ref_" + duplicateIndex + state.dump; } else { writeFlowMapping(state, level, state.dump); if (duplicate) state.dump = "&ref_" + duplicateIndex + " " + state.dump; } else if (type === "[object Array]") if (block && state.dump.length !== 0) { if (state.noArrayIndent && !isblockseq && level > 0) writeBlockSequence(state, level - 1, state.dump, compact); else writeBlockSequence(state, level, state.dump, compact); if (duplicate) state.dump = "&ref_" + duplicateIndex + state.dump; } else { writeFlowSequence(state, level, state.dump); if (duplicate) state.dump = "&ref_" + duplicateIndex + " " + state.dump; } else if (type === "[object String]") { if (state.tag !== "?") writeScalar(state, state.dump, level, iskey, inblock); } else if (type === "[object Undefined]") return false; else { if (state.skipInvalid) return false; throw new YAMLException("unacceptable kind of an object to dump " + type); } if (state.tag !== null && state.tag !== "?") { let tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21"); if (state.tag[0] === "!") tagStr = "!" + tagStr; else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") tagStr = "!!" + tagStr.slice(18); else tagStr = "!<" + tagStr + ">"; state.dump = tagStr + " " + state.dump; } } return true; } function getDuplicateReferences(object, state) { const objects = []; const duplicatesIndexes = []; inspectNode(object, objects, duplicatesIndexes); const length = duplicatesIndexes.length; for (let index = 0; index < length; index += 1) state.duplicates.push(objects[duplicatesIndexes[index]]); state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { if (object !== null && typeof object === "object") { const index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) duplicatesIndexes.push(index); } else { objects.push(object); if (Array.isArray(object)) for (let i = 0, length = object.length; i < length; i += 1) inspectNode(object[i], objects, duplicatesIndexes); else { const objectKeyList = Object.keys(object); for (let i = 0, length = objectKeyList.length; i < length; i += 1) inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes); } } } } function dump(input, options) { options = options || {}; const state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); let value = input; if (state.replacer) value = state.replacer.call({ "": value }, "", value); if (writeNode(state, 0, value, true, true)) return state.dump + "\n"; return ""; } module.exports.dump = dump; })); //#endregion //#region lib/index_vite_proxy.tmp.mjs var import_js_yaml = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => { var loader = require_loader(); var dumper = require_dumper(); function renamed(from, to) { return function() { throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default."); }; } module.exports.Type = require_type(); module.exports.Schema = require_schema(); module.exports.FAILSAFE_SCHEMA = require_failsafe(); module.exports.JSON_SCHEMA = require_json(); module.exports.CORE_SCHEMA = require_core(); module.exports.DEFAULT_SCHEMA = require_default(); module.exports.load = loader.load; module.exports.loadAll = loader.loadAll; module.exports.dump = dumper.dump; module.exports.YAMLException = require_exception(); module.exports.types = { binary: require_binary(), float: require_float(), map: require_map(), null: require_null(), pairs: require_pairs(), set: require_set(), timestamp: require_timestamp(), bool: require_bool(), int: require_int(), merge: require_merge(), omap: require_omap(), seq: require_seq(), str: require_str() }; module.exports.safeLoad = renamed("safeLoad", "load"); module.exports.safeLoadAll = renamed("safeLoadAll", "loadAll"); module.exports.safeDump = renamed("safeDump", "dump"); })))(), 1); var { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump } = import_js_yaml.default; var index_vite_proxy_tmp_default = import_js_yaml.default; //#endregion exports.CORE_SCHEMA = CORE_SCHEMA; exports.DEFAULT_SCHEMA = DEFAULT_SCHEMA; exports.FAILSAFE_SCHEMA = FAILSAFE_SCHEMA; exports.JSON_SCHEMA = JSON_SCHEMA; exports.Schema = Schema; exports.Type = Type; exports.YAMLException = YAMLException; exports.default = index_vite_proxy_tmp_default; exports.dump = dump; exports.load = load; exports.loadAll = loadAll; exports.safeDump = safeDump; exports.safeLoad = safeLoad; exports.safeLoadAll = safeLoadAll; exports.types = types; }); //# sourceMappingURL=js-yaml.js.map{"version":3,"file":"js-yaml.js","names":["yaml"],"sources":["../lib/common.js","../lib/exception.js","../lib/snippet.js","../lib/type.js","../lib/schema.js","../lib/type/str.js","../lib/type/seq.js","../lib/type/map.js","../lib/schema/failsafe.js","../lib/type/null.js","../lib/type/bool.js","../lib/type/int.js","../lib/type/float.js","../lib/schema/json.js","../lib/schema/core.js","../lib/type/timestamp.js","../lib/type/merge.js","../lib/type/binary.js","../lib/type/omap.js","../lib/type/pairs.js","../lib/type/set.js","../lib/schema/default.js","../lib/loader.js","../lib/dumper.js","../index.js","../lib/index_vite_proxy.tmp.mjs"],"sourcesContent":["'use strict'\n\nfunction isNothing (subject) {\n return (typeof subject === 'undefined') || (subject === null)\n}\n\nfunction isObject (subject) {\n return (typeof subject === 'object') && (subject !== null)\n}\n\nfunction toArray (sequence) {\n if (Array.isArray(sequence)) return sequence\n else if (isNothing(sequence)) return []\n\n return [sequence]\n}\n\nfunction extend (target, source) {\n if (source) {\n const sourceKeys = Object.keys(source)\n\n for (let index = 0, length = sourceKeys.length; index < length; index += 1) {\n const key = sourceKeys[index]\n target[key] = source[key]\n }\n }\n\n return target\n}\n\nfunction repeat (string, count) {\n let result = ''\n\n for (let cycle = 0; cycle < count; cycle += 1) {\n result += string\n }\n\n return result\n}\n\nfunction isNegativeZero (number) {\n return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number)\n}\n\nmodule.exports.isNothing = isNothing\nmodule.exports.isObject = isObject\nmodule.exports.toArray = toArray\nmodule.exports.repeat = repeat\nmodule.exports.isNegativeZero = isNegativeZero\nmodule.exports.extend = extend\n","// YAML error class. http://stackoverflow.com/questions/8458984\n//\n'use strict'\n\nfunction formatError (exception, compact) {\n let where = ''\n const message = exception.reason || '(unknown reason)'\n\n if (!exception.mark) return message\n\n if (exception.mark.name) {\n where += 'in \"' + exception.mark.name + '\" '\n }\n\n where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'\n\n if (!compact && exception.mark.snippet) {\n where += '\\n\\n' + exception.mark.snippet\n }\n\n return message + ' ' + where\n}\n\nfunction YAMLException (reason, mark) {\n // Super constructor\n Error.call(this)\n\n this.name = 'YAMLException'\n this.reason = reason\n this.mark = mark\n this.message = formatError(this, false)\n\n // Include stack trace in error object\n if (Error.captureStackTrace) {\n // Chrome and NodeJS\n Error.captureStackTrace(this, this.constructor)\n } else {\n // FF, IE 10+ and Safari 6+. Fallback for others\n this.stack = (new Error()).stack || ''\n }\n}\n\n// Inherit from Error\nYAMLException.prototype = Object.create(Error.prototype)\nYAMLException.prototype.constructor = YAMLException\n\nYAMLException.prototype.toString = function toString (compact) {\n return this.name + ': ' + formatError(this, compact)\n}\n\nmodule.exports = YAMLException\n","'use strict'\n\nconst common = require('./common')\n\n// get snippet for a single line, respecting maxLength\nfunction getLine (buffer, lineStart, lineEnd, position, maxLineLength) {\n let head = ''\n let tail = ''\n const maxHalfLength = Math.floor(maxLineLength / 2) - 1\n\n if (position - lineStart > maxHalfLength) {\n head = ' ... '\n lineStart = position - maxHalfLength + head.length\n }\n\n if (lineEnd - position > maxHalfLength) {\n tail = ' ...'\n lineEnd = position + maxHalfLength - tail.length\n }\n\n return {\n str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, '→') + tail,\n pos: position - lineStart + head.length // relative position\n }\n}\n\nfunction padStart (string, max) {\n return common.repeat(' ', max - string.length) + string\n}\n\nfunction makeSnippet (mark, options) {\n options = Object.create(options || null)\n\n if (!mark.buffer) return null\n\n if (!options.maxLength) options.maxLength = 79\n if (typeof options.indent !== 'number') options.indent = 1\n if (typeof options.linesBefore !== 'number') options.linesBefore = 3\n if (typeof options.linesAfter !== 'number') options.linesAfter = 2\n\n const re = /\\r?\\n|\\r|\\0/g\n const lineStarts = [0]\n const lineEnds = []\n let match\n let foundLineNo = -1\n\n while ((match = re.exec(mark.buffer))) {\n lineEnds.push(match.index)\n lineStarts.push(match.index + match[0].length)\n\n if (mark.position <= match.index && foundLineNo < 0) {\n foundLineNo = lineStarts.length - 2\n }\n }\n\n if (foundLineNo < 0) foundLineNo = lineStarts.length - 1\n\n let result = ''\n const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length\n const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3)\n\n for (let i = 1; i <= options.linesBefore; i++) {\n if (foundLineNo - i < 0) break\n const line = getLine(\n mark.buffer,\n lineStarts[foundLineNo - i],\n lineEnds[foundLineNo - i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n maxLineLength\n )\n result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n' + result\n }\n\n const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength)\n result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n'\n result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\\n'\n\n for (let i = 1; i <= options.linesAfter; i++) {\n if (foundLineNo + i >= lineEnds.length) break\n const line = getLine(\n mark.buffer,\n lineStarts[foundLineNo + i],\n lineEnds[foundLineNo + i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n maxLineLength\n )\n result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n'\n }\n\n return result.replace(/\\n$/, '')\n}\n\nmodule.exports = makeSnippet\n","'use strict'\n\nconst YAMLException = require('./exception')\n\nconst TYPE_CONSTRUCTOR_OPTIONS = [\n 'kind',\n 'multi',\n 'resolve',\n 'construct',\n 'instanceOf',\n 'predicate',\n 'represent',\n 'representName',\n 'defaultStyle',\n 'styleAliases'\n]\n\nconst YAML_NODE_KINDS = [\n 'scalar',\n 'sequence',\n 'mapping'\n]\n\nfunction compileStyleAliases (map) {\n const result = {}\n\n if (map !== null) {\n Object.keys(map).forEach(function (style) {\n map[style].forEach(function (alias) {\n result[String(alias)] = style\n })\n })\n }\n\n return result\n}\n\nfunction Type (tag, options) {\n options = options || {}\n\n Object.keys(options).forEach(function (name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new YAMLException('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.')\n }\n })\n\n // TODO: Add tag format check.\n this.options = options // keep original options in case user wants to extend this type later\n this.tag = tag\n this.kind = options['kind'] || null\n this.resolve = options['resolve'] || function () { return true }\n this.construct = options['construct'] || function (data) { return data }\n this.instanceOf = options['instanceOf'] || null\n this.predicate = options['predicate'] || null\n this.represent = options['represent'] || null\n this.representName = options['representName'] || null\n this.defaultStyle = options['defaultStyle'] || null\n this.multi = options['multi'] || false\n this.styleAliases = compileStyleAliases(options['styleAliases'] || null)\n\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new YAMLException('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.')\n }\n}\n\nmodule.exports = Type\n","'use strict'\n\nconst YAMLException = require('./exception')\nconst Type = require('./type')\n\nfunction compileList (schema, name) {\n const result = []\n\n schema[name].forEach(function (currentType) {\n let newIndex = result.length\n\n result.forEach(function (previousType, previousIndex) {\n if (previousType.tag === currentType.tag &&\n previousType.kind === currentType.kind &&\n previousType.multi === currentType.multi) {\n newIndex = previousIndex\n }\n })\n\n result[newIndex] = currentType\n })\n\n return result\n}\n\nfunction compileMap (/* lists... */) {\n const result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {},\n multi: {\n scalar: [],\n sequence: [],\n mapping: [],\n fallback: []\n }\n }\n function collectType (type) {\n if (type.multi) {\n result.multi[type.kind].push(type)\n result.multi['fallback'].push(type)\n } else {\n result[type.kind][type.tag] = result['fallback'][type.tag] = type\n }\n }\n\n for (let index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType)\n }\n return result\n}\n\nfunction Schema (definition) {\n return this.extend(definition)\n}\n\nSchema.prototype.extend = function extend (definition) {\n let implicit = []\n let explicit = []\n\n if (definition instanceof Type) {\n // Schema.extend(type)\n explicit.push(definition)\n } else if (Array.isArray(definition)) {\n // Schema.extend([ type1, type2, ... ])\n explicit = explicit.concat(definition)\n } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })\n if (definition.implicit) implicit = implicit.concat(definition.implicit)\n if (definition.explicit) explicit = explicit.concat(definition.explicit)\n } else {\n throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' +\n 'or a schema definition ({ implicit: [...], explicit: [...] })')\n }\n\n implicit.forEach(function (type) {\n if (!(type instanceof Type)) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.')\n }\n\n if (type.loadKind && type.loadKind !== 'scalar') {\n throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.')\n }\n\n if (type.multi) {\n throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.')\n }\n })\n\n explicit.forEach(function (type) {\n if (!(type instanceof Type)) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.')\n }\n })\n\n const result = Object.create(Schema.prototype)\n\n result.implicit = (this.implicit || []).concat(implicit)\n result.explicit = (this.explicit || []).concat(explicit)\n\n result.compiledImplicit = compileList(result, 'implicit')\n result.compiledExplicit = compileList(result, 'explicit')\n result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit)\n\n return result\n}\n\nmodule.exports = Schema\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:str', {\n kind: 'scalar',\n construct: function (data) { return data !== null ? data : '' }\n})\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:seq', {\n kind: 'sequence',\n construct: function (data) { return data !== null ? data : [] }\n})\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:map', {\n kind: 'mapping',\n construct: function (data) { return data !== null ? data : {} }\n})\n","// Standard YAML's Failsafe schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2802346\n\n'use strict'\n\nconst Schema = require('../schema')\n\nmodule.exports = new Schema({\n explicit: [\n require('../type/str'),\n require('../type/seq'),\n require('../type/map')\n ]\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlNull (data) {\n if (data === null) return true\n\n const max = data.length\n\n return (max === 1 && data === '~') ||\n (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'))\n}\n\nfunction constructYamlNull () {\n return null\n}\n\nfunction isNull (object) {\n return object === null\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:null', {\n kind: 'scalar',\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: function () { return '~' },\n lowercase: function () { return 'null' },\n uppercase: function () { return 'NULL' },\n camelcase: function () { return 'Null' },\n empty: function () { return '' }\n },\n defaultStyle: 'lowercase'\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlBoolean (data) {\n if (data === null) return false\n\n const max = data.length\n\n return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'))\n}\n\nfunction constructYamlBoolean (data) {\n return data === 'true' ||\n data === 'True' ||\n data === 'TRUE'\n}\n\nfunction isBoolean (object) {\n return Object.prototype.toString.call(object) === '[object Boolean]'\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:bool', {\n kind: 'scalar',\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: function (object) { return object ? 'true' : 'false' },\n uppercase: function (object) { return object ? 'TRUE' : 'FALSE' },\n camelcase: function (object) { return object ? 'True' : 'False' }\n },\n defaultStyle: 'lowercase'\n})\n","'use strict'\n\nconst common = require('../common')\nconst Type = require('../type')\n\nfunction isHexCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) ||\n ((c >= 0x41/* A */) && (c <= 0x46/* F */)) ||\n ((c >= 0x61/* a */) && (c <= 0x66/* f */))\n}\n\nfunction isOctCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x37/* 7 */))\n}\n\nfunction isDecCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */))\n}\n\nfunction resolveYamlInteger (data) {\n if (data === null) return false\n\n const max = data.length\n let index = 0\n let hasDigits = false\n\n if (!max) return false\n\n let ch = data[index]\n\n // sign\n if (ch === '-' || ch === '+') {\n ch = data[++index]\n }\n\n if (ch === '0') {\n // 0\n if (index + 1 === max) return true\n ch = data[++index]\n\n // base 2, base 8, base 16\n\n if (ch === 'b') {\n // base 2\n index++\n\n for (; index < max; index++) {\n ch = data[index]\n if (ch !== '0' && ch !== '1') return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n\n if (ch === 'x') {\n // base 16\n index++\n\n for (; index < max; index++) {\n if (!isHexCode(data.charCodeAt(index))) return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n\n if (ch === 'o') {\n // base 8\n index++\n\n for (; index < max; index++) {\n if (!isOctCode(data.charCodeAt(index))) return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n }\n\n // base 10 (except 0)\n\n for (; index < max; index++) {\n if (!isDecCode(data.charCodeAt(index))) {\n return false\n }\n hasDigits = true\n }\n\n if (!hasDigits) return false\n\n return Number.isFinite(parseYamlInteger(data))\n}\n\nfunction parseYamlInteger (data) {\n let value = data\n let sign = 1\n\n let ch = value[0]\n\n if (ch === '-' || ch === '+') {\n if (ch === '-') sign = -1\n value = value.slice(1)\n ch = value[0]\n }\n\n if (value === '0') return 0\n\n if (ch === '0') {\n if (value[1] === 'b') return sign * parseInt(value.slice(2), 2)\n if (value[1] === 'x') return sign * parseInt(value.slice(2), 16)\n if (value[1] === 'o') return sign * parseInt(value.slice(2), 8)\n }\n\n return sign * parseInt(value, 10)\n}\n\nfunction constructYamlInteger (data) {\n return parseYamlInteger(data)\n}\n\nfunction isInteger (object) {\n return (Object.prototype.toString.call(object)) === '[object Number]' &&\n (object % 1 === 0 && !common.isNegativeZero(object))\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:int', {\n kind: 'scalar',\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1) },\n octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1) },\n decimal: function (obj) { return obj.toString(10) },\n hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1) }\n },\n defaultStyle: 'decimal',\n styleAliases: {\n binary: [2, 'bin'],\n octal: [8, 'oct'],\n decimal: [10, 'dec'],\n hexadecimal: [16, 'hex']\n }\n})\n","'use strict'\n\nconst common = require('../common')\nconst Type = require('../type')\n\nconst YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n '^(?:[-+]?(?:[0-9]+)(?:\\\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?' +\n // .2e4, .2\n // special case, seems not from spec\n '|\\\\.[0-9]+(?:[eE][-+]?[0-9]+)?' +\n // .inf\n '|[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$')\n\nconst YAML_FLOAT_SPECIAL_PATTERN = new RegExp(\n '^(?:' +\n // .inf\n '[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$')\n\nfunction resolveYamlFloat (data) {\n if (data === null) return false\n\n if (!YAML_FLOAT_PATTERN.test(data)) {\n return false\n }\n\n if (Number.isFinite(parseFloat(data, 10))) {\n return true\n }\n\n return YAML_FLOAT_SPECIAL_PATTERN.test(data)\n}\n\nfunction constructYamlFloat (data) {\n let value = data.toLowerCase()\n const sign = value[0] === '-' ? -1 : 1\n\n if ('+-'.indexOf(value[0]) >= 0) {\n value = value.slice(1)\n }\n\n if (value === '.inf') {\n return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY\n } else if (value === '.nan') {\n return NaN\n }\n return sign * parseFloat(value, 10)\n}\n\nconst SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/\n\nfunction representYamlFloat (object, style) {\n if (isNaN(object)) {\n switch (style) {\n case 'lowercase': return '.nan'\n case 'uppercase': return '.NAN'\n case 'camelcase': return '.NaN'\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '.inf'\n case 'uppercase': return '.INF'\n case 'camelcase': return '.Inf'\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '-.inf'\n case 'uppercase': return '-.INF'\n case 'camelcase': return '-.Inf'\n }\n } else if (common.isNegativeZero(object)) {\n return '-0.0'\n }\n\n const res = object.toString(10)\n\n // JS stringifier can build scientific format without dots: 5e-100,\n // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res\n}\n\nfunction isFloat (object) {\n return (Object.prototype.toString.call(object) === '[object Number]') &&\n (object % 1 !== 0 || common.isNegativeZero(object))\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:float', {\n kind: 'scalar',\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: 'lowercase'\n})\n","// Standard YAML's JSON schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2803231\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, this schema is not such strict as defined in the YAML specification.\n// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.\n\n'use strict'\n\nmodule.exports = require('./failsafe').extend({\n implicit: [\n require('../type/null'),\n require('../type/bool'),\n require('../type/int'),\n require('../type/float')\n ]\n})\n","// Standard YAML's Core schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2804923\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, Core schema has no distinctions from JSON schema is JS-YAML.\n\n'use strict'\n\nmodule.exports = require('./json')\n","'use strict'\n\nconst Type = require('../type')\n\nconst YAML_DATE_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9])' + // [2] month\n '-([0-9][0-9])$') // [3] day\n\nconst YAML_TIMESTAMP_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9]?)' + // [2] month\n '-([0-9][0-9]?)' + // [3] day\n '(?:[Tt]|[ \\\\t]+)' + // ...\n '([0-9][0-9]?)' + // [4] hour\n ':([0-9][0-9])' + // [5] minute\n ':([0-9][0-9])' + // [6] second\n '(?:\\\\.([0-9]*))?' + // [7] fraction\n '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tzHour\n '(?::([0-9][0-9]))?))?$') // [11] tzMinute\n\nfunction resolveYamlTimestamp (data) {\n if (data === null) return false\n if (YAML_DATE_REGEXP.exec(data) !== null) return true\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true\n return false\n}\n\nfunction constructYamlTimestamp (data) {\n let fraction = 0\n let delta = null\n\n let match = YAML_DATE_REGEXP.exec(data)\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data)\n\n if (match === null) throw new Error('Date resolve error')\n\n // match: [1] year [2] month [3] day\n\n const year = +(match[1])\n const month = +(match[2]) - 1 // JS month starts with 0\n const day = +(match[3])\n\n if (!match[4]) { // no hour\n return new Date(Date.UTC(year, month, day))\n }\n\n // match: [4] hour [5] minute [6] second [7] fraction\n\n const hour = +(match[4])\n const minute = +(match[5])\n const second = +(match[6])\n\n if (match[7]) {\n fraction = match[7].slice(0, 3)\n while (fraction.length < 3) { // milli-seconds\n fraction += '0'\n }\n fraction = +fraction\n }\n\n // match: [8] tz [9] tz_sign [10] tzHour [11] tzMinute\n\n if (match[9]) {\n const tzHour = +(match[10])\n const tzMinute = +(match[11] || 0)\n delta = (tzHour * 60 + tzMinute) * 60000 // delta in mili-seconds\n if (match[9] === '-') delta = -delta\n }\n\n const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction))\n\n if (delta) date.setTime(date.getTime() - delta)\n\n return date\n}\n\nfunction representYamlTimestamp (object /*, style */) {\n return object.toISOString()\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:timestamp', {\n kind: 'scalar',\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlMerge (data) {\n return data === '<<' || data === null\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:merge', {\n kind: 'scalar',\n resolve: resolveYamlMerge\n})\n","'use strict'\n\nconst Type = require('../type')\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nconst BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r'\n\nfunction resolveYamlBinary (data) {\n if (data === null) return false\n\n let bitlen = 0\n const max = data.length\n const map = BASE64_MAP\n\n // Convert one by one.\n for (let idx = 0; idx < max; idx++) {\n const code = map.indexOf(data.charAt(idx))\n\n // Skip CR/LF\n if (code > 64) continue\n\n // Fail on illegal characters\n if (code < 0) return false\n\n bitlen += 6\n }\n\n // If there are any bits left, source was corrupted\n return (bitlen % 8) === 0\n}\n\nfunction constructYamlBinary (data) {\n const input = data.replace(/[\\r\\n=]/g, '') // remove CR/LF & padding to simplify scan\n const max = input.length\n const map = BASE64_MAP\n let bits = 0\n const result = []\n\n // Collect by 6*4 bits (3 bytes)\n\n for (let idx = 0; idx < max; idx++) {\n if ((idx % 4 === 0) && idx) {\n result.push((bits >> 16) & 0xFF)\n result.push((bits >> 8) & 0xFF)\n result.push(bits & 0xFF)\n }\n\n bits = (bits << 6) | map.indexOf(input.charAt(idx))\n }\n\n // Dump tail\n\n const tailbits = (max % 4) * 6\n\n if (tailbits === 0) {\n result.push((bits >> 16) & 0xFF)\n result.push((bits >> 8) & 0xFF)\n result.push(bits & 0xFF)\n } else if (tailbits === 18) {\n result.push((bits >> 10) & 0xFF)\n result.push((bits >> 2) & 0xFF)\n } else if (tailbits === 12) {\n result.push((bits >> 4) & 0xFF)\n }\n\n return new Uint8Array(result)\n}\n\nfunction representYamlBinary (object /*, style */) {\n let result = ''\n let bits = 0\n const max = object.length\n const map = BASE64_MAP\n\n // Convert every three bytes to 4 ASCII characters.\n\n for (let idx = 0; idx < max; idx++) {\n if ((idx % 3 === 0) && idx) {\n result += map[(bits >> 18) & 0x3F]\n result += map[(bits >> 12) & 0x3F]\n result += map[(bits >> 6) & 0x3F]\n result += map[bits & 0x3F]\n }\n\n bits = (bits << 8) + object[idx]\n }\n\n // Dump tail\n\n const tail = max % 3\n\n if (tail === 0) {\n result += map[(bits >> 18) & 0x3F]\n result += map[(bits >> 12) & 0x3F]\n result += map[(bits >> 6) & 0x3F]\n result += map[bits & 0x3F]\n } else if (tail === 2) {\n result += map[(bits >> 10) & 0x3F]\n result += map[(bits >> 4) & 0x3F]\n result += map[(bits << 2) & 0x3F]\n result += map[64]\n } else if (tail === 1) {\n result += map[(bits >> 2) & 0x3F]\n result += map[(bits << 4) & 0x3F]\n result += map[64]\n result += map[64]\n }\n\n return result\n}\n\nfunction isBinary (obj) {\n return Object.prototype.toString.call(obj) === '[object Uint8Array]'\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:binary', {\n kind: 'scalar',\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\nconst _toString = Object.prototype.toString\n\nfunction resolveYamlOmap (data) {\n if (data === null) return true\n\n const objectKeys = []\n const object = data\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n let pairHasKey = false\n\n if (_toString.call(pair) !== '[object Object]') return false\n\n let pairKey\n for (pairKey in pair) {\n if (_hasOwnProperty.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true\n else return false\n }\n }\n\n if (!pairHasKey) return false\n\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey)\n else return false\n }\n\n return true\n}\n\nfunction constructYamlOmap (data) {\n return data !== null ? data : []\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:omap', {\n kind: 'sequence',\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _toString = Object.prototype.toString\n\nfunction resolveYamlPairs (data) {\n if (data === null) return true\n\n const object = data\n\n const result = new Array(object.length)\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n\n if (_toString.call(pair) !== '[object Object]') return false\n\n const keys = Object.keys(pair)\n\n if (keys.length !== 1) return false\n\n result[index] = [keys[0], pair[keys[0]]]\n }\n\n return true\n}\n\nfunction constructYamlPairs (data) {\n if (data === null) return []\n\n const object = data\n const result = new Array(object.length)\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n\n const keys = Object.keys(pair)\n\n result[index] = [keys[0], pair[keys[0]]]\n }\n\n return result\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:pairs', {\n kind: 'sequence',\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nfunction resolveYamlSet (data) {\n if (data === null) return true\n\n const object = data\n\n for (const key in object) {\n if (_hasOwnProperty.call(object, key)) {\n if (object[key] !== null) return false\n }\n }\n\n return true\n}\n\nfunction constructYamlSet (data) {\n return data !== null ? data : {}\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:set', {\n kind: 'mapping',\n resolve: resolveYamlSet,\n construct: constructYamlSet\n})\n","// JS-YAML's default schema for `safeLoad` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on standard YAML's Core schema and includes most of\n// extra types described at YAML tag repository. (http://yaml.org/type/)\n\n'use strict'\n\nmodule.exports = require('./core').extend({\n implicit: [\n require('../type/timestamp'),\n require('../type/merge')\n ],\n explicit: [\n require('../type/binary'),\n require('../type/omap'),\n require('../type/pairs'),\n require('../type/set')\n ]\n})\n","'use strict'\n\nconst common = require('./common')\nconst YAMLException = require('./exception')\nconst makeSnippet = require('./snippet')\nconst DEFAULT_SCHEMA = require('./schema/default')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nconst CONTEXT_FLOW_IN = 1\nconst CONTEXT_FLOW_OUT = 2\nconst CONTEXT_BLOCK_IN = 3\nconst CONTEXT_BLOCK_OUT = 4\n\nconst CHOMPING_CLIP = 1\nconst CHOMPING_STRIP = 2\nconst CHOMPING_KEEP = 3\n\n// eslint-disable-next-line no-control-regex\nconst PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/\nconst PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_FLOW_INDICATORS = /[,\\[\\]{}]/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_TAG_URI = /^(?:!|[^,\\[\\]{}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;/?:@&=+$,_.!~*'()\\[\\]])*$/i\n\nfunction _class (obj) { return Object.prototype.toString.call(obj) }\n\nfunction isEol (c) {\n return (c === 0x0A/* LF */) || (c === 0x0D/* CR */)\n}\n\nfunction isWhiteSpace (c) {\n return (c === 0x09/* Tab */) || (c === 0x20/* Space */)\n}\n\nfunction isWsOrEol (c) {\n return (c === 0x09/* Tab */) ||\n (c === 0x20/* Space */) ||\n (c === 0x0A/* LF */) ||\n (c === 0x0D/* CR */)\n}\n\nfunction isFlowIndicator (c) {\n return c === 0x2C/* , */ ||\n c === 0x5B/* [ */ ||\n c === 0x5D/* ] */ ||\n c === 0x7B/* { */ ||\n c === 0x7D/* } */\n}\n\nfunction fromHexCode (c) {\n if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) {\n return c - 0x30\n }\n\n const lc = c | 0x20\n\n if ((lc >= 0x61/* a */) && (lc <= 0x66/* f */)) {\n return lc - 0x61 + 10\n }\n\n return -1\n}\n\nfunction escapedHexLen (c) {\n if (c === 0x78/* x */) { return 2 }\n if (c === 0x75/* u */) { return 4 }\n if (c === 0x55/* U */) { return 8 }\n return 0\n}\n\nfunction fromDecimalCode (c) {\n if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) {\n return c - 0x30\n }\n\n return -1\n}\n\nfunction simpleEscapeSequence (c) {\n switch (c) {\n case 0x30/* 0 */: return '\\x00'\n case 0x61/* a */: return '\\x07'\n case 0x62/* b */: return '\\x08'\n case 0x74/* t */: return '\\x09'\n case 0x09/* Tab */: return '\\x09'\n case 0x6E/* n */: return '\\x0A'\n case 0x76/* v */: return '\\x0B'\n case 0x66/* f */: return '\\x0C'\n case 0x72/* r */: return '\\x0D'\n case 0x65/* e */: return '\\x1B'\n case 0x20/* Space */: return ' '\n case 0x22/* \" */: return '\\x22'\n case 0x2F/* / */: return '/'\n case 0x5C/* \\ */: return '\\x5C'\n case 0x4E/* N */: return '\\x85'\n case 0x5F/* _ */: return '\\xA0'\n case 0x4C/* L */: return '\\u2028'\n case 0x50/* P */: return '\\u2029'\n default: return ''\n }\n}\n\nfunction charFromCodepoint (c) {\n if (c <= 0xFFFF) {\n return String.fromCharCode(c)\n }\n // Encode UTF-16 surrogate pair\n // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n return String.fromCharCode(\n ((c - 0x010000) >> 10) + 0xD800,\n ((c - 0x010000) & 0x03FF) + 0xDC00\n )\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty (object, key, value) {\n // used for this specific key only because Object.defineProperty is slow\n if (key === '__proto__') {\n Object.defineProperty(object, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: value\n })\n } else {\n object[key] = value\n }\n}\n\nconst simpleEscapeCheck = new Array(256) // integer, for fast access\nconst simpleEscapeMap = new Array(256)\nfor (let i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0\n simpleEscapeMap[i] = simpleEscapeSequence(i)\n}\n\nfunction State (input, options) {\n this.input = input\n\n this.filename = options['filename'] || null\n this.schema = options['schema'] || DEFAULT_SCHEMA\n this.onWarning = options['onWarning'] || null\n // (Hidden) Remove? makes the loader to expect YAML 1.1 documents\n // if such documents have no explicit %YAML directive\n this.legacy = options['legacy'] || false\n\n this.json = options['json'] || false\n this.listener = options['listener'] || null\n this.maxDepth = typeof options['maxDepth'] === 'number' ? options['maxDepth'] : 100\n this.maxMergeSeqLength = typeof options['maxMergeSeqLength'] === 'number' ? options['maxMergeSeqLength'] : 20\n\n this.implicitTypes = this.schema.compiledImplicit\n this.typeMap = this.schema.compiledTypeMap\n\n this.length = input.length\n this.position = 0\n this.line = 0\n this.lineStart = 0\n this.lineIndent = 0\n this.depth = 0\n\n // position of first leading tab in the current line,\n // used to make sure there are no tabs in the indentation\n this.firstTabInLine = -1\n\n this.documents = []\n this.anchorMapTransactions = []\n\n /*\n this.version;\n this.checkLineBreaks;\n this.tagMap;\n this.anchorMap;\n this.tag;\n this.anchor;\n this.kind;\n this.result; */\n}\n\nfunction generateError (state, message) {\n const mark = {\n name: state.filename,\n buffer: state.input.slice(0, -1), // omit trailing \\0\n position: state.position,\n line: state.line,\n column: state.position - state.lineStart\n }\n\n mark.snippet = makeSnippet(mark)\n\n return new YAMLException(message, mark)\n}\n\nfunction throwError (state, message) {\n throw generateError(state, message)\n}\n\nfunction throwWarning (state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message))\n }\n}\n\nfunction storeAnchor (state, name, value) {\n const transactions = state.anchorMapTransactions\n\n if (transactions.length !== 0) {\n const transaction = transactions[transactions.length - 1]\n\n if (!_hasOwnProperty.call(transaction, name)) {\n transaction[name] = {\n existed: _hasOwnProperty.call(state.anchorMap, name),\n value: state.anchorMap[name]\n }\n }\n }\n\n state.anchorMap[name] = value\n}\n\nfunction beginAnchorTransaction (state) {\n state.anchorMapTransactions.push(Object.create(null))\n}\n\nfunction commitAnchorTransaction (state) {\n const transaction = state.anchorMapTransactions.pop()\n const transactions = state.anchorMapTransactions\n\n if (transactions.length === 0) return\n\n const parent = transactions[transactions.length - 1]\n const names = Object.keys(transaction)\n\n for (let index = 0, length = names.length; index < length; index += 1) {\n const name = names[index]\n\n if (!_hasOwnProperty.call(parent, name)) {\n parent[name] = transaction[name]\n }\n }\n}\n\nfunction rollbackAnchorTransaction (state) {\n const transaction = state.anchorMapTransactions.pop()\n const names = Object.keys(transaction)\n\n for (let index = names.length - 1; index >= 0; index -= 1) {\n const entry = transaction[names[index]]\n\n if (entry.existed) {\n state.anchorMap[names[index]] = entry.value\n } else {\n delete state.anchorMap[names[index]]\n }\n }\n}\n\nfunction snapshotState (state) {\n return {\n position: state.position,\n line: state.line,\n lineStart: state.lineStart,\n lineIndent: state.lineIndent,\n firstTabInLine: state.firstTabInLine,\n tag: state.tag,\n anchor: state.anchor,\n kind: state.kind,\n result: state.result\n }\n}\n\nfunction restoreState (state, snapshot) {\n state.position = snapshot.position\n state.line = snapshot.line\n state.lineStart = snapshot.lineStart\n state.lineIndent = snapshot.lineIndent\n state.firstTabInLine = snapshot.firstTabInLine\n state.tag = snapshot.tag\n state.anchor = snapshot.anchor\n state.kind = snapshot.kind\n state.result = snapshot.result\n}\n\nconst directiveHandlers = {\n\n YAML: function handleYamlDirective (state, name, args) {\n if (state.version !== null) {\n throwError(state, 'duplication of %YAML directive')\n }\n\n if (args.length !== 1) {\n throwError(state, 'YAML directive accepts exactly one argument')\n }\n\n const match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0])\n\n if (match === null) {\n throwError(state, 'ill-formed argument of the YAML directive')\n }\n\n const major = parseInt(match[1], 10)\n const minor = parseInt(match[2], 10)\n\n if (major !== 1) {\n throwError(state, 'unacceptable YAML version of the document')\n }\n\n state.version = args[0]\n state.checkLineBreaks = (minor < 2)\n\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, 'unsupported YAML version of the document')\n }\n },\n\n TAG: function handleTagDirective (state, name, args) {\n let prefix\n\n if (args.length !== 2) {\n throwError(state, 'TAG directive accepts exactly two arguments')\n }\n\n const handle = args[0]\n prefix = args[1]\n\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, 'ill-formed tag handle (first argument) of the TAG directive')\n }\n\n if (_hasOwnProperty.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle')\n }\n\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive')\n }\n\n try {\n prefix = decodeURIComponent(prefix)\n } catch (err) {\n throwError(state, 'tag prefix is malformed: ' + prefix)\n }\n\n state.tagMap[handle] = prefix\n }\n}\n\nfunction captureSegment (state, start, end, checkJson) {\n if (start < end) {\n const _result = state.input.slice(start, end)\n\n if (checkJson) {\n for (let _position = 0, _length = _result.length; _position < _length; _position += 1) {\n const _character = _result.charCodeAt(_position)\n if (!(_character === 0x09 ||\n (_character >= 0x20 && _character <= 0x10FFFF))) {\n throwError(state, 'expected valid JSON character')\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, 'the stream contains non-printable characters')\n }\n\n state.result += _result\n }\n}\n\nfunction mergeMappings (state, destination, source, overridableKeys) {\n if (!common.isObject(source)) {\n throwError(state, 'cannot merge mappings; the provided source object is unacceptable')\n }\n\n const sourceKeys = Object.keys(source)\n\n for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n const key = sourceKeys[index]\n\n if (!_hasOwnProperty.call(destination, key)) {\n setProperty(destination, key, source[key])\n overridableKeys[key] = true\n }\n }\n}\n\nfunction storeMappingPair (state, _result, overridableKeys, keyTag, keyNode, valueNode,\n startLine, startLineStart, startPos) {\n // The output is a plain object here, so keys can only be strings.\n // We need to convert keyNode to a string, but doing so can hang the process\n // (deeply nested arrays that explode exponentially using aliases).\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode)\n\n for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, 'nested arrays are not supported inside keys')\n }\n\n if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n keyNode[index] = '[object Object]'\n }\n }\n }\n\n // Avoid code execution in load() via toString property\n // (still use its own toString for arrays, timestamps,\n // and whatever user schema extensions happen to have @@toStringTag)\n if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n keyNode = '[object Object]'\n }\n\n keyNode = String(keyNode)\n\n if (_result === null) {\n _result = {}\n }\n\n if (keyTag === 'tag:yaml.org,2002:merge') {\n if (Array.isArray(valueNode)) {\n if (valueNode.length > state.maxMergeSeqLength) {\n throwError(state, 'merge sequence length exceeded maxMergeSeqLength (' + state.maxMergeSeqLength + ')')\n }\n const seen = new Set()\n for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n const src = valueNode[index]\n // Existing keys are not overridden on merge, so dedupe sources to\n // avoid redundant work on repeated aliases.\n if (seen.has(src)) continue\n seen.add(src)\n mergeMappings(state, _result, src, overridableKeys)\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys)\n }\n } else {\n if (!state.json &&\n !_hasOwnProperty.call(overridableKeys, keyNode) &&\n _hasOwnProperty.call(_result, keyNode)) {\n state.line = startLine || state.line\n state.lineStart = startLineStart || state.lineStart\n state.position = startPos || state.position\n throwError(state, 'duplicated mapping key')\n }\n\n setProperty(_result, keyNode, valueNode)\n delete overridableKeys[keyNode]\n }\n\n return _result\n}\n\nfunction readLineBreak (state) {\n const ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x0A/* LF */) {\n state.position++\n } else if (ch === 0x0D/* CR */) {\n state.position++\n if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n state.position++\n }\n } else {\n throwError(state, 'a line break is expected')\n }\n\n state.line += 1\n state.lineStart = state.position\n state.firstTabInLine = -1\n}\n\nfunction skipSeparationSpace (state, allowComments, checkIndent) {\n let lineBreaks = 0\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n while (isWhiteSpace(ch)) {\n if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {\n state.firstTabInLine = state.position\n }\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (allowComments && ch === 0x23/* # */) {\n do {\n ch = state.input.charCodeAt(++state.position)\n } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0)\n }\n\n if (isEol(ch)) {\n readLineBreak(state)\n\n ch = state.input.charCodeAt(state.position)\n lineBreaks++\n state.lineIndent = 0\n\n while (ch === 0x20/* Space */) {\n state.lineIndent++\n ch = state.input.charCodeAt(++state.position)\n }\n } else {\n break\n }\n }\n\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, 'deficient indentation')\n }\n\n return lineBreaks\n}\n\nfunction testDocumentSeparator (state) {\n let _position = state.position\n let ch = state.input.charCodeAt(_position)\n\n // Condition state.position === state.lineStart is tested\n // in parent on each call, for efficiency. No needs to test here again.\n if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n ch === state.input.charCodeAt(_position + 1) &&\n ch === state.input.charCodeAt(_position + 2)) {\n _position += 3\n\n ch = state.input.charCodeAt(_position)\n\n if (ch === 0 || isWsOrEol(ch)) {\n return true\n }\n }\n\n return false\n}\n\nfunction writeFoldedLines (state, count) {\n if (count === 1) {\n state.result += ' '\n } else if (count > 1) {\n state.result += common.repeat('\\n', count - 1)\n }\n}\n\nfunction readPlainScalar (state, nodeIndent, withinFlowCollection) {\n let captureStart\n let captureEnd\n let hasPendingContent\n let _line\n let _lineStart\n let _lineIndent\n const _kind = state.kind\n const _result = state.result\n\n let ch = state.input.charCodeAt(state.position)\n\n if (isWsOrEol(ch) ||\n isFlowIndicator(ch) ||\n ch === 0x23/* # */ ||\n ch === 0x26/* & */ ||\n ch === 0x2A/* * */ ||\n ch === 0x21/* ! */ ||\n ch === 0x7C/* | */ ||\n ch === 0x3E/* > */ ||\n ch === 0x27/* ' */ ||\n ch === 0x22/* \" */ ||\n ch === 0x25/* % */ ||\n ch === 0x40/* @ */ ||\n ch === 0x60/* ` */) {\n return false\n }\n\n if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following) ||\n (withinFlowCollection && isFlowIndicator(following))) {\n return false\n }\n }\n\n state.kind = 'scalar'\n state.result = ''\n captureStart = captureEnd = state.position\n hasPendingContent = false\n\n while (ch !== 0) {\n if (ch === 0x3A/* : */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following) ||\n (withinFlowCollection && isFlowIndicator(following))) {\n break\n }\n } else if (ch === 0x23/* # */) {\n const preceding = state.input.charCodeAt(state.position - 1)\n\n if (isWsOrEol(preceding)) {\n break\n }\n } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n (withinFlowCollection && isFlowIndicator(ch))) {\n break\n } else if (isEol(ch)) {\n _line = state.line\n _lineStart = state.lineStart\n _lineIndent = state.lineIndent\n skipSeparationSpace(state, false, -1)\n\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true\n ch = state.input.charCodeAt(state.position)\n continue\n } else {\n state.position = captureEnd\n state.line = _line\n state.lineStart = _lineStart\n state.lineIndent = _lineIndent\n break\n }\n }\n\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false)\n writeFoldedLines(state, state.line - _line)\n captureStart = captureEnd = state.position\n hasPendingContent = false\n }\n\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position + 1\n }\n\n ch = state.input.charCodeAt(++state.position)\n }\n\n captureSegment(state, captureStart, captureEnd, false)\n\n if (state.result) {\n return true\n }\n\n state.kind = _kind\n state.result = _result\n return false\n}\n\nfunction readSingleQuotedScalar (state, nodeIndent) {\n let captureStart\n let captureEnd\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x27/* ' */) {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n state.position++\n captureStart = captureEnd = state.position\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x27/* ' */) {\n captureSegment(state, captureStart, state.position, true)\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x27/* ' */) {\n captureStart = state.position\n state.position++\n captureEnd = state.position\n } else {\n return true\n }\n } else if (isEol(ch)) {\n captureSegment(state, captureStart, captureEnd, true)\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent))\n captureStart = captureEnd = state.position\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a single quoted scalar')\n } else {\n state.position++\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position\n }\n }\n }\n\n throwError(state, 'unexpected end of the stream within a single quoted scalar')\n}\n\nfunction readDoubleQuotedScalar (state, nodeIndent) {\n let captureStart\n let captureEnd\n let tmp\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x22/* \" */) {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n state.position++\n captureStart = captureEnd = state.position\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x22/* \" */) {\n captureSegment(state, captureStart, state.position, true)\n state.position++\n return true\n } else if (ch === 0x5C/* \\ */) {\n captureSegment(state, captureStart, state.position, true)\n ch = state.input.charCodeAt(++state.position)\n\n if (isEol(ch)) {\n skipSeparationSpace(state, false, nodeIndent)\n\n // TODO: rework to inline fn with no type cast?\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch]\n state.position++\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n let hexLength = tmp\n let hexResult = 0\n\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position)\n\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp\n } else {\n throwError(state, 'expected hexadecimal character')\n }\n }\n\n state.result += charFromCodepoint(hexResult)\n\n state.position++\n } else {\n throwError(state, 'unknown escape sequence')\n }\n\n captureStart = captureEnd = state.position\n } else if (isEol(ch)) {\n captureSegment(state, captureStart, captureEnd, true)\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent))\n captureStart = captureEnd = state.position\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a double quoted scalar')\n } else {\n state.position++\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position\n }\n }\n }\n\n throwError(state, 'unexpected end of the stream within a double quoted scalar')\n}\n\nfunction readFlowCollection (state, nodeIndent) {\n let readNext = true\n let _line\n let _lineStart\n let _pos\n const _tag = state.tag\n let _result\n const _anchor = state.anchor\n let terminator\n let isPair\n let isExplicitPair\n let isMapping\n const overridableKeys = Object.create(null)\n let keyNode\n let keyTag\n let valueNode\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x5B/* [ */) {\n terminator = 0x5D/* ] */\n isMapping = false\n _result = []\n } else if (ch === 0x7B/* { */) {\n terminator = 0x7D/* } */\n isMapping = true\n _result = {}\n } else {\n return false\n }\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n ch = state.input.charCodeAt(++state.position)\n\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if (ch === terminator) {\n state.position++\n state.tag = _tag\n state.anchor = _anchor\n state.kind = isMapping ? 'mapping' : 'sequence'\n state.result = _result\n return true\n } else if (!readNext) {\n throwError(state, 'missed comma between flow collection entries')\n } else if (ch === 0x2C/* , */) {\n // \"flow collection entries can never be completely empty\", as per YAML 1.2, section 7.4\n throwError(state, \"expected the node content, but found ','\")\n }\n\n keyTag = keyNode = valueNode = null\n isPair = isExplicitPair = false\n\n if (ch === 0x3F/* ? */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following)) {\n isPair = isExplicitPair = true\n state.position++\n skipSeparationSpace(state, true, nodeIndent)\n }\n }\n\n _line = state.line // Save the current line.\n _lineStart = state.lineStart\n _pos = state.position\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)\n keyTag = state.tag\n keyNode = state.result\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n isPair = true\n ch = state.input.charCodeAt(++state.position)\n skipSeparationSpace(state, true, nodeIndent)\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)\n valueNode = state.result\n }\n\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos))\n } else {\n _result.push(keyNode)\n }\n\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x2C/* , */) {\n readNext = true\n ch = state.input.charCodeAt(++state.position)\n } else {\n readNext = false\n }\n }\n\n throwError(state, 'unexpected end of the stream within a flow collection')\n}\n\nfunction readBlockScalar (state, nodeIndent) {\n let folding\n let chomping = CHOMPING_CLIP\n let didReadContent = false\n let detectedIndent = false\n let textIndent = nodeIndent\n let emptyLines = 0\n let atMoreIndented = false\n let tmp\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x7C/* | */) {\n folding = false\n } else if (ch === 0x3E/* > */) {\n folding = true\n } else {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n if (CHOMPING_CLIP === chomping) {\n chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP\n } else {\n throwError(state, 'repeat of a chomping mode identifier')\n }\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one')\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1\n detectedIndent = true\n } else {\n throwError(state, 'repeat of an indentation width identifier')\n }\n } else {\n break\n }\n }\n\n if (isWhiteSpace(ch)) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (isWhiteSpace(ch))\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (!isEol(ch) && (ch !== 0))\n }\n }\n\n while (ch !== 0) {\n readLineBreak(state)\n state.lineIndent = 0\n\n ch = state.input.charCodeAt(state.position)\n\n // eslint-disable-next-line no-unmodified-loop-condition\n while ((!detectedIndent || state.lineIndent < textIndent) &&\n (ch === 0x20/* Space */)) {\n state.lineIndent++\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent\n }\n\n if (isEol(ch)) {\n emptyLines++\n continue\n }\n\n if (!detectedIndent && textIndent === 0) {\n throwError(state, 'missing indentation for block scalar')\n }\n\n // End of the scalar.\n if (state.lineIndent < textIndent) {\n // Perform the chomping.\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) { // i.e. only if the scalar is not empty.\n state.result += '\\n'\n }\n }\n\n // Break this `while` cycle and go to the funciton's epilogue.\n break\n }\n\n // Folded style: use fancy rules to handle line breaks.\n if (folding) {\n // Lines starting with white space characters (more-indented lines) are not folded.\n if (isWhiteSpace(ch)) {\n atMoreIndented = true\n // except for the first content line (cf. Example 8.1)\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n\n // End of more-indented block.\n } else if (atMoreIndented) {\n atMoreIndented = false\n state.result += common.repeat('\\n', emptyLines + 1)\n\n // Just one line break - perceive as the same line.\n } else if (emptyLines === 0) {\n if (didReadContent) { // i.e. only if we have already read some scalar content.\n state.result += ' '\n }\n\n // Several line breaks - perceive as different lines.\n } else {\n state.result += common.repeat('\\n', emptyLines)\n }\n\n // Literal style: just add exact number of line breaks between content lines.\n } else {\n // Keep all line breaks except the header line break.\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n }\n\n didReadContent = true\n detectedIndent = true\n emptyLines = 0\n const captureStart = state.position\n\n while (!isEol(ch) && (ch !== 0)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n captureSegment(state, captureStart, state.position, false)\n }\n\n return true\n}\n\nfunction readBlockSequence (state, nodeIndent) {\n const _tag = state.tag\n const _anchor = state.anchor\n const _result = []\n let detected = false\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n if (state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine\n throwError(state, 'tab characters must not be used in indentation')\n }\n\n if (ch !== 0x2D/* - */) {\n break\n }\n\n const following = state.input.charCodeAt(state.position + 1)\n\n if (!isWsOrEol(following)) {\n break\n }\n\n detected = true\n state.position++\n\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null)\n ch = state.input.charCodeAt(state.position)\n continue\n }\n }\n\n const _line = state.line\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true)\n _result.push(state.result)\n skipSeparationSpace(state, true, -1)\n\n ch = state.input.charCodeAt(state.position)\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a sequence entry')\n } else if (state.lineIndent < nodeIndent) {\n break\n }\n }\n\n if (detected) {\n state.tag = _tag\n state.anchor = _anchor\n state.kind = 'sequence'\n state.result = _result\n return true\n }\n return false\n}\n\nfunction readBlockMapping (state, nodeIndent, flowIndent) {\n let allowCompact\n let _keyLine\n let _keyLineStart\n let _keyPos\n const _tag = state.tag\n const _anchor = state.anchor\n const _result = {}\n const overridableKeys = Object.create(null)\n let keyTag = null\n let keyNode = null\n let valueNode = null\n let atExplicitKey = false\n let detected = false\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n if (!atExplicitKey && state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine\n throwError(state, 'tab characters must not be used in indentation')\n }\n\n const following = state.input.charCodeAt(state.position + 1)\n const _line = state.line // Save the current line.\n\n //\n // Explicit notation case. There are two separate blocks:\n // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n //\n if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && isWsOrEol(following)) {\n if (ch === 0x3F/* ? */) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n detected = true\n atExplicitKey = true\n allowCompact = true\n } else if (atExplicitKey) {\n // i.e. 0x3A/* : */ === character after the explicit key.\n atExplicitKey = false\n allowCompact = true\n } else {\n throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line')\n }\n\n state.position += 1\n ch = following\n\n //\n // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n //\n } else {\n _keyLine = state.line\n _keyLineStart = state.lineStart\n _keyPos = state.position\n\n if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n // Neither implicit nor explicit notation.\n // Reading is done. Go to the epilogue.\n break\n }\n\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position)\n\n while (isWhiteSpace(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (ch === 0x3A/* : */) {\n ch = state.input.charCodeAt(++state.position)\n\n if (!isWsOrEol(ch)) {\n throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping')\n }\n\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n detected = true\n atExplicitKey = false\n allowCompact = false\n keyTag = state.tag\n keyNode = state.result\n } else if (detected) {\n throwError(state, 'can not read an implicit mapping pair; a colon is missed')\n } else {\n state.tag = _tag\n state.anchor = _anchor\n return true // Keep the result of `composeNode`.\n }\n } else if (detected) {\n throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key')\n } else {\n state.tag = _tag\n state.anchor = _anchor\n return true // Keep the result of `composeNode`.\n }\n }\n\n //\n // Common reading code for both explicit and implicit notations.\n //\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (atExplicitKey) {\n _keyLine = state.line\n _keyLineStart = state.lineStart\n _keyPos = state.position\n }\n\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result\n } else {\n valueNode = state.result\n }\n }\n\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n skipSeparationSpace(state, true, -1)\n ch = state.input.charCodeAt(state.position)\n }\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a mapping entry')\n } else if (state.lineIndent < nodeIndent) {\n break\n }\n }\n\n //\n // Epilogue.\n //\n\n // Special case: last mapping's node contains only the key in explicit notation.\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n }\n\n // Expose the resulting mapping.\n if (detected) {\n state.tag = _tag\n state.anchor = _anchor\n state.kind = 'mapping'\n state.result = _result\n }\n\n return detected\n}\n\nfunction readTagProperty (state) {\n let isVerbatim = false\n let isNamed = false\n let tagHandle\n let tagName\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x21/* ! */) return false\n\n if (state.tag !== null) {\n throwError(state, 'duplication of a tag property')\n }\n\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x3C/* < */) {\n isVerbatim = true\n ch = state.input.charCodeAt(++state.position)\n } else if (ch === 0x21/* ! */) {\n isNamed = true\n tagHandle = '!!'\n ch = state.input.charCodeAt(++state.position)\n } else {\n tagHandle = '!'\n }\n\n let _position = state.position\n\n if (isVerbatim) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (ch !== 0 && ch !== 0x3E/* > */)\n\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position)\n ch = state.input.charCodeAt(++state.position)\n } else {\n throwError(state, 'unexpected end of the stream within a verbatim tag')\n }\n } else {\n while (ch !== 0 && !isWsOrEol(ch)) {\n if (ch === 0x21/* ! */) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1)\n\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, 'named tag handle cannot contain such characters')\n }\n\n isNamed = true\n _position = state.position + 1\n } else {\n throwError(state, 'tag suffix cannot contain exclamation marks')\n }\n }\n\n ch = state.input.charCodeAt(++state.position)\n }\n\n tagName = state.input.slice(_position, state.position)\n\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, 'tag suffix cannot contain flow indicator characters')\n }\n }\n\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, 'tag name cannot contain such characters: ' + tagName)\n }\n\n try {\n tagName = decodeURIComponent(tagName)\n } catch (err) {\n throwError(state, 'tag name is malformed: ' + tagName)\n }\n\n if (isVerbatim) {\n state.tag = tagName\n } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName\n } else if (tagHandle === '!') {\n state.tag = '!' + tagName\n } else if (tagHandle === '!!') {\n state.tag = 'tag:yaml.org,2002:' + tagName\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"')\n }\n\n return true\n}\n\nfunction readAnchorProperty (state) {\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x26/* & */) return false\n\n if (state.anchor !== null) {\n throwError(state, 'duplication of an anchor property')\n }\n\n ch = state.input.charCodeAt(++state.position)\n const _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an anchor node must contain at least one character')\n }\n\n state.anchor = state.input.slice(_position, state.position)\n return true\n}\n\nfunction readAlias (state) {\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x2A/* * */) return false\n\n ch = state.input.charCodeAt(++state.position)\n const _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an alias node must contain at least one character')\n }\n\n const alias = state.input.slice(_position, state.position)\n\n if (!_hasOwnProperty.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"')\n }\n\n state.result = state.anchorMap[alias]\n skipSeparationSpace(state, true, -1)\n return true\n}\n\nfunction tryReadBlockMappingFromProperty (state, propertyStart, nodeIndent, flowIndent) {\n const fallbackState = snapshotState(state)\n\n beginAnchorTransaction(state)\n restoreState(state, propertyStart)\n\n // Re-read the leading properties as part of the first implicit key, not as\n // properties of the current node.\n state.tag = null\n state.anchor = null\n state.kind = null\n state.result = null\n\n if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === 'mapping') {\n commitAnchorTransaction(state)\n return true\n }\n\n rollbackAnchorTransaction(state)\n restoreState(state, fallbackState)\n return false\n}\n\nfunction composeNode (state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n let allowBlockScalars\n let allowBlockCollections\n let indentStatus = 1 // 1: this>parent, 0: this=parent, -1: this= state.maxDepth) {\n throwError(state, 'nesting exceeded maxDepth (' + state.maxDepth + ')')\n }\n\n state.depth += 1\n\n if (state.listener !== null) {\n state.listener('open', state)\n }\n\n state.tag = null\n state.anchor = null\n state.kind = null\n state.result = null\n\n const allowBlockStyles = allowBlockScalars = allowBlockCollections =\n CONTEXT_BLOCK_OUT === nodeContext ||\n CONTEXT_BLOCK_IN === nodeContext\n\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1\n }\n }\n }\n\n if (indentStatus === 1) {\n while (true) {\n const ch = state.input.charCodeAt(state.position)\n const propertyState = snapshotState(state)\n\n // A duplicate property token after a line break can be the first key of\n // a nested block mapping, e.g. `!!map\\n !!str key: value`.\n if (atNewLine &&\n ((ch === 0x21/* ! */ && state.tag !== null) ||\n (ch === 0x26/* & */ && state.anchor !== null))) {\n break\n }\n\n if (!readTagProperty(state) && !readAnchorProperty(state)) {\n break\n }\n\n if (propertyStart === null) {\n propertyStart = propertyState\n }\n\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true\n allowBlockCollections = allowBlockStyles\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1\n }\n } else {\n allowBlockCollections = false\n }\n }\n }\n\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact\n }\n\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent\n } else {\n flowIndent = parentIndent + 1\n }\n\n blockIndent = state.position - state.lineStart\n\n if (indentStatus === 1) {\n if ((allowBlockCollections &&\n (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent))) ||\n readFlowCollection(state, flowIndent)) {\n hasContent = true\n } else {\n const ch = state.input.charCodeAt(state.position)\n\n if (propertyStart !== null && allowBlockStyles && !allowBlockCollections &&\n ch !== 0x7C/* | */ && ch !== 0x3E/* > */ &&\n tryReadBlockMappingFromProperty(\n state,\n propertyStart,\n propertyStart.position - propertyStart.lineStart,\n flowIndent\n )) {\n hasContent = true\n } else if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n readSingleQuotedScalar(state, flowIndent) ||\n readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true\n } else if (readAlias(state)) {\n hasContent = true\n\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, 'alias node should not have any properties')\n }\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true\n\n if (state.tag === null) {\n state.tag = '?'\n }\n }\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n }\n } else if (indentStatus === 0) {\n // Special case: block sequences are allowed to have same indentation level as the parent.\n // http://www.yaml.org/spec/1.2/spec.html#id2799784\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent)\n }\n }\n\n if (state.tag === null) {\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n } else if (state.tag === '?') {\n // Implicit resolving is not allowed for non-scalar types, and '?'\n // non-specific tag is only automatically assigned to plain scalars.\n //\n // We only need to check kind conformity in case user explicitly assigns '?'\n // tag, for example like this: \"! [0]\"\n //\n if (state.result !== null && state.kind !== 'scalar') {\n throwError(state, 'unacceptable node kind for ! tag; it should be \"scalar\", not \"' + state.kind + '\"')\n }\n\n for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type = state.implicitTypes[typeIndex]\n\n if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n state.result = type.construct(state.result)\n state.tag = type.tag\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n break\n }\n }\n } else if (state.tag !== '!') {\n if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n type = state.typeMap[state.kind || 'fallback'][state.tag]\n } else {\n // looking for multi type\n type = null\n const typeList = state.typeMap.multi[state.kind || 'fallback']\n\n for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {\n if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n type = typeList[typeIndex]\n break\n }\n }\n }\n\n if (!type) {\n throwError(state, 'unknown tag !<' + state.tag + '>')\n }\n\n if (state.result !== null && type.kind !== state.kind) {\n throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"')\n }\n\n if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched\n throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag')\n } else {\n state.result = type.construct(state.result, state.tag)\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n }\n }\n\n if (state.listener !== null) {\n state.listener('close', state)\n }\n\n state.depth -= 1\n return state.tag !== null || state.anchor !== null || hasContent\n}\n\nfunction readDocument (state) {\n const documentStart = state.position\n let hasDirectives = false\n let ch\n\n state.version = null\n state.checkLineBreaks = state.legacy\n state.tagMap = Object.create(null)\n state.anchorMap = Object.create(null)\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1)\n\n ch = state.input.charCodeAt(state.position)\n\n if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n break\n }\n\n hasDirectives = true\n ch = state.input.charCodeAt(++state.position)\n let _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n const directiveName = state.input.slice(_position, state.position)\n const directiveArgs = []\n\n if (directiveName.length < 1) {\n throwError(state, 'directive name must not be less than one character in length')\n }\n\n while (ch !== 0) {\n while (isWhiteSpace(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (ch !== 0 && !isEol(ch))\n break\n }\n\n if (isEol(ch)) break\n\n _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n directiveArgs.push(state.input.slice(_position, state.position))\n }\n\n if (ch !== 0) readLineBreak(state)\n\n if (_hasOwnProperty.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs)\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"')\n }\n }\n\n skipSeparationSpace(state, true, -1)\n\n if (state.lineIndent === 0 &&\n state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n state.position += 3\n skipSeparationSpace(state, true, -1)\n } else if (hasDirectives) {\n throwError(state, 'directives end mark is expected')\n }\n\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true)\n skipSeparationSpace(state, true, -1)\n\n if (state.checkLineBreaks &&\n PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, 'non-ASCII line breaks are interpreted as content')\n }\n\n state.documents.push(state.result)\n\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n state.position += 3\n skipSeparationSpace(state, true, -1)\n }\n return\n }\n\n if (state.position < (state.length - 1)) {\n throwError(state, 'end of the stream or a document separator is expected')\n }\n}\n\nfunction loadDocuments (input, options) {\n input = String(input)\n options = options || {}\n\n if (input.length !== 0) {\n // Add tailing `\\n` if not exists\n if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n input += '\\n'\n }\n\n // Strip BOM\n if (input.charCodeAt(0) === 0xFEFF) {\n input = input.slice(1)\n }\n }\n\n const state = new State(input, options)\n\n const nullpos = input.indexOf('\\0')\n\n if (nullpos !== -1) {\n state.position = nullpos\n throwError(state, 'null byte is not allowed in input')\n }\n\n // Use 0 as string terminator. That significantly simplifies bounds check.\n state.input += '\\0'\n\n while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n state.lineIndent += 1\n state.position += 1\n }\n\n while (state.position < (state.length - 1)) {\n readDocument(state)\n }\n\n return state.documents\n}\n\nfunction loadAll (input, iterator, options) {\n if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n options = iterator\n iterator = null\n }\n\n const documents = loadDocuments(input, options)\n\n if (typeof iterator !== 'function') {\n return documents\n }\n\n for (let index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index])\n }\n}\n\nfunction load (input, options) {\n const documents = loadDocuments(input, options)\n\n if (documents.length === 0) {\n return undefined\n } else if (documents.length === 1) {\n return documents[0]\n }\n throw new YAMLException('expected a single document in the stream, but found more')\n}\n\nmodule.exports.loadAll = loadAll\nmodule.exports.load = load\n","'use strict'\n\nconst common = require('./common')\nconst YAMLException = require('./exception')\nconst DEFAULT_SCHEMA = require('./schema/default')\n\nconst _toString = Object.prototype.toString\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nconst CHAR_BOM = 0xFEFF\nconst CHAR_TAB = 0x09 /* Tab */\nconst CHAR_LINE_FEED = 0x0A /* LF */\nconst CHAR_CARRIAGE_RETURN = 0x0D /* CR */\nconst CHAR_SPACE = 0x20 /* Space */\nconst CHAR_EXCLAMATION = 0x21 /* ! */\nconst CHAR_DOUBLE_QUOTE = 0x22 /* \" */\nconst CHAR_SHARP = 0x23 /* # */\nconst CHAR_PERCENT = 0x25 /* % */\nconst CHAR_AMPERSAND = 0x26 /* & */\nconst CHAR_SINGLE_QUOTE = 0x27 /* ' */\nconst CHAR_ASTERISK = 0x2A /* * */\nconst CHAR_COMMA = 0x2C /* , */\nconst CHAR_MINUS = 0x2D /* - */\nconst CHAR_COLON = 0x3A /* : */\nconst CHAR_EQUALS = 0x3D /* = */\nconst CHAR_GREATER_THAN = 0x3E /* > */\nconst CHAR_QUESTION = 0x3F /* ? */\nconst CHAR_COMMERCIAL_AT = 0x40 /* @ */\nconst CHAR_LEFT_SQUARE_BRACKET = 0x5B /* [ */\nconst CHAR_RIGHT_SQUARE_BRACKET = 0x5D /* ] */\nconst CHAR_GRAVE_ACCENT = 0x60 /* ` */\nconst CHAR_LEFT_CURLY_BRACKET = 0x7B /* { */\nconst CHAR_VERTICAL_LINE = 0x7C /* | */\nconst CHAR_RIGHT_CURLY_BRACKET = 0x7D /* } */\n\nconst ESCAPE_SEQUENCES = {}\n\nESCAPE_SEQUENCES[0x00] = '\\\\0'\nESCAPE_SEQUENCES[0x07] = '\\\\a'\nESCAPE_SEQUENCES[0x08] = '\\\\b'\nESCAPE_SEQUENCES[0x09] = '\\\\t'\nESCAPE_SEQUENCES[0x0A] = '\\\\n'\nESCAPE_SEQUENCES[0x0B] = '\\\\v'\nESCAPE_SEQUENCES[0x0C] = '\\\\f'\nESCAPE_SEQUENCES[0x0D] = '\\\\r'\nESCAPE_SEQUENCES[0x1B] = '\\\\e'\nESCAPE_SEQUENCES[0x22] = '\\\\\"'\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\'\nESCAPE_SEQUENCES[0x85] = '\\\\N'\nESCAPE_SEQUENCES[0xA0] = '\\\\_'\nESCAPE_SEQUENCES[0x2028] = '\\\\L'\nESCAPE_SEQUENCES[0x2029] = '\\\\P'\n\nconst DEPRECATED_BOOLEANS_SYNTAX = [\n 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n]\n\nconst DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/\n\nfunction compileStyleMap (schema, map) {\n if (map === null) return {}\n\n const result = {}\n const keys = Object.keys(map)\n\n for (let index = 0, length = keys.length; index < length; index += 1) {\n let tag = keys[index]\n let style = String(map[tag])\n\n if (tag.slice(0, 2) === '!!') {\n tag = 'tag:yaml.org,2002:' + tag.slice(2)\n }\n const type = schema.compiledTypeMap['fallback'][tag]\n\n if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n style = type.styleAliases[style]\n }\n\n result[tag] = style\n }\n\n return result\n}\n\nfunction encodeHex (character) {\n let handle\n let length\n\n const string = character.toString(16).toUpperCase()\n\n if (character <= 0xFF) {\n handle = 'x'\n length = 2\n } else if (character <= 0xFFFF) {\n handle = 'u'\n length = 4\n } else if (character <= 0xFFFFFFFF) {\n handle = 'U'\n length = 8\n } else {\n throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF')\n }\n\n return '\\\\' + handle + common.repeat('0', length - string.length) + string\n}\n\nconst QUOTING_TYPE_SINGLE = 1\nconst QUOTING_TYPE_DOUBLE = 2\n\nfunction State (options) {\n this.schema = options['schema'] || DEFAULT_SCHEMA\n this.indent = Math.max(1, (options['indent'] || 2))\n this.noArrayIndent = options['noArrayIndent'] || false\n this.skipInvalid = options['skipInvalid'] || false\n this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel'])\n this.styleMap = compileStyleMap(this.schema, options['styles'] || null)\n this.sortKeys = options['sortKeys'] || false\n this.lineWidth = options['lineWidth'] || 80\n this.noRefs = options['noRefs'] || false\n this.noCompatMode = options['noCompatMode'] || false\n this.condenseFlow = options['condenseFlow'] || false\n this.quotingType = options['quotingType'] === '\"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE\n this.forceQuotes = options['forceQuotes'] || false\n this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null\n\n this.implicitTypes = this.schema.compiledImplicit\n this.explicitTypes = this.schema.compiledExplicit\n\n this.tag = null\n this.result = ''\n\n this.duplicates = []\n this.usedDuplicates = null\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString (string, spaces) {\n const ind = common.repeat(' ', spaces)\n let position = 0\n let result = ''\n const length = string.length\n\n while (position < length) {\n let line\n const next = string.indexOf('\\n', position)\n if (next === -1) {\n line = string.slice(position)\n position = length\n } else {\n line = string.slice(position, next + 1)\n position = next + 1\n }\n\n if (line.length && line !== '\\n') result += ind\n\n result += line\n }\n\n return result\n}\n\nfunction generateNextLine (state, level) {\n return '\\n' + common.repeat(' ', state.indent * level)\n}\n\nfunction testImplicitResolving (state, str) {\n for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n const type = state.implicitTypes[index]\n\n if (type.resolve(str)) {\n return true\n }\n }\n\n return false\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace (c) {\n return c === CHAR_SPACE || c === CHAR_TAB\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable (c) {\n return (c >= 0x00020 && c <= 0x00007E) ||\n ((c >= 0x000A1 && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) ||\n ((c >= 0x0E000 && c <= 0x00FFFD) && c !== CHAR_BOM) ||\n (c >= 0x10000 && c <= 0x10FFFF)\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char ::= b-line-feed | b-carriage-return\n// Including s-white (for some reason, examples doesn't match specs in this aspect)\n// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark\nfunction isNsCharOrWhitespace (c) {\n return isPrintable(c) &&\n c !== CHAR_BOM &&\n // - b-char\n c !== CHAR_CARRIAGE_RETURN &&\n c !== CHAR_LINE_FEED\n}\n\n// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out\n// c = flow-in ⇒ ns-plain-safe-in\n// c = block-key ⇒ ns-plain-safe-out\n// c = flow-key ⇒ ns-plain-safe-in\n// [128] ns-plain-safe-out ::= ns-char\n// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator\n// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:� - “#� )\n// | ( /* An ns-char preceding */ “#� )\n// | ( “:� /* Followed by an ns-plain-safe(c) */ )\nfunction isPlainSafe (c, prev, inblock) {\n const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c)\n const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c)\n return (\n (\n // ns-plain-safe\n inblock // c = flow-in\n ? cIsNsCharOrWhitespace\n : cIsNsCharOrWhitespace &&\n // - c-flow-indicator\n c !== CHAR_COMMA &&\n c !== CHAR_LEFT_SQUARE_BRACKET &&\n c !== CHAR_RIGHT_SQUARE_BRACKET &&\n c !== CHAR_LEFT_CURLY_BRACKET &&\n c !== CHAR_RIGHT_CURLY_BRACKET\n ) &&\n // ns-plain-char\n c !== CHAR_SHARP && // false on '#'\n !(prev === CHAR_COLON && !cIsNsChar)\n ) || // false on ': '\n (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#'\n (prev === CHAR_COLON && cIsNsChar) // change to true on ':[^ ]'\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst (c) {\n // Uses a subset of ns-char - c-indicator\n // where ns-char = nb-char - s-white.\n // No support of ( ( “?� | “:� | “-� ) /* Followed by an ns-plain-safe(c)) */ ) part\n return isPrintable(c) &&\n c !== CHAR_BOM &&\n !isWhitespace(c) && // - s-white\n // - (c-indicator ::=\n // “-� | “?� | “:� | “,� | “[� | “]� | “{� | “}�\n c !== CHAR_MINUS &&\n c !== CHAR_QUESTION &&\n c !== CHAR_COLON &&\n c !== CHAR_COMMA &&\n c !== CHAR_LEFT_SQUARE_BRACKET &&\n c !== CHAR_RIGHT_SQUARE_BRACKET &&\n c !== CHAR_LEFT_CURLY_BRACKET &&\n c !== CHAR_RIGHT_CURLY_BRACKET &&\n // | “#� | “&� | “*� | “!� | “|� | “=� | “>� | “'� | “\"�\n c !== CHAR_SHARP &&\n c !== CHAR_AMPERSAND &&\n c !== CHAR_ASTERISK &&\n c !== CHAR_EXCLAMATION &&\n c !== CHAR_VERTICAL_LINE &&\n c !== CHAR_EQUALS &&\n c !== CHAR_GREATER_THAN &&\n c !== CHAR_SINGLE_QUOTE &&\n c !== CHAR_DOUBLE_QUOTE &&\n // | “%� | “@� | “`�)\n c !== CHAR_PERCENT &&\n c !== CHAR_COMMERCIAL_AT &&\n c !== CHAR_GRAVE_ACCENT\n}\n\n// Simplified test for values allowed as the last character in plain style.\nfunction isPlainSafeLast (c) {\n // just not whitespace or colon, it will be checked to be plain character later\n return !isWhitespace(c) && c !== CHAR_COLON\n}\n\n// Same as 'string'.codePointAt(pos), but works in older browsers.\nfunction codePointAt (string, pos) {\n const first = string.charCodeAt(pos)\n let second\n\n if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {\n second = string.charCodeAt(pos + 1)\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000\n }\n }\n return first\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator (string) {\n const leadingSpaceRe = /^\\n* /\n return leadingSpaceRe.test(string)\n}\n\nconst STYLE_PLAIN = 1\nconst STYLE_SINGLE = 2\nconst STYLE_LITERAL = 3\nconst STYLE_FOLDED = 4\nconst STYLE_DOUBLE = 5\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n// STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle (string, singleLineOnly, indentPerLevel, lineWidth,\n testAmbiguousType, quotingType, forceQuotes, inblock) {\n let i\n let char = 0\n let prevChar = null\n let hasLineBreak = false\n let hasFoldableLine = false // only checked if shouldTrackWidth\n const shouldTrackWidth = lineWidth !== -1\n let previousLineBreak = -1 // count the first line correctly\n let plain = isPlainSafeFirst(codePointAt(string, 0)) &&\n isPlainSafeLast(codePointAt(string, string.length - 1))\n\n if (singleLineOnly || forceQuotes) {\n // Case: no block styles.\n // Check for disallowed characters to rule out plain and single.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n if (!isPrintable(char)) {\n return STYLE_DOUBLE\n }\n plain = plain && isPlainSafe(char, prevChar, inblock)\n prevChar = char\n }\n } else {\n // Case: block styles permitted.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true\n // Check if any line can be folded.\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine ||\n // Foldable line = too long, and not more-indented.\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' ')\n previousLineBreak = i\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE\n }\n plain = plain && isPlainSafe(char, prevChar, inblock)\n prevChar = char\n }\n // in case the end is missing a \\n\n hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' '))\n }\n // Although every style can represent \\n without escaping, prefer block styles\n // for multiline, since they're more readable and they don't add empty lines.\n // Also prefer folding a super-long line.\n if (!hasLineBreak && !hasFoldableLine) {\n // Strings interpretable as another type have to be quoted;\n // e.g. the string 'true' vs. the boolean true.\n if (plain && !forceQuotes && !testAmbiguousType(string)) {\n return STYLE_PLAIN\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE\n }\n // Edge case: block indentation indicator can only have one digit.\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE\n }\n // At this point we know block styles are valid.\n // Prefer literal style unless we want to fold.\n if (!forceQuotes) {\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n// since the dumper adds its own newline. This always works:\n// • No ending newline => unaffected; already using strip \"-\" chomping.\n// • Ending newline => removed then restored.\n// Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar (state, string, level, iskey, inblock) {\n state.dump = (function () {\n if (string.length === 0) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? '\"\"' : \"''\"\n }\n if (!state.noCompatMode) {\n if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? ('\"' + string + '\"') : (\"'\" + string + \"'\")\n }\n }\n\n const indent = state.indent * Math.max(1, level) // no 0-indent scalars\n // As indentation gets deeper, let the width decrease monotonically\n // to the lower bound min(state.lineWidth, 40).\n // Note that this implies\n // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.\n // state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n // This behaves better than a constant minimum width which disallows narrower options,\n // or an indent threshold which causes the width to suddenly increase.\n const lineWidth = (state.lineWidth === -1)\n ? -1\n : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent)\n\n // Without knowing if keys are implicit/explicit, assume implicit for safety.\n const singleLineOnly = iskey ||\n // No block styles in flow mode.\n (state.flowLevel > -1 && level >= state.flowLevel)\n function testAmbiguity (string) {\n return testImplicitResolving(state, string)\n }\n\n switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,\n testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {\n case STYLE_PLAIN:\n return string\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\"\n case STYLE_LITERAL:\n return '|' + blockHeader(string, state.indent) +\n dropEndingNewline(indentString(string, indent))\n case STYLE_FOLDED:\n return '>' + blockHeader(string, state.indent) +\n dropEndingNewline(indentString(foldString(string, lineWidth), indent))\n case STYLE_DOUBLE:\n return '\"' + escapeString(string, lineWidth) + '\"'\n default:\n throw new YAMLException('impossible error: invalid scalar style')\n }\n }())\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader (string, indentPerLevel) {\n const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''\n\n // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n const clip = string[string.length - 1] === '\\n'\n const keep = clip && (string[string.length - 2] === '\\n' || string === '\\n')\n const chomp = keep ? '+' : (clip ? '' : '-')\n\n return indentIndicator + chomp + '\\n'\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline (string) {\n return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString (string, width) {\n // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n // unless they're before or after a more-indented line, or at the very\n // beginning or end, in which case $k$ maps to $k$.\n // Therefore, parse each chunk as newline(s) followed by a content line.\n const lineRe = /(\\n+)([^\\n]*)/g\n\n // first line (possibly an empty line)\n let result = (function () {\n let nextLF = string.indexOf('\\n')\n nextLF = nextLF !== -1 ? nextLF : string.length\n lineRe.lastIndex = nextLF\n return foldLine(string.slice(0, nextLF), width)\n }())\n // If we haven't reached the first content line yet, don't add an extra \\n.\n let prevMoreIndented = string[0] === '\\n' || string[0] === ' '\n let moreIndented\n\n // rest of the lines\n let match\n while ((match = lineRe.exec(string))) {\n const prefix = match[1]\n const line = match[2]\n\n moreIndented = (line[0] === ' ')\n result += prefix +\n ((!prevMoreIndented && !moreIndented && line !== '') ? '\\n' : '') +\n foldLine(line, width)\n prevMoreIndented = moreIndented\n }\n\n return result\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine (line, width) {\n if (line === '' || line[0] === ' ') return line\n\n // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n const breakRe = / [^ ]/g // note: the match index will always be <= length-2.\n let match\n // start is an inclusive index. end, curr, and next are exclusive.\n let start = 0\n let end\n let curr = 0\n let next = 0\n let result = ''\n\n // Invariants: 0 <= start <= length-1.\n // 0 <= curr <= next <= max(0, length-2). curr - start <= width.\n // Inside the loop:\n // A match implies length >= 2, so curr and next are <= length-2.\n while ((match = breakRe.exec(line))) {\n next = match.index\n // maintain invariant: curr - start <= width\n if (next - start > width) {\n end = (curr > start) ? curr : next // derive end <= length-2\n result += '\\n' + line.slice(start, end)\n // skip the space that was output as \\n\n start = end + 1 // derive start <= length-1\n }\n curr = next\n }\n\n // By the invariants, start <= length-1, so there is something left over.\n // It is either the whole string or a part starting from non-whitespace.\n result += '\\n'\n // Insert a break if the remainder is too long and there is a break available.\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + '\\n' + line.slice(curr + 1)\n } else {\n result += line.slice(start)\n }\n\n return result.slice(1) // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString (string) {\n let result = ''\n let char = 0\n\n for (let i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n const escapeSeq = ESCAPE_SEQUENCES[char]\n\n if (!escapeSeq && isPrintable(char)) {\n result += string[i]\n if (char >= 0x10000) result += string[i + 1]\n } else {\n result += escapeSeq || encodeHex(char)\n }\n }\n\n return result\n}\n\nfunction writeFlowSequence (state, level, object) {\n let _result = ''\n const _tag = state.tag\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n let value = object[index]\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value)\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level, value, false, false) ||\n (typeof value === 'undefined' &&\n writeNode(state, level, null, false, false))) {\n if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '')\n _result += state.dump\n }\n }\n\n state.tag = _tag\n state.dump = '[' + _result + ']'\n}\n\nfunction writeBlockSequence (state, level, object, compact) {\n let _result = ''\n const _tag = state.tag\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n let value = object[index]\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value)\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level + 1, value, true, true, false, true) ||\n (typeof value === 'undefined' &&\n writeNode(state, level + 1, null, true, true, false, true))) {\n if (!compact || _result !== '') {\n _result += generateNextLine(state, level)\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += '-'\n } else {\n _result += '- '\n }\n\n _result += state.dump\n }\n }\n\n state.tag = _tag\n state.dump = _result || '[]' // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping (state, level, object) {\n let _result = ''\n const _tag = state.tag\n const objectKeyList = Object.keys(object)\n\n for (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n let pairBuffer = ''\n if (_result !== '') pairBuffer += ', '\n\n if (state.condenseFlow) pairBuffer += '\"'\n\n const objectKey = objectKeyList[index]\n let objectValue = object[objectKey]\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue)\n }\n\n if (!writeNode(state, level, objectKey, false, false)) {\n continue // Skip this pair because of invalid key;\n }\n\n if (state.dump.length > 1024) pairBuffer += '? '\n\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ')\n\n if (!writeNode(state, level, objectValue, false, false)) {\n continue // Skip this pair because of invalid value.\n }\n\n pairBuffer += state.dump\n\n // Both key and value are valid.\n _result += pairBuffer\n }\n\n state.tag = _tag\n state.dump = '{' + _result + '}'\n}\n\nfunction writeBlockMapping (state, level, object, compact) {\n let _result = ''\n const _tag = state.tag\n const objectKeyList = Object.keys(object)\n\n // Allow sorting keys so that the output file is deterministic\n if (state.sortKeys === true) {\n // Default sorting\n objectKeyList.sort()\n } else if (typeof state.sortKeys === 'function') {\n // Custom sort function\n objectKeyList.sort(state.sortKeys)\n } else if (state.sortKeys) {\n // Something is wrong\n throw new YAMLException('sortKeys must be a boolean or a function')\n }\n\n for (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n let pairBuffer = ''\n\n if (!compact || _result !== '') {\n pairBuffer += generateNextLine(state, level)\n }\n\n const objectKey = objectKeyList[index]\n let objectValue = object[objectKey]\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue)\n }\n\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue // Skip this pair because of invalid key.\n }\n\n const explicitPair = (state.tag !== null && state.tag !== '?') ||\n (state.dump && state.dump.length > 1024)\n\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += '?'\n } else {\n pairBuffer += '? '\n }\n }\n\n pairBuffer += state.dump\n\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level)\n }\n\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue // Skip this pair because of invalid value.\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += ':'\n } else {\n pairBuffer += ': '\n }\n\n pairBuffer += state.dump\n\n // Both key and value are valid.\n _result += pairBuffer\n }\n\n state.tag = _tag\n state.dump = _result || '{}' // Empty mapping if no valid pairs.\n}\n\nfunction detectType (state, object, explicit) {\n const typeList = explicit ? state.explicitTypes : state.implicitTypes\n\n for (let index = 0, length = typeList.length; index < length; index += 1) {\n const type = typeList[index]\n\n if ((type.instanceOf || type.predicate) &&\n (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n (!type.predicate || type.predicate(object))) {\n if (explicit) {\n if (type.multi && type.representName) {\n state.tag = type.representName(object)\n } else {\n state.tag = type.tag\n }\n } else {\n state.tag = '?'\n }\n\n if (type.represent) {\n const style = state.styleMap[type.tag] || type.defaultStyle\n\n let _result\n if (_toString.call(type.represent) === '[object Function]') {\n _result = type.represent(object, style)\n } else if (_hasOwnProperty.call(type.represent, style)) {\n _result = type.represent[style](object, style)\n } else {\n throw new YAMLException('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style')\n }\n\n state.dump = _result\n }\n\n return true\n }\n }\n\n return false\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode (state, level, object, block, compact, iskey, isblockseq) {\n state.tag = null\n state.dump = object\n\n if (!detectType(state, object, false)) {\n detectType(state, object, true)\n }\n\n const type = _toString.call(state.dump)\n const inblock = block\n\n if (block) {\n block = (state.flowLevel < 0 || state.flowLevel > level)\n }\n\n const objectOrArray = type === '[object Object]' || type === '[object Array]'\n let duplicateIndex\n let duplicate\n\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object)\n duplicate = duplicateIndex !== -1\n }\n\n if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n compact = false\n }\n\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = '*ref_' + duplicateIndex\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true\n }\n if (type === '[object Object]') {\n if (block && (Object.keys(state.dump).length !== 0)) {\n writeBlockMapping(state, level, state.dump, compact)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump\n }\n } else {\n writeFlowMapping(state, level, state.dump)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump\n }\n }\n } else if (type === '[object Array]') {\n if (block && (state.dump.length !== 0)) {\n if (state.noArrayIndent && !isblockseq && level > 0) {\n writeBlockSequence(state, level - 1, state.dump, compact)\n } else {\n writeBlockSequence(state, level, state.dump, compact)\n }\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump\n }\n } else {\n writeFlowSequence(state, level, state.dump)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump\n }\n }\n } else if (type === '[object String]') {\n if (state.tag !== '?') {\n writeScalar(state, state.dump, level, iskey, inblock)\n }\n } else if (type === '[object Undefined]') {\n return false\n } else {\n if (state.skipInvalid) return false\n throw new YAMLException('unacceptable kind of an object to dump ' + type)\n }\n\n if (state.tag !== null && state.tag !== '?') {\n // Need to encode all characters except those allowed by the spec:\n //\n // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */\n // [36] ns-hex-digit ::= ns-dec-digit\n // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */\n // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */\n // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-�\n // [39] ns-uri-char ::= “%� ns-hex-digit ns-hex-digit | ns-word-char | “#�\n // | “;� | “/� | “?� | “:� | “@� | “&� | “=� | “+� | “$� | “,�\n // | “_� | “.� | “!� | “~� | “*� | “'� | “(� | “)� | “[� | “]�\n //\n // Also need to encode '!' because it has special meaning (end of tag prefix).\n //\n let tagStr = encodeURI(\n state.tag[0] === '!' ? state.tag.slice(1) : state.tag\n ).replace(/!/g, '%21')\n\n if (state.tag[0] === '!') {\n tagStr = '!' + tagStr\n } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {\n tagStr = '!!' + tagStr.slice(18)\n } else {\n tagStr = '!<' + tagStr + '>'\n }\n\n state.dump = tagStr + ' ' + state.dump\n }\n }\n\n return true\n}\n\nfunction getDuplicateReferences (object, state) {\n const objects = []\n const duplicatesIndexes = []\n\n inspectNode(object, objects, duplicatesIndexes)\n\n const length = duplicatesIndexes.length\n for (let index = 0; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]])\n }\n state.usedDuplicates = new Array(length)\n}\n\nfunction inspectNode (object, objects, duplicatesIndexes) {\n if (object !== null && typeof object === 'object') {\n const index = objects.indexOf(object)\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index)\n }\n } else {\n objects.push(object)\n\n if (Array.isArray(object)) {\n for (let i = 0, length = object.length; i < length; i += 1) {\n inspectNode(object[i], objects, duplicatesIndexes)\n }\n } else {\n const objectKeyList = Object.keys(object)\n\n for (let i = 0, length = objectKeyList.length; i < length; i += 1) {\n inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes)\n }\n }\n }\n }\n}\n\nfunction dump (input, options) {\n options = options || {}\n\n const state = new State(options)\n\n if (!state.noRefs) getDuplicateReferences(input, state)\n\n let value = input\n\n if (state.replacer) {\n value = state.replacer.call({ '': value }, '', value)\n }\n\n if (writeNode(state, 0, value, true, true)) return state.dump + '\\n'\n\n return ''\n}\n\nmodule.exports.dump = dump\n","'use strict'\n\nconst loader = require('./lib/loader')\nconst dumper = require('./lib/dumper')\n\nfunction renamed (from, to) {\n return function () {\n throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +\n 'Use yaml.' + to + ' instead, which is now safe by default.')\n }\n}\n\nmodule.exports.Type = require('./lib/type')\nmodule.exports.Schema = require('./lib/schema')\nmodule.exports.FAILSAFE_SCHEMA = require('./lib/schema/failsafe')\nmodule.exports.JSON_SCHEMA = require('./lib/schema/json')\nmodule.exports.CORE_SCHEMA = require('./lib/schema/core')\nmodule.exports.DEFAULT_SCHEMA = require('./lib/schema/default')\nmodule.exports.load = loader.load\nmodule.exports.loadAll = loader.loadAll\nmodule.exports.dump = dumper.dump\nmodule.exports.YAMLException = require('./lib/exception')\n\n// Re-export all types in case user wants to create custom schema\nmodule.exports.types = {\n binary: require('./lib/type/binary'),\n float: require('./lib/type/float'),\n map: require('./lib/type/map'),\n null: require('./lib/type/null'),\n pairs: require('./lib/type/pairs'),\n set: require('./lib/type/set'),\n timestamp: require('./lib/type/timestamp'),\n bool: require('./lib/type/bool'),\n int: require('./lib/type/int'),\n merge: require('./lib/type/merge'),\n omap: require('./lib/type/omap'),\n seq: require('./lib/type/seq'),\n str: require('./lib/type/str')\n}\n\n// Removed functions from JS-YAML 3.0.x\nmodule.exports.safeLoad = renamed('safeLoad', 'load')\nmodule.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll')\nmodule.exports.safeDump = renamed('safeDump', 'dump')\n","import yaml from '../index.js'\n\nconst {\n Type,\n Schema,\n FAILSAFE_SCHEMA,\n JSON_SCHEMA,\n CORE_SCHEMA,\n DEFAULT_SCHEMA,\n load,\n loadAll,\n dump,\n YAMLException,\n types,\n safeLoad,\n safeLoadAll,\n safeDump\n} = yaml\n\nexport {\n Type,\n Schema,\n FAILSAFE_SCHEMA,\n JSON_SCHEMA,\n CORE_SCHEMA,\n DEFAULT_SCHEMA,\n load,\n loadAll,\n dump,\n YAMLException,\n types,\n safeLoad,\n safeLoadAll,\n safeDump\n}\n\nexport default yaml\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAEA,SAAS,UAAW,SAAS;GAC3B,OAAQ,OAAO,YAAY,eAAiB,YAAY;EAC1D;EAEA,SAAS,SAAU,SAAS;GAC1B,OAAQ,OAAO,YAAY,YAAc,YAAY;EACvD;EAEA,SAAS,QAAS,UAAU;GAC1B,IAAI,MAAM,QAAQ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AAQ,SAAA,eAAA;EACf,OAAO,QAAQ,kBAAA,iBAAA;EACf,OAAO,QAAQ,cAAA,aAAA;EACf,OAAO,QAAQ,cAAA,aAAA;EACf,OAAO,QAAQ,iBAAA,gBAAA;EACf,OAAO,QAAQ,OAAO,OAAO;EAC7B,OAAO,QAAQ,UAAU,OAAO;EAChC,OAAO,QAAQ,OAAO,OAAO;EAC7B,OAAO,QAAQ,gBAAA,kBAAA;EAGf,OAAO,QAAQ,QAAQ;GACrB,QAAA,eAAA;GACA,OAAA,cAAA;GACA,KAAA,YAAA;GACA,MAAA,aAAA;GACA,OAAA,cAAA;GACA,KAAA,YAAA;GACA,WAAA,kBAAA;GACA,MAAA,aAAA;GACA,KAAA,YAAA;GACA,OAAA,cAAA;GACA,MAAA,aAAA;GACA,KAAA,YAAA;GACA,KAAA,YAAA;EACF;EAGA,OAAO,QAAQ,WAAW,QAAQ,YAAY,MAAM;EACpD,OAAO,QAAQ,cAAc,QAAQ,eAAe,SAAS;EAC7D,OAAO,QAAQ,WAAW,QAAQ,YAAY,MAAM;;CCzCpD,IAAM,EACJ,MACA,QACA,iBACA,aACA,aACA,gBACA,MACA,SACA,MACA,eACA,OACA,UACA,aACA,aACEA,eAAAA;CAmBJ,IAAA,+BAAeA,eAAAA"}(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.jsyaml={}))})(this,function(e){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;lt[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e)),u=s(((e,t)=>{function n(e){return e==null}function r(e){return typeof e==`object`&&!!e}function i(e){return Array.isArray(e)?e:n(e)?[]:[e]}function a(e,t){if(t){let n=Object.keys(t);for(let r=0,i=n.length;r{function n(e,t){let n=``,r=e.reason||`(unknown reason)`;return e.mark?(e.mark.name&&(n+=`in "`+e.mark.name+`" `),n+=`(`+(e.mark.line+1)+`:`+(e.mark.column+1)+`)`,!t&&e.mark.snippet&&(n+=` `+e.mark.snippet),r+` `+n):r}function r(e,t){Error.call(this),this.name=`YAMLException`,this.reason=e,this.mark=t,this.message=n(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack||``}r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r.prototype.toString=function(e){return this.name+`: `+n(this,e)},t.exports=r})),f=s(((e,t)=>{var n=u();function r(e,t,n,r,i){let a=``,o=``,s=Math.floor(i/2)-1;return r-t>s&&(a=` ... `,t=r-s+a.length),n-r>s&&(o=` ...`,n=r+s-o.length),{str:a+e.slice(t,n).replace(/\t/g,`→`)+o,pos:r-t+a.length}}function i(e,t){return n.repeat(` `,t-e.length)+e}function a(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),typeof t.indent!=`number`&&(t.indent=1),typeof t.linesBefore!=`number`&&(t.linesBefore=3),typeof t.linesAfter!=`number`&&(t.linesAfter=2);let a=/\r?\n|\r|\0/g,o=[0],s=[],c,l=-1;for(;c=a.exec(e.buffer);)s.push(c.index),o.push(c.index+c[0].length),e.position<=c.index&&l<0&&(l=o.length-2);l<0&&(l=o.length-1);let u=``,d=Math.min(e.line+t.linesAfter,s.length).toString().length,f=t.maxLength-(t.indent+d+3);for(let a=1;a<=t.linesBefore&&!(l-a<0);a++){let c=r(e.buffer,o[l-a],s[l-a],e.position-(o[l]-o[l-a]),f);u=n.repeat(` `,t.indent)+i((e.line-a+1).toString(),d)+` | `+c.str+` `+u}let p=r(e.buffer,o[l],s[l],e.position,f);u+=n.repeat(` `,t.indent)+i((e.line+1).toString(),d)+` | `+p.str+` `,u+=n.repeat(`-`,t.indent+d+3+p.pos)+`^ `;for(let a=1;a<=t.linesAfter&&!(l+a>=s.length);a++){let c=r(e.buffer,o[l+a],s[l+a],e.position-(o[l]-o[l+a]),f);u+=n.repeat(` `,t.indent)+i((e.line+a+1).toString(),d)+` | `+c.str+` `}return u.replace(/\n$/,``)}t.exports=a})),p=s(((e,t)=>{var n=d(),r=[`kind`,`multi`,`resolve`,`construct`,`instanceOf`,`predicate`,`represent`,`representName`,`defaultStyle`,`styleAliases`],i=[`scalar`,`sequence`,`mapping`];function a(e){let t={};return e!==null&&Object.keys(e).forEach(function(n){e[n].forEach(function(e){t[String(e)]=n})}),t}function o(e,t){if(t=t||{},Object.keys(t).forEach(function(t){if(r.indexOf(t)===-1)throw new n(`Unknown option "`+t+`" is met in definition of "`+e+`" YAML type.`)}),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=a(t.styleAliases||null),i.indexOf(this.kind)===-1)throw new n(`Unknown kind "`+this.kind+`" is specified for "`+e+`" YAML type.`)}t.exports=o})),m=s(((e,t)=>{var n=d(),r=p();function i(e,t){let n=[];return e[t].forEach(function(e){let t=n.length;n.forEach(function(n,r){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=r)}),n[t]=e}),n}function a(){let e={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function t(t){t.multi?(e.multi[t.kind].push(t),e.multi.fallback.push(t)):e[t.kind][t.tag]=e.fallback[t.tag]=t}for(let e=0,n=arguments.length;e{t.exports=new(p())(`tag:yaml.org,2002:str`,{kind:`scalar`,construct:function(e){return e===null?``:e}})})),g=s(((e,t)=>{t.exports=new(p())(`tag:yaml.org,2002:seq`,{kind:`sequence`,construct:function(e){return e===null?[]:e}})})),_=s(((e,t)=>{t.exports=new(p())(`tag:yaml.org,2002:map`,{kind:`mapping`,construct:function(e){return e===null?{}:e}})})),v=s(((e,t)=>{t.exports=new(m())({explicit:[h(),g(),_()]})})),y=s(((e,t)=>{var n=p();function r(e){if(e===null)return!0;let t=e.length;return t===1&&e===`~`||t===4&&(e===`null`||e===`Null`||e===`NULL`)}function i(){return null}function a(e){return e===null}t.exports=new n(`tag:yaml.org,2002:null`,{kind:`scalar`,resolve:r,construct:i,predicate:a,represent:{canonical:function(){return`~`},lowercase:function(){return`null`},uppercase:function(){return`NULL`},camelcase:function(){return`Null`},empty:function(){return``}},defaultStyle:`lowercase`})})),b=s(((e,t)=>{var n=p();function r(e){if(e===null)return!1;let t=e.length;return t===4&&(e===`true`||e===`True`||e===`TRUE`)||t===5&&(e===`false`||e===`False`||e===`FALSE`)}function i(e){return e===`true`||e===`True`||e===`TRUE`}function a(e){return Object.prototype.toString.call(e)===`[object Boolean]`}t.exports=new n(`tag:yaml.org,2002:bool`,{kind:`scalar`,resolve:r,construct:i,predicate:a,represent:{lowercase:function(e){return e?`true`:`false`},uppercase:function(e){return e?`TRUE`:`FALSE`},camelcase:function(e){return e?`True`:`False`}},defaultStyle:`lowercase`})})),x=s(((e,t)=>{var n=u(),r=p();function i(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function a(e){return e>=48&&e<=55}function o(e){return e>=48&&e<=57}function s(e){if(e===null)return!1;let t=e.length,n=0,r=!1;if(!t)return!1;let s=e[n];if((s===`-`||s===`+`)&&(s=e[++n]),s===`0`){if(n+1===t)return!0;if(s=e[++n],s===`b`){for(n++;n=0?`0b`+e.toString(2):`-0b`+e.toString(2).slice(1)},octal:function(e){return e>=0?`0o`+e.toString(8):`-0o`+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?`0x`+e.toString(16).toUpperCase():`-0x`+e.toString(16).toUpperCase().slice(1)}},defaultStyle:`decimal`,styleAliases:{binary:[2,`bin`],octal:[8,`oct`],decimal:[10,`dec`],hexadecimal:[16,`hex`]}})})),S=s(((e,t)=>{var n=u(),r=p(),i=RegExp(`^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$`),a=RegExp(`^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$`);function o(e){return e===null||!i.test(e)?!1:Number.isFinite(parseFloat(e,10))?!0:a.test(e)}function s(e){let t=e.toLowerCase(),n=t[0]===`-`?-1:1;return`+-`.indexOf(t[0])>=0&&(t=t.slice(1)),t===`.inf`?n===1?1/0:-1/0:t===`.nan`?NaN:n*parseFloat(t,10)}var c=/^[-+]?[0-9]+e/;function l(e,t){if(isNaN(e))switch(t){case`lowercase`:return`.nan`;case`uppercase`:return`.NAN`;case`camelcase`:return`.NaN`}else if(e===1/0)switch(t){case`lowercase`:return`.inf`;case`uppercase`:return`.INF`;case`camelcase`:return`.Inf`}else if(e===-1/0)switch(t){case`lowercase`:return`-.inf`;case`uppercase`:return`-.INF`;case`camelcase`:return`-.Inf`}else if(n.isNegativeZero(e))return`-0.0`;let r=e.toString(10);return c.test(r)?r.replace(`e`,`.e`):r}function d(e){return Object.prototype.toString.call(e)===`[object Number]`&&(e%1!=0||n.isNegativeZero(e))}t.exports=new r(`tag:yaml.org,2002:float`,{kind:`scalar`,resolve:o,construct:s,predicate:d,represent:l,defaultStyle:`lowercase`})})),C=s(((e,t)=>{t.exports=v().extend({implicit:[y(),b(),x(),S()]})})),w=s(((e,t)=>{t.exports=C()})),T=s(((e,t)=>{var n=p(),r=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$`),i=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$`);function a(e){return e===null?!1:r.exec(e)!==null||i.exec(e)!==null}function o(e){let t=0,n=null,a=r.exec(e);if(a===null&&(a=i.exec(e)),a===null)throw Error(`Date resolve error`);let o=+a[1],s=a[2]-1,c=+a[3];if(!a[4])return new Date(Date.UTC(o,s,c));let l=+a[4],u=+a[5],d=+a[6];if(a[7]){for(t=a[7].slice(0,3);t.length<3;)t+=`0`;t=+t}if(a[9]){let e=+a[10],t=+(a[11]||0);n=(e*60+t)*6e4,a[9]===`-`&&(n=-n)}let f=new Date(Date.UTC(o,s,c,l,u,d,t));return n&&f.setTime(f.getTime()-n),f}function s(e){return e.toISOString()}t.exports=new n(`tag:yaml.org,2002:timestamp`,{kind:`scalar`,resolve:a,construct:o,instanceOf:Date,represent:s})})),E=s(((e,t)=>{var n=p();function r(e){return e===`<<`||e===null}t.exports=new n(`tag:yaml.org,2002:merge`,{kind:`scalar`,resolve:r})})),D=s(((e,t)=>{var n=p(),r=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= \r`;function i(e){if(e===null)return!1;let t=0,n=e.length,i=r;for(let r=0;r64)){if(n<0)return!1;t+=6}}return t%8==0}function a(e){let t=e.replace(/[\r\n=]/g,``),n=t.length,i=r,a=0,o=[];for(let e=0;e>16&255),o.push(a>>8&255),o.push(a&255)),a=a<<6|i.indexOf(t.charAt(e));let s=n%4*6;return s===0?(o.push(a>>16&255),o.push(a>>8&255),o.push(a&255)):s===18?(o.push(a>>10&255),o.push(a>>2&255)):s===12&&o.push(a>>4&255),new Uint8Array(o)}function o(e){let t=``,n=0,i=e.length,a=r;for(let r=0;r>18&63],t+=a[n>>12&63],t+=a[n>>6&63],t+=a[n&63]),n=(n<<8)+e[r];let o=i%3;return o===0?(t+=a[n>>18&63],t+=a[n>>12&63],t+=a[n>>6&63],t+=a[n&63]):o===2?(t+=a[n>>10&63],t+=a[n>>4&63],t+=a[n<<2&63],t+=a[64]):o===1&&(t+=a[n>>2&63],t+=a[n<<4&63],t+=a[64],t+=a[64]),t}function s(e){return Object.prototype.toString.call(e)===`[object Uint8Array]`}t.exports=new n(`tag:yaml.org,2002:binary`,{kind:`scalar`,resolve:i,construct:a,predicate:s,represent:o})})),O=s(((e,t)=>{var n=p(),r=Object.prototype.hasOwnProperty,i=Object.prototype.toString;function a(e){if(e===null)return!0;let t=[],n=e;for(let e=0,a=n.length;e{var n=p(),r=Object.prototype.toString;function i(e){if(e===null)return!0;let t=e,n=Array(t.length);for(let e=0,i=t.length;e{var n=p(),r=Object.prototype.hasOwnProperty;function i(e){if(e===null)return!0;let t=e;for(let e in t)if(r.call(t,e)&&t[e]!==null)return!1;return!0}function a(e){return e===null?{}:e}t.exports=new n(`tag:yaml.org,2002:set`,{kind:`mapping`,resolve:i,construct:a})})),ee=s(((e,t)=>{t.exports=w().extend({implicit:[T(),E()],explicit:[D(),O(),k(),A()]})})),j=s(((e,t)=>{var n=u(),r=d(),i=f(),a=ee(),o=Object.prototype.hasOwnProperty,s=1,c=2,l=3,p=4,m=1,h=2,g=3,_=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,v=/[\x85\u2028\u2029]/,y=/[,\[\]{}]/,b=/^(?:!|!!|![0-9A-Za-z-]+!)$/,x=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function S(e){return Object.prototype.toString.call(e)}function C(e){return e===10||e===13}function w(e){return e===9||e===32}function T(e){return e===9||e===32||e===10||e===13}function E(e){return e===44||e===91||e===93||e===123||e===125}function D(e){if(e>=48&&e<=57)return e-48;let t=e|32;return t>=97&&t<=102?t-97+10:-1}function O(e){return e===120?2:e===117?4:e===85?8:0}function k(e){return e>=48&&e<=57?e-48:-1}function A(e){switch(e){case 48:return`\0`;case 97:return`\x07`;case 98:return`\b`;case 116:return` `;case 9:return` `;case 110:return` `;case 118:return`\v`;case 102:return`\f`;case 114:return`\r`;case 101:return`\x1B`;case 32:return` `;case 34:return`"`;case 47:return`/`;case 92:return`\\`;case 78:return`…`;case 95:return`\xA0`;case 76:return`\u2028`;case 80:return`\u2029`;default:return``}}function j(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}function te(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!0,value:n}):e[t]=n}var M=Array(256),N=Array(256);for(let e=0;e<256;e++)M[e]=+!!A(e),N[e]=A(e);function ne(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||a,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.maxDepth=typeof t.maxDepth==`number`?t.maxDepth:100,this.maxMergeSeqLength=typeof t.maxMergeSeqLength==`number`?t.maxMergeSeqLength:20,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function P(e,t){let n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=i(n),new r(t,n)}function F(e,t){throw P(e,t)}function I(e,t){e.onWarning&&e.onWarning.call(null,P(e,t))}function L(e,t,n){let r=e.anchorMapTransactions;if(r.length!==0){let n=r[r.length-1];o.call(n,t)||(n[t]={existed:o.call(e.anchorMap,t),value:e.anchorMap[t]})}e.anchorMap[t]=n}function R(e){e.anchorMapTransactions.push(Object.create(null))}function re(e){let t=e.anchorMapTransactions.pop(),n=e.anchorMapTransactions;if(n.length===0)return;let r=n[n.length-1],i=Object.keys(t);for(let e=0,n=i.length;e=0;--r){let i=t[n[r]];i.existed?e.anchorMap[n[r]]=i.value:delete e.anchorMap[n[r]]}}function B(e){return{position:e.position,line:e.line,lineStart:e.lineStart,lineIndent:e.lineIndent,firstTabInLine:e.firstTabInLine,tag:e.tag,anchor:e.anchor,kind:e.kind,result:e.result}}function V(e,t){e.position=t.position,e.line=t.line,e.lineStart=t.lineStart,e.lineIndent=t.lineIndent,e.firstTabInLine=t.firstTabInLine,e.tag=t.tag,e.anchor=t.anchor,e.kind=t.kind,e.result=t.result}var H={YAML:function(e,t,n){e.version!==null&&F(e,`duplication of %YAML directive`),n.length!==1&&F(e,`YAML directive accepts exactly one argument`);let r=/^([0-9]+)\.([0-9]+)$/.exec(n[0]);r===null&&F(e,`ill-formed argument of the YAML directive`);let i=parseInt(r[1],10),a=parseInt(r[2],10);i!==1&&F(e,`unacceptable YAML version of the document`),e.version=n[0],e.checkLineBreaks=a<2,a!==1&&a!==2&&I(e,`unsupported YAML version of the document`)},TAG:function(e,t,n){let r;n.length!==2&&F(e,`TAG directive accepts exactly two arguments`);let i=n[0];r=n[1],b.test(i)||F(e,`ill-formed tag handle (first argument) of the TAG directive`),o.call(e.tagMap,i)&&F(e,`there is a previously declared suffix for "`+i+`" tag handle`),x.test(r)||F(e,`ill-formed tag prefix (second argument) of the TAG directive`);try{r=decodeURIComponent(r)}catch(t){F(e,`tag prefix is malformed: `+r)}e.tagMap[i]=r}};function U(e,t,n,r){if(t=32&&n<=1114111||F(e,`expected valid JSON character`)}else _.test(i)&&F(e,`the stream contains non-printable characters`);e.result+=i}}function W(e,t,r,i){n.isObject(r)||F(e,`cannot merge mappings; the provided source object is unacceptable`);let a=Object.keys(r);for(let e=0,n=a.length;ee.maxMergeSeqLength&&F(e,`merge sequence length exceeded maxMergeSeqLength (`+e.maxMergeSeqLength+`)`);let r=new Set;for(let i=0,o=a.length;i1&&(e.result+=n.repeat(` `,t-1))}function ie(e,t,n){let r,i,a,o,s,c,l=e.kind,u=e.result,d=e.input.charCodeAt(e.position);if(T(d)||E(d)||d===35||d===38||d===42||d===33||d===124||d===62||d===39||d===34||d===37||d===64||d===96)return!1;if(d===63||d===45){let t=e.input.charCodeAt(e.position+1);if(T(t)||n&&E(t))return!1}for(e.kind=`scalar`,e.result=``,r=i=e.position,a=!1;d!==0;){if(d===58){let t=e.input.charCodeAt(e.position+1);if(T(t)||n&&E(t))break}else if(d===35){if(T(e.input.charCodeAt(e.position-1)))break}else if(e.position===e.lineStart&&J(e)||n&&E(d))break;else if(C(d))if(o=e.line,s=e.lineStart,c=e.lineIndent,q(e,!1,-1),e.lineIndent>=t){a=!0,d=e.input.charCodeAt(e.position);continue}else{e.position=i,e.line=o,e.lineStart=s,e.lineIndent=c;break}a&&(U(e,r,i,!1),Y(e,e.line-o),r=i=e.position,a=!1),w(d)||(i=e.position+1),d=e.input.charCodeAt(++e.position)}return U(e,r,i,!1),e.result?!0:(e.kind=l,e.result=u,!1)}function X(e,t){let n,r,i=e.input.charCodeAt(e.position);if(i!==39)return!1;for(e.kind=`scalar`,e.result=``,e.position++,n=r=e.position;(i=e.input.charCodeAt(e.position))!==0;)if(i===39)if(U(e,n,e.position,!0),i=e.input.charCodeAt(++e.position),i===39)n=e.position,e.position++,r=e.position;else return!0;else C(i)?(U(e,n,r,!0),Y(e,q(e,!1,t)),n=r=e.position):e.position===e.lineStart&&J(e)?F(e,`unexpected end of the document within a single quoted scalar`):(e.position++,w(i)||(r=e.position));F(e,`unexpected end of the stream within a single quoted scalar`)}function ae(e,t){let n,r,i,a=e.input.charCodeAt(e.position);if(a!==34)return!1;for(e.kind=`scalar`,e.result=``,e.position++,n=r=e.position;(a=e.input.charCodeAt(e.position))!==0;)if(a===34)return U(e,n,e.position,!0),e.position++,!0;else if(a===92){if(U(e,n,e.position,!0),a=e.input.charCodeAt(++e.position),C(a))q(e,!1,t);else if(a<256&&M[a])e.result+=N[a],e.position++;else if((i=O(a))>0){let t=i,n=0;for(;t>0;t--)a=e.input.charCodeAt(++e.position),(i=D(a))>=0?n=(n<<4)+i:F(e,`expected hexadecimal character`);e.result+=j(n),e.position++}else F(e,`unknown escape sequence`);n=r=e.position}else C(a)?(U(e,n,r,!0),Y(e,q(e,!1,t)),n=r=e.position):e.position===e.lineStart&&J(e)?F(e,`unexpected end of the document within a double quoted scalar`):(e.position++,w(a)||(r=e.position));F(e,`unexpected end of the stream within a double quoted scalar`)}function oe(e,t){let n=!0,r,i,a,o=e.tag,c,l=e.anchor,u,d,f,p,m=Object.create(null),h,g,_,v=e.input.charCodeAt(e.position);if(v===91)u=93,p=!1,c=[];else if(v===123)u=125,p=!0,c={};else return!1;for(e.anchor!==null&&L(e,e.anchor,c),v=e.input.charCodeAt(++e.position);v!==0;){if(q(e,!0,t),v=e.input.charCodeAt(e.position),v===u)return e.position++,e.tag=o,e.anchor=l,e.kind=p?`mapping`:`sequence`,e.result=c,!0;n?v===44&&F(e,`expected the node content, but found ','`):F(e,`missed comma between flow collection entries`),g=h=_=null,d=f=!1,v===63&&T(e.input.charCodeAt(e.position+1))&&(d=f=!0,e.position++,q(e,!0,t)),r=e.line,i=e.lineStart,a=e.position,Q(e,t,s,!1,!0),g=e.tag,h=e.result,q(e,!0,t),v=e.input.charCodeAt(e.position),(f||e.line===r)&&v===58&&(d=!0,v=e.input.charCodeAt(++e.position),q(e,!0,t),Q(e,t,s,!1,!0),_=e.result),p?G(e,c,m,g,h,_,r,i,a):d?c.push(G(e,null,m,g,h,_,r,i,a)):c.push(h),q(e,!0,t),v=e.input.charCodeAt(e.position),v===44?(n=!0,v=e.input.charCodeAt(++e.position)):n=!1}F(e,`unexpected end of the stream within a flow collection`)}function Z(e,t){let r,i=m,a=!1,o=!1,s=t,c=0,l=!1,u,d=e.input.charCodeAt(e.position);if(d===124)r=!1;else if(d===62)r=!0;else return!1;for(e.kind=`scalar`,e.result=``;d!==0;)if(d=e.input.charCodeAt(++e.position),d===43||d===45)m===i?i=d===43?g:h:F(e,`repeat of a chomping mode identifier`);else if((u=k(d))>=0)u===0?F(e,`bad explicit indentation width of a block scalar; it cannot be less than one`):o?F(e,`repeat of an indentation width identifier`):(s=t+u-1,o=!0);else break;if(w(d)){do d=e.input.charCodeAt(++e.position);while(w(d));if(d===35)do d=e.input.charCodeAt(++e.position);while(!C(d)&&d!==0)}for(;d!==0;){for(K(e),e.lineIndent=0,d=e.input.charCodeAt(e.position);(!o||e.lineIndents&&(s=e.lineIndent),C(d)){c++;continue}if(!o&&s===0&&F(e,`missing indentation for block scalar`),e.lineIndentt)&&o!==0)F(e,`bad indentation of a sequence entry`);else if(e.lineIndentt)&&(g&&(i=e.line,a=e.lineStart,o=e.position),Q(e,t,p,!0,r)&&(g?m=e.result:h=e.result),g||(G(e,u,d,f,m,h,i,a,o),f=m=h=null),q(e,!0,-1),v=e.input.charCodeAt(e.position)),(e.line===b||e.lineIndent>t)&&v!==0)F(e,`bad indentation of a mapping entry`);else if(e.lineIndent=e.maxDepth&&F(e,`nesting exceeded maxDepth (`+e.maxDepth+`)`),e.depth+=1,e.listener!==null&&e.listener(`open`,e),e.tag=null,e.anchor=null,e.kind=null,e.result=null;let y=a=u=p===n||l===n;if(r&&q(e,!0,-1)&&(f=!0,e.lineIndent>t?d=1:e.lineIndent===t?d=0:e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndent tag; it should be "scalar", not "`+e.kind+`"`);for(let t=0,n=e.implicitTypes.length;t`),e.result!==null&&g.kind!==e.kind&&F(e,`unacceptable node kind for !<`+e.tag+`> tag; it should be "`+g.kind+`", not "`+e.kind+`"`),g.resolve(e.result,e.tag)?(e.result=g.construct(e.result,e.tag),e.anchor!==null&&L(e,e.anchor,e.result)):F(e,`cannot resolve a node with !<`+e.tag+`> explicit tag`)}return e.listener!==null&&e.listener(`close`,e),--e.depth,e.tag!==null||e.anchor!==null||m}function pe(e){let t=e.position,n=!1,r;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(r=e.input.charCodeAt(e.position))!==0&&(q(e,!0,-1),r=e.input.charCodeAt(e.position),!(e.lineIndent>0||r!==37));){n=!0,r=e.input.charCodeAt(++e.position);let t=e.position;for(;r!==0&&!T(r);)r=e.input.charCodeAt(++e.position);let i=e.input.slice(t,e.position),a=[];for(i.length<1&&F(e,`directive name must not be less than one character in length`);r!==0;){for(;w(r);)r=e.input.charCodeAt(++e.position);if(r===35){do r=e.input.charCodeAt(++e.position);while(r!==0&&!C(r));break}if(C(r))break;for(t=e.position;r!==0&&!T(r);)r=e.input.charCodeAt(++e.position);a.push(e.input.slice(t,e.position))}r!==0&&K(e),o.call(H,i)?H[i](e,i,a):I(e,`unknown document directive "`+i+`"`)}if(q(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,q(e,!0,-1)):n&&F(e,`directives end mark is expected`),Q(e,e.lineIndent-1,p,!1,!0),q(e,!0,-1),e.checkLineBreaks&&v.test(e.input.slice(t,e.position))&&I(e,`non-ASCII line breaks are interpreted as content`),e.documents.push(e.result),e.position===e.lineStart&&J(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,q(e,!0,-1));return}e.position{var n=u(),r=d(),i=ee(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,s=65279,c=9,l=10,f=13,p=32,m=33,h=34,g=35,_=37,v=38,y=39,b=42,x=44,S=45,C=58,w=61,T=62,E=63,D=64,O=91,k=93,A=96,j=123,te=124,M=125,N={};N[0]=`\\0`,N[7]=`\\a`,N[8]=`\\b`,N[9]=`\\t`,N[10]=`\\n`,N[11]=`\\v`,N[12]=`\\f`,N[13]=`\\r`,N[27]=`\\e`,N[34]=`\\"`,N[92]=`\\\\`,N[133]=`\\N`,N[160]=`\\_`,N[8232]=`\\L`,N[8233]=`\\P`;var ne=[`y`,`Y`,`yes`,`Yes`,`YES`,`on`,`On`,`ON`,`n`,`N`,`no`,`No`,`NO`,`off`,`Off`,`OFF`],P=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function F(e,t){if(t===null)return{};let n={},r=Object.keys(t);for(let i=0,a=r.length;i=32&&e<=126||e>=161&&e<=55295&&e!==8232&&e!==8233||e>=57344&&e<=65533&&e!==s||e>=65536&&e<=1114111}function W(e){return U(e)&&e!==s&&e!==f&&e!==l}function G(e,t,n){let r=W(e),i=r&&!H(e);return(n?r:r&&e!==x&&e!==O&&e!==k&&e!==j&&e!==M)&&e!==g&&!(t===C&&!i)||W(t)&&!H(t)&&e===g||t===C&&i}function K(e){return U(e)&&e!==s&&!H(e)&&e!==S&&e!==E&&e!==C&&e!==x&&e!==O&&e!==k&&e!==j&&e!==M&&e!==g&&e!==v&&e!==b&&e!==m&&e!==te&&e!==w&&e!==T&&e!==y&&e!==h&&e!==_&&e!==D&&e!==A}function q(e){return!H(e)&&e!==C}function J(e,t){let n=e.charCodeAt(t),r;return n>=55296&&n<=56319&&t+1=56320&&r<=57343)?(n-55296)*1024+r-56320+65536:n}function Y(e){return/^\n* /.test(e)}var ie=1,X=2,ae=3,oe=4,Z=5;function se(e,t,n,r,i,a,o,s){let c,u=0,d=null,f=!1,p=!1,m=r!==-1,h=-1,g=K(J(e,0))&&q(J(e,e.length-1));if(t||o)for(c=0;c=65536?c+=2:c++){if(u=J(e,c),!U(u))return Z;g=g&&G(u,d,s),d=u}else{for(c=0;c=65536?c+=2:c++){if(u=J(e,c),u===l)f=!0,m&&(p=p||c-h-1>r&&e[h+1]!==` `,h=c);else if(!U(u))return Z;g=g&&G(u,d,s),d=u}p=p||m&&c-h-1>r&&e[h+1]!==` `}return!f&&!p?g&&!o&&!i(e)?ie:a===R?Z:X:n>9&&Y(e)?Z:o?a===R?Z:X:p?oe:ae}function ce(e,t,n,i,a){e.dump=function(){if(t.length===0)return e.quotingType===R?`""`:`''`;if(!e.noCompatMode&&(ne.indexOf(t)!==-1||P.test(t)))return e.quotingType===R?`"`+t+`"`:`'`+t+`'`;let o=e.indent*Math.max(1,n),s=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-o),c=i||e.flowLevel>-1&&n>=e.flowLevel;function l(t){return V(e,t)}switch(se(t,c,e.indent,s,l,e.quotingType,e.forceQuotes&&!i,a)){case ie:return t;case X:return`'`+t.replace(/'/g,`''`)+`'`;case ae:return`|`+le(t,e.indent)+ue(z(t,o));case oe:return`>`+le(t,e.indent)+ue(z(de(t,s),o));case Z:return`"`+Q(t,s)+`"`;default:throw new r(`impossible error: invalid scalar style`)}}()}function le(e,t){let n=Y(e)?String(t):``,r=e[e.length-1]===` `;return n+(r&&(e[e.length-2]===` `||e===` `)?`+`:r?``:`-`)+` `}function ue(e){return e[e.length-1]===` `?e.slice(0,-1):e}function de(e,t){let n=/(\n+)([^\n]*)/g,r=function(){let r=e.indexOf(` `);return r=r===-1?e.length:r,n.lastIndex=r,fe(e.slice(0,r),t)}(),i=e[0]===` `||e[0]===` `,a,o;for(;o=n.exec(e);){let e=o[1],n=o[2];a=n[0]===` `,r+=e+(!i&&!a&&n!==``?` `:``)+fe(n,t),i=a}return r}function fe(e,t){if(e===``||e[0]===` `)return e;let n=/ [^ ]/g,r,i=0,a,o=0,s=0,c=``;for(;r=n.exec(e);)s=r.index,s-i>t&&(a=o>i?o:s,c+=` `+e.slice(i,a),i=a+1),o=s;return c+=` `,e.length-i>t&&o>i?c+=e.slice(i,o)+` `+e.slice(o+1):c+=e.slice(i),c.slice(1)}function Q(e){let t=``,n=0;for(let r=0;r=65536?r+=2:r++){n=J(e,r);let i=N[n];!i&&U(n)?(t+=e[r],n>=65536&&(t+=e[r+1])):t+=i||I(n)}return t}function pe(e,t,n){let r=``,i=e.tag;for(let i=0,a=n.length;i1024&&(o+=`? `),o+=e.dump+(e.condenseFlow?`"`:``)+`:`+(e.condenseFlow?``:` `),$(e,t,c,!1,!1)&&(o+=e.dump,r+=o))}e.tag=i,e.dump=`{`+r+`}`}function ge(e,t,n,i){let a=``,o=e.tag,s=Object.keys(n);if(e.sortKeys===!0)s.sort();else if(typeof e.sortKeys==`function`)s.sort(e.sortKeys);else if(e.sortKeys)throw new r(`sortKeys must be a boolean or a function`);for(let r=0,o=s.length;r1024;d&&(e.dump&&l===e.dump.charCodeAt(0)?o+=`?`:o+=`? `),o+=e.dump,d&&(o+=B(e,t)),$(e,t+1,u,!0,d)&&(e.dump&&l===e.dump.charCodeAt(0)?o+=`:`:o+=`: `,o+=e.dump,a+=o)}e.tag=o,e.dump=a||`{}`}function _e(e,t,n){let i=n?e.explicitTypes:e.implicitTypes;for(let s=0,c=i.length;s tag resolver accepts not "`+n+`" style`);e.dump=i}return!0}}return!1}function $(e,t,n,i,o,s,c){e.tag=null,e.dump=n,_e(e,n,!1)||_e(e,n,!0);let l=a.call(e.dump),u=i;i&&(i=e.flowLevel<0||e.flowLevel>t);let d=l===`[object Object]`||l===`[object Array]`,f,p;if(d&&(f=e.duplicates.indexOf(n),p=f!==-1),(e.tag!==null&&e.tag!==`?`||p||e.indent!==2&&t>0)&&(o=!1),p&&e.usedDuplicates[f])e.dump=`*ref_`+f;else{if(d&&p&&!e.usedDuplicates[f]&&(e.usedDuplicates[f]=!0),l===`[object Object]`)i&&Object.keys(e.dump).length!==0?(ge(e,t,e.dump,o),p&&(e.dump=`&ref_`+f+e.dump)):(he(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(l===`[object Array]`)i&&e.dump.length!==0?(e.noArrayIndent&&!c&&t>0?me(e,t-1,e.dump,o):me(e,t,e.dump,o),p&&(e.dump=`&ref_`+f+e.dump)):(pe(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(l===`[object String]`)e.tag!==`?`&&ce(e,e.dump,t,s,u);else if(l===`[object Undefined]`)return!1;else{if(e.skipInvalid)return!1;throw new r(`unacceptable kind of an object to dump `+l)}if(e.tag!==null&&e.tag!==`?`){let t=encodeURI(e.tag[0]===`!`?e.tag.slice(1):e.tag).replace(/!/g,`%21`);t=e.tag[0]===`!`?`!`+t:t.slice(0,18)===`tag:yaml.org,2002:`?`!!`+t.slice(18):`!<`+t+`>`,e.dump=t+` `+e.dump}}return!0}function ve(e,t){let n=[],r=[];ye(e,n,r);let i=r.length;for(let e=0;e{var n=j(),r=te();function i(e,t){return function(){throw Error(`Function yaml.`+e+` is removed in js-yaml 4. Use yaml.`+t+` instead, which is now safe by default.`)}}t.exports.Type=p(),t.exports.Schema=m(),t.exports.FAILSAFE_SCHEMA=v(),t.exports.JSON_SCHEMA=C(),t.exports.CORE_SCHEMA=w(),t.exports.DEFAULT_SCHEMA=ee(),t.exports.load=n.load,t.exports.loadAll=n.loadAll,t.exports.dump=r.dump,t.exports.YAMLException=d(),t.exports.types={binary:D(),float:S(),map:_(),null:y(),pairs:k(),set:A(),timestamp:T(),bool:b(),int:x(),merge:E(),omap:O(),seq:g(),str:h()},t.exports.safeLoad=i(`safeLoad`,`load`),t.exports.safeLoadAll=i(`safeLoadAll`,`loadAll`),t.exports.safeDump=i(`safeDump`,`dump`)}))(),1),{Type:N,Schema:ne,FAILSAFE_SCHEMA:P,JSON_SCHEMA:F,CORE_SCHEMA:I,DEFAULT_SCHEMA:L,load:R,loadAll:re,dump:z,YAMLException:B,types:V,safeLoad:H,safeLoadAll:U,safeDump:W}=M.default,G=M.default;e.CORE_SCHEMA=I,e.DEFAULT_SCHEMA=L,e.FAILSAFE_SCHEMA=P,e.JSON_SCHEMA=F,e.Schema=ne,e.Type=N,e.YAMLException=B,e.default=G,e.dump=z,e.load=R,e.loadAll=re,e.safeDump=W,e.safeLoad=H,e.safeLoadAll=U,e.types=V}); //# sourceMappingURL=js-yaml.min.js.map{"version":3,"file":"js-yaml.min.js","names":["yaml"],"sources":["../lib/common.js","../lib/exception.js","../lib/snippet.js","../lib/type.js","../lib/schema.js","../lib/type/str.js","../lib/type/seq.js","../lib/type/map.js","../lib/schema/failsafe.js","../lib/type/null.js","../lib/type/bool.js","../lib/type/int.js","../lib/type/float.js","../lib/schema/json.js","../lib/schema/core.js","../lib/type/timestamp.js","../lib/type/merge.js","../lib/type/binary.js","../lib/type/omap.js","../lib/type/pairs.js","../lib/type/set.js","../lib/schema/default.js","../lib/loader.js","../lib/dumper.js","../index.js","../lib/index_vite_proxy.tmp.mjs"],"sourcesContent":["'use strict'\n\nfunction isNothing (subject) {\n return (typeof subject === 'undefined') || (subject === null)\n}\n\nfunction isObject (subject) {\n return (typeof subject === 'object') && (subject !== null)\n}\n\nfunction toArray (sequence) {\n if (Array.isArray(sequence)) return sequence\n else if (isNothing(sequence)) return []\n\n return [sequence]\n}\n\nfunction extend (target, source) {\n if (source) {\n const sourceKeys = Object.keys(source)\n\n for (let index = 0, length = sourceKeys.length; index < length; index += 1) {\n const key = sourceKeys[index]\n target[key] = source[key]\n }\n }\n\n return target\n}\n\nfunction repeat (string, count) {\n let result = ''\n\n for (let cycle = 0; cycle < count; cycle += 1) {\n result += string\n }\n\n return result\n}\n\nfunction isNegativeZero (number) {\n return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number)\n}\n\nmodule.exports.isNothing = isNothing\nmodule.exports.isObject = isObject\nmodule.exports.toArray = toArray\nmodule.exports.repeat = repeat\nmodule.exports.isNegativeZero = isNegativeZero\nmodule.exports.extend = extend\n","// YAML error class. http://stackoverflow.com/questions/8458984\n//\n'use strict'\n\nfunction formatError (exception, compact) {\n let where = ''\n const message = exception.reason || '(unknown reason)'\n\n if (!exception.mark) return message\n\n if (exception.mark.name) {\n where += 'in \"' + exception.mark.name + '\" '\n }\n\n where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'\n\n if (!compact && exception.mark.snippet) {\n where += '\\n\\n' + exception.mark.snippet\n }\n\n return message + ' ' + where\n}\n\nfunction YAMLException (reason, mark) {\n // Super constructor\n Error.call(this)\n\n this.name = 'YAMLException'\n this.reason = reason\n this.mark = mark\n this.message = formatError(this, false)\n\n // Include stack trace in error object\n if (Error.captureStackTrace) {\n // Chrome and NodeJS\n Error.captureStackTrace(this, this.constructor)\n } else {\n // FF, IE 10+ and Safari 6+. Fallback for others\n this.stack = (new Error()).stack || ''\n }\n}\n\n// Inherit from Error\nYAMLException.prototype = Object.create(Error.prototype)\nYAMLException.prototype.constructor = YAMLException\n\nYAMLException.prototype.toString = function toString (compact) {\n return this.name + ': ' + formatError(this, compact)\n}\n\nmodule.exports = YAMLException\n","'use strict'\n\nconst common = require('./common')\n\n// get snippet for a single line, respecting maxLength\nfunction getLine (buffer, lineStart, lineEnd, position, maxLineLength) {\n let head = ''\n let tail = ''\n const maxHalfLength = Math.floor(maxLineLength / 2) - 1\n\n if (position - lineStart > maxHalfLength) {\n head = ' ... '\n lineStart = position - maxHalfLength + head.length\n }\n\n if (lineEnd - position > maxHalfLength) {\n tail = ' ...'\n lineEnd = position + maxHalfLength - tail.length\n }\n\n return {\n str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, '→') + tail,\n pos: position - lineStart + head.length // relative position\n }\n}\n\nfunction padStart (string, max) {\n return common.repeat(' ', max - string.length) + string\n}\n\nfunction makeSnippet (mark, options) {\n options = Object.create(options || null)\n\n if (!mark.buffer) return null\n\n if (!options.maxLength) options.maxLength = 79\n if (typeof options.indent !== 'number') options.indent = 1\n if (typeof options.linesBefore !== 'number') options.linesBefore = 3\n if (typeof options.linesAfter !== 'number') options.linesAfter = 2\n\n const re = /\\r?\\n|\\r|\\0/g\n const lineStarts = [0]\n const lineEnds = []\n let match\n let foundLineNo = -1\n\n while ((match = re.exec(mark.buffer))) {\n lineEnds.push(match.index)\n lineStarts.push(match.index + match[0].length)\n\n if (mark.position <= match.index && foundLineNo < 0) {\n foundLineNo = lineStarts.length - 2\n }\n }\n\n if (foundLineNo < 0) foundLineNo = lineStarts.length - 1\n\n let result = ''\n const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length\n const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3)\n\n for (let i = 1; i <= options.linesBefore; i++) {\n if (foundLineNo - i < 0) break\n const line = getLine(\n mark.buffer,\n lineStarts[foundLineNo - i],\n lineEnds[foundLineNo - i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n maxLineLength\n )\n result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n' + result\n }\n\n const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength)\n result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n'\n result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\\n'\n\n for (let i = 1; i <= options.linesAfter; i++) {\n if (foundLineNo + i >= lineEnds.length) break\n const line = getLine(\n mark.buffer,\n lineStarts[foundLineNo + i],\n lineEnds[foundLineNo + i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n maxLineLength\n )\n result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n'\n }\n\n return result.replace(/\\n$/, '')\n}\n\nmodule.exports = makeSnippet\n","'use strict'\n\nconst YAMLException = require('./exception')\n\nconst TYPE_CONSTRUCTOR_OPTIONS = [\n 'kind',\n 'multi',\n 'resolve',\n 'construct',\n 'instanceOf',\n 'predicate',\n 'represent',\n 'representName',\n 'defaultStyle',\n 'styleAliases'\n]\n\nconst YAML_NODE_KINDS = [\n 'scalar',\n 'sequence',\n 'mapping'\n]\n\nfunction compileStyleAliases (map) {\n const result = {}\n\n if (map !== null) {\n Object.keys(map).forEach(function (style) {\n map[style].forEach(function (alias) {\n result[String(alias)] = style\n })\n })\n }\n\n return result\n}\n\nfunction Type (tag, options) {\n options = options || {}\n\n Object.keys(options).forEach(function (name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new YAMLException('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.')\n }\n })\n\n // TODO: Add tag format check.\n this.options = options // keep original options in case user wants to extend this type later\n this.tag = tag\n this.kind = options['kind'] || null\n this.resolve = options['resolve'] || function () { return true }\n this.construct = options['construct'] || function (data) { return data }\n this.instanceOf = options['instanceOf'] || null\n this.predicate = options['predicate'] || null\n this.represent = options['represent'] || null\n this.representName = options['representName'] || null\n this.defaultStyle = options['defaultStyle'] || null\n this.multi = options['multi'] || false\n this.styleAliases = compileStyleAliases(options['styleAliases'] || null)\n\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new YAMLException('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.')\n }\n}\n\nmodule.exports = Type\n","'use strict'\n\nconst YAMLException = require('./exception')\nconst Type = require('./type')\n\nfunction compileList (schema, name) {\n const result = []\n\n schema[name].forEach(function (currentType) {\n let newIndex = result.length\n\n result.forEach(function (previousType, previousIndex) {\n if (previousType.tag === currentType.tag &&\n previousType.kind === currentType.kind &&\n previousType.multi === currentType.multi) {\n newIndex = previousIndex\n }\n })\n\n result[newIndex] = currentType\n })\n\n return result\n}\n\nfunction compileMap (/* lists... */) {\n const result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {},\n multi: {\n scalar: [],\n sequence: [],\n mapping: [],\n fallback: []\n }\n }\n function collectType (type) {\n if (type.multi) {\n result.multi[type.kind].push(type)\n result.multi['fallback'].push(type)\n } else {\n result[type.kind][type.tag] = result['fallback'][type.tag] = type\n }\n }\n\n for (let index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType)\n }\n return result\n}\n\nfunction Schema (definition) {\n return this.extend(definition)\n}\n\nSchema.prototype.extend = function extend (definition) {\n let implicit = []\n let explicit = []\n\n if (definition instanceof Type) {\n // Schema.extend(type)\n explicit.push(definition)\n } else if (Array.isArray(definition)) {\n // Schema.extend([ type1, type2, ... ])\n explicit = explicit.concat(definition)\n } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })\n if (definition.implicit) implicit = implicit.concat(definition.implicit)\n if (definition.explicit) explicit = explicit.concat(definition.explicit)\n } else {\n throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' +\n 'or a schema definition ({ implicit: [...], explicit: [...] })')\n }\n\n implicit.forEach(function (type) {\n if (!(type instanceof Type)) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.')\n }\n\n if (type.loadKind && type.loadKind !== 'scalar') {\n throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.')\n }\n\n if (type.multi) {\n throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.')\n }\n })\n\n explicit.forEach(function (type) {\n if (!(type instanceof Type)) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.')\n }\n })\n\n const result = Object.create(Schema.prototype)\n\n result.implicit = (this.implicit || []).concat(implicit)\n result.explicit = (this.explicit || []).concat(explicit)\n\n result.compiledImplicit = compileList(result, 'implicit')\n result.compiledExplicit = compileList(result, 'explicit')\n result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit)\n\n return result\n}\n\nmodule.exports = Schema\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:str', {\n kind: 'scalar',\n construct: function (data) { return data !== null ? data : '' }\n})\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:seq', {\n kind: 'sequence',\n construct: function (data) { return data !== null ? data : [] }\n})\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:map', {\n kind: 'mapping',\n construct: function (data) { return data !== null ? data : {} }\n})\n","// Standard YAML's Failsafe schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2802346\n\n'use strict'\n\nconst Schema = require('../schema')\n\nmodule.exports = new Schema({\n explicit: [\n require('../type/str'),\n require('../type/seq'),\n require('../type/map')\n ]\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlNull (data) {\n if (data === null) return true\n\n const max = data.length\n\n return (max === 1 && data === '~') ||\n (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'))\n}\n\nfunction constructYamlNull () {\n return null\n}\n\nfunction isNull (object) {\n return object === null\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:null', {\n kind: 'scalar',\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: function () { return '~' },\n lowercase: function () { return 'null' },\n uppercase: function () { return 'NULL' },\n camelcase: function () { return 'Null' },\n empty: function () { return '' }\n },\n defaultStyle: 'lowercase'\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlBoolean (data) {\n if (data === null) return false\n\n const max = data.length\n\n return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'))\n}\n\nfunction constructYamlBoolean (data) {\n return data === 'true' ||\n data === 'True' ||\n data === 'TRUE'\n}\n\nfunction isBoolean (object) {\n return Object.prototype.toString.call(object) === '[object Boolean]'\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:bool', {\n kind: 'scalar',\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: function (object) { return object ? 'true' : 'false' },\n uppercase: function (object) { return object ? 'TRUE' : 'FALSE' },\n camelcase: function (object) { return object ? 'True' : 'False' }\n },\n defaultStyle: 'lowercase'\n})\n","'use strict'\n\nconst common = require('../common')\nconst Type = require('../type')\n\nfunction isHexCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) ||\n ((c >= 0x41/* A */) && (c <= 0x46/* F */)) ||\n ((c >= 0x61/* a */) && (c <= 0x66/* f */))\n}\n\nfunction isOctCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x37/* 7 */))\n}\n\nfunction isDecCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */))\n}\n\nfunction resolveYamlInteger (data) {\n if (data === null) return false\n\n const max = data.length\n let index = 0\n let hasDigits = false\n\n if (!max) return false\n\n let ch = data[index]\n\n // sign\n if (ch === '-' || ch === '+') {\n ch = data[++index]\n }\n\n if (ch === '0') {\n // 0\n if (index + 1 === max) return true\n ch = data[++index]\n\n // base 2, base 8, base 16\n\n if (ch === 'b') {\n // base 2\n index++\n\n for (; index < max; index++) {\n ch = data[index]\n if (ch !== '0' && ch !== '1') return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n\n if (ch === 'x') {\n // base 16\n index++\n\n for (; index < max; index++) {\n if (!isHexCode(data.charCodeAt(index))) return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n\n if (ch === 'o') {\n // base 8\n index++\n\n for (; index < max; index++) {\n if (!isOctCode(data.charCodeAt(index))) return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n }\n\n // base 10 (except 0)\n\n for (; index < max; index++) {\n if (!isDecCode(data.charCodeAt(index))) {\n return false\n }\n hasDigits = true\n }\n\n if (!hasDigits) return false\n\n return Number.isFinite(parseYamlInteger(data))\n}\n\nfunction parseYamlInteger (data) {\n let value = data\n let sign = 1\n\n let ch = value[0]\n\n if (ch === '-' || ch === '+') {\n if (ch === '-') sign = -1\n value = value.slice(1)\n ch = value[0]\n }\n\n if (value === '0') return 0\n\n if (ch === '0') {\n if (value[1] === 'b') return sign * parseInt(value.slice(2), 2)\n if (value[1] === 'x') return sign * parseInt(value.slice(2), 16)\n if (value[1] === 'o') return sign * parseInt(value.slice(2), 8)\n }\n\n return sign * parseInt(value, 10)\n}\n\nfunction constructYamlInteger (data) {\n return parseYamlInteger(data)\n}\n\nfunction isInteger (object) {\n return (Object.prototype.toString.call(object)) === '[object Number]' &&\n (object % 1 === 0 && !common.isNegativeZero(object))\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:int', {\n kind: 'scalar',\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1) },\n octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1) },\n decimal: function (obj) { return obj.toString(10) },\n hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1) }\n },\n defaultStyle: 'decimal',\n styleAliases: {\n binary: [2, 'bin'],\n octal: [8, 'oct'],\n decimal: [10, 'dec'],\n hexadecimal: [16, 'hex']\n }\n})\n","'use strict'\n\nconst common = require('../common')\nconst Type = require('../type')\n\nconst YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n '^(?:[-+]?(?:[0-9]+)(?:\\\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?' +\n // .2e4, .2\n // special case, seems not from spec\n '|\\\\.[0-9]+(?:[eE][-+]?[0-9]+)?' +\n // .inf\n '|[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$')\n\nconst YAML_FLOAT_SPECIAL_PATTERN = new RegExp(\n '^(?:' +\n // .inf\n '[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$')\n\nfunction resolveYamlFloat (data) {\n if (data === null) return false\n\n if (!YAML_FLOAT_PATTERN.test(data)) {\n return false\n }\n\n if (Number.isFinite(parseFloat(data, 10))) {\n return true\n }\n\n return YAML_FLOAT_SPECIAL_PATTERN.test(data)\n}\n\nfunction constructYamlFloat (data) {\n let value = data.toLowerCase()\n const sign = value[0] === '-' ? -1 : 1\n\n if ('+-'.indexOf(value[0]) >= 0) {\n value = value.slice(1)\n }\n\n if (value === '.inf') {\n return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY\n } else if (value === '.nan') {\n return NaN\n }\n return sign * parseFloat(value, 10)\n}\n\nconst SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/\n\nfunction representYamlFloat (object, style) {\n if (isNaN(object)) {\n switch (style) {\n case 'lowercase': return '.nan'\n case 'uppercase': return '.NAN'\n case 'camelcase': return '.NaN'\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '.inf'\n case 'uppercase': return '.INF'\n case 'camelcase': return '.Inf'\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '-.inf'\n case 'uppercase': return '-.INF'\n case 'camelcase': return '-.Inf'\n }\n } else if (common.isNegativeZero(object)) {\n return '-0.0'\n }\n\n const res = object.toString(10)\n\n // JS stringifier can build scientific format without dots: 5e-100,\n // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res\n}\n\nfunction isFloat (object) {\n return (Object.prototype.toString.call(object) === '[object Number]') &&\n (object % 1 !== 0 || common.isNegativeZero(object))\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:float', {\n kind: 'scalar',\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: 'lowercase'\n})\n","// Standard YAML's JSON schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2803231\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, this schema is not such strict as defined in the YAML specification.\n// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.\n\n'use strict'\n\nmodule.exports = require('./failsafe').extend({\n implicit: [\n require('../type/null'),\n require('../type/bool'),\n require('../type/int'),\n require('../type/float')\n ]\n})\n","// Standard YAML's Core schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2804923\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, Core schema has no distinctions from JSON schema is JS-YAML.\n\n'use strict'\n\nmodule.exports = require('./json')\n","'use strict'\n\nconst Type = require('../type')\n\nconst YAML_DATE_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9])' + // [2] month\n '-([0-9][0-9])$') // [3] day\n\nconst YAML_TIMESTAMP_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9]?)' + // [2] month\n '-([0-9][0-9]?)' + // [3] day\n '(?:[Tt]|[ \\\\t]+)' + // ...\n '([0-9][0-9]?)' + // [4] hour\n ':([0-9][0-9])' + // [5] minute\n ':([0-9][0-9])' + // [6] second\n '(?:\\\\.([0-9]*))?' + // [7] fraction\n '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tzHour\n '(?::([0-9][0-9]))?))?$') // [11] tzMinute\n\nfunction resolveYamlTimestamp (data) {\n if (data === null) return false\n if (YAML_DATE_REGEXP.exec(data) !== null) return true\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true\n return false\n}\n\nfunction constructYamlTimestamp (data) {\n let fraction = 0\n let delta = null\n\n let match = YAML_DATE_REGEXP.exec(data)\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data)\n\n if (match === null) throw new Error('Date resolve error')\n\n // match: [1] year [2] month [3] day\n\n const year = +(match[1])\n const month = +(match[2]) - 1 // JS month starts with 0\n const day = +(match[3])\n\n if (!match[4]) { // no hour\n return new Date(Date.UTC(year, month, day))\n }\n\n // match: [4] hour [5] minute [6] second [7] fraction\n\n const hour = +(match[4])\n const minute = +(match[5])\n const second = +(match[6])\n\n if (match[7]) {\n fraction = match[7].slice(0, 3)\n while (fraction.length < 3) { // milli-seconds\n fraction += '0'\n }\n fraction = +fraction\n }\n\n // match: [8] tz [9] tz_sign [10] tzHour [11] tzMinute\n\n if (match[9]) {\n const tzHour = +(match[10])\n const tzMinute = +(match[11] || 0)\n delta = (tzHour * 60 + tzMinute) * 60000 // delta in mili-seconds\n if (match[9] === '-') delta = -delta\n }\n\n const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction))\n\n if (delta) date.setTime(date.getTime() - delta)\n\n return date\n}\n\nfunction representYamlTimestamp (object /*, style */) {\n return object.toISOString()\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:timestamp', {\n kind: 'scalar',\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlMerge (data) {\n return data === '<<' || data === null\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:merge', {\n kind: 'scalar',\n resolve: resolveYamlMerge\n})\n","'use strict'\n\nconst Type = require('../type')\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nconst BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r'\n\nfunction resolveYamlBinary (data) {\n if (data === null) return false\n\n let bitlen = 0\n const max = data.length\n const map = BASE64_MAP\n\n // Convert one by one.\n for (let idx = 0; idx < max; idx++) {\n const code = map.indexOf(data.charAt(idx))\n\n // Skip CR/LF\n if (code > 64) continue\n\n // Fail on illegal characters\n if (code < 0) return false\n\n bitlen += 6\n }\n\n // If there are any bits left, source was corrupted\n return (bitlen % 8) === 0\n}\n\nfunction constructYamlBinary (data) {\n const input = data.replace(/[\\r\\n=]/g, '') // remove CR/LF & padding to simplify scan\n const max = input.length\n const map = BASE64_MAP\n let bits = 0\n const result = []\n\n // Collect by 6*4 bits (3 bytes)\n\n for (let idx = 0; idx < max; idx++) {\n if ((idx % 4 === 0) && idx) {\n result.push((bits >> 16) & 0xFF)\n result.push((bits >> 8) & 0xFF)\n result.push(bits & 0xFF)\n }\n\n bits = (bits << 6) | map.indexOf(input.charAt(idx))\n }\n\n // Dump tail\n\n const tailbits = (max % 4) * 6\n\n if (tailbits === 0) {\n result.push((bits >> 16) & 0xFF)\n result.push((bits >> 8) & 0xFF)\n result.push(bits & 0xFF)\n } else if (tailbits === 18) {\n result.push((bits >> 10) & 0xFF)\n result.push((bits >> 2) & 0xFF)\n } else if (tailbits === 12) {\n result.push((bits >> 4) & 0xFF)\n }\n\n return new Uint8Array(result)\n}\n\nfunction representYamlBinary (object /*, style */) {\n let result = ''\n let bits = 0\n const max = object.length\n const map = BASE64_MAP\n\n // Convert every three bytes to 4 ASCII characters.\n\n for (let idx = 0; idx < max; idx++) {\n if ((idx % 3 === 0) && idx) {\n result += map[(bits >> 18) & 0x3F]\n result += map[(bits >> 12) & 0x3F]\n result += map[(bits >> 6) & 0x3F]\n result += map[bits & 0x3F]\n }\n\n bits = (bits << 8) + object[idx]\n }\n\n // Dump tail\n\n const tail = max % 3\n\n if (tail === 0) {\n result += map[(bits >> 18) & 0x3F]\n result += map[(bits >> 12) & 0x3F]\n result += map[(bits >> 6) & 0x3F]\n result += map[bits & 0x3F]\n } else if (tail === 2) {\n result += map[(bits >> 10) & 0x3F]\n result += map[(bits >> 4) & 0x3F]\n result += map[(bits << 2) & 0x3F]\n result += map[64]\n } else if (tail === 1) {\n result += map[(bits >> 2) & 0x3F]\n result += map[(bits << 4) & 0x3F]\n result += map[64]\n result += map[64]\n }\n\n return result\n}\n\nfunction isBinary (obj) {\n return Object.prototype.toString.call(obj) === '[object Uint8Array]'\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:binary', {\n kind: 'scalar',\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\nconst _toString = Object.prototype.toString\n\nfunction resolveYamlOmap (data) {\n if (data === null) return true\n\n const objectKeys = []\n const object = data\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n let pairHasKey = false\n\n if (_toString.call(pair) !== '[object Object]') return false\n\n let pairKey\n for (pairKey in pair) {\n if (_hasOwnProperty.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true\n else return false\n }\n }\n\n if (!pairHasKey) return false\n\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey)\n else return false\n }\n\n return true\n}\n\nfunction constructYamlOmap (data) {\n return data !== null ? data : []\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:omap', {\n kind: 'sequence',\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _toString = Object.prototype.toString\n\nfunction resolveYamlPairs (data) {\n if (data === null) return true\n\n const object = data\n\n const result = new Array(object.length)\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n\n if (_toString.call(pair) !== '[object Object]') return false\n\n const keys = Object.keys(pair)\n\n if (keys.length !== 1) return false\n\n result[index] = [keys[0], pair[keys[0]]]\n }\n\n return true\n}\n\nfunction constructYamlPairs (data) {\n if (data === null) return []\n\n const object = data\n const result = new Array(object.length)\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n\n const keys = Object.keys(pair)\n\n result[index] = [keys[0], pair[keys[0]]]\n }\n\n return result\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:pairs', {\n kind: 'sequence',\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nfunction resolveYamlSet (data) {\n if (data === null) return true\n\n const object = data\n\n for (const key in object) {\n if (_hasOwnProperty.call(object, key)) {\n if (object[key] !== null) return false\n }\n }\n\n return true\n}\n\nfunction constructYamlSet (data) {\n return data !== null ? data : {}\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:set', {\n kind: 'mapping',\n resolve: resolveYamlSet,\n construct: constructYamlSet\n})\n","// JS-YAML's default schema for `safeLoad` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on standard YAML's Core schema and includes most of\n// extra types described at YAML tag repository. (http://yaml.org/type/)\n\n'use strict'\n\nmodule.exports = require('./core').extend({\n implicit: [\n require('../type/timestamp'),\n require('../type/merge')\n ],\n explicit: [\n require('../type/binary'),\n require('../type/omap'),\n require('../type/pairs'),\n require('../type/set')\n ]\n})\n","'use strict'\n\nconst common = require('./common')\nconst YAMLException = require('./exception')\nconst makeSnippet = require('./snippet')\nconst DEFAULT_SCHEMA = require('./schema/default')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nconst CONTEXT_FLOW_IN = 1\nconst CONTEXT_FLOW_OUT = 2\nconst CONTEXT_BLOCK_IN = 3\nconst CONTEXT_BLOCK_OUT = 4\n\nconst CHOMPING_CLIP = 1\nconst CHOMPING_STRIP = 2\nconst CHOMPING_KEEP = 3\n\n// eslint-disable-next-line no-control-regex\nconst PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/\nconst PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_FLOW_INDICATORS = /[,\\[\\]{}]/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_TAG_URI = /^(?:!|[^,\\[\\]{}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;/?:@&=+$,_.!~*'()\\[\\]])*$/i\n\nfunction _class (obj) { return Object.prototype.toString.call(obj) }\n\nfunction isEol (c) {\n return (c === 0x0A/* LF */) || (c === 0x0D/* CR */)\n}\n\nfunction isWhiteSpace (c) {\n return (c === 0x09/* Tab */) || (c === 0x20/* Space */)\n}\n\nfunction isWsOrEol (c) {\n return (c === 0x09/* Tab */) ||\n (c === 0x20/* Space */) ||\n (c === 0x0A/* LF */) ||\n (c === 0x0D/* CR */)\n}\n\nfunction isFlowIndicator (c) {\n return c === 0x2C/* , */ ||\n c === 0x5B/* [ */ ||\n c === 0x5D/* ] */ ||\n c === 0x7B/* { */ ||\n c === 0x7D/* } */\n}\n\nfunction fromHexCode (c) {\n if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) {\n return c - 0x30\n }\n\n const lc = c | 0x20\n\n if ((lc >= 0x61/* a */) && (lc <= 0x66/* f */)) {\n return lc - 0x61 + 10\n }\n\n return -1\n}\n\nfunction escapedHexLen (c) {\n if (c === 0x78/* x */) { return 2 }\n if (c === 0x75/* u */) { return 4 }\n if (c === 0x55/* U */) { return 8 }\n return 0\n}\n\nfunction fromDecimalCode (c) {\n if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) {\n return c - 0x30\n }\n\n return -1\n}\n\nfunction simpleEscapeSequence (c) {\n switch (c) {\n case 0x30/* 0 */: return '\\x00'\n case 0x61/* a */: return '\\x07'\n case 0x62/* b */: return '\\x08'\n case 0x74/* t */: return '\\x09'\n case 0x09/* Tab */: return '\\x09'\n case 0x6E/* n */: return '\\x0A'\n case 0x76/* v */: return '\\x0B'\n case 0x66/* f */: return '\\x0C'\n case 0x72/* r */: return '\\x0D'\n case 0x65/* e */: return '\\x1B'\n case 0x20/* Space */: return ' '\n case 0x22/* \" */: return '\\x22'\n case 0x2F/* / */: return '/'\n case 0x5C/* \\ */: return '\\x5C'\n case 0x4E/* N */: return '\\x85'\n case 0x5F/* _ */: return '\\xA0'\n case 0x4C/* L */: return '\\u2028'\n case 0x50/* P */: return '\\u2029'\n default: return ''\n }\n}\n\nfunction charFromCodepoint (c) {\n if (c <= 0xFFFF) {\n return String.fromCharCode(c)\n }\n // Encode UTF-16 surrogate pair\n // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n return String.fromCharCode(\n ((c - 0x010000) >> 10) + 0xD800,\n ((c - 0x010000) & 0x03FF) + 0xDC00\n )\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty (object, key, value) {\n // used for this specific key only because Object.defineProperty is slow\n if (key === '__proto__') {\n Object.defineProperty(object, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: value\n })\n } else {\n object[key] = value\n }\n}\n\nconst simpleEscapeCheck = new Array(256) // integer, for fast access\nconst simpleEscapeMap = new Array(256)\nfor (let i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0\n simpleEscapeMap[i] = simpleEscapeSequence(i)\n}\n\nfunction State (input, options) {\n this.input = input\n\n this.filename = options['filename'] || null\n this.schema = options['schema'] || DEFAULT_SCHEMA\n this.onWarning = options['onWarning'] || null\n // (Hidden) Remove? makes the loader to expect YAML 1.1 documents\n // if such documents have no explicit %YAML directive\n this.legacy = options['legacy'] || false\n\n this.json = options['json'] || false\n this.listener = options['listener'] || null\n this.maxDepth = typeof options['maxDepth'] === 'number' ? options['maxDepth'] : 100\n this.maxMergeSeqLength = typeof options['maxMergeSeqLength'] === 'number' ? options['maxMergeSeqLength'] : 20\n\n this.implicitTypes = this.schema.compiledImplicit\n this.typeMap = this.schema.compiledTypeMap\n\n this.length = input.length\n this.position = 0\n this.line = 0\n this.lineStart = 0\n this.lineIndent = 0\n this.depth = 0\n\n // position of first leading tab in the current line,\n // used to make sure there are no tabs in the indentation\n this.firstTabInLine = -1\n\n this.documents = []\n this.anchorMapTransactions = []\n\n /*\n this.version;\n this.checkLineBreaks;\n this.tagMap;\n this.anchorMap;\n this.tag;\n this.anchor;\n this.kind;\n this.result; */\n}\n\nfunction generateError (state, message) {\n const mark = {\n name: state.filename,\n buffer: state.input.slice(0, -1), // omit trailing \\0\n position: state.position,\n line: state.line,\n column: state.position - state.lineStart\n }\n\n mark.snippet = makeSnippet(mark)\n\n return new YAMLException(message, mark)\n}\n\nfunction throwError (state, message) {\n throw generateError(state, message)\n}\n\nfunction throwWarning (state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message))\n }\n}\n\nfunction storeAnchor (state, name, value) {\n const transactions = state.anchorMapTransactions\n\n if (transactions.length !== 0) {\n const transaction = transactions[transactions.length - 1]\n\n if (!_hasOwnProperty.call(transaction, name)) {\n transaction[name] = {\n existed: _hasOwnProperty.call(state.anchorMap, name),\n value: state.anchorMap[name]\n }\n }\n }\n\n state.anchorMap[name] = value\n}\n\nfunction beginAnchorTransaction (state) {\n state.anchorMapTransactions.push(Object.create(null))\n}\n\nfunction commitAnchorTransaction (state) {\n const transaction = state.anchorMapTransactions.pop()\n const transactions = state.anchorMapTransactions\n\n if (transactions.length === 0) return\n\n const parent = transactions[transactions.length - 1]\n const names = Object.keys(transaction)\n\n for (let index = 0, length = names.length; index < length; index += 1) {\n const name = names[index]\n\n if (!_hasOwnProperty.call(parent, name)) {\n parent[name] = transaction[name]\n }\n }\n}\n\nfunction rollbackAnchorTransaction (state) {\n const transaction = state.anchorMapTransactions.pop()\n const names = Object.keys(transaction)\n\n for (let index = names.length - 1; index >= 0; index -= 1) {\n const entry = transaction[names[index]]\n\n if (entry.existed) {\n state.anchorMap[names[index]] = entry.value\n } else {\n delete state.anchorMap[names[index]]\n }\n }\n}\n\nfunction snapshotState (state) {\n return {\n position: state.position,\n line: state.line,\n lineStart: state.lineStart,\n lineIndent: state.lineIndent,\n firstTabInLine: state.firstTabInLine,\n tag: state.tag,\n anchor: state.anchor,\n kind: state.kind,\n result: state.result\n }\n}\n\nfunction restoreState (state, snapshot) {\n state.position = snapshot.position\n state.line = snapshot.line\n state.lineStart = snapshot.lineStart\n state.lineIndent = snapshot.lineIndent\n state.firstTabInLine = snapshot.firstTabInLine\n state.tag = snapshot.tag\n state.anchor = snapshot.anchor\n state.kind = snapshot.kind\n state.result = snapshot.result\n}\n\nconst directiveHandlers = {\n\n YAML: function handleYamlDirective (state, name, args) {\n if (state.version !== null) {\n throwError(state, 'duplication of %YAML directive')\n }\n\n if (args.length !== 1) {\n throwError(state, 'YAML directive accepts exactly one argument')\n }\n\n const match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0])\n\n if (match === null) {\n throwError(state, 'ill-formed argument of the YAML directive')\n }\n\n const major = parseInt(match[1], 10)\n const minor = parseInt(match[2], 10)\n\n if (major !== 1) {\n throwError(state, 'unacceptable YAML version of the document')\n }\n\n state.version = args[0]\n state.checkLineBreaks = (minor < 2)\n\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, 'unsupported YAML version of the document')\n }\n },\n\n TAG: function handleTagDirective (state, name, args) {\n let prefix\n\n if (args.length !== 2) {\n throwError(state, 'TAG directive accepts exactly two arguments')\n }\n\n const handle = args[0]\n prefix = args[1]\n\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, 'ill-formed tag handle (first argument) of the TAG directive')\n }\n\n if (_hasOwnProperty.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle')\n }\n\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive')\n }\n\n try {\n prefix = decodeURIComponent(prefix)\n } catch (err) {\n throwError(state, 'tag prefix is malformed: ' + prefix)\n }\n\n state.tagMap[handle] = prefix\n }\n}\n\nfunction captureSegment (state, start, end, checkJson) {\n if (start < end) {\n const _result = state.input.slice(start, end)\n\n if (checkJson) {\n for (let _position = 0, _length = _result.length; _position < _length; _position += 1) {\n const _character = _result.charCodeAt(_position)\n if (!(_character === 0x09 ||\n (_character >= 0x20 && _character <= 0x10FFFF))) {\n throwError(state, 'expected valid JSON character')\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, 'the stream contains non-printable characters')\n }\n\n state.result += _result\n }\n}\n\nfunction mergeMappings (state, destination, source, overridableKeys) {\n if (!common.isObject(source)) {\n throwError(state, 'cannot merge mappings; the provided source object is unacceptable')\n }\n\n const sourceKeys = Object.keys(source)\n\n for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n const key = sourceKeys[index]\n\n if (!_hasOwnProperty.call(destination, key)) {\n setProperty(destination, key, source[key])\n overridableKeys[key] = true\n }\n }\n}\n\nfunction storeMappingPair (state, _result, overridableKeys, keyTag, keyNode, valueNode,\n startLine, startLineStart, startPos) {\n // The output is a plain object here, so keys can only be strings.\n // We need to convert keyNode to a string, but doing so can hang the process\n // (deeply nested arrays that explode exponentially using aliases).\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode)\n\n for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, 'nested arrays are not supported inside keys')\n }\n\n if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n keyNode[index] = '[object Object]'\n }\n }\n }\n\n // Avoid code execution in load() via toString property\n // (still use its own toString for arrays, timestamps,\n // and whatever user schema extensions happen to have @@toStringTag)\n if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n keyNode = '[object Object]'\n }\n\n keyNode = String(keyNode)\n\n if (_result === null) {\n _result = {}\n }\n\n if (keyTag === 'tag:yaml.org,2002:merge') {\n if (Array.isArray(valueNode)) {\n if (valueNode.length > state.maxMergeSeqLength) {\n throwError(state, 'merge sequence length exceeded maxMergeSeqLength (' + state.maxMergeSeqLength + ')')\n }\n const seen = new Set()\n for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n const src = valueNode[index]\n // Existing keys are not overridden on merge, so dedupe sources to\n // avoid redundant work on repeated aliases.\n if (seen.has(src)) continue\n seen.add(src)\n mergeMappings(state, _result, src, overridableKeys)\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys)\n }\n } else {\n if (!state.json &&\n !_hasOwnProperty.call(overridableKeys, keyNode) &&\n _hasOwnProperty.call(_result, keyNode)) {\n state.line = startLine || state.line\n state.lineStart = startLineStart || state.lineStart\n state.position = startPos || state.position\n throwError(state, 'duplicated mapping key')\n }\n\n setProperty(_result, keyNode, valueNode)\n delete overridableKeys[keyNode]\n }\n\n return _result\n}\n\nfunction readLineBreak (state) {\n const ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x0A/* LF */) {\n state.position++\n } else if (ch === 0x0D/* CR */) {\n state.position++\n if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n state.position++\n }\n } else {\n throwError(state, 'a line break is expected')\n }\n\n state.line += 1\n state.lineStart = state.position\n state.firstTabInLine = -1\n}\n\nfunction skipSeparationSpace (state, allowComments, checkIndent) {\n let lineBreaks = 0\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n while (isWhiteSpace(ch)) {\n if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {\n state.firstTabInLine = state.position\n }\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (allowComments && ch === 0x23/* # */) {\n do {\n ch = state.input.charCodeAt(++state.position)\n } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0)\n }\n\n if (isEol(ch)) {\n readLineBreak(state)\n\n ch = state.input.charCodeAt(state.position)\n lineBreaks++\n state.lineIndent = 0\n\n while (ch === 0x20/* Space */) {\n state.lineIndent++\n ch = state.input.charCodeAt(++state.position)\n }\n } else {\n break\n }\n }\n\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, 'deficient indentation')\n }\n\n return lineBreaks\n}\n\nfunction testDocumentSeparator (state) {\n let _position = state.position\n let ch = state.input.charCodeAt(_position)\n\n // Condition state.position === state.lineStart is tested\n // in parent on each call, for efficiency. No needs to test here again.\n if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n ch === state.input.charCodeAt(_position + 1) &&\n ch === state.input.charCodeAt(_position + 2)) {\n _position += 3\n\n ch = state.input.charCodeAt(_position)\n\n if (ch === 0 || isWsOrEol(ch)) {\n return true\n }\n }\n\n return false\n}\n\nfunction writeFoldedLines (state, count) {\n if (count === 1) {\n state.result += ' '\n } else if (count > 1) {\n state.result += common.repeat('\\n', count - 1)\n }\n}\n\nfunction readPlainScalar (state, nodeIndent, withinFlowCollection) {\n let captureStart\n let captureEnd\n let hasPendingContent\n let _line\n let _lineStart\n let _lineIndent\n const _kind = state.kind\n const _result = state.result\n\n let ch = state.input.charCodeAt(state.position)\n\n if (isWsOrEol(ch) ||\n isFlowIndicator(ch) ||\n ch === 0x23/* # */ ||\n ch === 0x26/* & */ ||\n ch === 0x2A/* * */ ||\n ch === 0x21/* ! */ ||\n ch === 0x7C/* | */ ||\n ch === 0x3E/* > */ ||\n ch === 0x27/* ' */ ||\n ch === 0x22/* \" */ ||\n ch === 0x25/* % */ ||\n ch === 0x40/* @ */ ||\n ch === 0x60/* ` */) {\n return false\n }\n\n if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following) ||\n (withinFlowCollection && isFlowIndicator(following))) {\n return false\n }\n }\n\n state.kind = 'scalar'\n state.result = ''\n captureStart = captureEnd = state.position\n hasPendingContent = false\n\n while (ch !== 0) {\n if (ch === 0x3A/* : */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following) ||\n (withinFlowCollection && isFlowIndicator(following))) {\n break\n }\n } else if (ch === 0x23/* # */) {\n const preceding = state.input.charCodeAt(state.position - 1)\n\n if (isWsOrEol(preceding)) {\n break\n }\n } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n (withinFlowCollection && isFlowIndicator(ch))) {\n break\n } else if (isEol(ch)) {\n _line = state.line\n _lineStart = state.lineStart\n _lineIndent = state.lineIndent\n skipSeparationSpace(state, false, -1)\n\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true\n ch = state.input.charCodeAt(state.position)\n continue\n } else {\n state.position = captureEnd\n state.line = _line\n state.lineStart = _lineStart\n state.lineIndent = _lineIndent\n break\n }\n }\n\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false)\n writeFoldedLines(state, state.line - _line)\n captureStart = captureEnd = state.position\n hasPendingContent = false\n }\n\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position + 1\n }\n\n ch = state.input.charCodeAt(++state.position)\n }\n\n captureSegment(state, captureStart, captureEnd, false)\n\n if (state.result) {\n return true\n }\n\n state.kind = _kind\n state.result = _result\n return false\n}\n\nfunction readSingleQuotedScalar (state, nodeIndent) {\n let captureStart\n let captureEnd\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x27/* ' */) {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n state.position++\n captureStart = captureEnd = state.position\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x27/* ' */) {\n captureSegment(state, captureStart, state.position, true)\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x27/* ' */) {\n captureStart = state.position\n state.position++\n captureEnd = state.position\n } else {\n return true\n }\n } else if (isEol(ch)) {\n captureSegment(state, captureStart, captureEnd, true)\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent))\n captureStart = captureEnd = state.position\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a single quoted scalar')\n } else {\n state.position++\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position\n }\n }\n }\n\n throwError(state, 'unexpected end of the stream within a single quoted scalar')\n}\n\nfunction readDoubleQuotedScalar (state, nodeIndent) {\n let captureStart\n let captureEnd\n let tmp\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x22/* \" */) {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n state.position++\n captureStart = captureEnd = state.position\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x22/* \" */) {\n captureSegment(state, captureStart, state.position, true)\n state.position++\n return true\n } else if (ch === 0x5C/* \\ */) {\n captureSegment(state, captureStart, state.position, true)\n ch = state.input.charCodeAt(++state.position)\n\n if (isEol(ch)) {\n skipSeparationSpace(state, false, nodeIndent)\n\n // TODO: rework to inline fn with no type cast?\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch]\n state.position++\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n let hexLength = tmp\n let hexResult = 0\n\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position)\n\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp\n } else {\n throwError(state, 'expected hexadecimal character')\n }\n }\n\n state.result += charFromCodepoint(hexResult)\n\n state.position++\n } else {\n throwError(state, 'unknown escape sequence')\n }\n\n captureStart = captureEnd = state.position\n } else if (isEol(ch)) {\n captureSegment(state, captureStart, captureEnd, true)\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent))\n captureStart = captureEnd = state.position\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a double quoted scalar')\n } else {\n state.position++\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position\n }\n }\n }\n\n throwError(state, 'unexpected end of the stream within a double quoted scalar')\n}\n\nfunction readFlowCollection (state, nodeIndent) {\n let readNext = true\n let _line\n let _lineStart\n let _pos\n const _tag = state.tag\n let _result\n const _anchor = state.anchor\n let terminator\n let isPair\n let isExplicitPair\n let isMapping\n const overridableKeys = Object.create(null)\n let keyNode\n let keyTag\n let valueNode\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x5B/* [ */) {\n terminator = 0x5D/* ] */\n isMapping = false\n _result = []\n } else if (ch === 0x7B/* { */) {\n terminator = 0x7D/* } */\n isMapping = true\n _result = {}\n } else {\n return false\n }\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n ch = state.input.charCodeAt(++state.position)\n\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if (ch === terminator) {\n state.position++\n state.tag = _tag\n state.anchor = _anchor\n state.kind = isMapping ? 'mapping' : 'sequence'\n state.result = _result\n return true\n } else if (!readNext) {\n throwError(state, 'missed comma between flow collection entries')\n } else if (ch === 0x2C/* , */) {\n // \"flow collection entries can never be completely empty\", as per YAML 1.2, section 7.4\n throwError(state, \"expected the node content, but found ','\")\n }\n\n keyTag = keyNode = valueNode = null\n isPair = isExplicitPair = false\n\n if (ch === 0x3F/* ? */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following)) {\n isPair = isExplicitPair = true\n state.position++\n skipSeparationSpace(state, true, nodeIndent)\n }\n }\n\n _line = state.line // Save the current line.\n _lineStart = state.lineStart\n _pos = state.position\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)\n keyTag = state.tag\n keyNode = state.result\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n isPair = true\n ch = state.input.charCodeAt(++state.position)\n skipSeparationSpace(state, true, nodeIndent)\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)\n valueNode = state.result\n }\n\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos))\n } else {\n _result.push(keyNode)\n }\n\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x2C/* , */) {\n readNext = true\n ch = state.input.charCodeAt(++state.position)\n } else {\n readNext = false\n }\n }\n\n throwError(state, 'unexpected end of the stream within a flow collection')\n}\n\nfunction readBlockScalar (state, nodeIndent) {\n let folding\n let chomping = CHOMPING_CLIP\n let didReadContent = false\n let detectedIndent = false\n let textIndent = nodeIndent\n let emptyLines = 0\n let atMoreIndented = false\n let tmp\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x7C/* | */) {\n folding = false\n } else if (ch === 0x3E/* > */) {\n folding = true\n } else {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n if (CHOMPING_CLIP === chomping) {\n chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP\n } else {\n throwError(state, 'repeat of a chomping mode identifier')\n }\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one')\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1\n detectedIndent = true\n } else {\n throwError(state, 'repeat of an indentation width identifier')\n }\n } else {\n break\n }\n }\n\n if (isWhiteSpace(ch)) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (isWhiteSpace(ch))\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (!isEol(ch) && (ch !== 0))\n }\n }\n\n while (ch !== 0) {\n readLineBreak(state)\n state.lineIndent = 0\n\n ch = state.input.charCodeAt(state.position)\n\n // eslint-disable-next-line no-unmodified-loop-condition\n while ((!detectedIndent || state.lineIndent < textIndent) &&\n (ch === 0x20/* Space */)) {\n state.lineIndent++\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent\n }\n\n if (isEol(ch)) {\n emptyLines++\n continue\n }\n\n if (!detectedIndent && textIndent === 0) {\n throwError(state, 'missing indentation for block scalar')\n }\n\n // End of the scalar.\n if (state.lineIndent < textIndent) {\n // Perform the chomping.\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) { // i.e. only if the scalar is not empty.\n state.result += '\\n'\n }\n }\n\n // Break this `while` cycle and go to the funciton's epilogue.\n break\n }\n\n // Folded style: use fancy rules to handle line breaks.\n if (folding) {\n // Lines starting with white space characters (more-indented lines) are not folded.\n if (isWhiteSpace(ch)) {\n atMoreIndented = true\n // except for the first content line (cf. Example 8.1)\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n\n // End of more-indented block.\n } else if (atMoreIndented) {\n atMoreIndented = false\n state.result += common.repeat('\\n', emptyLines + 1)\n\n // Just one line break - perceive as the same line.\n } else if (emptyLines === 0) {\n if (didReadContent) { // i.e. only if we have already read some scalar content.\n state.result += ' '\n }\n\n // Several line breaks - perceive as different lines.\n } else {\n state.result += common.repeat('\\n', emptyLines)\n }\n\n // Literal style: just add exact number of line breaks between content lines.\n } else {\n // Keep all line breaks except the header line break.\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n }\n\n didReadContent = true\n detectedIndent = true\n emptyLines = 0\n const captureStart = state.position\n\n while (!isEol(ch) && (ch !== 0)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n captureSegment(state, captureStart, state.position, false)\n }\n\n return true\n}\n\nfunction readBlockSequence (state, nodeIndent) {\n const _tag = state.tag\n const _anchor = state.anchor\n const _result = []\n let detected = false\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n if (state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine\n throwError(state, 'tab characters must not be used in indentation')\n }\n\n if (ch !== 0x2D/* - */) {\n break\n }\n\n const following = state.input.charCodeAt(state.position + 1)\n\n if (!isWsOrEol(following)) {\n break\n }\n\n detected = true\n state.position++\n\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null)\n ch = state.input.charCodeAt(state.position)\n continue\n }\n }\n\n const _line = state.line\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true)\n _result.push(state.result)\n skipSeparationSpace(state, true, -1)\n\n ch = state.input.charCodeAt(state.position)\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a sequence entry')\n } else if (state.lineIndent < nodeIndent) {\n break\n }\n }\n\n if (detected) {\n state.tag = _tag\n state.anchor = _anchor\n state.kind = 'sequence'\n state.result = _result\n return true\n }\n return false\n}\n\nfunction readBlockMapping (state, nodeIndent, flowIndent) {\n let allowCompact\n let _keyLine\n let _keyLineStart\n let _keyPos\n const _tag = state.tag\n const _anchor = state.anchor\n const _result = {}\n const overridableKeys = Object.create(null)\n let keyTag = null\n let keyNode = null\n let valueNode = null\n let atExplicitKey = false\n let detected = false\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n if (!atExplicitKey && state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine\n throwError(state, 'tab characters must not be used in indentation')\n }\n\n const following = state.input.charCodeAt(state.position + 1)\n const _line = state.line // Save the current line.\n\n //\n // Explicit notation case. There are two separate blocks:\n // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n //\n if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && isWsOrEol(following)) {\n if (ch === 0x3F/* ? */) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n detected = true\n atExplicitKey = true\n allowCompact = true\n } else if (atExplicitKey) {\n // i.e. 0x3A/* : */ === character after the explicit key.\n atExplicitKey = false\n allowCompact = true\n } else {\n throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line')\n }\n\n state.position += 1\n ch = following\n\n //\n // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n //\n } else {\n _keyLine = state.line\n _keyLineStart = state.lineStart\n _keyPos = state.position\n\n if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n // Neither implicit nor explicit notation.\n // Reading is done. Go to the epilogue.\n break\n }\n\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position)\n\n while (isWhiteSpace(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (ch === 0x3A/* : */) {\n ch = state.input.charCodeAt(++state.position)\n\n if (!isWsOrEol(ch)) {\n throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping')\n }\n\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n detected = true\n atExplicitKey = false\n allowCompact = false\n keyTag = state.tag\n keyNode = state.result\n } else if (detected) {\n throwError(state, 'can not read an implicit mapping pair; a colon is missed')\n } else {\n state.tag = _tag\n state.anchor = _anchor\n return true // Keep the result of `composeNode`.\n }\n } else if (detected) {\n throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key')\n } else {\n state.tag = _tag\n state.anchor = _anchor\n return true // Keep the result of `composeNode`.\n }\n }\n\n //\n // Common reading code for both explicit and implicit notations.\n //\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (atExplicitKey) {\n _keyLine = state.line\n _keyLineStart = state.lineStart\n _keyPos = state.position\n }\n\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result\n } else {\n valueNode = state.result\n }\n }\n\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n skipSeparationSpace(state, true, -1)\n ch = state.input.charCodeAt(state.position)\n }\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a mapping entry')\n } else if (state.lineIndent < nodeIndent) {\n break\n }\n }\n\n //\n // Epilogue.\n //\n\n // Special case: last mapping's node contains only the key in explicit notation.\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n }\n\n // Expose the resulting mapping.\n if (detected) {\n state.tag = _tag\n state.anchor = _anchor\n state.kind = 'mapping'\n state.result = _result\n }\n\n return detected\n}\n\nfunction readTagProperty (state) {\n let isVerbatim = false\n let isNamed = false\n let tagHandle\n let tagName\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x21/* ! */) return false\n\n if (state.tag !== null) {\n throwError(state, 'duplication of a tag property')\n }\n\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x3C/* < */) {\n isVerbatim = true\n ch = state.input.charCodeAt(++state.position)\n } else if (ch === 0x21/* ! */) {\n isNamed = true\n tagHandle = '!!'\n ch = state.input.charCodeAt(++state.position)\n } else {\n tagHandle = '!'\n }\n\n let _position = state.position\n\n if (isVerbatim) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (ch !== 0 && ch !== 0x3E/* > */)\n\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position)\n ch = state.input.charCodeAt(++state.position)\n } else {\n throwError(state, 'unexpected end of the stream within a verbatim tag')\n }\n } else {\n while (ch !== 0 && !isWsOrEol(ch)) {\n if (ch === 0x21/* ! */) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1)\n\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, 'named tag handle cannot contain such characters')\n }\n\n isNamed = true\n _position = state.position + 1\n } else {\n throwError(state, 'tag suffix cannot contain exclamation marks')\n }\n }\n\n ch = state.input.charCodeAt(++state.position)\n }\n\n tagName = state.input.slice(_position, state.position)\n\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, 'tag suffix cannot contain flow indicator characters')\n }\n }\n\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, 'tag name cannot contain such characters: ' + tagName)\n }\n\n try {\n tagName = decodeURIComponent(tagName)\n } catch (err) {\n throwError(state, 'tag name is malformed: ' + tagName)\n }\n\n if (isVerbatim) {\n state.tag = tagName\n } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName\n } else if (tagHandle === '!') {\n state.tag = '!' + tagName\n } else if (tagHandle === '!!') {\n state.tag = 'tag:yaml.org,2002:' + tagName\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"')\n }\n\n return true\n}\n\nfunction readAnchorProperty (state) {\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x26/* & */) return false\n\n if (state.anchor !== null) {\n throwError(state, 'duplication of an anchor property')\n }\n\n ch = state.input.charCodeAt(++state.position)\n const _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an anchor node must contain at least one character')\n }\n\n state.anchor = state.input.slice(_position, state.position)\n return true\n}\n\nfunction readAlias (state) {\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x2A/* * */) return false\n\n ch = state.input.charCodeAt(++state.position)\n const _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an alias node must contain at least one character')\n }\n\n const alias = state.input.slice(_position, state.position)\n\n if (!_hasOwnProperty.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"')\n }\n\n state.result = state.anchorMap[alias]\n skipSeparationSpace(state, true, -1)\n return true\n}\n\nfunction tryReadBlockMappingFromProperty (state, propertyStart, nodeIndent, flowIndent) {\n const fallbackState = snapshotState(state)\n\n beginAnchorTransaction(state)\n restoreState(state, propertyStart)\n\n // Re-read the leading properties as part of the first implicit key, not as\n // properties of the current node.\n state.tag = null\n state.anchor = null\n state.kind = null\n state.result = null\n\n if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === 'mapping') {\n commitAnchorTransaction(state)\n return true\n }\n\n rollbackAnchorTransaction(state)\n restoreState(state, fallbackState)\n return false\n}\n\nfunction composeNode (state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n let allowBlockScalars\n let allowBlockCollections\n let indentStatus = 1 // 1: this>parent, 0: this=parent, -1: this= state.maxDepth) {\n throwError(state, 'nesting exceeded maxDepth (' + state.maxDepth + ')')\n }\n\n state.depth += 1\n\n if (state.listener !== null) {\n state.listener('open', state)\n }\n\n state.tag = null\n state.anchor = null\n state.kind = null\n state.result = null\n\n const allowBlockStyles = allowBlockScalars = allowBlockCollections =\n CONTEXT_BLOCK_OUT === nodeContext ||\n CONTEXT_BLOCK_IN === nodeContext\n\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1\n }\n }\n }\n\n if (indentStatus === 1) {\n while (true) {\n const ch = state.input.charCodeAt(state.position)\n const propertyState = snapshotState(state)\n\n // A duplicate property token after a line break can be the first key of\n // a nested block mapping, e.g. `!!map\\n !!str key: value`.\n if (atNewLine &&\n ((ch === 0x21/* ! */ && state.tag !== null) ||\n (ch === 0x26/* & */ && state.anchor !== null))) {\n break\n }\n\n if (!readTagProperty(state) && !readAnchorProperty(state)) {\n break\n }\n\n if (propertyStart === null) {\n propertyStart = propertyState\n }\n\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true\n allowBlockCollections = allowBlockStyles\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1\n }\n } else {\n allowBlockCollections = false\n }\n }\n }\n\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact\n }\n\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent\n } else {\n flowIndent = parentIndent + 1\n }\n\n blockIndent = state.position - state.lineStart\n\n if (indentStatus === 1) {\n if ((allowBlockCollections &&\n (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent))) ||\n readFlowCollection(state, flowIndent)) {\n hasContent = true\n } else {\n const ch = state.input.charCodeAt(state.position)\n\n if (propertyStart !== null && allowBlockStyles && !allowBlockCollections &&\n ch !== 0x7C/* | */ && ch !== 0x3E/* > */ &&\n tryReadBlockMappingFromProperty(\n state,\n propertyStart,\n propertyStart.position - propertyStart.lineStart,\n flowIndent\n )) {\n hasContent = true\n } else if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n readSingleQuotedScalar(state, flowIndent) ||\n readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true\n } else if (readAlias(state)) {\n hasContent = true\n\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, 'alias node should not have any properties')\n }\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true\n\n if (state.tag === null) {\n state.tag = '?'\n }\n }\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n }\n } else if (indentStatus === 0) {\n // Special case: block sequences are allowed to have same indentation level as the parent.\n // http://www.yaml.org/spec/1.2/spec.html#id2799784\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent)\n }\n }\n\n if (state.tag === null) {\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n } else if (state.tag === '?') {\n // Implicit resolving is not allowed for non-scalar types, and '?'\n // non-specific tag is only automatically assigned to plain scalars.\n //\n // We only need to check kind conformity in case user explicitly assigns '?'\n // tag, for example like this: \"! [0]\"\n //\n if (state.result !== null && state.kind !== 'scalar') {\n throwError(state, 'unacceptable node kind for ! tag; it should be \"scalar\", not \"' + state.kind + '\"')\n }\n\n for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type = state.implicitTypes[typeIndex]\n\n if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n state.result = type.construct(state.result)\n state.tag = type.tag\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n break\n }\n }\n } else if (state.tag !== '!') {\n if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n type = state.typeMap[state.kind || 'fallback'][state.tag]\n } else {\n // looking for multi type\n type = null\n const typeList = state.typeMap.multi[state.kind || 'fallback']\n\n for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {\n if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n type = typeList[typeIndex]\n break\n }\n }\n }\n\n if (!type) {\n throwError(state, 'unknown tag !<' + state.tag + '>')\n }\n\n if (state.result !== null && type.kind !== state.kind) {\n throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"')\n }\n\n if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched\n throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag')\n } else {\n state.result = type.construct(state.result, state.tag)\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n }\n }\n\n if (state.listener !== null) {\n state.listener('close', state)\n }\n\n state.depth -= 1\n return state.tag !== null || state.anchor !== null || hasContent\n}\n\nfunction readDocument (state) {\n const documentStart = state.position\n let hasDirectives = false\n let ch\n\n state.version = null\n state.checkLineBreaks = state.legacy\n state.tagMap = Object.create(null)\n state.anchorMap = Object.create(null)\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1)\n\n ch = state.input.charCodeAt(state.position)\n\n if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n break\n }\n\n hasDirectives = true\n ch = state.input.charCodeAt(++state.position)\n let _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n const directiveName = state.input.slice(_position, state.position)\n const directiveArgs = []\n\n if (directiveName.length < 1) {\n throwError(state, 'directive name must not be less than one character in length')\n }\n\n while (ch !== 0) {\n while (isWhiteSpace(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (ch !== 0 && !isEol(ch))\n break\n }\n\n if (isEol(ch)) break\n\n _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n directiveArgs.push(state.input.slice(_position, state.position))\n }\n\n if (ch !== 0) readLineBreak(state)\n\n if (_hasOwnProperty.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs)\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"')\n }\n }\n\n skipSeparationSpace(state, true, -1)\n\n if (state.lineIndent === 0 &&\n state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n state.position += 3\n skipSeparationSpace(state, true, -1)\n } else if (hasDirectives) {\n throwError(state, 'directives end mark is expected')\n }\n\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true)\n skipSeparationSpace(state, true, -1)\n\n if (state.checkLineBreaks &&\n PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, 'non-ASCII line breaks are interpreted as content')\n }\n\n state.documents.push(state.result)\n\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n state.position += 3\n skipSeparationSpace(state, true, -1)\n }\n return\n }\n\n if (state.position < (state.length - 1)) {\n throwError(state, 'end of the stream or a document separator is expected')\n }\n}\n\nfunction loadDocuments (input, options) {\n input = String(input)\n options = options || {}\n\n if (input.length !== 0) {\n // Add tailing `\\n` if not exists\n if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n input += '\\n'\n }\n\n // Strip BOM\n if (input.charCodeAt(0) === 0xFEFF) {\n input = input.slice(1)\n }\n }\n\n const state = new State(input, options)\n\n const nullpos = input.indexOf('\\0')\n\n if (nullpos !== -1) {\n state.position = nullpos\n throwError(state, 'null byte is not allowed in input')\n }\n\n // Use 0 as string terminator. That significantly simplifies bounds check.\n state.input += '\\0'\n\n while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n state.lineIndent += 1\n state.position += 1\n }\n\n while (state.position < (state.length - 1)) {\n readDocument(state)\n }\n\n return state.documents\n}\n\nfunction loadAll (input, iterator, options) {\n if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n options = iterator\n iterator = null\n }\n\n const documents = loadDocuments(input, options)\n\n if (typeof iterator !== 'function') {\n return documents\n }\n\n for (let index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index])\n }\n}\n\nfunction load (input, options) {\n const documents = loadDocuments(input, options)\n\n if (documents.length === 0) {\n return undefined\n } else if (documents.length === 1) {\n return documents[0]\n }\n throw new YAMLException('expected a single document in the stream, but found more')\n}\n\nmodule.exports.loadAll = loadAll\nmodule.exports.load = load\n","'use strict'\n\nconst common = require('./common')\nconst YAMLException = require('./exception')\nconst DEFAULT_SCHEMA = require('./schema/default')\n\nconst _toString = Object.prototype.toString\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nconst CHAR_BOM = 0xFEFF\nconst CHAR_TAB = 0x09 /* Tab */\nconst CHAR_LINE_FEED = 0x0A /* LF */\nconst CHAR_CARRIAGE_RETURN = 0x0D /* CR */\nconst CHAR_SPACE = 0x20 /* Space */\nconst CHAR_EXCLAMATION = 0x21 /* ! */\nconst CHAR_DOUBLE_QUOTE = 0x22 /* \" */\nconst CHAR_SHARP = 0x23 /* # */\nconst CHAR_PERCENT = 0x25 /* % */\nconst CHAR_AMPERSAND = 0x26 /* & */\nconst CHAR_SINGLE_QUOTE = 0x27 /* ' */\nconst CHAR_ASTERISK = 0x2A /* * */\nconst CHAR_COMMA = 0x2C /* , */\nconst CHAR_MINUS = 0x2D /* - */\nconst CHAR_COLON = 0x3A /* : */\nconst CHAR_EQUALS = 0x3D /* = */\nconst CHAR_GREATER_THAN = 0x3E /* > */\nconst CHAR_QUESTION = 0x3F /* ? */\nconst CHAR_COMMERCIAL_AT = 0x40 /* @ */\nconst CHAR_LEFT_SQUARE_BRACKET = 0x5B /* [ */\nconst CHAR_RIGHT_SQUARE_BRACKET = 0x5D /* ] */\nconst CHAR_GRAVE_ACCENT = 0x60 /* ` */\nconst CHAR_LEFT_CURLY_BRACKET = 0x7B /* { */\nconst CHAR_VERTICAL_LINE = 0x7C /* | */\nconst CHAR_RIGHT_CURLY_BRACKET = 0x7D /* } */\n\nconst ESCAPE_SEQUENCES = {}\n\nESCAPE_SEQUENCES[0x00] = '\\\\0'\nESCAPE_SEQUENCES[0x07] = '\\\\a'\nESCAPE_SEQUENCES[0x08] = '\\\\b'\nESCAPE_SEQUENCES[0x09] = '\\\\t'\nESCAPE_SEQUENCES[0x0A] = '\\\\n'\nESCAPE_SEQUENCES[0x0B] = '\\\\v'\nESCAPE_SEQUENCES[0x0C] = '\\\\f'\nESCAPE_SEQUENCES[0x0D] = '\\\\r'\nESCAPE_SEQUENCES[0x1B] = '\\\\e'\nESCAPE_SEQUENCES[0x22] = '\\\\\"'\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\'\nESCAPE_SEQUENCES[0x85] = '\\\\N'\nESCAPE_SEQUENCES[0xA0] = '\\\\_'\nESCAPE_SEQUENCES[0x2028] = '\\\\L'\nESCAPE_SEQUENCES[0x2029] = '\\\\P'\n\nconst DEPRECATED_BOOLEANS_SYNTAX = [\n 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n]\n\nconst DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/\n\nfunction compileStyleMap (schema, map) {\n if (map === null) return {}\n\n const result = {}\n const keys = Object.keys(map)\n\n for (let index = 0, length = keys.length; index < length; index += 1) {\n let tag = keys[index]\n let style = String(map[tag])\n\n if (tag.slice(0, 2) === '!!') {\n tag = 'tag:yaml.org,2002:' + tag.slice(2)\n }\n const type = schema.compiledTypeMap['fallback'][tag]\n\n if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n style = type.styleAliases[style]\n }\n\n result[tag] = style\n }\n\n return result\n}\n\nfunction encodeHex (character) {\n let handle\n let length\n\n const string = character.toString(16).toUpperCase()\n\n if (character <= 0xFF) {\n handle = 'x'\n length = 2\n } else if (character <= 0xFFFF) {\n handle = 'u'\n length = 4\n } else if (character <= 0xFFFFFFFF) {\n handle = 'U'\n length = 8\n } else {\n throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF')\n }\n\n return '\\\\' + handle + common.repeat('0', length - string.length) + string\n}\n\nconst QUOTING_TYPE_SINGLE = 1\nconst QUOTING_TYPE_DOUBLE = 2\n\nfunction State (options) {\n this.schema = options['schema'] || DEFAULT_SCHEMA\n this.indent = Math.max(1, (options['indent'] || 2))\n this.noArrayIndent = options['noArrayIndent'] || false\n this.skipInvalid = options['skipInvalid'] || false\n this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel'])\n this.styleMap = compileStyleMap(this.schema, options['styles'] || null)\n this.sortKeys = options['sortKeys'] || false\n this.lineWidth = options['lineWidth'] || 80\n this.noRefs = options['noRefs'] || false\n this.noCompatMode = options['noCompatMode'] || false\n this.condenseFlow = options['condenseFlow'] || false\n this.quotingType = options['quotingType'] === '\"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE\n this.forceQuotes = options['forceQuotes'] || false\n this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null\n\n this.implicitTypes = this.schema.compiledImplicit\n this.explicitTypes = this.schema.compiledExplicit\n\n this.tag = null\n this.result = ''\n\n this.duplicates = []\n this.usedDuplicates = null\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString (string, spaces) {\n const ind = common.repeat(' ', spaces)\n let position = 0\n let result = ''\n const length = string.length\n\n while (position < length) {\n let line\n const next = string.indexOf('\\n', position)\n if (next === -1) {\n line = string.slice(position)\n position = length\n } else {\n line = string.slice(position, next + 1)\n position = next + 1\n }\n\n if (line.length && line !== '\\n') result += ind\n\n result += line\n }\n\n return result\n}\n\nfunction generateNextLine (state, level) {\n return '\\n' + common.repeat(' ', state.indent * level)\n}\n\nfunction testImplicitResolving (state, str) {\n for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n const type = state.implicitTypes[index]\n\n if (type.resolve(str)) {\n return true\n }\n }\n\n return false\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace (c) {\n return c === CHAR_SPACE || c === CHAR_TAB\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable (c) {\n return (c >= 0x00020 && c <= 0x00007E) ||\n ((c >= 0x000A1 && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) ||\n ((c >= 0x0E000 && c <= 0x00FFFD) && c !== CHAR_BOM) ||\n (c >= 0x10000 && c <= 0x10FFFF)\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char ::= b-line-feed | b-carriage-return\n// Including s-white (for some reason, examples doesn't match specs in this aspect)\n// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark\nfunction isNsCharOrWhitespace (c) {\n return isPrintable(c) &&\n c !== CHAR_BOM &&\n // - b-char\n c !== CHAR_CARRIAGE_RETURN &&\n c !== CHAR_LINE_FEED\n}\n\n// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out\n// c = flow-in ⇒ ns-plain-safe-in\n// c = block-key ⇒ ns-plain-safe-out\n// c = flow-key ⇒ ns-plain-safe-in\n// [128] ns-plain-safe-out ::= ns-char\n// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator\n// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:� - “#� )\n// | ( /* An ns-char preceding */ “#� )\n// | ( “:� /* Followed by an ns-plain-safe(c) */ )\nfunction isPlainSafe (c, prev, inblock) {\n const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c)\n const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c)\n return (\n (\n // ns-plain-safe\n inblock // c = flow-in\n ? cIsNsCharOrWhitespace\n : cIsNsCharOrWhitespace &&\n // - c-flow-indicator\n c !== CHAR_COMMA &&\n c !== CHAR_LEFT_SQUARE_BRACKET &&\n c !== CHAR_RIGHT_SQUARE_BRACKET &&\n c !== CHAR_LEFT_CURLY_BRACKET &&\n c !== CHAR_RIGHT_CURLY_BRACKET\n ) &&\n // ns-plain-char\n c !== CHAR_SHARP && // false on '#'\n !(prev === CHAR_COLON && !cIsNsChar)\n ) || // false on ': '\n (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#'\n (prev === CHAR_COLON && cIsNsChar) // change to true on ':[^ ]'\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst (c) {\n // Uses a subset of ns-char - c-indicator\n // where ns-char = nb-char - s-white.\n // No support of ( ( “?� | “:� | “-� ) /* Followed by an ns-plain-safe(c)) */ ) part\n return isPrintable(c) &&\n c !== CHAR_BOM &&\n !isWhitespace(c) && // - s-white\n // - (c-indicator ::=\n // “-� | “?� | “:� | “,� | “[� | “]� | “{� | “}�\n c !== CHAR_MINUS &&\n c !== CHAR_QUESTION &&\n c !== CHAR_COLON &&\n c !== CHAR_COMMA &&\n c !== CHAR_LEFT_SQUARE_BRACKET &&\n c !== CHAR_RIGHT_SQUARE_BRACKET &&\n c !== CHAR_LEFT_CURLY_BRACKET &&\n c !== CHAR_RIGHT_CURLY_BRACKET &&\n // | “#� | “&� | “*� | “!� | “|� | “=� | “>� | “'� | “\"�\n c !== CHAR_SHARP &&\n c !== CHAR_AMPERSAND &&\n c !== CHAR_ASTERISK &&\n c !== CHAR_EXCLAMATION &&\n c !== CHAR_VERTICAL_LINE &&\n c !== CHAR_EQUALS &&\n c !== CHAR_GREATER_THAN &&\n c !== CHAR_SINGLE_QUOTE &&\n c !== CHAR_DOUBLE_QUOTE &&\n // | “%� | “@� | “`�)\n c !== CHAR_PERCENT &&\n c !== CHAR_COMMERCIAL_AT &&\n c !== CHAR_GRAVE_ACCENT\n}\n\n// Simplified test for values allowed as the last character in plain style.\nfunction isPlainSafeLast (c) {\n // just not whitespace or colon, it will be checked to be plain character later\n return !isWhitespace(c) && c !== CHAR_COLON\n}\n\n// Same as 'string'.codePointAt(pos), but works in older browsers.\nfunction codePointAt (string, pos) {\n const first = string.charCodeAt(pos)\n let second\n\n if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {\n second = string.charCodeAt(pos + 1)\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000\n }\n }\n return first\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator (string) {\n const leadingSpaceRe = /^\\n* /\n return leadingSpaceRe.test(string)\n}\n\nconst STYLE_PLAIN = 1\nconst STYLE_SINGLE = 2\nconst STYLE_LITERAL = 3\nconst STYLE_FOLDED = 4\nconst STYLE_DOUBLE = 5\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n// STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle (string, singleLineOnly, indentPerLevel, lineWidth,\n testAmbiguousType, quotingType, forceQuotes, inblock) {\n let i\n let char = 0\n let prevChar = null\n let hasLineBreak = false\n let hasFoldableLine = false // only checked if shouldTrackWidth\n const shouldTrackWidth = lineWidth !== -1\n let previousLineBreak = -1 // count the first line correctly\n let plain = isPlainSafeFirst(codePointAt(string, 0)) &&\n isPlainSafeLast(codePointAt(string, string.length - 1))\n\n if (singleLineOnly || forceQuotes) {\n // Case: no block styles.\n // Check for disallowed characters to rule out plain and single.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n if (!isPrintable(char)) {\n return STYLE_DOUBLE\n }\n plain = plain && isPlainSafe(char, prevChar, inblock)\n prevChar = char\n }\n } else {\n // Case: block styles permitted.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true\n // Check if any line can be folded.\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine ||\n // Foldable line = too long, and not more-indented.\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' ')\n previousLineBreak = i\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE\n }\n plain = plain && isPlainSafe(char, prevChar, inblock)\n prevChar = char\n }\n // in case the end is missing a \\n\n hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' '))\n }\n // Although every style can represent \\n without escaping, prefer block styles\n // for multiline, since they're more readable and they don't add empty lines.\n // Also prefer folding a super-long line.\n if (!hasLineBreak && !hasFoldableLine) {\n // Strings interpretable as another type have to be quoted;\n // e.g. the string 'true' vs. the boolean true.\n if (plain && !forceQuotes && !testAmbiguousType(string)) {\n return STYLE_PLAIN\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE\n }\n // Edge case: block indentation indicator can only have one digit.\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE\n }\n // At this point we know block styles are valid.\n // Prefer literal style unless we want to fold.\n if (!forceQuotes) {\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n// since the dumper adds its own newline. This always works:\n// • No ending newline => unaffected; already using strip \"-\" chomping.\n// • Ending newline => removed then restored.\n// Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar (state, string, level, iskey, inblock) {\n state.dump = (function () {\n if (string.length === 0) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? '\"\"' : \"''\"\n }\n if (!state.noCompatMode) {\n if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? ('\"' + string + '\"') : (\"'\" + string + \"'\")\n }\n }\n\n const indent = state.indent * Math.max(1, level) // no 0-indent scalars\n // As indentation gets deeper, let the width decrease monotonically\n // to the lower bound min(state.lineWidth, 40).\n // Note that this implies\n // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.\n // state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n // This behaves better than a constant minimum width which disallows narrower options,\n // or an indent threshold which causes the width to suddenly increase.\n const lineWidth = (state.lineWidth === -1)\n ? -1\n : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent)\n\n // Without knowing if keys are implicit/explicit, assume implicit for safety.\n const singleLineOnly = iskey ||\n // No block styles in flow mode.\n (state.flowLevel > -1 && level >= state.flowLevel)\n function testAmbiguity (string) {\n return testImplicitResolving(state, string)\n }\n\n switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,\n testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {\n case STYLE_PLAIN:\n return string\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\"\n case STYLE_LITERAL:\n return '|' + blockHeader(string, state.indent) +\n dropEndingNewline(indentString(string, indent))\n case STYLE_FOLDED:\n return '>' + blockHeader(string, state.indent) +\n dropEndingNewline(indentString(foldString(string, lineWidth), indent))\n case STYLE_DOUBLE:\n return '\"' + escapeString(string, lineWidth) + '\"'\n default:\n throw new YAMLException('impossible error: invalid scalar style')\n }\n }())\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader (string, indentPerLevel) {\n const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''\n\n // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n const clip = string[string.length - 1] === '\\n'\n const keep = clip && (string[string.length - 2] === '\\n' || string === '\\n')\n const chomp = keep ? '+' : (clip ? '' : '-')\n\n return indentIndicator + chomp + '\\n'\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline (string) {\n return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString (string, width) {\n // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n // unless they're before or after a more-indented line, or at the very\n // beginning or end, in which case $k$ maps to $k$.\n // Therefore, parse each chunk as newline(s) followed by a content line.\n const lineRe = /(\\n+)([^\\n]*)/g\n\n // first line (possibly an empty line)\n let result = (function () {\n let nextLF = string.indexOf('\\n')\n nextLF = nextLF !== -1 ? nextLF : string.length\n lineRe.lastIndex = nextLF\n return foldLine(string.slice(0, nextLF), width)\n }())\n // If we haven't reached the first content line yet, don't add an extra \\n.\n let prevMoreIndented = string[0] === '\\n' || string[0] === ' '\n let moreIndented\n\n // rest of the lines\n let match\n while ((match = lineRe.exec(string))) {\n const prefix = match[1]\n const line = match[2]\n\n moreIndented = (line[0] === ' ')\n result += prefix +\n ((!prevMoreIndented && !moreIndented && line !== '') ? '\\n' : '') +\n foldLine(line, width)\n prevMoreIndented = moreIndented\n }\n\n return result\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine (line, width) {\n if (line === '' || line[0] === ' ') return line\n\n // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n const breakRe = / [^ ]/g // note: the match index will always be <= length-2.\n let match\n // start is an inclusive index. end, curr, and next are exclusive.\n let start = 0\n let end\n let curr = 0\n let next = 0\n let result = ''\n\n // Invariants: 0 <= start <= length-1.\n // 0 <= curr <= next <= max(0, length-2). curr - start <= width.\n // Inside the loop:\n // A match implies length >= 2, so curr and next are <= length-2.\n while ((match = breakRe.exec(line))) {\n next = match.index\n // maintain invariant: curr - start <= width\n if (next - start > width) {\n end = (curr > start) ? curr : next // derive end <= length-2\n result += '\\n' + line.slice(start, end)\n // skip the space that was output as \\n\n start = end + 1 // derive start <= length-1\n }\n curr = next\n }\n\n // By the invariants, start <= length-1, so there is something left over.\n // It is either the whole string or a part starting from non-whitespace.\n result += '\\n'\n // Insert a break if the remainder is too long and there is a break available.\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + '\\n' + line.slice(curr + 1)\n } else {\n result += line.slice(start)\n }\n\n return result.slice(1) // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString (string) {\n let result = ''\n let char = 0\n\n for (let i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n const escapeSeq = ESCAPE_SEQUENCES[char]\n\n if (!escapeSeq && isPrintable(char)) {\n result += string[i]\n if (char >= 0x10000) result += string[i + 1]\n } else {\n result += escapeSeq || encodeHex(char)\n }\n }\n\n return result\n}\n\nfunction writeFlowSequence (state, level, object) {\n let _result = ''\n const _tag = state.tag\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n let value = object[index]\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value)\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level, value, false, false) ||\n (typeof value === 'undefined' &&\n writeNode(state, level, null, false, false))) {\n if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '')\n _result += state.dump\n }\n }\n\n state.tag = _tag\n state.dump = '[' + _result + ']'\n}\n\nfunction writeBlockSequence (state, level, object, compact) {\n let _result = ''\n const _tag = state.tag\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n let value = object[index]\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value)\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level + 1, value, true, true, false, true) ||\n (typeof value === 'undefined' &&\n writeNode(state, level + 1, null, true, true, false, true))) {\n if (!compact || _result !== '') {\n _result += generateNextLine(state, level)\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += '-'\n } else {\n _result += '- '\n }\n\n _result += state.dump\n }\n }\n\n state.tag = _tag\n state.dump = _result || '[]' // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping (state, level, object) {\n let _result = ''\n const _tag = state.tag\n const objectKeyList = Object.keys(object)\n\n for (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n let pairBuffer = ''\n if (_result !== '') pairBuffer += ', '\n\n if (state.condenseFlow) pairBuffer += '\"'\n\n const objectKey = objectKeyList[index]\n let objectValue = object[objectKey]\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue)\n }\n\n if (!writeNode(state, level, objectKey, false, false)) {\n continue // Skip this pair because of invalid key;\n }\n\n if (state.dump.length > 1024) pairBuffer += '? '\n\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ')\n\n if (!writeNode(state, level, objectValue, false, false)) {\n continue // Skip this pair because of invalid value.\n }\n\n pairBuffer += state.dump\n\n // Both key and value are valid.\n _result += pairBuffer\n }\n\n state.tag = _tag\n state.dump = '{' + _result + '}'\n}\n\nfunction writeBlockMapping (state, level, object, compact) {\n let _result = ''\n const _tag = state.tag\n const objectKeyList = Object.keys(object)\n\n // Allow sorting keys so that the output file is deterministic\n if (state.sortKeys === true) {\n // Default sorting\n objectKeyList.sort()\n } else if (typeof state.sortKeys === 'function') {\n // Custom sort function\n objectKeyList.sort(state.sortKeys)\n } else if (state.sortKeys) {\n // Something is wrong\n throw new YAMLException('sortKeys must be a boolean or a function')\n }\n\n for (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n let pairBuffer = ''\n\n if (!compact || _result !== '') {\n pairBuffer += generateNextLine(state, level)\n }\n\n const objectKey = objectKeyList[index]\n let objectValue = object[objectKey]\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue)\n }\n\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue // Skip this pair because of invalid key.\n }\n\n const explicitPair = (state.tag !== null && state.tag !== '?') ||\n (state.dump && state.dump.length > 1024)\n\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += '?'\n } else {\n pairBuffer += '? '\n }\n }\n\n pairBuffer += state.dump\n\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level)\n }\n\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue // Skip this pair because of invalid value.\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += ':'\n } else {\n pairBuffer += ': '\n }\n\n pairBuffer += state.dump\n\n // Both key and value are valid.\n _result += pairBuffer\n }\n\n state.tag = _tag\n state.dump = _result || '{}' // Empty mapping if no valid pairs.\n}\n\nfunction detectType (state, object, explicit) {\n const typeList = explicit ? state.explicitTypes : state.implicitTypes\n\n for (let index = 0, length = typeList.length; index < length; index += 1) {\n const type = typeList[index]\n\n if ((type.instanceOf || type.predicate) &&\n (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n (!type.predicate || type.predicate(object))) {\n if (explicit) {\n if (type.multi && type.representName) {\n state.tag = type.representName(object)\n } else {\n state.tag = type.tag\n }\n } else {\n state.tag = '?'\n }\n\n if (type.represent) {\n const style = state.styleMap[type.tag] || type.defaultStyle\n\n let _result\n if (_toString.call(type.represent) === '[object Function]') {\n _result = type.represent(object, style)\n } else if (_hasOwnProperty.call(type.represent, style)) {\n _result = type.represent[style](object, style)\n } else {\n throw new YAMLException('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style')\n }\n\n state.dump = _result\n }\n\n return true\n }\n }\n\n return false\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode (state, level, object, block, compact, iskey, isblockseq) {\n state.tag = null\n state.dump = object\n\n if (!detectType(state, object, false)) {\n detectType(state, object, true)\n }\n\n const type = _toString.call(state.dump)\n const inblock = block\n\n if (block) {\n block = (state.flowLevel < 0 || state.flowLevel > level)\n }\n\n const objectOrArray = type === '[object Object]' || type === '[object Array]'\n let duplicateIndex\n let duplicate\n\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object)\n duplicate = duplicateIndex !== -1\n }\n\n if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n compact = false\n }\n\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = '*ref_' + duplicateIndex\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true\n }\n if (type === '[object Object]') {\n if (block && (Object.keys(state.dump).length !== 0)) {\n writeBlockMapping(state, level, state.dump, compact)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump\n }\n } else {\n writeFlowMapping(state, level, state.dump)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump\n }\n }\n } else if (type === '[object Array]') {\n if (block && (state.dump.length !== 0)) {\n if (state.noArrayIndent && !isblockseq && level > 0) {\n writeBlockSequence(state, level - 1, state.dump, compact)\n } else {\n writeBlockSequence(state, level, state.dump, compact)\n }\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump\n }\n } else {\n writeFlowSequence(state, level, state.dump)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump\n }\n }\n } else if (type === '[object String]') {\n if (state.tag !== '?') {\n writeScalar(state, state.dump, level, iskey, inblock)\n }\n } else if (type === '[object Undefined]') {\n return false\n } else {\n if (state.skipInvalid) return false\n throw new YAMLException('unacceptable kind of an object to dump ' + type)\n }\n\n if (state.tag !== null && state.tag !== '?') {\n // Need to encode all characters except those allowed by the spec:\n //\n // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */\n // [36] ns-hex-digit ::= ns-dec-digit\n // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */\n // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */\n // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-�\n // [39] ns-uri-char ::= “%� ns-hex-digit ns-hex-digit | ns-word-char | “#�\n // | “;� | “/� | “?� | “:� | “@� | “&� | “=� | “+� | “$� | “,�\n // | “_� | “.� | “!� | “~� | “*� | “'� | “(� | “)� | “[� | “]�\n //\n // Also need to encode '!' because it has special meaning (end of tag prefix).\n //\n let tagStr = encodeURI(\n state.tag[0] === '!' ? state.tag.slice(1) : state.tag\n ).replace(/!/g, '%21')\n\n if (state.tag[0] === '!') {\n tagStr = '!' + tagStr\n } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {\n tagStr = '!!' + tagStr.slice(18)\n } else {\n tagStr = '!<' + tagStr + '>'\n }\n\n state.dump = tagStr + ' ' + state.dump\n }\n }\n\n return true\n}\n\nfunction getDuplicateReferences (object, state) {\n const objects = []\n const duplicatesIndexes = []\n\n inspectNode(object, objects, duplicatesIndexes)\n\n const length = duplicatesIndexes.length\n for (let index = 0; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]])\n }\n state.usedDuplicates = new Array(length)\n}\n\nfunction inspectNode (object, objects, duplicatesIndexes) {\n if (object !== null && typeof object === 'object') {\n const index = objects.indexOf(object)\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index)\n }\n } else {\n objects.push(object)\n\n if (Array.isArray(object)) {\n for (let i = 0, length = object.length; i < length; i += 1) {\n inspectNode(object[i], objects, duplicatesIndexes)\n }\n } else {\n const objectKeyList = Object.keys(object)\n\n for (let i = 0, length = objectKeyList.length; i < length; i += 1) {\n inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes)\n }\n }\n }\n }\n}\n\nfunction dump (input, options) {\n options = options || {}\n\n const state = new State(options)\n\n if (!state.noRefs) getDuplicateReferences(input, state)\n\n let value = input\n\n if (state.replacer) {\n value = state.replacer.call({ '': value }, '', value)\n }\n\n if (writeNode(state, 0, value, true, true)) return state.dump + '\\n'\n\n return ''\n}\n\nmodule.exports.dump = dump\n","'use strict'\n\nconst loader = require('./lib/loader')\nconst dumper = require('./lib/dumper')\n\nfunction renamed (from, to) {\n return function () {\n throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +\n 'Use yaml.' + to + ' instead, which is now safe by default.')\n }\n}\n\nmodule.exports.Type = require('./lib/type')\nmodule.exports.Schema = require('./lib/schema')\nmodule.exports.FAILSAFE_SCHEMA = require('./lib/schema/failsafe')\nmodule.exports.JSON_SCHEMA = require('./lib/schema/json')\nmodule.exports.CORE_SCHEMA = require('./lib/schema/core')\nmodule.exports.DEFAULT_SCHEMA = require('./lib/schema/default')\nmodule.exports.load = loader.load\nmodule.exports.loadAll = loader.loadAll\nmodule.exports.dump = dumper.dump\nmodule.exports.YAMLException = require('./lib/exception')\n\n// Re-export all types in case user wants to create custom schema\nmodule.exports.types = {\n binary: require('./lib/type/binary'),\n float: require('./lib/type/float'),\n map: require('./lib/type/map'),\n null: require('./lib/type/null'),\n pairs: require('./lib/type/pairs'),\n set: require('./lib/type/set'),\n timestamp: require('./lib/type/timestamp'),\n bool: require('./lib/type/bool'),\n int: require('./lib/type/int'),\n merge: require('./lib/type/merge'),\n omap: require('./lib/type/omap'),\n seq: require('./lib/type/seq'),\n str: require('./lib/type/str')\n}\n\n// Removed functions from JS-YAML 3.0.x\nmodule.exports.safeLoad = renamed('safeLoad', 'load')\nmodule.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll')\nmodule.exports.safeDump = renamed('safeDump', 'dump')\n","import yaml from '../index.js'\n\nconst {\n Type,\n Schema,\n FAILSAFE_SCHEMA,\n JSON_SCHEMA,\n CORE_SCHEMA,\n DEFAULT_SCHEMA,\n load,\n loadAll,\n dump,\n YAMLException,\n types,\n safeLoad,\n safeLoadAll,\n safeDump\n} = yaml\n\nexport {\n Type,\n Schema,\n FAILSAFE_SCHEMA,\n JSON_SCHEMA,\n CORE_SCHEMA,\n DEFAULT_SCHEMA,\n load,\n loadAll,\n dump,\n YAMLException,\n types,\n safeLoad,\n safeLoadAll,\n safeDump\n}\n\nexport default yaml\n"],"mappings":"w1BAEA,SAAS,EAAW,EAAS,CAC3B,OAAe,GAAyC,IAC1D,CAEA,SAAS,EAAU,EAAS,CAC1B,OAAQ,OAAO,GAAY,YAAc,CAC3C,CAEA,SAAS,EAAS,EAAU,CAI1B,OAHI,MAAM,QAAQ,CAAQ,EAAU,EAC3B,EAAU,CAA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AQ,SAAW,EAAQ,WAAY,MAAM,UCzC9C,CACJ,OACA,UACA,kBACA,cACA,cACA,iBACA,OACA,WACA,OACA,gBACA,QACA,WACA,cACA,YACEA,EAAAA,QAmBJ,EAAeA,EAAAA"}/*! js-yaml 4.2.0 https://github.com/nodeca/js-yaml @license MIT */ //#region \0rolldown/runtime.js var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports); var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion //#region lib/common.js var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => { function isNothing(subject) { return typeof subject === "undefined" || subject === null; } function isObject(subject) { return typeof subject === "object" && subject !== null; } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [sequence]; } function extend(target, source) { if (source) { const sourceKeys = Object.keys(source); for (let index = 0, length = sourceKeys.length; index < length; index += 1) { const key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { let result = ""; for (let cycle = 0; cycle < count; cycle += 1) result += string; return result; } function isNegativeZero(number) { return number === 0 && Number.NEGATIVE_INFINITY === 1 / number; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.toArray = toArray; module.exports.repeat = repeat; module.exports.isNegativeZero = isNegativeZero; module.exports.extend = extend; })); //#endregion //#region lib/exception.js var require_exception = /* @__PURE__ */ __commonJSMin(((exports, module) => { function formatError(exception, compact) { let where = ""; const message = exception.reason || "(unknown reason)"; if (!exception.mark) return message; if (exception.mark.name) where += "in \"" + exception.mark.name + "\" "; where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")"; if (!compact && exception.mark.snippet) where += "\n\n" + exception.mark.snippet; return message + " " + where; } function YAMLException(reason, mark) { Error.call(this); this.name = "YAMLException"; this.reason = reason; this.mark = mark; this.message = formatError(this, false); if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); else this.stack = (/* @__PURE__ */ new Error()).stack || ""; } YAMLException.prototype = Object.create(Error.prototype); YAMLException.prototype.constructor = YAMLException; YAMLException.prototype.toString = function toString(compact) { return this.name + ": " + formatError(this, compact); }; module.exports = YAMLException; })); //#endregion //#region lib/snippet.js var require_snippet = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { let head = ""; let tail = ""; const maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = " ... "; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = " ..."; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail, pos: position - lineStart + head.length }; } function padStart(string, max) { return common.repeat(" ", max - string.length) + string; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== "number") options.indent = 1; if (typeof options.linesBefore !== "number") options.linesBefore = 3; if (typeof options.linesAfter !== "number") options.linesAfter = 2; const re = /\r?\n|\r|\0/g; const lineStarts = [0]; const lineEnds = []; let match; let foundLineNo = -1; while (match = re.exec(mark.buffer)) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2; } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; let result = ""; const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (let i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; const line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength); result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; } const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; for (let i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; const line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength); result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n"; } return result.replace(/\n$/, ""); } module.exports = makeSnippet; })); //#endregion //#region lib/type.js var require_type = /* @__PURE__ */ __commonJSMin(((exports, module) => { var YAMLException = require_exception(); var TYPE_CONSTRUCTOR_OPTIONS = [ "kind", "multi", "resolve", "construct", "instanceOf", "predicate", "represent", "representName", "defaultStyle", "styleAliases" ]; var YAML_NODE_KINDS = [ "scalar", "sequence", "mapping" ]; function compileStyleAliases(map) { const result = {}; if (map !== null) Object.keys(map).forEach(function(style) { map[style].forEach(function(alias) { result[String(alias)] = style; }); }); return result; } function Type(tag, options) { options = options || {}; Object.keys(options).forEach(function(name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) throw new YAMLException("Unknown option \"" + name + "\" is met in definition of \"" + tag + "\" YAML type."); }); this.options = options; this.tag = tag; this.kind = options["kind"] || null; this.resolve = options["resolve"] || function() { return true; }; this.construct = options["construct"] || function(data) { return data; }; this.instanceOf = options["instanceOf"] || null; this.predicate = options["predicate"] || null; this.represent = options["represent"] || null; this.representName = options["representName"] || null; this.defaultStyle = options["defaultStyle"] || null; this.multi = options["multi"] || false; this.styleAliases = compileStyleAliases(options["styleAliases"] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) throw new YAMLException("Unknown kind \"" + this.kind + "\" is specified for \"" + tag + "\" YAML type."); } module.exports = Type; })); //#endregion //#region lib/schema.js var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { var YAMLException = require_exception(); var Type = require_type(); function compileList(schema, name) { const result = []; schema[name].forEach(function(currentType) { let newIndex = result.length; result.forEach(function(previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) newIndex = previousIndex; }); result[newIndex] = currentType; }); return result; } function compileMap() { const result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }; function collectType(type) { if (type.multi) { result.multi[type.kind].push(type); result.multi["fallback"].push(type); } else result[type.kind][type.tag] = result["fallback"][type.tag] = type; } for (let index = 0, length = arguments.length; index < length; index += 1) arguments[index].forEach(collectType); return result; } function Schema(definition) { return this.extend(definition); } Schema.prototype.extend = function extend(definition) { let implicit = []; let explicit = []; if (definition instanceof Type) explicit.push(definition); else if (Array.isArray(definition)) explicit = explicit.concat(definition); else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else throw new YAMLException("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); implicit.forEach(function(type) { if (!(type instanceof Type)) throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object."); if (type.loadKind && type.loadKind !== "scalar") throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); if (type.multi) throw new YAMLException("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); }); explicit.forEach(function(type) { if (!(type instanceof Type)) throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object."); }); const result = Object.create(Schema.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, "implicit"); result.compiledExplicit = compileList(result, "explicit"); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; module.exports = Schema; })); //#endregion //#region lib/type/str.js var require_str = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_type())("tag:yaml.org,2002:str", { kind: "scalar", construct: function(data) { return data !== null ? data : ""; } }); })); //#endregion //#region lib/type/seq.js var require_seq = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_type())("tag:yaml.org,2002:seq", { kind: "sequence", construct: function(data) { return data !== null ? data : []; } }); })); //#endregion //#region lib/type/map.js var require_map = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_type())("tag:yaml.org,2002:map", { kind: "mapping", construct: function(data) { return data !== null ? data : {}; } }); })); //#endregion //#region lib/schema/failsafe.js var require_failsafe = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = new (require_schema())({ explicit: [ require_str(), require_seq(), require_map() ] }); })); //#endregion //#region lib/type/null.js var require_null = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); function resolveYamlNull(data) { if (data === null) return true; const max = data.length; return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL"); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } module.exports = new Type("tag:yaml.org,2002:null", { kind: "scalar", resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function() { return "~"; }, lowercase: function() { return "null"; }, uppercase: function() { return "NULL"; }, camelcase: function() { return "Null"; }, empty: function() { return ""; } }, defaultStyle: "lowercase" }); })); //#endregion //#region lib/type/bool.js var require_bool = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); function resolveYamlBoolean(data) { if (data === null) return false; const max = data.length; return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE"); } function constructYamlBoolean(data) { return data === "true" || data === "True" || data === "TRUE"; } function isBoolean(object) { return Object.prototype.toString.call(object) === "[object Boolean]"; } module.exports = new Type("tag:yaml.org,2002:bool", { kind: "scalar", resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function(object) { return object ? "true" : "false"; }, uppercase: function(object) { return object ? "TRUE" : "FALSE"; }, camelcase: function(object) { return object ? "True" : "False"; } }, defaultStyle: "lowercase" }); })); //#endregion //#region lib/type/int.js var require_int = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var Type = require_type(); function isHexCode(c) { return c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102; } function isOctCode(c) { return c >= 48 && c <= 55; } function isDecCode(c) { return c >= 48 && c <= 57; } function resolveYamlInteger(data) { if (data === null) return false; const max = data.length; let index = 0; let hasDigits = false; if (!max) return false; let ch = data[index]; if (ch === "-" || ch === "+") ch = data[++index]; if (ch === "0") { if (index + 1 === max) return true; ch = data[++index]; if (ch === "b") { index++; for (; index < max; index++) { ch = data[index]; if (ch !== "0" && ch !== "1") return false; hasDigits = true; } return hasDigits && Number.isFinite(parseYamlInteger(data)); } if (ch === "x") { index++; for (; index < max; index++) { if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && Number.isFinite(parseYamlInteger(data)); } if (ch === "o") { index++; for (; index < max; index++) { if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && Number.isFinite(parseYamlInteger(data)); } } for (; index < max; index++) { if (!isDecCode(data.charCodeAt(index))) return false; hasDigits = true; } if (!hasDigits) return false; return Number.isFinite(parseYamlInteger(data)); } function parseYamlInteger(data) { let value = data; let sign = 1; let ch = value[0]; if (ch === "-" || ch === "+") { if (ch === "-") sign = -1; value = value.slice(1); ch = value[0]; } if (value === "0") return 0; if (ch === "0") { if (value[1] === "b") return sign * parseInt(value.slice(2), 2); if (value[1] === "x") return sign * parseInt(value.slice(2), 16); if (value[1] === "o") return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function constructYamlInteger(data) { return parseYamlInteger(data); } function isInteger(object) { return Object.prototype.toString.call(object) === "[object Number]" && object % 1 === 0 && !common.isNegativeZero(object); } module.exports = new Type("tag:yaml.org,2002:int", { kind: "scalar", resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function(obj) { return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1); }, octal: function(obj) { return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1); }, decimal: function(obj) { return obj.toString(10); }, hexadecimal: function(obj) { return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: "decimal", styleAliases: { binary: [2, "bin"], octal: [8, "oct"], decimal: [10, "dec"], hexadecimal: [16, "hex"] } }); })); //#endregion //#region lib/type/float.js var require_float = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var Type = require_type(); var YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); var YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data)) return false; if (Number.isFinite(parseFloat(data, 10))) return true; return YAML_FLOAT_SPECIAL_PATTERN.test(data); } function constructYamlFloat(data) { let value = data.toLowerCase(); const sign = value[0] === "-" ? -1 : 1; if ("+-".indexOf(value[0]) >= 0) value = value.slice(1); if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; else if (value === ".nan") return NaN; return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { if (isNaN(object)) switch (style) { case "lowercase": return ".nan"; case "uppercase": return ".NAN"; case "camelcase": return ".NaN"; } else if (Number.POSITIVE_INFINITY === object) switch (style) { case "lowercase": return ".inf"; case "uppercase": return ".INF"; case "camelcase": return ".Inf"; } else if (Number.NEGATIVE_INFINITY === object) switch (style) { case "lowercase": return "-.inf"; case "uppercase": return "-.INF"; case "camelcase": return "-.Inf"; } else if (common.isNegativeZero(object)) return "-0.0"; const res = object.toString(10); return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; } function isFloat(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object)); } module.exports = new Type("tag:yaml.org,2002:float", { kind: "scalar", resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: "lowercase" }); })); //#endregion //#region lib/schema/json.js var require_json = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = require_failsafe().extend({ implicit: [ require_null(), require_bool(), require_int(), require_float() ] }); })); //#endregion //#region lib/schema/core.js var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = require_json(); })); //#endregion //#region lib/type/timestamp.js var require_timestamp = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"); var YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"); function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { let fraction = 0; let delta = null; let match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error("Date resolve error"); const year = +match[1]; const month = +match[2] - 1; const day = +match[3]; if (!match[4]) return new Date(Date.UTC(year, month, day)); const hour = +match[4]; const minute = +match[5]; const second = +match[6]; if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) fraction += "0"; fraction = +fraction; } if (match[9]) { const tzHour = +match[10]; const tzMinute = +(match[11] || 0); delta = (tzHour * 60 + tzMinute) * 6e4; if (match[9] === "-") delta = -delta; } const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object) { return object.toISOString(); } module.exports = new Type("tag:yaml.org,2002:timestamp", { kind: "scalar", resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); })); //#endregion //#region lib/type/merge.js var require_merge = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); function resolveYamlMerge(data) { return data === "<<" || data === null; } module.exports = new Type("tag:yaml.org,2002:merge", { kind: "scalar", resolve: resolveYamlMerge }); })); //#endregion //#region lib/type/binary.js var require_binary = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; function resolveYamlBinary(data) { if (data === null) return false; let bitlen = 0; const max = data.length; const map = BASE64_MAP; for (let idx = 0; idx < max; idx++) { const code = map.indexOf(data.charAt(idx)); if (code > 64) continue; if (code < 0) return false; bitlen += 6; } return bitlen % 8 === 0; } function constructYamlBinary(data) { const input = data.replace(/[\r\n=]/g, ""); const max = input.length; const map = BASE64_MAP; let bits = 0; const result = []; for (let idx = 0; idx < max; idx++) { if (idx % 4 === 0 && idx) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } bits = bits << 6 | map.indexOf(input.charAt(idx)); } const tailbits = max % 4 * 6; if (tailbits === 0) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } else if (tailbits === 18) { result.push(bits >> 10 & 255); result.push(bits >> 2 & 255); } else if (tailbits === 12) result.push(bits >> 4 & 255); return new Uint8Array(result); } function representYamlBinary(object) { let result = ""; let bits = 0; const max = object.length; const map = BASE64_MAP; for (let idx = 0; idx < max; idx++) { if (idx % 3 === 0 && idx) { result += map[bits >> 18 & 63]; result += map[bits >> 12 & 63]; result += map[bits >> 6 & 63]; result += map[bits & 63]; } bits = (bits << 8) + object[idx]; } const tail = max % 3; if (tail === 0) { result += map[bits >> 18 & 63]; result += map[bits >> 12 & 63]; result += map[bits >> 6 & 63]; result += map[bits & 63]; } else if (tail === 2) { result += map[bits >> 10 & 63]; result += map[bits >> 4 & 63]; result += map[bits << 2 & 63]; result += map[64]; } else if (tail === 1) { result += map[bits >> 2 & 63]; result += map[bits << 4 & 63]; result += map[64]; result += map[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === "[object Uint8Array]"; } module.exports = new Type("tag:yaml.org,2002:binary", { kind: "scalar", resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); })); //#endregion //#region lib/type/omap.js var require_omap = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var _hasOwnProperty = Object.prototype.hasOwnProperty; var _toString = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; const objectKeys = []; const object = data; for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index]; let pairHasKey = false; if (_toString.call(pair) !== "[object Object]") return false; let pairKey; for (pairKey in pair) if (_hasOwnProperty.call(pair, pairKey)) if (!pairHasKey) pairHasKey = true; else return false; if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } module.exports = new Type("tag:yaml.org,2002:omap", { kind: "sequence", resolve: resolveYamlOmap, construct: constructYamlOmap }); })); //#endregion //#region lib/type/pairs.js var require_pairs = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var _toString = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; const object = data; const result = new Array(object.length); for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index]; if (_toString.call(pair) !== "[object Object]") return false; const keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [keys[0], pair[keys[0]]]; } return true; } function constructYamlPairs(data) { if (data === null) return []; const object = data; const result = new Array(object.length); for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index]; const keys = Object.keys(pair); result[index] = [keys[0], pair[keys[0]]]; } return result; } module.exports = new Type("tag:yaml.org,2002:pairs", { kind: "sequence", resolve: resolveYamlPairs, construct: constructYamlPairs }); })); //#endregion //#region lib/type/set.js var require_set = /* @__PURE__ */ __commonJSMin(((exports, module) => { var Type = require_type(); var _hasOwnProperty = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; const object = data; for (const key in object) if (_hasOwnProperty.call(object, key)) { if (object[key] !== null) return false; } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } module.exports = new Type("tag:yaml.org,2002:set", { kind: "mapping", resolve: resolveYamlSet, construct: constructYamlSet }); })); //#endregion //#region lib/schema/default.js var require_default = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = require_core().extend({ implicit: [require_timestamp(), require_merge()], explicit: [ require_binary(), require_omap(), require_pairs(), require_set() ] }); })); //#endregion //#region lib/loader.js var require_loader = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var YAMLException = require_exception(); var makeSnippet = require_snippet(); var DEFAULT_SCHEMA = require_default(); var _hasOwnProperty = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]{}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/; var PATTERN_TAG_URI = /^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function isEol(c) { return c === 10 || c === 13; } function isWhiteSpace(c) { return c === 9 || c === 32; } function isWsOrEol(c) { return c === 9 || c === 32 || c === 10 || c === 13; } function isFlowIndicator(c) { return c === 44 || c === 91 || c === 93 || c === 123 || c === 125; } function fromHexCode(c) { if (c >= 48 && c <= 57) return c - 48; const lc = c | 32; if (lc >= 97 && lc <= 102) return lc - 97 + 10; return -1; } function escapedHexLen(c) { if (c === 120) return 2; if (c === 117) return 4; if (c === 85) return 8; return 0; } function fromDecimalCode(c) { if (c >= 48 && c <= 57) return c - 48; return -1; } function simpleEscapeSequence(c) { switch (c) { case 48: return "\0"; case 97: return "\x07"; case 98: return "\b"; case 116: return " "; case 9: return " "; case 110: return "\n"; case 118: return "\v"; case 102: return "\f"; case 114: return "\r"; case 101: return "\x1B"; case 32: return " "; case 34: return "\""; case 47: return "/"; case 92: return "\\"; case 78: return "…"; case 95: return "\xA0"; case 76: return "\u2028"; case 80: return "\u2029"; default: return ""; } } function charFromCodepoint(c) { if (c <= 65535) return String.fromCharCode(c); return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320); } function setProperty(object, key, value) { if (key === "__proto__") Object.defineProperty(object, key, { configurable: true, enumerable: true, writable: true, value }); else object[key] = value; } var simpleEscapeCheck = new Array(256); var simpleEscapeMap = new Array(256); for (let i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } function State(input, options) { this.input = input; this.filename = options["filename"] || null; this.schema = options["schema"] || DEFAULT_SCHEMA; this.onWarning = options["onWarning"] || null; this.legacy = options["legacy"] || false; this.json = options["json"] || false; this.listener = options["listener"] || null; this.maxDepth = typeof options["maxDepth"] === "number" ? options["maxDepth"] : 100; this.maxMergeSeqLength = typeof options["maxMergeSeqLength"] === "number" ? options["maxMergeSeqLength"] : 20; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; this.depth = 0; this.firstTabInLine = -1; this.documents = []; this.anchorMapTransactions = []; } function generateError(state, message) { const mark = { name: state.filename, buffer: state.input.slice(0, -1), position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = makeSnippet(mark); return new YAMLException(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) state.onWarning.call(null, generateError(state, message)); } function storeAnchor(state, name, value) { const transactions = state.anchorMapTransactions; if (transactions.length !== 0) { const transaction = transactions[transactions.length - 1]; if (!_hasOwnProperty.call(transaction, name)) transaction[name] = { existed: _hasOwnProperty.call(state.anchorMap, name), value: state.anchorMap[name] }; } state.anchorMap[name] = value; } function beginAnchorTransaction(state) { state.anchorMapTransactions.push(Object.create(null)); } function commitAnchorTransaction(state) { const transaction = state.anchorMapTransactions.pop(); const transactions = state.anchorMapTransactions; if (transactions.length === 0) return; const parent = transactions[transactions.length - 1]; const names = Object.keys(transaction); for (let index = 0, length = names.length; index < length; index += 1) { const name = names[index]; if (!_hasOwnProperty.call(parent, name)) parent[name] = transaction[name]; } } function rollbackAnchorTransaction(state) { const transaction = state.anchorMapTransactions.pop(); const names = Object.keys(transaction); for (let index = names.length - 1; index >= 0; index -= 1) { const entry = transaction[names[index]]; if (entry.existed) state.anchorMap[names[index]] = entry.value; else delete state.anchorMap[names[index]]; } } function snapshotState(state) { return { position: state.position, line: state.line, lineStart: state.lineStart, lineIndent: state.lineIndent, firstTabInLine: state.firstTabInLine, tag: state.tag, anchor: state.anchor, kind: state.kind, result: state.result }; } function restoreState(state, snapshot) { state.position = snapshot.position; state.line = snapshot.line; state.lineStart = snapshot.lineStart; state.lineIndent = snapshot.lineIndent; state.firstTabInLine = snapshot.firstTabInLine; state.tag = snapshot.tag; state.anchor = snapshot.anchor; state.kind = snapshot.kind; state.result = snapshot.result; } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { if (state.version !== null) throwError(state, "duplication of %YAML directive"); if (args.length !== 1) throwError(state, "YAML directive accepts exactly one argument"); const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) throwError(state, "ill-formed argument of the YAML directive"); const major = parseInt(match[1], 10); const minor = parseInt(match[2], 10); if (major !== 1) throwError(state, "unacceptable YAML version of the document"); state.version = args[0]; state.checkLineBreaks = minor < 2; if (minor !== 1 && minor !== 2) throwWarning(state, "unsupported YAML version of the document"); }, TAG: function handleTagDirective(state, name, args) { let prefix; if (args.length !== 2) throwError(state, "TAG directive accepts exactly two arguments"); const handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); if (_hasOwnProperty.call(state.tagMap, handle)) throwError(state, "there is a previously declared suffix for \"" + handle + "\" tag handle"); if (!PATTERN_TAG_URI.test(prefix)) throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, "tag prefix is malformed: " + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { if (start < end) { const _result = state.input.slice(start, end); if (checkJson) for (let _position = 0, _length = _result.length; _position < _length; _position += 1) { const _character = _result.charCodeAt(_position); if (!(_character === 9 || _character >= 32 && _character <= 1114111)) throwError(state, "expected valid JSON character"); } else if (PATTERN_NON_PRINTABLE.test(_result)) throwError(state, "the stream contains non-printable characters"); state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { if (!common.isObject(source)) throwError(state, "cannot merge mappings; the provided source object is unacceptable"); const sourceKeys = Object.keys(source); for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { const key = sourceKeys[index]; if (!_hasOwnProperty.call(destination, key)) { setProperty(destination, key, source[key]); overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) throwError(state, "nested arrays are not supported inside keys"); if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") keyNode[index] = "[object Object]"; } } if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") keyNode = "[object Object]"; keyNode = String(keyNode); if (_result === null) _result = {}; if (keyTag === "tag:yaml.org,2002:merge") if (Array.isArray(valueNode)) { if (valueNode.length > state.maxMergeSeqLength) throwError(state, "merge sequence length exceeded maxMergeSeqLength (" + state.maxMergeSeqLength + ")"); const seen = /* @__PURE__ */ new Set(); for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) { const src = valueNode[index]; if (seen.has(src)) continue; seen.add(src); mergeMappings(state, _result, src, overridableKeys); } } else mergeMappings(state, _result, valueNode, overridableKeys); else { if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, "duplicated mapping key"); } setProperty(_result, keyNode, valueNode); delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { const ch = state.input.charCodeAt(state.position); if (ch === 10) state.position++; else if (ch === 13) { state.position++; if (state.input.charCodeAt(state.position) === 10) state.position++; } else throwError(state, "a line break is expected"); state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { let lineBreaks = 0; let ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (isWhiteSpace(ch)) { if (ch === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position; ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 35) do ch = state.input.charCodeAt(++state.position); while (ch !== 10 && ch !== 13 && ch !== 0); if (isEol(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else break; } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) throwWarning(state, "deficient indentation"); return lineBreaks; } function testDocumentSeparator(state) { let _position = state.position; let ch = state.input.charCodeAt(_position); if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || isWsOrEol(ch)) return true; } return false; } function writeFoldedLines(state, count) { if (count === 1) state.result += " "; else if (count > 1) state.result += common.repeat("\n", count - 1); } function readPlainScalar(state, nodeIndent, withinFlowCollection) { let captureStart; let captureEnd; let hasPendingContent; let _line; let _lineStart; let _lineIndent; const _kind = state.kind; const _result = state.result; let ch = state.input.charCodeAt(state.position); if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) return false; if (ch === 63 || ch === 45) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) return false; } state.kind = "scalar"; state.result = ""; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 58) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) break; } else if (ch === 35) { if (isWsOrEol(state.input.charCodeAt(state.position - 1))) break; } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && isFlowIndicator(ch)) break; else if (isEol(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!isWhiteSpace(ch)) captureEnd = state.position + 1; ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) return true; state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { let captureStart; let captureEnd; let ch = state.input.charCodeAt(state.position); if (ch !== 39) return false; state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) if (ch === 39) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 39) { captureStart = state.position; state.position++; captureEnd = state.position; } else return true; } else if (isEol(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a single quoted scalar"); else { state.position++; if (!isWhiteSpace(ch)) captureEnd = state.position; } throwError(state, "unexpected end of the stream within a single quoted scalar"); } function readDoubleQuotedScalar(state, nodeIndent) { let captureStart; let captureEnd; let tmp; let ch = state.input.charCodeAt(state.position); if (ch !== 34) return false; state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) if (ch === 34) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 92) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (isEol(ch)) skipSeparationSpace(state, false, nodeIndent); else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { let hexLength = tmp; let hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) hexResult = (hexResult << 4) + tmp; else throwError(state, "expected hexadecimal character"); } state.result += charFromCodepoint(hexResult); state.position++; } else throwError(state, "unknown escape sequence"); captureStart = captureEnd = state.position; } else if (isEol(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a double quoted scalar"); else { state.position++; if (!isWhiteSpace(ch)) captureEnd = state.position; } throwError(state, "unexpected end of the stream within a double quoted scalar"); } function readFlowCollection(state, nodeIndent) { let readNext = true; let _line; let _lineStart; let _pos; const _tag = state.tag; let _result; const _anchor = state.anchor; let terminator; let isPair; let isExplicitPair; let isMapping; const overridableKeys = Object.create(null); let keyNode; let keyTag; let valueNode; let ch = state.input.charCodeAt(state.position); if (ch === 91) { terminator = 93; isMapping = false; _result = []; } else if (ch === 123) { terminator = 125; isMapping = true; _result = {}; } else return false; if (state.anchor !== null) storeAnchor(state, state.anchor, _result); ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? "mapping" : "sequence"; state.result = _result; return true; } else if (!readNext) throwError(state, "missed comma between flow collection entries"); else if (ch === 44) throwError(state, "expected the node content, but found ','"); keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 63) { if (isWsOrEol(state.input.charCodeAt(state.position + 1))) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 58) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); else if (isPair) _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); else _result.push(keyNode); skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 44) { readNext = true; ch = state.input.charCodeAt(++state.position); } else readNext = false; } throwError(state, "unexpected end of the stream within a flow collection"); } function readBlockScalar(state, nodeIndent) { let folding; let chomping = CHOMPING_CLIP; let didReadContent = false; let detectedIndent = false; let textIndent = nodeIndent; let emptyLines = 0; let atMoreIndented = false; let tmp; let ch = state.input.charCodeAt(state.position); if (ch === 124) folding = false; else if (ch === 62) folding = true; else return false; state.kind = "scalar"; state.result = ""; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 43 || ch === 45) if (CHOMPING_CLIP === chomping) chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP; else throwError(state, "repeat of a chomping mode identifier"); else if ((tmp = fromDecimalCode(ch)) >= 0) if (tmp === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else throwError(state, "repeat of an indentation width identifier"); else break; } if (isWhiteSpace(ch)) { do ch = state.input.charCodeAt(++state.position); while (isWhiteSpace(ch)); if (ch === 35) do ch = state.input.charCodeAt(++state.position); while (!isEol(ch) && ch !== 0); } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) textIndent = state.lineIndent; if (isEol(ch)) { emptyLines++; continue; } if (!detectedIndent && textIndent === 0) throwError(state, "missing indentation for block scalar"); if (state.lineIndent < textIndent) { if (chomping === CHOMPING_KEEP) state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); else if (chomping === CHOMPING_CLIP) { if (didReadContent) state.result += "\n"; } break; } if (folding) if (isWhiteSpace(ch)) { atMoreIndented = true; state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat("\n", emptyLines + 1); } else if (emptyLines === 0) { if (didReadContent) state.result += " "; } else state.result += common.repeat("\n", emptyLines); else state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); didReadContent = true; detectedIndent = true; emptyLines = 0; const captureStart = state.position; while (!isEol(ch) && ch !== 0) ch = state.input.charCodeAt(++state.position); captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { const _tag = state.tag; const _anchor = state.anchor; const _result = []; let detected = false; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) storeAnchor(state, state.anchor, _result); let ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } if (ch !== 45) break; if (!isWsOrEol(state.input.charCodeAt(state.position + 1))) break; detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } const _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a sequence entry"); else if (state.lineIndent < nodeIndent) break; } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "sequence"; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { let allowCompact; let _keyLine; let _keyLineStart; let _keyPos; const _tag = state.tag; const _anchor = state.anchor; const _result = {}; const overridableKeys = Object.create(null); let keyTag = null; let keyNode = null; let valueNode = null; let atExplicitKey = false; let detected = false; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) storeAnchor(state, state.anchor, _result); let ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } const following = state.input.charCodeAt(state.position + 1); const _line = state.line; if ((ch === 63 || ch === 58) && isWsOrEol(following)) { if (ch === 63) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { atExplicitKey = false; allowCompact = true; } else throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"); state.position += 1; ch = following; } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break; if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position); if (ch === 58) { ch = state.input.charCodeAt(++state.position); if (!isWsOrEol(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) throwError(state, "can not read an implicit mapping pair; a colon is missed"); else { state.tag = _tag; state.anchor = _anchor; return true; } } else if (detected) throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); else { state.tag = _tag; state.anchor = _anchor; return true; } } if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) if (atExplicitKey) keyNode = state.result; else valueNode = state.result; if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a mapping entry"); else if (state.lineIndent < nodeIndent) break; } if (atExplicitKey) storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "mapping"; state.result = _result; } return detected; } function readTagProperty(state) { let isVerbatim = false; let isNamed = false; let tagHandle; let tagName; let ch = state.input.charCodeAt(state.position); if (ch !== 33) return false; if (state.tag !== null) throwError(state, "duplication of a tag property"); ch = state.input.charCodeAt(++state.position); if (ch === 60) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 33) { isNamed = true; tagHandle = "!!"; ch = state.input.charCodeAt(++state.position); } else tagHandle = "!"; let _position = state.position; if (isVerbatim) { do ch = state.input.charCodeAt(++state.position); while (ch !== 0 && ch !== 62); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else throwError(state, "unexpected end of the stream within a verbatim tag"); } else { while (ch !== 0 && !isWsOrEol(ch)) { if (ch === 33) if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters"); isNamed = true; _position = state.position + 1; } else throwError(state, "tag suffix cannot contain exclamation marks"); ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, "tag suffix cannot contain flow indicator characters"); } if (tagName && !PATTERN_TAG_URI.test(tagName)) throwError(state, "tag name cannot contain such characters: " + tagName); try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, "tag name is malformed: " + tagName); } if (isVerbatim) state.tag = tagName; else if (_hasOwnProperty.call(state.tagMap, tagHandle)) state.tag = state.tagMap[tagHandle] + tagName; else if (tagHandle === "!") state.tag = "!" + tagName; else if (tagHandle === "!!") state.tag = "tag:yaml.org,2002:" + tagName; else throwError(state, "undeclared tag handle \"" + tagHandle + "\""); return true; } function readAnchorProperty(state) { let ch = state.input.charCodeAt(state.position); if (ch !== 38) return false; if (state.anchor !== null) throwError(state, "duplication of an anchor property"); ch = state.input.charCodeAt(++state.position); const _position = state.position; while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) ch = state.input.charCodeAt(++state.position); if (state.position === _position) throwError(state, "name of an anchor node must contain at least one character"); state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { let ch = state.input.charCodeAt(state.position); if (ch !== 42) return false; ch = state.input.charCodeAt(++state.position); const _position = state.position; while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) ch = state.input.charCodeAt(++state.position); if (state.position === _position) throwError(state, "name of an alias node must contain at least one character"); const alias = state.input.slice(_position, state.position); if (!_hasOwnProperty.call(state.anchorMap, alias)) throwError(state, "unidentified alias \"" + alias + "\""); state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function tryReadBlockMappingFromProperty(state, propertyStart, nodeIndent, flowIndent) { const fallbackState = snapshotState(state); beginAnchorTransaction(state); restoreState(state, propertyStart); state.tag = null; state.anchor = null; state.kind = null; state.result = null; if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === "mapping") { commitAnchorTransaction(state); return true; } rollbackAnchorTransaction(state); restoreState(state, fallbackState); return false; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { let allowBlockScalars; let allowBlockCollections; let indentStatus = 1; let atNewLine = false; let hasContent = false; let propertyStart = null; let type; let flowIndent; let blockIndent; if (state.depth >= state.maxDepth) throwError(state, "nesting exceeded maxDepth (" + state.maxDepth + ")"); state.depth += 1; if (state.listener !== null) state.listener("open", state); state.tag = null; state.anchor = null; state.kind = null; state.result = null; const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext; if (allowToSeek) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; if (state.lineIndent > parentIndent) indentStatus = 1; else if (state.lineIndent === parentIndent) indentStatus = 0; else if (state.lineIndent < parentIndent) indentStatus = -1; } } if (indentStatus === 1) while (true) { const ch = state.input.charCodeAt(state.position); const propertyState = snapshotState(state); if (atNewLine && (ch === 33 && state.tag !== null || ch === 38 && state.anchor !== null)) break; if (!readTagProperty(state) && !readAnchorProperty(state)) break; if (propertyStart === null) propertyStart = propertyState; if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) indentStatus = 1; else if (state.lineIndent === parentIndent) indentStatus = 0; else if (state.lineIndent < parentIndent) indentStatus = -1; } else allowBlockCollections = false; } if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact; if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) flowIndent = parentIndent; else flowIndent = parentIndent + 1; blockIndent = state.position - state.lineStart; if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) hasContent = true; else { const ch = state.input.charCodeAt(state.position); if (propertyStart !== null && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62 && tryReadBlockMappingFromProperty(state, propertyStart, propertyStart.position - propertyStart.lineStart, flowIndent)) hasContent = true; else if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) hasContent = true; else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) throwError(state, "alias node should not have any properties"); } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) state.tag = "?"; } if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); } else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } if (state.tag === null) { if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); } else if (state.tag === "?") { if (state.result !== null && state.kind !== "scalar") throwError(state, "unacceptable node kind for ! tag; it should be \"scalar\", not \"" + state.kind + "\""); for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); break; } } } else if (state.tag !== "!") { if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) type = state.typeMap[state.kind || "fallback"][state.tag]; else { type = null; const typeList = state.typeMap.multi[state.kind || "fallback"]; for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex]; break; } } if (!type) throwError(state, "unknown tag !<" + state.tag + ">"); if (state.result !== null && type.kind !== state.kind) throwError(state, "unacceptable node kind for !<" + state.tag + "> tag; it should be \"" + type.kind + "\", not \"" + state.kind + "\""); if (!type.resolve(state.result, state.tag)) throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag"); else { state.result = type.construct(state.result, state.tag); if (state.anchor !== null) storeAnchor(state, state.anchor, state.result); } } if (state.listener !== null) state.listener("close", state); state.depth -= 1; return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { const documentStart = state.position; let hasDirectives = false; let ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = Object.create(null); state.anchorMap = Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 37) break; hasDirectives = true; ch = state.input.charCodeAt(++state.position); let _position = state.position; while (ch !== 0 && !isWsOrEol(ch)) ch = state.input.charCodeAt(++state.position); const directiveName = state.input.slice(_position, state.position); const directiveArgs = []; if (directiveName.length < 1) throwError(state, "directive name must not be less than one character in length"); while (ch !== 0) { while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position); if (ch === 35) { do ch = state.input.charCodeAt(++state.position); while (ch !== 0 && !isEol(ch)); break; } if (isEol(ch)) break; _position = state.position; while (ch !== 0 && !isWsOrEol(ch)) ch = state.input.charCodeAt(++state.position); directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty.call(directiveHandlers, directiveName)) directiveHandlers[directiveName](state, directiveName, directiveArgs); else throwWarning(state, "unknown document directive \"" + directiveName + "\""); } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) throwError(state, "directives end mark is expected"); composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) throwWarning(state, "non-ASCII line breaks are interpreted as content"); state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 46) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < state.length - 1) throwError(state, "end of the stream or a document separator is expected"); } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) input += "\n"; if (input.charCodeAt(0) === 65279) input = input.slice(1); } const state = new State(input, options); const nullpos = input.indexOf("\0"); if (nullpos !== -1) { state.position = nullpos; throwError(state, "null byte is not allowed in input"); } state.input += "\0"; while (state.input.charCodeAt(state.position) === 32) { state.lineIndent += 1; state.position += 1; } while (state.position < state.length - 1) readDocument(state); return state.documents; } function loadAll(input, iterator, options) { if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") { options = iterator; iterator = null; } const documents = loadDocuments(input, options); if (typeof iterator !== "function") return documents; for (let index = 0, length = documents.length; index < length; index += 1) iterator(documents[index]); } function load(input, options) { const documents = loadDocuments(input, options); if (documents.length === 0) return; else if (documents.length === 1) return documents[0]; throw new YAMLException("expected a single document in the stream, but found more"); } module.exports.loadAll = loadAll; module.exports.load = load; })); //#endregion //#region lib/dumper.js var require_dumper = /* @__PURE__ */ __commonJSMin(((exports, module) => { var common = require_common(); var YAMLException = require_exception(); var DEFAULT_SCHEMA = require_default(); var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 65279; var CHAR_TAB = 9; var CHAR_LINE_FEED = 10; var CHAR_CARRIAGE_RETURN = 13; var CHAR_SPACE = 32; var CHAR_EXCLAMATION = 33; var CHAR_DOUBLE_QUOTE = 34; var CHAR_SHARP = 35; var CHAR_PERCENT = 37; var CHAR_AMPERSAND = 38; var CHAR_SINGLE_QUOTE = 39; var CHAR_ASTERISK = 42; var CHAR_COMMA = 44; var CHAR_MINUS = 45; var CHAR_COLON = 58; var CHAR_EQUALS = 61; var CHAR_GREATER_THAN = 62; var CHAR_QUESTION = 63; var CHAR_COMMERCIAL_AT = 64; var CHAR_LEFT_SQUARE_BRACKET = 91; var CHAR_RIGHT_SQUARE_BRACKET = 93; var CHAR_GRAVE_ACCENT = 96; var CHAR_LEFT_CURLY_BRACKET = 123; var CHAR_VERTICAL_LINE = 124; var CHAR_RIGHT_CURLY_BRACKET = 125; var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0] = "\\0"; ESCAPE_SEQUENCES[7] = "\\a"; ESCAPE_SEQUENCES[8] = "\\b"; ESCAPE_SEQUENCES[9] = "\\t"; ESCAPE_SEQUENCES[10] = "\\n"; ESCAPE_SEQUENCES[11] = "\\v"; ESCAPE_SEQUENCES[12] = "\\f"; ESCAPE_SEQUENCES[13] = "\\r"; ESCAPE_SEQUENCES[27] = "\\e"; ESCAPE_SEQUENCES[34] = "\\\""; ESCAPE_SEQUENCES[92] = "\\\\"; ESCAPE_SEQUENCES[133] = "\\N"; ESCAPE_SEQUENCES[160] = "\\_"; ESCAPE_SEQUENCES[8232] = "\\L"; ESCAPE_SEQUENCES[8233] = "\\P"; var DEPRECATED_BOOLEANS_SYNTAX = [ "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", "n", "N", "no", "No", "NO", "off", "Off", "OFF" ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema, map) { if (map === null) return {}; const result = {}; const keys = Object.keys(map); for (let index = 0, length = keys.length; index < length; index += 1) { let tag = keys[index]; let style = String(map[tag]); if (tag.slice(0, 2) === "!!") tag = "tag:yaml.org,2002:" + tag.slice(2); const type = schema.compiledTypeMap["fallback"][tag]; if (type && _hasOwnProperty.call(type.styleAliases, style)) style = type.styleAliases[style]; result[tag] = style; } return result; } function encodeHex(character) { let handle; let length; const string = character.toString(16).toUpperCase(); if (character <= 255) { handle = "x"; length = 2; } else if (character <= 65535) { handle = "u"; length = 4; } else if (character <= 4294967295) { handle = "U"; length = 8; } else throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF"); return "\\" + handle + common.repeat("0", length - string.length) + string; } var QUOTING_TYPE_SINGLE = 1; var QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options["schema"] || DEFAULT_SCHEMA; this.indent = Math.max(1, options["indent"] || 2); this.noArrayIndent = options["noArrayIndent"] || false; this.skipInvalid = options["skipInvalid"] || false; this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"]; this.styleMap = compileStyleMap(this.schema, options["styles"] || null); this.sortKeys = options["sortKeys"] || false; this.lineWidth = options["lineWidth"] || 80; this.noRefs = options["noRefs"] || false; this.noCompatMode = options["noCompatMode"] || false; this.condenseFlow = options["condenseFlow"] || false; this.quotingType = options["quotingType"] === "\"" ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options["forceQuotes"] || false; this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ""; this.duplicates = []; this.usedDuplicates = null; } function indentString(string, spaces) { const ind = common.repeat(" ", spaces); let position = 0; let result = ""; const length = string.length; while (position < length) { let line; const next = string.indexOf("\n", position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== "\n") result += ind; result += line; } return result; } function generateNextLine(state, level) { return "\n" + common.repeat(" ", state.indent * level); } function testImplicitResolving(state, str) { for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) if (state.implicitTypes[index].resolve(str)) return true; return false; } function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } function isPrintable(c) { return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111; } function isNsCharOrWhitespace(c) { return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } function isPlainSafe(c, prev, inblock) { const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar; } function isPlainSafeFirst(c) { return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } function isPlainSafeLast(c) { return !isWhitespace(c) && c !== CHAR_COLON; } function codePointAt(string, pos) { const first = string.charCodeAt(pos); let second; if (first >= 55296 && first <= 56319 && pos + 1 < string.length) { second = string.charCodeAt(pos + 1); if (second >= 56320 && second <= 57343) return (first - 55296) * 1024 + second - 56320 + 65536; } return first; } function needIndentIndicator(string) { return /^\n* /.test(string); } var STYLE_PLAIN = 1; var STYLE_SINGLE = 2; var STYLE_LITERAL = 3; var STYLE_FOLDED = 4; var STYLE_DOUBLE = 5; function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { let i; let char = 0; let prevChar = null; let hasLineBreak = false; let hasFoldableLine = false; const shouldTrackWidth = lineWidth !== -1; let previousLineBreak = -1; let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1)); if (singleLineOnly || forceQuotes) for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string, i); if (!isPrintable(char)) return STYLE_DOUBLE; plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } else { for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string, i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " "; previousLineBreak = i; } } else if (!isPrintable(char)) return STYLE_DOUBLE; plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " "; } if (!hasLineBreak && !hasFoldableLine) { if (plain && !forceQuotes && !testAmbiguousType(string)) return STYLE_PLAIN; return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } if (indentPerLevel > 9 && needIndentIndicator(string)) return STYLE_DOUBLE; if (!forceQuotes) return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } function writeScalar(state, string, level, iskey, inblock) { state.dump = function() { if (string.length === 0) return state.quotingType === QUOTING_TYPE_DOUBLE ? "\"\"" : "''"; if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) return state.quotingType === QUOTING_TYPE_DOUBLE ? "\"" + string + "\"" : "'" + string + "'"; } const indent = state.indent * Math.max(1, level); const lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); const singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel; function testAmbiguity(string) { return testImplicitResolving(state, string); } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { case STYLE_PLAIN: return string; case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)); case STYLE_FOLDED: return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); case STYLE_DOUBLE: return "\"" + escapeString(string, lineWidth) + "\""; default: throw new YAMLException("impossible error: invalid scalar style"); } }(); } function blockHeader(string, indentPerLevel) { const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ""; const clip = string[string.length - 1] === "\n"; return indentIndicator + (clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-") + "\n"; } function dropEndingNewline(string) { return string[string.length - 1] === "\n" ? string.slice(0, -1) : string; } function foldString(string, width) { const lineRe = /(\n+)([^\n]*)/g; let result = function() { let nextLF = string.indexOf("\n"); nextLF = nextLF !== -1 ? nextLF : string.length; lineRe.lastIndex = nextLF; return foldLine(string.slice(0, nextLF), width); }(); let prevMoreIndented = string[0] === "\n" || string[0] === " "; let moreIndented; let match; while (match = lineRe.exec(string)) { const prefix = match[1]; const line = match[2]; moreIndented = line[0] === " "; result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } function foldLine(line, width) { if (line === "" || line[0] === " ") return line; const breakRe = / [^ ]/g; let match; let start = 0; let end; let curr = 0; let next = 0; let result = ""; while (match = breakRe.exec(line)) { next = match.index; if (next - start > width) { end = curr > start ? curr : next; result += "\n" + line.slice(start, end); start = end + 1; } curr = next; } result += "\n"; if (line.length - start > width && curr > start) result += line.slice(start, curr) + "\n" + line.slice(curr + 1); else result += line.slice(start); return result.slice(1); } function escapeString(string) { let result = ""; let char = 0; for (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) { char = codePointAt(string, i); const escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string[i]; if (char >= 65536) result += string[i + 1]; } else result += escapeSeq || encodeHex(char); } return result; } function writeFlowSequence(state, level, object) { let _result = ""; const _tag = state.tag; for (let index = 0, length = object.length; index < length; index += 1) { let value = object[index]; if (state.replacer) value = state.replacer.call(object, String(index), value); if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) { if (_result !== "") _result += "," + (!state.condenseFlow ? " " : ""); _result += state.dump; } } state.tag = _tag; state.dump = "[" + _result + "]"; } function writeBlockSequence(state, level, object, compact) { let _result = ""; const _tag = state.tag; for (let index = 0, length = object.length; index < length; index += 1) { let value = object[index]; if (state.replacer) value = state.replacer.call(object, String(index), value); if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) { if (!compact || _result !== "") _result += generateNextLine(state, level); if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) _result += "-"; else _result += "- "; _result += state.dump; } } state.tag = _tag; state.dump = _result || "[]"; } function writeFlowMapping(state, level, object) { let _result = ""; const _tag = state.tag; const objectKeyList = Object.keys(object); for (let index = 0, length = objectKeyList.length; index < length; index += 1) { let pairBuffer = ""; if (_result !== "") pairBuffer += ", "; if (state.condenseFlow) pairBuffer += "\""; const objectKey = objectKeyList[index]; let objectValue = object[objectKey]; if (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue); if (!writeNode(state, level, objectKey, false, false)) continue; if (state.dump.length > 1024) pairBuffer += "? "; pairBuffer += state.dump + (state.condenseFlow ? "\"" : "") + ":" + (state.condenseFlow ? "" : " "); if (!writeNode(state, level, objectValue, false, false)) continue; pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = "{" + _result + "}"; } function writeBlockMapping(state, level, object, compact) { let _result = ""; const _tag = state.tag; const objectKeyList = Object.keys(object); if (state.sortKeys === true) objectKeyList.sort(); else if (typeof state.sortKeys === "function") objectKeyList.sort(state.sortKeys); else if (state.sortKeys) throw new YAMLException("sortKeys must be a boolean or a function"); for (let index = 0, length = objectKeyList.length; index < length; index += 1) { let pairBuffer = ""; if (!compact || _result !== "") pairBuffer += generateNextLine(state, level); const objectKey = objectKeyList[index]; let objectValue = object[objectKey]; if (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue); if (!writeNode(state, level + 1, objectKey, true, true, true)) continue; const explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024; if (explicitPair) if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) pairBuffer += "?"; else pairBuffer += "? "; pairBuffer += state.dump; if (explicitPair) pairBuffer += generateNextLine(state, level); if (!writeNode(state, level + 1, objectValue, true, explicitPair)) continue; if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) pairBuffer += ":"; else pairBuffer += ": "; pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = _result || "{}"; } function detectType(state, object, explicit) { const typeList = explicit ? state.explicitTypes : state.implicitTypes; for (let index = 0, length = typeList.length; index < length; index += 1) { const type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) { if (explicit) if (type.multi && type.representName) state.tag = type.representName(object); else state.tag = type.tag; else state.tag = "?"; if (type.represent) { const style = state.styleMap[type.tag] || type.defaultStyle; let _result; if (_toString.call(type.represent) === "[object Function]") _result = type.represent(object, style); else if (_hasOwnProperty.call(type.represent, style)) _result = type.represent[style](object, style); else throw new YAMLException("!<" + type.tag + "> tag resolver accepts not \"" + style + "\" style"); state.dump = _result; } return true; } } return false; } function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) detectType(state, object, true); const type = _toString.call(state.dump); const inblock = block; if (block) block = state.flowLevel < 0 || state.flowLevel > level; const objectOrArray = type === "[object Object]" || type === "[object Array]"; let duplicateIndex; let duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) compact = false; if (duplicate && state.usedDuplicates[duplicateIndex]) state.dump = "*ref_" + duplicateIndex; else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) state.usedDuplicates[duplicateIndex] = true; if (type === "[object Object]") if (block && Object.keys(state.dump).length !== 0) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) state.dump = "&ref_" + duplicateIndex + state.dump; } else { writeFlowMapping(state, level, state.dump); if (duplicate) state.dump = "&ref_" + duplicateIndex + " " + state.dump; } else if (type === "[object Array]") if (block && state.dump.length !== 0) { if (state.noArrayIndent && !isblockseq && level > 0) writeBlockSequence(state, level - 1, state.dump, compact); else writeBlockSequence(state, level, state.dump, compact); if (duplicate) state.dump = "&ref_" + duplicateIndex + state.dump; } else { writeFlowSequence(state, level, state.dump); if (duplicate) state.dump = "&ref_" + duplicateIndex + " " + state.dump; } else if (type === "[object String]") { if (state.tag !== "?") writeScalar(state, state.dump, level, iskey, inblock); } else if (type === "[object Undefined]") return false; else { if (state.skipInvalid) return false; throw new YAMLException("unacceptable kind of an object to dump " + type); } if (state.tag !== null && state.tag !== "?") { let tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21"); if (state.tag[0] === "!") tagStr = "!" + tagStr; else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") tagStr = "!!" + tagStr.slice(18); else tagStr = "!<" + tagStr + ">"; state.dump = tagStr + " " + state.dump; } } return true; } function getDuplicateReferences(object, state) { const objects = []; const duplicatesIndexes = []; inspectNode(object, objects, duplicatesIndexes); const length = duplicatesIndexes.length; for (let index = 0; index < length; index += 1) state.duplicates.push(objects[duplicatesIndexes[index]]); state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { if (object !== null && typeof object === "object") { const index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) duplicatesIndexes.push(index); } else { objects.push(object); if (Array.isArray(object)) for (let i = 0, length = object.length; i < length; i += 1) inspectNode(object[i], objects, duplicatesIndexes); else { const objectKeyList = Object.keys(object); for (let i = 0, length = objectKeyList.length; i < length; i += 1) inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes); } } } } function dump(input, options) { options = options || {}; const state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); let value = input; if (state.replacer) value = state.replacer.call({ "": value }, "", value); if (writeNode(state, 0, value, true, true)) return state.dump + "\n"; return ""; } module.exports.dump = dump; })); //#endregion //#region lib/index_vite_proxy.tmp.mjs var import_js_yaml = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => { var loader = require_loader(); var dumper = require_dumper(); function renamed(from, to) { return function() { throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default."); }; } module.exports.Type = require_type(); module.exports.Schema = require_schema(); module.exports.FAILSAFE_SCHEMA = require_failsafe(); module.exports.JSON_SCHEMA = require_json(); module.exports.CORE_SCHEMA = require_core(); module.exports.DEFAULT_SCHEMA = require_default(); module.exports.load = loader.load; module.exports.loadAll = loader.loadAll; module.exports.dump = dumper.dump; module.exports.YAMLException = require_exception(); module.exports.types = { binary: require_binary(), float: require_float(), map: require_map(), null: require_null(), pairs: require_pairs(), set: require_set(), timestamp: require_timestamp(), bool: require_bool(), int: require_int(), merge: require_merge(), omap: require_omap(), seq: require_seq(), str: require_str() }; module.exports.safeLoad = renamed("safeLoad", "load"); module.exports.safeLoadAll = renamed("safeLoadAll", "loadAll"); module.exports.safeDump = renamed("safeDump", "dump"); })))(), 1); var { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump } = import_js_yaml.default; var index_vite_proxy_tmp_default = import_js_yaml.default; //#endregion export { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, index_vite_proxy_tmp_default as default, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types }; //# sourceMappingURL=js-yaml.mjs.map{"version":3,"file":"js-yaml.mjs","names":["yaml"],"sources":["../lib/common.js","../lib/exception.js","../lib/snippet.js","../lib/type.js","../lib/schema.js","../lib/type/str.js","../lib/type/seq.js","../lib/type/map.js","../lib/schema/failsafe.js","../lib/type/null.js","../lib/type/bool.js","../lib/type/int.js","../lib/type/float.js","../lib/schema/json.js","../lib/schema/core.js","../lib/type/timestamp.js","../lib/type/merge.js","../lib/type/binary.js","../lib/type/omap.js","../lib/type/pairs.js","../lib/type/set.js","../lib/schema/default.js","../lib/loader.js","../lib/dumper.js","../index.js","../lib/index_vite_proxy.tmp.mjs"],"sourcesContent":["'use strict'\n\nfunction isNothing (subject) {\n return (typeof subject === 'undefined') || (subject === null)\n}\n\nfunction isObject (subject) {\n return (typeof subject === 'object') && (subject !== null)\n}\n\nfunction toArray (sequence) {\n if (Array.isArray(sequence)) return sequence\n else if (isNothing(sequence)) return []\n\n return [sequence]\n}\n\nfunction extend (target, source) {\n if (source) {\n const sourceKeys = Object.keys(source)\n\n for (let index = 0, length = sourceKeys.length; index < length; index += 1) {\n const key = sourceKeys[index]\n target[key] = source[key]\n }\n }\n\n return target\n}\n\nfunction repeat (string, count) {\n let result = ''\n\n for (let cycle = 0; cycle < count; cycle += 1) {\n result += string\n }\n\n return result\n}\n\nfunction isNegativeZero (number) {\n return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number)\n}\n\nmodule.exports.isNothing = isNothing\nmodule.exports.isObject = isObject\nmodule.exports.toArray = toArray\nmodule.exports.repeat = repeat\nmodule.exports.isNegativeZero = isNegativeZero\nmodule.exports.extend = extend\n","// YAML error class. http://stackoverflow.com/questions/8458984\n//\n'use strict'\n\nfunction formatError (exception, compact) {\n let where = ''\n const message = exception.reason || '(unknown reason)'\n\n if (!exception.mark) return message\n\n if (exception.mark.name) {\n where += 'in \"' + exception.mark.name + '\" '\n }\n\n where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'\n\n if (!compact && exception.mark.snippet) {\n where += '\\n\\n' + exception.mark.snippet\n }\n\n return message + ' ' + where\n}\n\nfunction YAMLException (reason, mark) {\n // Super constructor\n Error.call(this)\n\n this.name = 'YAMLException'\n this.reason = reason\n this.mark = mark\n this.message = formatError(this, false)\n\n // Include stack trace in error object\n if (Error.captureStackTrace) {\n // Chrome and NodeJS\n Error.captureStackTrace(this, this.constructor)\n } else {\n // FF, IE 10+ and Safari 6+. Fallback for others\n this.stack = (new Error()).stack || ''\n }\n}\n\n// Inherit from Error\nYAMLException.prototype = Object.create(Error.prototype)\nYAMLException.prototype.constructor = YAMLException\n\nYAMLException.prototype.toString = function toString (compact) {\n return this.name + ': ' + formatError(this, compact)\n}\n\nmodule.exports = YAMLException\n","'use strict'\n\nconst common = require('./common')\n\n// get snippet for a single line, respecting maxLength\nfunction getLine (buffer, lineStart, lineEnd, position, maxLineLength) {\n let head = ''\n let tail = ''\n const maxHalfLength = Math.floor(maxLineLength / 2) - 1\n\n if (position - lineStart > maxHalfLength) {\n head = ' ... '\n lineStart = position - maxHalfLength + head.length\n }\n\n if (lineEnd - position > maxHalfLength) {\n tail = ' ...'\n lineEnd = position + maxHalfLength - tail.length\n }\n\n return {\n str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, '→') + tail,\n pos: position - lineStart + head.length // relative position\n }\n}\n\nfunction padStart (string, max) {\n return common.repeat(' ', max - string.length) + string\n}\n\nfunction makeSnippet (mark, options) {\n options = Object.create(options || null)\n\n if (!mark.buffer) return null\n\n if (!options.maxLength) options.maxLength = 79\n if (typeof options.indent !== 'number') options.indent = 1\n if (typeof options.linesBefore !== 'number') options.linesBefore = 3\n if (typeof options.linesAfter !== 'number') options.linesAfter = 2\n\n const re = /\\r?\\n|\\r|\\0/g\n const lineStarts = [0]\n const lineEnds = []\n let match\n let foundLineNo = -1\n\n while ((match = re.exec(mark.buffer))) {\n lineEnds.push(match.index)\n lineStarts.push(match.index + match[0].length)\n\n if (mark.position <= match.index && foundLineNo < 0) {\n foundLineNo = lineStarts.length - 2\n }\n }\n\n if (foundLineNo < 0) foundLineNo = lineStarts.length - 1\n\n let result = ''\n const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length\n const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3)\n\n for (let i = 1; i <= options.linesBefore; i++) {\n if (foundLineNo - i < 0) break\n const line = getLine(\n mark.buffer,\n lineStarts[foundLineNo - i],\n lineEnds[foundLineNo - i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n maxLineLength\n )\n result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n' + result\n }\n\n const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength)\n result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n'\n result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\\n'\n\n for (let i = 1; i <= options.linesAfter; i++) {\n if (foundLineNo + i >= lineEnds.length) break\n const line = getLine(\n mark.buffer,\n lineStarts[foundLineNo + i],\n lineEnds[foundLineNo + i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n maxLineLength\n )\n result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n'\n }\n\n return result.replace(/\\n$/, '')\n}\n\nmodule.exports = makeSnippet\n","'use strict'\n\nconst YAMLException = require('./exception')\n\nconst TYPE_CONSTRUCTOR_OPTIONS = [\n 'kind',\n 'multi',\n 'resolve',\n 'construct',\n 'instanceOf',\n 'predicate',\n 'represent',\n 'representName',\n 'defaultStyle',\n 'styleAliases'\n]\n\nconst YAML_NODE_KINDS = [\n 'scalar',\n 'sequence',\n 'mapping'\n]\n\nfunction compileStyleAliases (map) {\n const result = {}\n\n if (map !== null) {\n Object.keys(map).forEach(function (style) {\n map[style].forEach(function (alias) {\n result[String(alias)] = style\n })\n })\n }\n\n return result\n}\n\nfunction Type (tag, options) {\n options = options || {}\n\n Object.keys(options).forEach(function (name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new YAMLException('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.')\n }\n })\n\n // TODO: Add tag format check.\n this.options = options // keep original options in case user wants to extend this type later\n this.tag = tag\n this.kind = options['kind'] || null\n this.resolve = options['resolve'] || function () { return true }\n this.construct = options['construct'] || function (data) { return data }\n this.instanceOf = options['instanceOf'] || null\n this.predicate = options['predicate'] || null\n this.represent = options['represent'] || null\n this.representName = options['representName'] || null\n this.defaultStyle = options['defaultStyle'] || null\n this.multi = options['multi'] || false\n this.styleAliases = compileStyleAliases(options['styleAliases'] || null)\n\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new YAMLException('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.')\n }\n}\n\nmodule.exports = Type\n","'use strict'\n\nconst YAMLException = require('./exception')\nconst Type = require('./type')\n\nfunction compileList (schema, name) {\n const result = []\n\n schema[name].forEach(function (currentType) {\n let newIndex = result.length\n\n result.forEach(function (previousType, previousIndex) {\n if (previousType.tag === currentType.tag &&\n previousType.kind === currentType.kind &&\n previousType.multi === currentType.multi) {\n newIndex = previousIndex\n }\n })\n\n result[newIndex] = currentType\n })\n\n return result\n}\n\nfunction compileMap (/* lists... */) {\n const result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {},\n multi: {\n scalar: [],\n sequence: [],\n mapping: [],\n fallback: []\n }\n }\n function collectType (type) {\n if (type.multi) {\n result.multi[type.kind].push(type)\n result.multi['fallback'].push(type)\n } else {\n result[type.kind][type.tag] = result['fallback'][type.tag] = type\n }\n }\n\n for (let index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType)\n }\n return result\n}\n\nfunction Schema (definition) {\n return this.extend(definition)\n}\n\nSchema.prototype.extend = function extend (definition) {\n let implicit = []\n let explicit = []\n\n if (definition instanceof Type) {\n // Schema.extend(type)\n explicit.push(definition)\n } else if (Array.isArray(definition)) {\n // Schema.extend([ type1, type2, ... ])\n explicit = explicit.concat(definition)\n } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })\n if (definition.implicit) implicit = implicit.concat(definition.implicit)\n if (definition.explicit) explicit = explicit.concat(definition.explicit)\n } else {\n throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' +\n 'or a schema definition ({ implicit: [...], explicit: [...] })')\n }\n\n implicit.forEach(function (type) {\n if (!(type instanceof Type)) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.')\n }\n\n if (type.loadKind && type.loadKind !== 'scalar') {\n throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.')\n }\n\n if (type.multi) {\n throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.')\n }\n })\n\n explicit.forEach(function (type) {\n if (!(type instanceof Type)) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.')\n }\n })\n\n const result = Object.create(Schema.prototype)\n\n result.implicit = (this.implicit || []).concat(implicit)\n result.explicit = (this.explicit || []).concat(explicit)\n\n result.compiledImplicit = compileList(result, 'implicit')\n result.compiledExplicit = compileList(result, 'explicit')\n result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit)\n\n return result\n}\n\nmodule.exports = Schema\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:str', {\n kind: 'scalar',\n construct: function (data) { return data !== null ? data : '' }\n})\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:seq', {\n kind: 'sequence',\n construct: function (data) { return data !== null ? data : [] }\n})\n","'use strict'\n\nconst Type = require('../type')\n\nmodule.exports = new Type('tag:yaml.org,2002:map', {\n kind: 'mapping',\n construct: function (data) { return data !== null ? data : {} }\n})\n","// Standard YAML's Failsafe schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2802346\n\n'use strict'\n\nconst Schema = require('../schema')\n\nmodule.exports = new Schema({\n explicit: [\n require('../type/str'),\n require('../type/seq'),\n require('../type/map')\n ]\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlNull (data) {\n if (data === null) return true\n\n const max = data.length\n\n return (max === 1 && data === '~') ||\n (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'))\n}\n\nfunction constructYamlNull () {\n return null\n}\n\nfunction isNull (object) {\n return object === null\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:null', {\n kind: 'scalar',\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: function () { return '~' },\n lowercase: function () { return 'null' },\n uppercase: function () { return 'NULL' },\n camelcase: function () { return 'Null' },\n empty: function () { return '' }\n },\n defaultStyle: 'lowercase'\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlBoolean (data) {\n if (data === null) return false\n\n const max = data.length\n\n return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'))\n}\n\nfunction constructYamlBoolean (data) {\n return data === 'true' ||\n data === 'True' ||\n data === 'TRUE'\n}\n\nfunction isBoolean (object) {\n return Object.prototype.toString.call(object) === '[object Boolean]'\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:bool', {\n kind: 'scalar',\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: function (object) { return object ? 'true' : 'false' },\n uppercase: function (object) { return object ? 'TRUE' : 'FALSE' },\n camelcase: function (object) { return object ? 'True' : 'False' }\n },\n defaultStyle: 'lowercase'\n})\n","'use strict'\n\nconst common = require('../common')\nconst Type = require('../type')\n\nfunction isHexCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) ||\n ((c >= 0x41/* A */) && (c <= 0x46/* F */)) ||\n ((c >= 0x61/* a */) && (c <= 0x66/* f */))\n}\n\nfunction isOctCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x37/* 7 */))\n}\n\nfunction isDecCode (c) {\n return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */))\n}\n\nfunction resolveYamlInteger (data) {\n if (data === null) return false\n\n const max = data.length\n let index = 0\n let hasDigits = false\n\n if (!max) return false\n\n let ch = data[index]\n\n // sign\n if (ch === '-' || ch === '+') {\n ch = data[++index]\n }\n\n if (ch === '0') {\n // 0\n if (index + 1 === max) return true\n ch = data[++index]\n\n // base 2, base 8, base 16\n\n if (ch === 'b') {\n // base 2\n index++\n\n for (; index < max; index++) {\n ch = data[index]\n if (ch !== '0' && ch !== '1') return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n\n if (ch === 'x') {\n // base 16\n index++\n\n for (; index < max; index++) {\n if (!isHexCode(data.charCodeAt(index))) return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n\n if (ch === 'o') {\n // base 8\n index++\n\n for (; index < max; index++) {\n if (!isOctCode(data.charCodeAt(index))) return false\n hasDigits = true\n }\n return hasDigits && Number.isFinite(parseYamlInteger(data))\n }\n }\n\n // base 10 (except 0)\n\n for (; index < max; index++) {\n if (!isDecCode(data.charCodeAt(index))) {\n return false\n }\n hasDigits = true\n }\n\n if (!hasDigits) return false\n\n return Number.isFinite(parseYamlInteger(data))\n}\n\nfunction parseYamlInteger (data) {\n let value = data\n let sign = 1\n\n let ch = value[0]\n\n if (ch === '-' || ch === '+') {\n if (ch === '-') sign = -1\n value = value.slice(1)\n ch = value[0]\n }\n\n if (value === '0') return 0\n\n if (ch === '0') {\n if (value[1] === 'b') return sign * parseInt(value.slice(2), 2)\n if (value[1] === 'x') return sign * parseInt(value.slice(2), 16)\n if (value[1] === 'o') return sign * parseInt(value.slice(2), 8)\n }\n\n return sign * parseInt(value, 10)\n}\n\nfunction constructYamlInteger (data) {\n return parseYamlInteger(data)\n}\n\nfunction isInteger (object) {\n return (Object.prototype.toString.call(object)) === '[object Number]' &&\n (object % 1 === 0 && !common.isNegativeZero(object))\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:int', {\n kind: 'scalar',\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1) },\n octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1) },\n decimal: function (obj) { return obj.toString(10) },\n hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1) }\n },\n defaultStyle: 'decimal',\n styleAliases: {\n binary: [2, 'bin'],\n octal: [8, 'oct'],\n decimal: [10, 'dec'],\n hexadecimal: [16, 'hex']\n }\n})\n","'use strict'\n\nconst common = require('../common')\nconst Type = require('../type')\n\nconst YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n '^(?:[-+]?(?:[0-9]+)(?:\\\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?' +\n // .2e4, .2\n // special case, seems not from spec\n '|\\\\.[0-9]+(?:[eE][-+]?[0-9]+)?' +\n // .inf\n '|[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$')\n\nconst YAML_FLOAT_SPECIAL_PATTERN = new RegExp(\n '^(?:' +\n // .inf\n '[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$')\n\nfunction resolveYamlFloat (data) {\n if (data === null) return false\n\n if (!YAML_FLOAT_PATTERN.test(data)) {\n return false\n }\n\n if (Number.isFinite(parseFloat(data, 10))) {\n return true\n }\n\n return YAML_FLOAT_SPECIAL_PATTERN.test(data)\n}\n\nfunction constructYamlFloat (data) {\n let value = data.toLowerCase()\n const sign = value[0] === '-' ? -1 : 1\n\n if ('+-'.indexOf(value[0]) >= 0) {\n value = value.slice(1)\n }\n\n if (value === '.inf') {\n return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY\n } else if (value === '.nan') {\n return NaN\n }\n return sign * parseFloat(value, 10)\n}\n\nconst SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/\n\nfunction representYamlFloat (object, style) {\n if (isNaN(object)) {\n switch (style) {\n case 'lowercase': return '.nan'\n case 'uppercase': return '.NAN'\n case 'camelcase': return '.NaN'\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '.inf'\n case 'uppercase': return '.INF'\n case 'camelcase': return '.Inf'\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '-.inf'\n case 'uppercase': return '-.INF'\n case 'camelcase': return '-.Inf'\n }\n } else if (common.isNegativeZero(object)) {\n return '-0.0'\n }\n\n const res = object.toString(10)\n\n // JS stringifier can build scientific format without dots: 5e-100,\n // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res\n}\n\nfunction isFloat (object) {\n return (Object.prototype.toString.call(object) === '[object Number]') &&\n (object % 1 !== 0 || common.isNegativeZero(object))\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:float', {\n kind: 'scalar',\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: 'lowercase'\n})\n","// Standard YAML's JSON schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2803231\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, this schema is not such strict as defined in the YAML specification.\n// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.\n\n'use strict'\n\nmodule.exports = require('./failsafe').extend({\n implicit: [\n require('../type/null'),\n require('../type/bool'),\n require('../type/int'),\n require('../type/float')\n ]\n})\n","// Standard YAML's Core schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2804923\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, Core schema has no distinctions from JSON schema is JS-YAML.\n\n'use strict'\n\nmodule.exports = require('./json')\n","'use strict'\n\nconst Type = require('../type')\n\nconst YAML_DATE_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9])' + // [2] month\n '-([0-9][0-9])$') // [3] day\n\nconst YAML_TIMESTAMP_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9]?)' + // [2] month\n '-([0-9][0-9]?)' + // [3] day\n '(?:[Tt]|[ \\\\t]+)' + // ...\n '([0-9][0-9]?)' + // [4] hour\n ':([0-9][0-9])' + // [5] minute\n ':([0-9][0-9])' + // [6] second\n '(?:\\\\.([0-9]*))?' + // [7] fraction\n '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tzHour\n '(?::([0-9][0-9]))?))?$') // [11] tzMinute\n\nfunction resolveYamlTimestamp (data) {\n if (data === null) return false\n if (YAML_DATE_REGEXP.exec(data) !== null) return true\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true\n return false\n}\n\nfunction constructYamlTimestamp (data) {\n let fraction = 0\n let delta = null\n\n let match = YAML_DATE_REGEXP.exec(data)\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data)\n\n if (match === null) throw new Error('Date resolve error')\n\n // match: [1] year [2] month [3] day\n\n const year = +(match[1])\n const month = +(match[2]) - 1 // JS month starts with 0\n const day = +(match[3])\n\n if (!match[4]) { // no hour\n return new Date(Date.UTC(year, month, day))\n }\n\n // match: [4] hour [5] minute [6] second [7] fraction\n\n const hour = +(match[4])\n const minute = +(match[5])\n const second = +(match[6])\n\n if (match[7]) {\n fraction = match[7].slice(0, 3)\n while (fraction.length < 3) { // milli-seconds\n fraction += '0'\n }\n fraction = +fraction\n }\n\n // match: [8] tz [9] tz_sign [10] tzHour [11] tzMinute\n\n if (match[9]) {\n const tzHour = +(match[10])\n const tzMinute = +(match[11] || 0)\n delta = (tzHour * 60 + tzMinute) * 60000 // delta in mili-seconds\n if (match[9] === '-') delta = -delta\n }\n\n const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction))\n\n if (delta) date.setTime(date.getTime() - delta)\n\n return date\n}\n\nfunction representYamlTimestamp (object /*, style */) {\n return object.toISOString()\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:timestamp', {\n kind: 'scalar',\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n})\n","'use strict'\n\nconst Type = require('../type')\n\nfunction resolveYamlMerge (data) {\n return data === '<<' || data === null\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:merge', {\n kind: 'scalar',\n resolve: resolveYamlMerge\n})\n","'use strict'\n\nconst Type = require('../type')\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nconst BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r'\n\nfunction resolveYamlBinary (data) {\n if (data === null) return false\n\n let bitlen = 0\n const max = data.length\n const map = BASE64_MAP\n\n // Convert one by one.\n for (let idx = 0; idx < max; idx++) {\n const code = map.indexOf(data.charAt(idx))\n\n // Skip CR/LF\n if (code > 64) continue\n\n // Fail on illegal characters\n if (code < 0) return false\n\n bitlen += 6\n }\n\n // If there are any bits left, source was corrupted\n return (bitlen % 8) === 0\n}\n\nfunction constructYamlBinary (data) {\n const input = data.replace(/[\\r\\n=]/g, '') // remove CR/LF & padding to simplify scan\n const max = input.length\n const map = BASE64_MAP\n let bits = 0\n const result = []\n\n // Collect by 6*4 bits (3 bytes)\n\n for (let idx = 0; idx < max; idx++) {\n if ((idx % 4 === 0) && idx) {\n result.push((bits >> 16) & 0xFF)\n result.push((bits >> 8) & 0xFF)\n result.push(bits & 0xFF)\n }\n\n bits = (bits << 6) | map.indexOf(input.charAt(idx))\n }\n\n // Dump tail\n\n const tailbits = (max % 4) * 6\n\n if (tailbits === 0) {\n result.push((bits >> 16) & 0xFF)\n result.push((bits >> 8) & 0xFF)\n result.push(bits & 0xFF)\n } else if (tailbits === 18) {\n result.push((bits >> 10) & 0xFF)\n result.push((bits >> 2) & 0xFF)\n } else if (tailbits === 12) {\n result.push((bits >> 4) & 0xFF)\n }\n\n return new Uint8Array(result)\n}\n\nfunction representYamlBinary (object /*, style */) {\n let result = ''\n let bits = 0\n const max = object.length\n const map = BASE64_MAP\n\n // Convert every three bytes to 4 ASCII characters.\n\n for (let idx = 0; idx < max; idx++) {\n if ((idx % 3 === 0) && idx) {\n result += map[(bits >> 18) & 0x3F]\n result += map[(bits >> 12) & 0x3F]\n result += map[(bits >> 6) & 0x3F]\n result += map[bits & 0x3F]\n }\n\n bits = (bits << 8) + object[idx]\n }\n\n // Dump tail\n\n const tail = max % 3\n\n if (tail === 0) {\n result += map[(bits >> 18) & 0x3F]\n result += map[(bits >> 12) & 0x3F]\n result += map[(bits >> 6) & 0x3F]\n result += map[bits & 0x3F]\n } else if (tail === 2) {\n result += map[(bits >> 10) & 0x3F]\n result += map[(bits >> 4) & 0x3F]\n result += map[(bits << 2) & 0x3F]\n result += map[64]\n } else if (tail === 1) {\n result += map[(bits >> 2) & 0x3F]\n result += map[(bits << 4) & 0x3F]\n result += map[64]\n result += map[64]\n }\n\n return result\n}\n\nfunction isBinary (obj) {\n return Object.prototype.toString.call(obj) === '[object Uint8Array]'\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:binary', {\n kind: 'scalar',\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\nconst _toString = Object.prototype.toString\n\nfunction resolveYamlOmap (data) {\n if (data === null) return true\n\n const objectKeys = []\n const object = data\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n let pairHasKey = false\n\n if (_toString.call(pair) !== '[object Object]') return false\n\n let pairKey\n for (pairKey in pair) {\n if (_hasOwnProperty.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true\n else return false\n }\n }\n\n if (!pairHasKey) return false\n\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey)\n else return false\n }\n\n return true\n}\n\nfunction constructYamlOmap (data) {\n return data !== null ? data : []\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:omap', {\n kind: 'sequence',\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _toString = Object.prototype.toString\n\nfunction resolveYamlPairs (data) {\n if (data === null) return true\n\n const object = data\n\n const result = new Array(object.length)\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n\n if (_toString.call(pair) !== '[object Object]') return false\n\n const keys = Object.keys(pair)\n\n if (keys.length !== 1) return false\n\n result[index] = [keys[0], pair[keys[0]]]\n }\n\n return true\n}\n\nfunction constructYamlPairs (data) {\n if (data === null) return []\n\n const object = data\n const result = new Array(object.length)\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n const pair = object[index]\n\n const keys = Object.keys(pair)\n\n result[index] = [keys[0], pair[keys[0]]]\n }\n\n return result\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:pairs', {\n kind: 'sequence',\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n})\n","'use strict'\n\nconst Type = require('../type')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nfunction resolveYamlSet (data) {\n if (data === null) return true\n\n const object = data\n\n for (const key in object) {\n if (_hasOwnProperty.call(object, key)) {\n if (object[key] !== null) return false\n }\n }\n\n return true\n}\n\nfunction constructYamlSet (data) {\n return data !== null ? data : {}\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:set', {\n kind: 'mapping',\n resolve: resolveYamlSet,\n construct: constructYamlSet\n})\n","// JS-YAML's default schema for `safeLoad` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on standard YAML's Core schema and includes most of\n// extra types described at YAML tag repository. (http://yaml.org/type/)\n\n'use strict'\n\nmodule.exports = require('./core').extend({\n implicit: [\n require('../type/timestamp'),\n require('../type/merge')\n ],\n explicit: [\n require('../type/binary'),\n require('../type/omap'),\n require('../type/pairs'),\n require('../type/set')\n ]\n})\n","'use strict'\n\nconst common = require('./common')\nconst YAMLException = require('./exception')\nconst makeSnippet = require('./snippet')\nconst DEFAULT_SCHEMA = require('./schema/default')\n\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nconst CONTEXT_FLOW_IN = 1\nconst CONTEXT_FLOW_OUT = 2\nconst CONTEXT_BLOCK_IN = 3\nconst CONTEXT_BLOCK_OUT = 4\n\nconst CHOMPING_CLIP = 1\nconst CHOMPING_STRIP = 2\nconst CHOMPING_KEEP = 3\n\n// eslint-disable-next-line no-control-regex\nconst PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/\nconst PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_FLOW_INDICATORS = /[,\\[\\]{}]/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_TAG_URI = /^(?:!|[^,\\[\\]{}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;/?:@&=+$,_.!~*'()\\[\\]])*$/i\n\nfunction _class (obj) { return Object.prototype.toString.call(obj) }\n\nfunction isEol (c) {\n return (c === 0x0A/* LF */) || (c === 0x0D/* CR */)\n}\n\nfunction isWhiteSpace (c) {\n return (c === 0x09/* Tab */) || (c === 0x20/* Space */)\n}\n\nfunction isWsOrEol (c) {\n return (c === 0x09/* Tab */) ||\n (c === 0x20/* Space */) ||\n (c === 0x0A/* LF */) ||\n (c === 0x0D/* CR */)\n}\n\nfunction isFlowIndicator (c) {\n return c === 0x2C/* , */ ||\n c === 0x5B/* [ */ ||\n c === 0x5D/* ] */ ||\n c === 0x7B/* { */ ||\n c === 0x7D/* } */\n}\n\nfunction fromHexCode (c) {\n if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) {\n return c - 0x30\n }\n\n const lc = c | 0x20\n\n if ((lc >= 0x61/* a */) && (lc <= 0x66/* f */)) {\n return lc - 0x61 + 10\n }\n\n return -1\n}\n\nfunction escapedHexLen (c) {\n if (c === 0x78/* x */) { return 2 }\n if (c === 0x75/* u */) { return 4 }\n if (c === 0x55/* U */) { return 8 }\n return 0\n}\n\nfunction fromDecimalCode (c) {\n if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) {\n return c - 0x30\n }\n\n return -1\n}\n\nfunction simpleEscapeSequence (c) {\n switch (c) {\n case 0x30/* 0 */: return '\\x00'\n case 0x61/* a */: return '\\x07'\n case 0x62/* b */: return '\\x08'\n case 0x74/* t */: return '\\x09'\n case 0x09/* Tab */: return '\\x09'\n case 0x6E/* n */: return '\\x0A'\n case 0x76/* v */: return '\\x0B'\n case 0x66/* f */: return '\\x0C'\n case 0x72/* r */: return '\\x0D'\n case 0x65/* e */: return '\\x1B'\n case 0x20/* Space */: return ' '\n case 0x22/* \" */: return '\\x22'\n case 0x2F/* / */: return '/'\n case 0x5C/* \\ */: return '\\x5C'\n case 0x4E/* N */: return '\\x85'\n case 0x5F/* _ */: return '\\xA0'\n case 0x4C/* L */: return '\\u2028'\n case 0x50/* P */: return '\\u2029'\n default: return ''\n }\n}\n\nfunction charFromCodepoint (c) {\n if (c <= 0xFFFF) {\n return String.fromCharCode(c)\n }\n // Encode UTF-16 surrogate pair\n // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n return String.fromCharCode(\n ((c - 0x010000) >> 10) + 0xD800,\n ((c - 0x010000) & 0x03FF) + 0xDC00\n )\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty (object, key, value) {\n // used for this specific key only because Object.defineProperty is slow\n if (key === '__proto__') {\n Object.defineProperty(object, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: value\n })\n } else {\n object[key] = value\n }\n}\n\nconst simpleEscapeCheck = new Array(256) // integer, for fast access\nconst simpleEscapeMap = new Array(256)\nfor (let i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0\n simpleEscapeMap[i] = simpleEscapeSequence(i)\n}\n\nfunction State (input, options) {\n this.input = input\n\n this.filename = options['filename'] || null\n this.schema = options['schema'] || DEFAULT_SCHEMA\n this.onWarning = options['onWarning'] || null\n // (Hidden) Remove? makes the loader to expect YAML 1.1 documents\n // if such documents have no explicit %YAML directive\n this.legacy = options['legacy'] || false\n\n this.json = options['json'] || false\n this.listener = options['listener'] || null\n this.maxDepth = typeof options['maxDepth'] === 'number' ? options['maxDepth'] : 100\n this.maxMergeSeqLength = typeof options['maxMergeSeqLength'] === 'number' ? options['maxMergeSeqLength'] : 20\n\n this.implicitTypes = this.schema.compiledImplicit\n this.typeMap = this.schema.compiledTypeMap\n\n this.length = input.length\n this.position = 0\n this.line = 0\n this.lineStart = 0\n this.lineIndent = 0\n this.depth = 0\n\n // position of first leading tab in the current line,\n // used to make sure there are no tabs in the indentation\n this.firstTabInLine = -1\n\n this.documents = []\n this.anchorMapTransactions = []\n\n /*\n this.version;\n this.checkLineBreaks;\n this.tagMap;\n this.anchorMap;\n this.tag;\n this.anchor;\n this.kind;\n this.result; */\n}\n\nfunction generateError (state, message) {\n const mark = {\n name: state.filename,\n buffer: state.input.slice(0, -1), // omit trailing \\0\n position: state.position,\n line: state.line,\n column: state.position - state.lineStart\n }\n\n mark.snippet = makeSnippet(mark)\n\n return new YAMLException(message, mark)\n}\n\nfunction throwError (state, message) {\n throw generateError(state, message)\n}\n\nfunction throwWarning (state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message))\n }\n}\n\nfunction storeAnchor (state, name, value) {\n const transactions = state.anchorMapTransactions\n\n if (transactions.length !== 0) {\n const transaction = transactions[transactions.length - 1]\n\n if (!_hasOwnProperty.call(transaction, name)) {\n transaction[name] = {\n existed: _hasOwnProperty.call(state.anchorMap, name),\n value: state.anchorMap[name]\n }\n }\n }\n\n state.anchorMap[name] = value\n}\n\nfunction beginAnchorTransaction (state) {\n state.anchorMapTransactions.push(Object.create(null))\n}\n\nfunction commitAnchorTransaction (state) {\n const transaction = state.anchorMapTransactions.pop()\n const transactions = state.anchorMapTransactions\n\n if (transactions.length === 0) return\n\n const parent = transactions[transactions.length - 1]\n const names = Object.keys(transaction)\n\n for (let index = 0, length = names.length; index < length; index += 1) {\n const name = names[index]\n\n if (!_hasOwnProperty.call(parent, name)) {\n parent[name] = transaction[name]\n }\n }\n}\n\nfunction rollbackAnchorTransaction (state) {\n const transaction = state.anchorMapTransactions.pop()\n const names = Object.keys(transaction)\n\n for (let index = names.length - 1; index >= 0; index -= 1) {\n const entry = transaction[names[index]]\n\n if (entry.existed) {\n state.anchorMap[names[index]] = entry.value\n } else {\n delete state.anchorMap[names[index]]\n }\n }\n}\n\nfunction snapshotState (state) {\n return {\n position: state.position,\n line: state.line,\n lineStart: state.lineStart,\n lineIndent: state.lineIndent,\n firstTabInLine: state.firstTabInLine,\n tag: state.tag,\n anchor: state.anchor,\n kind: state.kind,\n result: state.result\n }\n}\n\nfunction restoreState (state, snapshot) {\n state.position = snapshot.position\n state.line = snapshot.line\n state.lineStart = snapshot.lineStart\n state.lineIndent = snapshot.lineIndent\n state.firstTabInLine = snapshot.firstTabInLine\n state.tag = snapshot.tag\n state.anchor = snapshot.anchor\n state.kind = snapshot.kind\n state.result = snapshot.result\n}\n\nconst directiveHandlers = {\n\n YAML: function handleYamlDirective (state, name, args) {\n if (state.version !== null) {\n throwError(state, 'duplication of %YAML directive')\n }\n\n if (args.length !== 1) {\n throwError(state, 'YAML directive accepts exactly one argument')\n }\n\n const match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0])\n\n if (match === null) {\n throwError(state, 'ill-formed argument of the YAML directive')\n }\n\n const major = parseInt(match[1], 10)\n const minor = parseInt(match[2], 10)\n\n if (major !== 1) {\n throwError(state, 'unacceptable YAML version of the document')\n }\n\n state.version = args[0]\n state.checkLineBreaks = (minor < 2)\n\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, 'unsupported YAML version of the document')\n }\n },\n\n TAG: function handleTagDirective (state, name, args) {\n let prefix\n\n if (args.length !== 2) {\n throwError(state, 'TAG directive accepts exactly two arguments')\n }\n\n const handle = args[0]\n prefix = args[1]\n\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, 'ill-formed tag handle (first argument) of the TAG directive')\n }\n\n if (_hasOwnProperty.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle')\n }\n\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive')\n }\n\n try {\n prefix = decodeURIComponent(prefix)\n } catch (err) {\n throwError(state, 'tag prefix is malformed: ' + prefix)\n }\n\n state.tagMap[handle] = prefix\n }\n}\n\nfunction captureSegment (state, start, end, checkJson) {\n if (start < end) {\n const _result = state.input.slice(start, end)\n\n if (checkJson) {\n for (let _position = 0, _length = _result.length; _position < _length; _position += 1) {\n const _character = _result.charCodeAt(_position)\n if (!(_character === 0x09 ||\n (_character >= 0x20 && _character <= 0x10FFFF))) {\n throwError(state, 'expected valid JSON character')\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, 'the stream contains non-printable characters')\n }\n\n state.result += _result\n }\n}\n\nfunction mergeMappings (state, destination, source, overridableKeys) {\n if (!common.isObject(source)) {\n throwError(state, 'cannot merge mappings; the provided source object is unacceptable')\n }\n\n const sourceKeys = Object.keys(source)\n\n for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n const key = sourceKeys[index]\n\n if (!_hasOwnProperty.call(destination, key)) {\n setProperty(destination, key, source[key])\n overridableKeys[key] = true\n }\n }\n}\n\nfunction storeMappingPair (state, _result, overridableKeys, keyTag, keyNode, valueNode,\n startLine, startLineStart, startPos) {\n // The output is a plain object here, so keys can only be strings.\n // We need to convert keyNode to a string, but doing so can hang the process\n // (deeply nested arrays that explode exponentially using aliases).\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode)\n\n for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, 'nested arrays are not supported inside keys')\n }\n\n if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n keyNode[index] = '[object Object]'\n }\n }\n }\n\n // Avoid code execution in load() via toString property\n // (still use its own toString for arrays, timestamps,\n // and whatever user schema extensions happen to have @@toStringTag)\n if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n keyNode = '[object Object]'\n }\n\n keyNode = String(keyNode)\n\n if (_result === null) {\n _result = {}\n }\n\n if (keyTag === 'tag:yaml.org,2002:merge') {\n if (Array.isArray(valueNode)) {\n if (valueNode.length > state.maxMergeSeqLength) {\n throwError(state, 'merge sequence length exceeded maxMergeSeqLength (' + state.maxMergeSeqLength + ')')\n }\n const seen = new Set()\n for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n const src = valueNode[index]\n // Existing keys are not overridden on merge, so dedupe sources to\n // avoid redundant work on repeated aliases.\n if (seen.has(src)) continue\n seen.add(src)\n mergeMappings(state, _result, src, overridableKeys)\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys)\n }\n } else {\n if (!state.json &&\n !_hasOwnProperty.call(overridableKeys, keyNode) &&\n _hasOwnProperty.call(_result, keyNode)) {\n state.line = startLine || state.line\n state.lineStart = startLineStart || state.lineStart\n state.position = startPos || state.position\n throwError(state, 'duplicated mapping key')\n }\n\n setProperty(_result, keyNode, valueNode)\n delete overridableKeys[keyNode]\n }\n\n return _result\n}\n\nfunction readLineBreak (state) {\n const ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x0A/* LF */) {\n state.position++\n } else if (ch === 0x0D/* CR */) {\n state.position++\n if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n state.position++\n }\n } else {\n throwError(state, 'a line break is expected')\n }\n\n state.line += 1\n state.lineStart = state.position\n state.firstTabInLine = -1\n}\n\nfunction skipSeparationSpace (state, allowComments, checkIndent) {\n let lineBreaks = 0\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n while (isWhiteSpace(ch)) {\n if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {\n state.firstTabInLine = state.position\n }\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (allowComments && ch === 0x23/* # */) {\n do {\n ch = state.input.charCodeAt(++state.position)\n } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0)\n }\n\n if (isEol(ch)) {\n readLineBreak(state)\n\n ch = state.input.charCodeAt(state.position)\n lineBreaks++\n state.lineIndent = 0\n\n while (ch === 0x20/* Space */) {\n state.lineIndent++\n ch = state.input.charCodeAt(++state.position)\n }\n } else {\n break\n }\n }\n\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, 'deficient indentation')\n }\n\n return lineBreaks\n}\n\nfunction testDocumentSeparator (state) {\n let _position = state.position\n let ch = state.input.charCodeAt(_position)\n\n // Condition state.position === state.lineStart is tested\n // in parent on each call, for efficiency. No needs to test here again.\n if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n ch === state.input.charCodeAt(_position + 1) &&\n ch === state.input.charCodeAt(_position + 2)) {\n _position += 3\n\n ch = state.input.charCodeAt(_position)\n\n if (ch === 0 || isWsOrEol(ch)) {\n return true\n }\n }\n\n return false\n}\n\nfunction writeFoldedLines (state, count) {\n if (count === 1) {\n state.result += ' '\n } else if (count > 1) {\n state.result += common.repeat('\\n', count - 1)\n }\n}\n\nfunction readPlainScalar (state, nodeIndent, withinFlowCollection) {\n let captureStart\n let captureEnd\n let hasPendingContent\n let _line\n let _lineStart\n let _lineIndent\n const _kind = state.kind\n const _result = state.result\n\n let ch = state.input.charCodeAt(state.position)\n\n if (isWsOrEol(ch) ||\n isFlowIndicator(ch) ||\n ch === 0x23/* # */ ||\n ch === 0x26/* & */ ||\n ch === 0x2A/* * */ ||\n ch === 0x21/* ! */ ||\n ch === 0x7C/* | */ ||\n ch === 0x3E/* > */ ||\n ch === 0x27/* ' */ ||\n ch === 0x22/* \" */ ||\n ch === 0x25/* % */ ||\n ch === 0x40/* @ */ ||\n ch === 0x60/* ` */) {\n return false\n }\n\n if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following) ||\n (withinFlowCollection && isFlowIndicator(following))) {\n return false\n }\n }\n\n state.kind = 'scalar'\n state.result = ''\n captureStart = captureEnd = state.position\n hasPendingContent = false\n\n while (ch !== 0) {\n if (ch === 0x3A/* : */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following) ||\n (withinFlowCollection && isFlowIndicator(following))) {\n break\n }\n } else if (ch === 0x23/* # */) {\n const preceding = state.input.charCodeAt(state.position - 1)\n\n if (isWsOrEol(preceding)) {\n break\n }\n } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n (withinFlowCollection && isFlowIndicator(ch))) {\n break\n } else if (isEol(ch)) {\n _line = state.line\n _lineStart = state.lineStart\n _lineIndent = state.lineIndent\n skipSeparationSpace(state, false, -1)\n\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true\n ch = state.input.charCodeAt(state.position)\n continue\n } else {\n state.position = captureEnd\n state.line = _line\n state.lineStart = _lineStart\n state.lineIndent = _lineIndent\n break\n }\n }\n\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false)\n writeFoldedLines(state, state.line - _line)\n captureStart = captureEnd = state.position\n hasPendingContent = false\n }\n\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position + 1\n }\n\n ch = state.input.charCodeAt(++state.position)\n }\n\n captureSegment(state, captureStart, captureEnd, false)\n\n if (state.result) {\n return true\n }\n\n state.kind = _kind\n state.result = _result\n return false\n}\n\nfunction readSingleQuotedScalar (state, nodeIndent) {\n let captureStart\n let captureEnd\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x27/* ' */) {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n state.position++\n captureStart = captureEnd = state.position\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x27/* ' */) {\n captureSegment(state, captureStart, state.position, true)\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x27/* ' */) {\n captureStart = state.position\n state.position++\n captureEnd = state.position\n } else {\n return true\n }\n } else if (isEol(ch)) {\n captureSegment(state, captureStart, captureEnd, true)\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent))\n captureStart = captureEnd = state.position\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a single quoted scalar')\n } else {\n state.position++\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position\n }\n }\n }\n\n throwError(state, 'unexpected end of the stream within a single quoted scalar')\n}\n\nfunction readDoubleQuotedScalar (state, nodeIndent) {\n let captureStart\n let captureEnd\n let tmp\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x22/* \" */) {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n state.position++\n captureStart = captureEnd = state.position\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x22/* \" */) {\n captureSegment(state, captureStart, state.position, true)\n state.position++\n return true\n } else if (ch === 0x5C/* \\ */) {\n captureSegment(state, captureStart, state.position, true)\n ch = state.input.charCodeAt(++state.position)\n\n if (isEol(ch)) {\n skipSeparationSpace(state, false, nodeIndent)\n\n // TODO: rework to inline fn with no type cast?\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch]\n state.position++\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n let hexLength = tmp\n let hexResult = 0\n\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position)\n\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp\n } else {\n throwError(state, 'expected hexadecimal character')\n }\n }\n\n state.result += charFromCodepoint(hexResult)\n\n state.position++\n } else {\n throwError(state, 'unknown escape sequence')\n }\n\n captureStart = captureEnd = state.position\n } else if (isEol(ch)) {\n captureSegment(state, captureStart, captureEnd, true)\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent))\n captureStart = captureEnd = state.position\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a double quoted scalar')\n } else {\n state.position++\n if (!isWhiteSpace(ch)) {\n captureEnd = state.position\n }\n }\n }\n\n throwError(state, 'unexpected end of the stream within a double quoted scalar')\n}\n\nfunction readFlowCollection (state, nodeIndent) {\n let readNext = true\n let _line\n let _lineStart\n let _pos\n const _tag = state.tag\n let _result\n const _anchor = state.anchor\n let terminator\n let isPair\n let isExplicitPair\n let isMapping\n const overridableKeys = Object.create(null)\n let keyNode\n let keyTag\n let valueNode\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x5B/* [ */) {\n terminator = 0x5D/* ] */\n isMapping = false\n _result = []\n } else if (ch === 0x7B/* { */) {\n terminator = 0x7D/* } */\n isMapping = true\n _result = {}\n } else {\n return false\n }\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n ch = state.input.charCodeAt(++state.position)\n\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if (ch === terminator) {\n state.position++\n state.tag = _tag\n state.anchor = _anchor\n state.kind = isMapping ? 'mapping' : 'sequence'\n state.result = _result\n return true\n } else if (!readNext) {\n throwError(state, 'missed comma between flow collection entries')\n } else if (ch === 0x2C/* , */) {\n // \"flow collection entries can never be completely empty\", as per YAML 1.2, section 7.4\n throwError(state, \"expected the node content, but found ','\")\n }\n\n keyTag = keyNode = valueNode = null\n isPair = isExplicitPair = false\n\n if (ch === 0x3F/* ? */) {\n const following = state.input.charCodeAt(state.position + 1)\n\n if (isWsOrEol(following)) {\n isPair = isExplicitPair = true\n state.position++\n skipSeparationSpace(state, true, nodeIndent)\n }\n }\n\n _line = state.line // Save the current line.\n _lineStart = state.lineStart\n _pos = state.position\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)\n keyTag = state.tag\n keyNode = state.result\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n isPair = true\n ch = state.input.charCodeAt(++state.position)\n skipSeparationSpace(state, true, nodeIndent)\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)\n valueNode = state.result\n }\n\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos))\n } else {\n _result.push(keyNode)\n }\n\n skipSeparationSpace(state, true, nodeIndent)\n\n ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x2C/* , */) {\n readNext = true\n ch = state.input.charCodeAt(++state.position)\n } else {\n readNext = false\n }\n }\n\n throwError(state, 'unexpected end of the stream within a flow collection')\n}\n\nfunction readBlockScalar (state, nodeIndent) {\n let folding\n let chomping = CHOMPING_CLIP\n let didReadContent = false\n let detectedIndent = false\n let textIndent = nodeIndent\n let emptyLines = 0\n let atMoreIndented = false\n let tmp\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch === 0x7C/* | */) {\n folding = false\n } else if (ch === 0x3E/* > */) {\n folding = true\n } else {\n return false\n }\n\n state.kind = 'scalar'\n state.result = ''\n\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n if (CHOMPING_CLIP === chomping) {\n chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP\n } else {\n throwError(state, 'repeat of a chomping mode identifier')\n }\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one')\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1\n detectedIndent = true\n } else {\n throwError(state, 'repeat of an indentation width identifier')\n }\n } else {\n break\n }\n }\n\n if (isWhiteSpace(ch)) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (isWhiteSpace(ch))\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (!isEol(ch) && (ch !== 0))\n }\n }\n\n while (ch !== 0) {\n readLineBreak(state)\n state.lineIndent = 0\n\n ch = state.input.charCodeAt(state.position)\n\n // eslint-disable-next-line no-unmodified-loop-condition\n while ((!detectedIndent || state.lineIndent < textIndent) &&\n (ch === 0x20/* Space */)) {\n state.lineIndent++\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent\n }\n\n if (isEol(ch)) {\n emptyLines++\n continue\n }\n\n if (!detectedIndent && textIndent === 0) {\n throwError(state, 'missing indentation for block scalar')\n }\n\n // End of the scalar.\n if (state.lineIndent < textIndent) {\n // Perform the chomping.\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) { // i.e. only if the scalar is not empty.\n state.result += '\\n'\n }\n }\n\n // Break this `while` cycle and go to the funciton's epilogue.\n break\n }\n\n // Folded style: use fancy rules to handle line breaks.\n if (folding) {\n // Lines starting with white space characters (more-indented lines) are not folded.\n if (isWhiteSpace(ch)) {\n atMoreIndented = true\n // except for the first content line (cf. Example 8.1)\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n\n // End of more-indented block.\n } else if (atMoreIndented) {\n atMoreIndented = false\n state.result += common.repeat('\\n', emptyLines + 1)\n\n // Just one line break - perceive as the same line.\n } else if (emptyLines === 0) {\n if (didReadContent) { // i.e. only if we have already read some scalar content.\n state.result += ' '\n }\n\n // Several line breaks - perceive as different lines.\n } else {\n state.result += common.repeat('\\n', emptyLines)\n }\n\n // Literal style: just add exact number of line breaks between content lines.\n } else {\n // Keep all line breaks except the header line break.\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines)\n }\n\n didReadContent = true\n detectedIndent = true\n emptyLines = 0\n const captureStart = state.position\n\n while (!isEol(ch) && (ch !== 0)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n captureSegment(state, captureStart, state.position, false)\n }\n\n return true\n}\n\nfunction readBlockSequence (state, nodeIndent) {\n const _tag = state.tag\n const _anchor = state.anchor\n const _result = []\n let detected = false\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n if (state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine\n throwError(state, 'tab characters must not be used in indentation')\n }\n\n if (ch !== 0x2D/* - */) {\n break\n }\n\n const following = state.input.charCodeAt(state.position + 1)\n\n if (!isWsOrEol(following)) {\n break\n }\n\n detected = true\n state.position++\n\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null)\n ch = state.input.charCodeAt(state.position)\n continue\n }\n }\n\n const _line = state.line\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true)\n _result.push(state.result)\n skipSeparationSpace(state, true, -1)\n\n ch = state.input.charCodeAt(state.position)\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a sequence entry')\n } else if (state.lineIndent < nodeIndent) {\n break\n }\n }\n\n if (detected) {\n state.tag = _tag\n state.anchor = _anchor\n state.kind = 'sequence'\n state.result = _result\n return true\n }\n return false\n}\n\nfunction readBlockMapping (state, nodeIndent, flowIndent) {\n let allowCompact\n let _keyLine\n let _keyLineStart\n let _keyPos\n const _tag = state.tag\n const _anchor = state.anchor\n const _result = {}\n const overridableKeys = Object.create(null)\n let keyTag = null\n let keyNode = null\n let valueNode = null\n let atExplicitKey = false\n let detected = false\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, _result)\n }\n\n let ch = state.input.charCodeAt(state.position)\n\n while (ch !== 0) {\n if (!atExplicitKey && state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine\n throwError(state, 'tab characters must not be used in indentation')\n }\n\n const following = state.input.charCodeAt(state.position + 1)\n const _line = state.line // Save the current line.\n\n //\n // Explicit notation case. There are two separate blocks:\n // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n //\n if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && isWsOrEol(following)) {\n if (ch === 0x3F/* ? */) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n detected = true\n atExplicitKey = true\n allowCompact = true\n } else if (atExplicitKey) {\n // i.e. 0x3A/* : */ === character after the explicit key.\n atExplicitKey = false\n allowCompact = true\n } else {\n throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line')\n }\n\n state.position += 1\n ch = following\n\n //\n // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n //\n } else {\n _keyLine = state.line\n _keyLineStart = state.lineStart\n _keyPos = state.position\n\n if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n // Neither implicit nor explicit notation.\n // Reading is done. Go to the epilogue.\n break\n }\n\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position)\n\n while (isWhiteSpace(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (ch === 0x3A/* : */) {\n ch = state.input.charCodeAt(++state.position)\n\n if (!isWsOrEol(ch)) {\n throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping')\n }\n\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n detected = true\n atExplicitKey = false\n allowCompact = false\n keyTag = state.tag\n keyNode = state.result\n } else if (detected) {\n throwError(state, 'can not read an implicit mapping pair; a colon is missed')\n } else {\n state.tag = _tag\n state.anchor = _anchor\n return true // Keep the result of `composeNode`.\n }\n } else if (detected) {\n throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key')\n } else {\n state.tag = _tag\n state.anchor = _anchor\n return true // Keep the result of `composeNode`.\n }\n }\n\n //\n // Common reading code for both explicit and implicit notations.\n //\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (atExplicitKey) {\n _keyLine = state.line\n _keyLineStart = state.lineStart\n _keyPos = state.position\n }\n\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result\n } else {\n valueNode = state.result\n }\n }\n\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos)\n keyTag = keyNode = valueNode = null\n }\n\n skipSeparationSpace(state, true, -1)\n ch = state.input.charCodeAt(state.position)\n }\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a mapping entry')\n } else if (state.lineIndent < nodeIndent) {\n break\n }\n }\n\n //\n // Epilogue.\n //\n\n // Special case: last mapping's node contains only the key in explicit notation.\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos)\n }\n\n // Expose the resulting mapping.\n if (detected) {\n state.tag = _tag\n state.anchor = _anchor\n state.kind = 'mapping'\n state.result = _result\n }\n\n return detected\n}\n\nfunction readTagProperty (state) {\n let isVerbatim = false\n let isNamed = false\n let tagHandle\n let tagName\n\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x21/* ! */) return false\n\n if (state.tag !== null) {\n throwError(state, 'duplication of a tag property')\n }\n\n ch = state.input.charCodeAt(++state.position)\n\n if (ch === 0x3C/* < */) {\n isVerbatim = true\n ch = state.input.charCodeAt(++state.position)\n } else if (ch === 0x21/* ! */) {\n isNamed = true\n tagHandle = '!!'\n ch = state.input.charCodeAt(++state.position)\n } else {\n tagHandle = '!'\n }\n\n let _position = state.position\n\n if (isVerbatim) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (ch !== 0 && ch !== 0x3E/* > */)\n\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position)\n ch = state.input.charCodeAt(++state.position)\n } else {\n throwError(state, 'unexpected end of the stream within a verbatim tag')\n }\n } else {\n while (ch !== 0 && !isWsOrEol(ch)) {\n if (ch === 0x21/* ! */) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1)\n\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, 'named tag handle cannot contain such characters')\n }\n\n isNamed = true\n _position = state.position + 1\n } else {\n throwError(state, 'tag suffix cannot contain exclamation marks')\n }\n }\n\n ch = state.input.charCodeAt(++state.position)\n }\n\n tagName = state.input.slice(_position, state.position)\n\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, 'tag suffix cannot contain flow indicator characters')\n }\n }\n\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, 'tag name cannot contain such characters: ' + tagName)\n }\n\n try {\n tagName = decodeURIComponent(tagName)\n } catch (err) {\n throwError(state, 'tag name is malformed: ' + tagName)\n }\n\n if (isVerbatim) {\n state.tag = tagName\n } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName\n } else if (tagHandle === '!') {\n state.tag = '!' + tagName\n } else if (tagHandle === '!!') {\n state.tag = 'tag:yaml.org,2002:' + tagName\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"')\n }\n\n return true\n}\n\nfunction readAnchorProperty (state) {\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x26/* & */) return false\n\n if (state.anchor !== null) {\n throwError(state, 'duplication of an anchor property')\n }\n\n ch = state.input.charCodeAt(++state.position)\n const _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an anchor node must contain at least one character')\n }\n\n state.anchor = state.input.slice(_position, state.position)\n return true\n}\n\nfunction readAlias (state) {\n let ch = state.input.charCodeAt(state.position)\n\n if (ch !== 0x2A/* * */) return false\n\n ch = state.input.charCodeAt(++state.position)\n const _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an alias node must contain at least one character')\n }\n\n const alias = state.input.slice(_position, state.position)\n\n if (!_hasOwnProperty.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"')\n }\n\n state.result = state.anchorMap[alias]\n skipSeparationSpace(state, true, -1)\n return true\n}\n\nfunction tryReadBlockMappingFromProperty (state, propertyStart, nodeIndent, flowIndent) {\n const fallbackState = snapshotState(state)\n\n beginAnchorTransaction(state)\n restoreState(state, propertyStart)\n\n // Re-read the leading properties as part of the first implicit key, not as\n // properties of the current node.\n state.tag = null\n state.anchor = null\n state.kind = null\n state.result = null\n\n if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === 'mapping') {\n commitAnchorTransaction(state)\n return true\n }\n\n rollbackAnchorTransaction(state)\n restoreState(state, fallbackState)\n return false\n}\n\nfunction composeNode (state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n let allowBlockScalars\n let allowBlockCollections\n let indentStatus = 1 // 1: this>parent, 0: this=parent, -1: this= state.maxDepth) {\n throwError(state, 'nesting exceeded maxDepth (' + state.maxDepth + ')')\n }\n\n state.depth += 1\n\n if (state.listener !== null) {\n state.listener('open', state)\n }\n\n state.tag = null\n state.anchor = null\n state.kind = null\n state.result = null\n\n const allowBlockStyles = allowBlockScalars = allowBlockCollections =\n CONTEXT_BLOCK_OUT === nodeContext ||\n CONTEXT_BLOCK_IN === nodeContext\n\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1\n }\n }\n }\n\n if (indentStatus === 1) {\n while (true) {\n const ch = state.input.charCodeAt(state.position)\n const propertyState = snapshotState(state)\n\n // A duplicate property token after a line break can be the first key of\n // a nested block mapping, e.g. `!!map\\n !!str key: value`.\n if (atNewLine &&\n ((ch === 0x21/* ! */ && state.tag !== null) ||\n (ch === 0x26/* & */ && state.anchor !== null))) {\n break\n }\n\n if (!readTagProperty(state) && !readAnchorProperty(state)) {\n break\n }\n\n if (propertyStart === null) {\n propertyStart = propertyState\n }\n\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true\n allowBlockCollections = allowBlockStyles\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1\n }\n } else {\n allowBlockCollections = false\n }\n }\n }\n\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact\n }\n\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent\n } else {\n flowIndent = parentIndent + 1\n }\n\n blockIndent = state.position - state.lineStart\n\n if (indentStatus === 1) {\n if ((allowBlockCollections &&\n (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent))) ||\n readFlowCollection(state, flowIndent)) {\n hasContent = true\n } else {\n const ch = state.input.charCodeAt(state.position)\n\n if (propertyStart !== null && allowBlockStyles && !allowBlockCollections &&\n ch !== 0x7C/* | */ && ch !== 0x3E/* > */ &&\n tryReadBlockMappingFromProperty(\n state,\n propertyStart,\n propertyStart.position - propertyStart.lineStart,\n flowIndent\n )) {\n hasContent = true\n } else if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n readSingleQuotedScalar(state, flowIndent) ||\n readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true\n } else if (readAlias(state)) {\n hasContent = true\n\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, 'alias node should not have any properties')\n }\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true\n\n if (state.tag === null) {\n state.tag = '?'\n }\n }\n\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n }\n } else if (indentStatus === 0) {\n // Special case: block sequences are allowed to have same indentation level as the parent.\n // http://www.yaml.org/spec/1.2/spec.html#id2799784\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent)\n }\n }\n\n if (state.tag === null) {\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n } else if (state.tag === '?') {\n // Implicit resolving is not allowed for non-scalar types, and '?'\n // non-specific tag is only automatically assigned to plain scalars.\n //\n // We only need to check kind conformity in case user explicitly assigns '?'\n // tag, for example like this: \"! [0]\"\n //\n if (state.result !== null && state.kind !== 'scalar') {\n throwError(state, 'unacceptable node kind for ! tag; it should be \"scalar\", not \"' + state.kind + '\"')\n }\n\n for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type = state.implicitTypes[typeIndex]\n\n if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n state.result = type.construct(state.result)\n state.tag = type.tag\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n break\n }\n }\n } else if (state.tag !== '!') {\n if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n type = state.typeMap[state.kind || 'fallback'][state.tag]\n } else {\n // looking for multi type\n type = null\n const typeList = state.typeMap.multi[state.kind || 'fallback']\n\n for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {\n if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n type = typeList[typeIndex]\n break\n }\n }\n }\n\n if (!type) {\n throwError(state, 'unknown tag !<' + state.tag + '>')\n }\n\n if (state.result !== null && type.kind !== state.kind) {\n throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"')\n }\n\n if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched\n throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag')\n } else {\n state.result = type.construct(state.result, state.tag)\n if (state.anchor !== null) {\n storeAnchor(state, state.anchor, state.result)\n }\n }\n }\n\n if (state.listener !== null) {\n state.listener('close', state)\n }\n\n state.depth -= 1\n return state.tag !== null || state.anchor !== null || hasContent\n}\n\nfunction readDocument (state) {\n const documentStart = state.position\n let hasDirectives = false\n let ch\n\n state.version = null\n state.checkLineBreaks = state.legacy\n state.tagMap = Object.create(null)\n state.anchorMap = Object.create(null)\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1)\n\n ch = state.input.charCodeAt(state.position)\n\n if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n break\n }\n\n hasDirectives = true\n ch = state.input.charCodeAt(++state.position)\n let _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n const directiveName = state.input.slice(_position, state.position)\n const directiveArgs = []\n\n if (directiveName.length < 1) {\n throwError(state, 'directive name must not be less than one character in length')\n }\n\n while (ch !== 0) {\n while (isWhiteSpace(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position) }\n while (ch !== 0 && !isEol(ch))\n break\n }\n\n if (isEol(ch)) break\n\n _position = state.position\n\n while (ch !== 0 && !isWsOrEol(ch)) {\n ch = state.input.charCodeAt(++state.position)\n }\n\n directiveArgs.push(state.input.slice(_position, state.position))\n }\n\n if (ch !== 0) readLineBreak(state)\n\n if (_hasOwnProperty.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs)\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"')\n }\n }\n\n skipSeparationSpace(state, true, -1)\n\n if (state.lineIndent === 0 &&\n state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n state.position += 3\n skipSeparationSpace(state, true, -1)\n } else if (hasDirectives) {\n throwError(state, 'directives end mark is expected')\n }\n\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true)\n skipSeparationSpace(state, true, -1)\n\n if (state.checkLineBreaks &&\n PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, 'non-ASCII line breaks are interpreted as content')\n }\n\n state.documents.push(state.result)\n\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n state.position += 3\n skipSeparationSpace(state, true, -1)\n }\n return\n }\n\n if (state.position < (state.length - 1)) {\n throwError(state, 'end of the stream or a document separator is expected')\n }\n}\n\nfunction loadDocuments (input, options) {\n input = String(input)\n options = options || {}\n\n if (input.length !== 0) {\n // Add tailing `\\n` if not exists\n if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n input += '\\n'\n }\n\n // Strip BOM\n if (input.charCodeAt(0) === 0xFEFF) {\n input = input.slice(1)\n }\n }\n\n const state = new State(input, options)\n\n const nullpos = input.indexOf('\\0')\n\n if (nullpos !== -1) {\n state.position = nullpos\n throwError(state, 'null byte is not allowed in input')\n }\n\n // Use 0 as string terminator. That significantly simplifies bounds check.\n state.input += '\\0'\n\n while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n state.lineIndent += 1\n state.position += 1\n }\n\n while (state.position < (state.length - 1)) {\n readDocument(state)\n }\n\n return state.documents\n}\n\nfunction loadAll (input, iterator, options) {\n if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n options = iterator\n iterator = null\n }\n\n const documents = loadDocuments(input, options)\n\n if (typeof iterator !== 'function') {\n return documents\n }\n\n for (let index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index])\n }\n}\n\nfunction load (input, options) {\n const documents = loadDocuments(input, options)\n\n if (documents.length === 0) {\n return undefined\n } else if (documents.length === 1) {\n return documents[0]\n }\n throw new YAMLException('expected a single document in the stream, but found more')\n}\n\nmodule.exports.loadAll = loadAll\nmodule.exports.load = load\n","'use strict'\n\nconst common = require('./common')\nconst YAMLException = require('./exception')\nconst DEFAULT_SCHEMA = require('./schema/default')\n\nconst _toString = Object.prototype.toString\nconst _hasOwnProperty = Object.prototype.hasOwnProperty\n\nconst CHAR_BOM = 0xFEFF\nconst CHAR_TAB = 0x09 /* Tab */\nconst CHAR_LINE_FEED = 0x0A /* LF */\nconst CHAR_CARRIAGE_RETURN = 0x0D /* CR */\nconst CHAR_SPACE = 0x20 /* Space */\nconst CHAR_EXCLAMATION = 0x21 /* ! */\nconst CHAR_DOUBLE_QUOTE = 0x22 /* \" */\nconst CHAR_SHARP = 0x23 /* # */\nconst CHAR_PERCENT = 0x25 /* % */\nconst CHAR_AMPERSAND = 0x26 /* & */\nconst CHAR_SINGLE_QUOTE = 0x27 /* ' */\nconst CHAR_ASTERISK = 0x2A /* * */\nconst CHAR_COMMA = 0x2C /* , */\nconst CHAR_MINUS = 0x2D /* - */\nconst CHAR_COLON = 0x3A /* : */\nconst CHAR_EQUALS = 0x3D /* = */\nconst CHAR_GREATER_THAN = 0x3E /* > */\nconst CHAR_QUESTION = 0x3F /* ? */\nconst CHAR_COMMERCIAL_AT = 0x40 /* @ */\nconst CHAR_LEFT_SQUARE_BRACKET = 0x5B /* [ */\nconst CHAR_RIGHT_SQUARE_BRACKET = 0x5D /* ] */\nconst CHAR_GRAVE_ACCENT = 0x60 /* ` */\nconst CHAR_LEFT_CURLY_BRACKET = 0x7B /* { */\nconst CHAR_VERTICAL_LINE = 0x7C /* | */\nconst CHAR_RIGHT_CURLY_BRACKET = 0x7D /* } */\n\nconst ESCAPE_SEQUENCES = {}\n\nESCAPE_SEQUENCES[0x00] = '\\\\0'\nESCAPE_SEQUENCES[0x07] = '\\\\a'\nESCAPE_SEQUENCES[0x08] = '\\\\b'\nESCAPE_SEQUENCES[0x09] = '\\\\t'\nESCAPE_SEQUENCES[0x0A] = '\\\\n'\nESCAPE_SEQUENCES[0x0B] = '\\\\v'\nESCAPE_SEQUENCES[0x0C] = '\\\\f'\nESCAPE_SEQUENCES[0x0D] = '\\\\r'\nESCAPE_SEQUENCES[0x1B] = '\\\\e'\nESCAPE_SEQUENCES[0x22] = '\\\\\"'\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\'\nESCAPE_SEQUENCES[0x85] = '\\\\N'\nESCAPE_SEQUENCES[0xA0] = '\\\\_'\nESCAPE_SEQUENCES[0x2028] = '\\\\L'\nESCAPE_SEQUENCES[0x2029] = '\\\\P'\n\nconst DEPRECATED_BOOLEANS_SYNTAX = [\n 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n]\n\nconst DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/\n\nfunction compileStyleMap (schema, map) {\n if (map === null) return {}\n\n const result = {}\n const keys = Object.keys(map)\n\n for (let index = 0, length = keys.length; index < length; index += 1) {\n let tag = keys[index]\n let style = String(map[tag])\n\n if (tag.slice(0, 2) === '!!') {\n tag = 'tag:yaml.org,2002:' + tag.slice(2)\n }\n const type = schema.compiledTypeMap['fallback'][tag]\n\n if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n style = type.styleAliases[style]\n }\n\n result[tag] = style\n }\n\n return result\n}\n\nfunction encodeHex (character) {\n let handle\n let length\n\n const string = character.toString(16).toUpperCase()\n\n if (character <= 0xFF) {\n handle = 'x'\n length = 2\n } else if (character <= 0xFFFF) {\n handle = 'u'\n length = 4\n } else if (character <= 0xFFFFFFFF) {\n handle = 'U'\n length = 8\n } else {\n throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF')\n }\n\n return '\\\\' + handle + common.repeat('0', length - string.length) + string\n}\n\nconst QUOTING_TYPE_SINGLE = 1\nconst QUOTING_TYPE_DOUBLE = 2\n\nfunction State (options) {\n this.schema = options['schema'] || DEFAULT_SCHEMA\n this.indent = Math.max(1, (options['indent'] || 2))\n this.noArrayIndent = options['noArrayIndent'] || false\n this.skipInvalid = options['skipInvalid'] || false\n this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel'])\n this.styleMap = compileStyleMap(this.schema, options['styles'] || null)\n this.sortKeys = options['sortKeys'] || false\n this.lineWidth = options['lineWidth'] || 80\n this.noRefs = options['noRefs'] || false\n this.noCompatMode = options['noCompatMode'] || false\n this.condenseFlow = options['condenseFlow'] || false\n this.quotingType = options['quotingType'] === '\"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE\n this.forceQuotes = options['forceQuotes'] || false\n this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null\n\n this.implicitTypes = this.schema.compiledImplicit\n this.explicitTypes = this.schema.compiledExplicit\n\n this.tag = null\n this.result = ''\n\n this.duplicates = []\n this.usedDuplicates = null\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString (string, spaces) {\n const ind = common.repeat(' ', spaces)\n let position = 0\n let result = ''\n const length = string.length\n\n while (position < length) {\n let line\n const next = string.indexOf('\\n', position)\n if (next === -1) {\n line = string.slice(position)\n position = length\n } else {\n line = string.slice(position, next + 1)\n position = next + 1\n }\n\n if (line.length && line !== '\\n') result += ind\n\n result += line\n }\n\n return result\n}\n\nfunction generateNextLine (state, level) {\n return '\\n' + common.repeat(' ', state.indent * level)\n}\n\nfunction testImplicitResolving (state, str) {\n for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n const type = state.implicitTypes[index]\n\n if (type.resolve(str)) {\n return true\n }\n }\n\n return false\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace (c) {\n return c === CHAR_SPACE || c === CHAR_TAB\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable (c) {\n return (c >= 0x00020 && c <= 0x00007E) ||\n ((c >= 0x000A1 && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) ||\n ((c >= 0x0E000 && c <= 0x00FFFD) && c !== CHAR_BOM) ||\n (c >= 0x10000 && c <= 0x10FFFF)\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char ::= b-line-feed | b-carriage-return\n// Including s-white (for some reason, examples doesn't match specs in this aspect)\n// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark\nfunction isNsCharOrWhitespace (c) {\n return isPrintable(c) &&\n c !== CHAR_BOM &&\n // - b-char\n c !== CHAR_CARRIAGE_RETURN &&\n c !== CHAR_LINE_FEED\n}\n\n// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out\n// c = flow-in ⇒ ns-plain-safe-in\n// c = block-key ⇒ ns-plain-safe-out\n// c = flow-key ⇒ ns-plain-safe-in\n// [128] ns-plain-safe-out ::= ns-char\n// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator\n// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:� - “#� )\n// | ( /* An ns-char preceding */ “#� )\n// | ( “:� /* Followed by an ns-plain-safe(c) */ )\nfunction isPlainSafe (c, prev, inblock) {\n const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c)\n const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c)\n return (\n (\n // ns-plain-safe\n inblock // c = flow-in\n ? cIsNsCharOrWhitespace\n : cIsNsCharOrWhitespace &&\n // - c-flow-indicator\n c !== CHAR_COMMA &&\n c !== CHAR_LEFT_SQUARE_BRACKET &&\n c !== CHAR_RIGHT_SQUARE_BRACKET &&\n c !== CHAR_LEFT_CURLY_BRACKET &&\n c !== CHAR_RIGHT_CURLY_BRACKET\n ) &&\n // ns-plain-char\n c !== CHAR_SHARP && // false on '#'\n !(prev === CHAR_COLON && !cIsNsChar)\n ) || // false on ': '\n (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#'\n (prev === CHAR_COLON && cIsNsChar) // change to true on ':[^ ]'\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst (c) {\n // Uses a subset of ns-char - c-indicator\n // where ns-char = nb-char - s-white.\n // No support of ( ( “?� | “:� | “-� ) /* Followed by an ns-plain-safe(c)) */ ) part\n return isPrintable(c) &&\n c !== CHAR_BOM &&\n !isWhitespace(c) && // - s-white\n // - (c-indicator ::=\n // “-� | “?� | “:� | “,� | “[� | “]� | “{� | “}�\n c !== CHAR_MINUS &&\n c !== CHAR_QUESTION &&\n c !== CHAR_COLON &&\n c !== CHAR_COMMA &&\n c !== CHAR_LEFT_SQUARE_BRACKET &&\n c !== CHAR_RIGHT_SQUARE_BRACKET &&\n c !== CHAR_LEFT_CURLY_BRACKET &&\n c !== CHAR_RIGHT_CURLY_BRACKET &&\n // | “#� | “&� | “*� | “!� | “|� | “=� | “>� | “'� | “\"�\n c !== CHAR_SHARP &&\n c !== CHAR_AMPERSAND &&\n c !== CHAR_ASTERISK &&\n c !== CHAR_EXCLAMATION &&\n c !== CHAR_VERTICAL_LINE &&\n c !== CHAR_EQUALS &&\n c !== CHAR_GREATER_THAN &&\n c !== CHAR_SINGLE_QUOTE &&\n c !== CHAR_DOUBLE_QUOTE &&\n // | “%� | “@� | “`�)\n c !== CHAR_PERCENT &&\n c !== CHAR_COMMERCIAL_AT &&\n c !== CHAR_GRAVE_ACCENT\n}\n\n// Simplified test for values allowed as the last character in plain style.\nfunction isPlainSafeLast (c) {\n // just not whitespace or colon, it will be checked to be plain character later\n return !isWhitespace(c) && c !== CHAR_COLON\n}\n\n// Same as 'string'.codePointAt(pos), but works in older browsers.\nfunction codePointAt (string, pos) {\n const first = string.charCodeAt(pos)\n let second\n\n if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {\n second = string.charCodeAt(pos + 1)\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000\n }\n }\n return first\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator (string) {\n const leadingSpaceRe = /^\\n* /\n return leadingSpaceRe.test(string)\n}\n\nconst STYLE_PLAIN = 1\nconst STYLE_SINGLE = 2\nconst STYLE_LITERAL = 3\nconst STYLE_FOLDED = 4\nconst STYLE_DOUBLE = 5\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n// STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle (string, singleLineOnly, indentPerLevel, lineWidth,\n testAmbiguousType, quotingType, forceQuotes, inblock) {\n let i\n let char = 0\n let prevChar = null\n let hasLineBreak = false\n let hasFoldableLine = false // only checked if shouldTrackWidth\n const shouldTrackWidth = lineWidth !== -1\n let previousLineBreak = -1 // count the first line correctly\n let plain = isPlainSafeFirst(codePointAt(string, 0)) &&\n isPlainSafeLast(codePointAt(string, string.length - 1))\n\n if (singleLineOnly || forceQuotes) {\n // Case: no block styles.\n // Check for disallowed characters to rule out plain and single.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n if (!isPrintable(char)) {\n return STYLE_DOUBLE\n }\n plain = plain && isPlainSafe(char, prevChar, inblock)\n prevChar = char\n }\n } else {\n // Case: block styles permitted.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true\n // Check if any line can be folded.\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine ||\n // Foldable line = too long, and not more-indented.\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' ')\n previousLineBreak = i\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE\n }\n plain = plain && isPlainSafe(char, prevChar, inblock)\n prevChar = char\n }\n // in case the end is missing a \\n\n hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' '))\n }\n // Although every style can represent \\n without escaping, prefer block styles\n // for multiline, since they're more readable and they don't add empty lines.\n // Also prefer folding a super-long line.\n if (!hasLineBreak && !hasFoldableLine) {\n // Strings interpretable as another type have to be quoted;\n // e.g. the string 'true' vs. the boolean true.\n if (plain && !forceQuotes && !testAmbiguousType(string)) {\n return STYLE_PLAIN\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE\n }\n // Edge case: block indentation indicator can only have one digit.\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE\n }\n // At this point we know block styles are valid.\n // Prefer literal style unless we want to fold.\n if (!forceQuotes) {\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n// since the dumper adds its own newline. This always works:\n// • No ending newline => unaffected; already using strip \"-\" chomping.\n// • Ending newline => removed then restored.\n// Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar (state, string, level, iskey, inblock) {\n state.dump = (function () {\n if (string.length === 0) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? '\"\"' : \"''\"\n }\n if (!state.noCompatMode) {\n if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? ('\"' + string + '\"') : (\"'\" + string + \"'\")\n }\n }\n\n const indent = state.indent * Math.max(1, level) // no 0-indent scalars\n // As indentation gets deeper, let the width decrease monotonically\n // to the lower bound min(state.lineWidth, 40).\n // Note that this implies\n // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.\n // state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n // This behaves better than a constant minimum width which disallows narrower options,\n // or an indent threshold which causes the width to suddenly increase.\n const lineWidth = (state.lineWidth === -1)\n ? -1\n : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent)\n\n // Without knowing if keys are implicit/explicit, assume implicit for safety.\n const singleLineOnly = iskey ||\n // No block styles in flow mode.\n (state.flowLevel > -1 && level >= state.flowLevel)\n function testAmbiguity (string) {\n return testImplicitResolving(state, string)\n }\n\n switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,\n testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {\n case STYLE_PLAIN:\n return string\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\"\n case STYLE_LITERAL:\n return '|' + blockHeader(string, state.indent) +\n dropEndingNewline(indentString(string, indent))\n case STYLE_FOLDED:\n return '>' + blockHeader(string, state.indent) +\n dropEndingNewline(indentString(foldString(string, lineWidth), indent))\n case STYLE_DOUBLE:\n return '\"' + escapeString(string, lineWidth) + '\"'\n default:\n throw new YAMLException('impossible error: invalid scalar style')\n }\n }())\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader (string, indentPerLevel) {\n const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''\n\n // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n const clip = string[string.length - 1] === '\\n'\n const keep = clip && (string[string.length - 2] === '\\n' || string === '\\n')\n const chomp = keep ? '+' : (clip ? '' : '-')\n\n return indentIndicator + chomp + '\\n'\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline (string) {\n return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString (string, width) {\n // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n // unless they're before or after a more-indented line, or at the very\n // beginning or end, in which case $k$ maps to $k$.\n // Therefore, parse each chunk as newline(s) followed by a content line.\n const lineRe = /(\\n+)([^\\n]*)/g\n\n // first line (possibly an empty line)\n let result = (function () {\n let nextLF = string.indexOf('\\n')\n nextLF = nextLF !== -1 ? nextLF : string.length\n lineRe.lastIndex = nextLF\n return foldLine(string.slice(0, nextLF), width)\n }())\n // If we haven't reached the first content line yet, don't add an extra \\n.\n let prevMoreIndented = string[0] === '\\n' || string[0] === ' '\n let moreIndented\n\n // rest of the lines\n let match\n while ((match = lineRe.exec(string))) {\n const prefix = match[1]\n const line = match[2]\n\n moreIndented = (line[0] === ' ')\n result += prefix +\n ((!prevMoreIndented && !moreIndented && line !== '') ? '\\n' : '') +\n foldLine(line, width)\n prevMoreIndented = moreIndented\n }\n\n return result\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine (line, width) {\n if (line === '' || line[0] === ' ') return line\n\n // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n const breakRe = / [^ ]/g // note: the match index will always be <= length-2.\n let match\n // start is an inclusive index. end, curr, and next are exclusive.\n let start = 0\n let end\n let curr = 0\n let next = 0\n let result = ''\n\n // Invariants: 0 <= start <= length-1.\n // 0 <= curr <= next <= max(0, length-2). curr - start <= width.\n // Inside the loop:\n // A match implies length >= 2, so curr and next are <= length-2.\n while ((match = breakRe.exec(line))) {\n next = match.index\n // maintain invariant: curr - start <= width\n if (next - start > width) {\n end = (curr > start) ? curr : next // derive end <= length-2\n result += '\\n' + line.slice(start, end)\n // skip the space that was output as \\n\n start = end + 1 // derive start <= length-1\n }\n curr = next\n }\n\n // By the invariants, start <= length-1, so there is something left over.\n // It is either the whole string or a part starting from non-whitespace.\n result += '\\n'\n // Insert a break if the remainder is too long and there is a break available.\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + '\\n' + line.slice(curr + 1)\n } else {\n result += line.slice(start)\n }\n\n return result.slice(1) // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString (string) {\n let result = ''\n let char = 0\n\n for (let i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i)\n const escapeSeq = ESCAPE_SEQUENCES[char]\n\n if (!escapeSeq && isPrintable(char)) {\n result += string[i]\n if (char >= 0x10000) result += string[i + 1]\n } else {\n result += escapeSeq || encodeHex(char)\n }\n }\n\n return result\n}\n\nfunction writeFlowSequence (state, level, object) {\n let _result = ''\n const _tag = state.tag\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n let value = object[index]\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value)\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level, value, false, false) ||\n (typeof value === 'undefined' &&\n writeNode(state, level, null, false, false))) {\n if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '')\n _result += state.dump\n }\n }\n\n state.tag = _tag\n state.dump = '[' + _result + ']'\n}\n\nfunction writeBlockSequence (state, level, object, compact) {\n let _result = ''\n const _tag = state.tag\n\n for (let index = 0, length = object.length; index < length; index += 1) {\n let value = object[index]\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value)\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level + 1, value, true, true, false, true) ||\n (typeof value === 'undefined' &&\n writeNode(state, level + 1, null, true, true, false, true))) {\n if (!compact || _result !== '') {\n _result += generateNextLine(state, level)\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += '-'\n } else {\n _result += '- '\n }\n\n _result += state.dump\n }\n }\n\n state.tag = _tag\n state.dump = _result || '[]' // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping (state, level, object) {\n let _result = ''\n const _tag = state.tag\n const objectKeyList = Object.keys(object)\n\n for (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n let pairBuffer = ''\n if (_result !== '') pairBuffer += ', '\n\n if (state.condenseFlow) pairBuffer += '\"'\n\n const objectKey = objectKeyList[index]\n let objectValue = object[objectKey]\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue)\n }\n\n if (!writeNode(state, level, objectKey, false, false)) {\n continue // Skip this pair because of invalid key;\n }\n\n if (state.dump.length > 1024) pairBuffer += '? '\n\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ')\n\n if (!writeNode(state, level, objectValue, false, false)) {\n continue // Skip this pair because of invalid value.\n }\n\n pairBuffer += state.dump\n\n // Both key and value are valid.\n _result += pairBuffer\n }\n\n state.tag = _tag\n state.dump = '{' + _result + '}'\n}\n\nfunction writeBlockMapping (state, level, object, compact) {\n let _result = ''\n const _tag = state.tag\n const objectKeyList = Object.keys(object)\n\n // Allow sorting keys so that the output file is deterministic\n if (state.sortKeys === true) {\n // Default sorting\n objectKeyList.sort()\n } else if (typeof state.sortKeys === 'function') {\n // Custom sort function\n objectKeyList.sort(state.sortKeys)\n } else if (state.sortKeys) {\n // Something is wrong\n throw new YAMLException('sortKeys must be a boolean or a function')\n }\n\n for (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n let pairBuffer = ''\n\n if (!compact || _result !== '') {\n pairBuffer += generateNextLine(state, level)\n }\n\n const objectKey = objectKeyList[index]\n let objectValue = object[objectKey]\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue)\n }\n\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue // Skip this pair because of invalid key.\n }\n\n const explicitPair = (state.tag !== null && state.tag !== '?') ||\n (state.dump && state.dump.length > 1024)\n\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += '?'\n } else {\n pairBuffer += '? '\n }\n }\n\n pairBuffer += state.dump\n\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level)\n }\n\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue // Skip this pair because of invalid value.\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += ':'\n } else {\n pairBuffer += ': '\n }\n\n pairBuffer += state.dump\n\n // Both key and value are valid.\n _result += pairBuffer\n }\n\n state.tag = _tag\n state.dump = _result || '{}' // Empty mapping if no valid pairs.\n}\n\nfunction detectType (state, object, explicit) {\n const typeList = explicit ? state.explicitTypes : state.implicitTypes\n\n for (let index = 0, length = typeList.length; index < length; index += 1) {\n const type = typeList[index]\n\n if ((type.instanceOf || type.predicate) &&\n (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n (!type.predicate || type.predicate(object))) {\n if (explicit) {\n if (type.multi && type.representName) {\n state.tag = type.representName(object)\n } else {\n state.tag = type.tag\n }\n } else {\n state.tag = '?'\n }\n\n if (type.represent) {\n const style = state.styleMap[type.tag] || type.defaultStyle\n\n let _result\n if (_toString.call(type.represent) === '[object Function]') {\n _result = type.represent(object, style)\n } else if (_hasOwnProperty.call(type.represent, style)) {\n _result = type.represent[style](object, style)\n } else {\n throw new YAMLException('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style')\n }\n\n state.dump = _result\n }\n\n return true\n }\n }\n\n return false\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode (state, level, object, block, compact, iskey, isblockseq) {\n state.tag = null\n state.dump = object\n\n if (!detectType(state, object, false)) {\n detectType(state, object, true)\n }\n\n const type = _toString.call(state.dump)\n const inblock = block\n\n if (block) {\n block = (state.flowLevel < 0 || state.flowLevel > level)\n }\n\n const objectOrArray = type === '[object Object]' || type === '[object Array]'\n let duplicateIndex\n let duplicate\n\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object)\n duplicate = duplicateIndex !== -1\n }\n\n if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n compact = false\n }\n\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = '*ref_' + duplicateIndex\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true\n }\n if (type === '[object Object]') {\n if (block && (Object.keys(state.dump).length !== 0)) {\n writeBlockMapping(state, level, state.dump, compact)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump\n }\n } else {\n writeFlowMapping(state, level, state.dump)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump\n }\n }\n } else if (type === '[object Array]') {\n if (block && (state.dump.length !== 0)) {\n if (state.noArrayIndent && !isblockseq && level > 0) {\n writeBlockSequence(state, level - 1, state.dump, compact)\n } else {\n writeBlockSequence(state, level, state.dump, compact)\n }\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump\n }\n } else {\n writeFlowSequence(state, level, state.dump)\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump\n }\n }\n } else if (type === '[object String]') {\n if (state.tag !== '?') {\n writeScalar(state, state.dump, level, iskey, inblock)\n }\n } else if (type === '[object Undefined]') {\n return false\n } else {\n if (state.skipInvalid) return false\n throw new YAMLException('unacceptable kind of an object to dump ' + type)\n }\n\n if (state.tag !== null && state.tag !== '?') {\n // Need to encode all characters except those allowed by the spec:\n //\n // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */\n // [36] ns-hex-digit ::= ns-dec-digit\n // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */\n // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */\n // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-�\n // [39] ns-uri-char ::= “%� ns-hex-digit ns-hex-digit | ns-word-char | “#�\n // | “;� | “/� | “?� | “:� | “@� | “&� | “=� | “+� | “$� | “,�\n // | “_� | “.� | “!� | “~� | “*� | “'� | “(� | “)� | “[� | “]�\n //\n // Also need to encode '!' because it has special meaning (end of tag prefix).\n //\n let tagStr = encodeURI(\n state.tag[0] === '!' ? state.tag.slice(1) : state.tag\n ).replace(/!/g, '%21')\n\n if (state.tag[0] === '!') {\n tagStr = '!' + tagStr\n } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {\n tagStr = '!!' + tagStr.slice(18)\n } else {\n tagStr = '!<' + tagStr + '>'\n }\n\n state.dump = tagStr + ' ' + state.dump\n }\n }\n\n return true\n}\n\nfunction getDuplicateReferences (object, state) {\n const objects = []\n const duplicatesIndexes = []\n\n inspectNode(object, objects, duplicatesIndexes)\n\n const length = duplicatesIndexes.length\n for (let index = 0; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]])\n }\n state.usedDuplicates = new Array(length)\n}\n\nfunction inspectNode (object, objects, duplicatesIndexes) {\n if (object !== null && typeof object === 'object') {\n const index = objects.indexOf(object)\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index)\n }\n } else {\n objects.push(object)\n\n if (Array.isArray(object)) {\n for (let i = 0, length = object.length; i < length; i += 1) {\n inspectNode(object[i], objects, duplicatesIndexes)\n }\n } else {\n const objectKeyList = Object.keys(object)\n\n for (let i = 0, length = objectKeyList.length; i < length; i += 1) {\n inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes)\n }\n }\n }\n }\n}\n\nfunction dump (input, options) {\n options = options || {}\n\n const state = new State(options)\n\n if (!state.noRefs) getDuplicateReferences(input, state)\n\n let value = input\n\n if (state.replacer) {\n value = state.replacer.call({ '': value }, '', value)\n }\n\n if (writeNode(state, 0, value, true, true)) return state.dump + '\\n'\n\n return ''\n}\n\nmodule.exports.dump = dump\n","'use strict'\n\nconst loader = require('./lib/loader')\nconst dumper = require('./lib/dumper')\n\nfunction renamed (from, to) {\n return function () {\n throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +\n 'Use yaml.' + to + ' instead, which is now safe by default.')\n }\n}\n\nmodule.exports.Type = require('./lib/type')\nmodule.exports.Schema = require('./lib/schema')\nmodule.exports.FAILSAFE_SCHEMA = require('./lib/schema/failsafe')\nmodule.exports.JSON_SCHEMA = require('./lib/schema/json')\nmodule.exports.CORE_SCHEMA = require('./lib/schema/core')\nmodule.exports.DEFAULT_SCHEMA = require('./lib/schema/default')\nmodule.exports.load = loader.load\nmodule.exports.loadAll = loader.loadAll\nmodule.exports.dump = dumper.dump\nmodule.exports.YAMLException = require('./lib/exception')\n\n// Re-export all types in case user wants to create custom schema\nmodule.exports.types = {\n binary: require('./lib/type/binary'),\n float: require('./lib/type/float'),\n map: require('./lib/type/map'),\n null: require('./lib/type/null'),\n pairs: require('./lib/type/pairs'),\n set: require('./lib/type/set'),\n timestamp: require('./lib/type/timestamp'),\n bool: require('./lib/type/bool'),\n int: require('./lib/type/int'),\n merge: require('./lib/type/merge'),\n omap: require('./lib/type/omap'),\n seq: require('./lib/type/seq'),\n str: require('./lib/type/str')\n}\n\n// Removed functions from JS-YAML 3.0.x\nmodule.exports.safeLoad = renamed('safeLoad', 'load')\nmodule.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll')\nmodule.exports.safeDump = renamed('safeDump', 'dump')\n","import yaml from '../index.js'\n\nconst {\n Type,\n Schema,\n FAILSAFE_SCHEMA,\n JSON_SCHEMA,\n CORE_SCHEMA,\n DEFAULT_SCHEMA,\n load,\n loadAll,\n dump,\n YAMLException,\n types,\n safeLoad,\n safeLoadAll,\n safeDump\n} = yaml\n\nexport {\n Type,\n Schema,\n FAILSAFE_SCHEMA,\n JSON_SCHEMA,\n CORE_SCHEMA,\n DEFAULT_SCHEMA,\n load,\n loadAll,\n dump,\n YAMLException,\n types,\n safeLoad,\n safeLoadAll,\n safeDump\n}\n\nexport default yaml\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;CAEA,SAAS,UAAW,SAAS;EAC3B,OAAQ,OAAO,YAAY,eAAiB,YAAY;CAC1D;CAEA,SAAS,SAAU,SAAS;EAC1B,OAAQ,OAAO,YAAY,YAAc,YAAY;CACvD;CAEA,SAAS,QAAS,UAAU;EAC1B,IAAI,MAAM,QAAQ,QAAQ,GAAG,OAAO;OAC/B,IAAI,UAAU,QAAQ,GAAG,OAAO,CAAC;EAEtC,OAAO,CAAC,QAAQ;CAClB;CAEA,SAAS,OAAQ,QAAQ,QAAQ;EAC/B,IAAI,QAAQ;GACV,MAAM,aAAa,OAAO,KAAK,MAAM;GAErC,KAAK,IAAI,QAAQ,GAAG,SAAS,WAAW,QAAQ,QAAQ,QAAQ,SAAS,GAAG;IAC1E,MAAM,MAAM,WAAW;IACvB,OAAO,OAAO,OAAO;GACvB;EACF;EAEA,OAAO;CACT;CAEA,SAAS,OAAQ,QAAQ,OAAO;EAC9B,IAAI,SAAS;EAEb,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,SAAS,GAC1C,UAAU;EAGZ,OAAO;CACT;CAEA,SAAS,eAAgB,QAAQ;EAC/B,OAAQ,WAAW,KAAO,OAAO,sBAAsB,IAAI;CAC7D;CAEA,OAAO,QAA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pD,OAAO,QAAQ,cAAc,QAAQ,eAAe,SAAS;CAC7D,OAAO,QAAQ,WAAW,QAAQ,YAAY,MAAM;;ACzCpD,IAAM,EACJ,MACA,QACA,iBACA,aACA,aACA,gBACA,MACA,SACA,MACA,eACA,OACA,UACA,aACA,aACEA,eAAAA;AAmBJ,IAAA,+BAAeA,eAAAA"}'use strict' const loader = require('./lib/loader') const dumper = require('./lib/dumper') function renamed (from, to) { return function () { throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + 'Use yaml.' + to + ' instead, which is now safe by default.') } } module.exports.Type = require('./lib/type') module.exports.Schema = require('./lib/schema') module.exports.FAILSAFE_SCHEMA = require('./lib/schema/failsafe') module.exports.JSON_SCHEMA = require('./lib/schema/json') module.exports.CORE_SCHEMA = require('./lib/schema/core') module.exports.DEFAULT_SCHEMA = require('./lib/schema/default') module.exports.load = loader.load module.exports.loadAll = loader.loadAll module.exports.dump = dumper.dump module.exports.YAMLException = require('./lib/exception') // Re-export all types in case user wants to create custom schema module.exports.types = { binary: require('./lib/type/binary'), float: require('./lib/type/float'), map: require('./lib/type/map'), null: require('./lib/type/null'), pairs: require('./lib/type/pairs'), set: require('./lib/type/set'), timestamp: require('./lib/type/timestamp'), bool: require('./lib/type/bool'), int: require('./lib/type/int'), merge: require('./lib/type/merge'), omap: require('./lib/type/omap'), seq: require('./lib/type/seq'), str: require('./lib/type/str') } // Removed functions from JS-YAML 3.0.x module.exports.safeLoad = renamed('safeLoad', 'load') module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll') module.exports.safeDump = renamed('safeDump', 'dump') 'use strict' function isNothing (subject) { return (typeof subject === 'undefined') || (subject === null) } function isObject (subject) { return (typeof subject === 'object') && (subject !== null) } function toArray (sequence) { if (Array.isArray(sequence)) return sequence else if (isNothing(sequence)) return [] return [sequence] } function extend (target, source) { if (source) { const sourceKeys = Object.keys(source) for (let index = 0, length = sourceKeys.length; index < length; index += 1) { const key = sourceKeys[index] target[key] = source[key] } } return target } function repeat (string, count) { let result = '' for (let cycle = 0; cycle < count; cycle += 1) { result += string } return result } function isNegativeZero (number) { return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number) } module.exports.isNothing = isNothing module.exports.isObject = isObject module.exports.toArray = toArray module.exports.repeat = repeat module.exports.isNegativeZero = isNegativeZero module.exports.extend = extend 'use strict' const common = require('./common') const YAMLException = require('./exception') const DEFAULT_SCHEMA = require('./schema/default') const _toString = Object.prototype.toString const _hasOwnProperty = Object.prototype.hasOwnProperty const CHAR_BOM = 0xFEFF const CHAR_TAB = 0x09 /* Tab */ const CHAR_LINE_FEED = 0x0A /* LF */ const CHAR_CARRIAGE_RETURN = 0x0D /* CR */ const CHAR_SPACE = 0x20 /* Space */ const CHAR_EXCLAMATION = 0x21 /* ! */ const CHAR_DOUBLE_QUOTE = 0x22 /* " */ const CHAR_SHARP = 0x23 /* # */ const CHAR_PERCENT = 0x25 /* % */ const CHAR_AMPERSAND = 0x26 /* & */ const CHAR_SINGLE_QUOTE = 0x27 /* ' */ const CHAR_ASTERISK = 0x2A /* * */ const CHAR_COMMA = 0x2C /* , */ const CHAR_MINUS = 0x2D /* - */ const CHAR_COLON = 0x3A /* : */ const CHAR_EQUALS = 0x3D /* = */ const CHAR_GREATER_THAN = 0x3E /* > */ const CHAR_QUESTION = 0x3F /* ? */ const CHAR_COMMERCIAL_AT = 0x40 /* @ */ const CHAR_LEFT_SQUARE_BRACKET = 0x5B /* [ */ const CHAR_RIGHT_SQUARE_BRACKET = 0x5D /* ] */ const CHAR_GRAVE_ACCENT = 0x60 /* ` */ const CHAR_LEFT_CURLY_BRACKET = 0x7B /* { */ const CHAR_VERTICAL_LINE = 0x7C /* | */ const CHAR_RIGHT_CURLY_BRACKET = 0x7D /* } */ const ESCAPE_SEQUENCES = {} ESCAPE_SEQUENCES[0x00] = '\\0' ESCAPE_SEQUENCES[0x07] = '\\a' ESCAPE_SEQUENCES[0x08] = '\\b' ESCAPE_SEQUENCES[0x09] = '\\t' ESCAPE_SEQUENCES[0x0A] = '\\n' ESCAPE_SEQUENCES[0x0B] = '\\v' ESCAPE_SEQUENCES[0x0C] = '\\f' ESCAPE_SEQUENCES[0x0D] = '\\r' ESCAPE_SEQUENCES[0x1B] = '\\e' ESCAPE_SEQUENCES[0x22] = '\\"' ESCAPE_SEQUENCES[0x5C] = '\\\\' ESCAPE_SEQUENCES[0x85] = '\\N' ESCAPE_SEQUENCES[0xA0] = '\\_' ESCAPE_SEQUENCES[0x2028] = '\\L' ESCAPE_SEQUENCES[0x2029] = '\\P' const DEPRECATED_BOOLEANS_SYNTAX = [ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' ] const DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/ function compileStyleMap (schema, map) { if (map === null) return {} const result = {} const keys = Object.keys(map) for (let index = 0, length = keys.length; index < length; index += 1) { let tag = keys[index] let style = String(map[tag]) if (tag.slice(0, 2) === '!!') { tag = 'tag:yaml.org,2002:' + tag.slice(2) } const type = schema.compiledTypeMap['fallback'][tag] if (type && _hasOwnProperty.call(type.styleAliases, style)) { style = type.styleAliases[style] } result[tag] = style } return result } function encodeHex (character) { let handle let length const string = character.toString(16).toUpperCase() if (character <= 0xFF) { handle = 'x' length = 2 } else if (character <= 0xFFFF) { handle = 'u' length = 4 } else if (character <= 0xFFFFFFFF) { handle = 'U' length = 8 } else { throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF') } return '\\' + handle + common.repeat('0', length - string.length) + string } const QUOTING_TYPE_SINGLE = 1 const QUOTING_TYPE_DOUBLE = 2 function State (options) { this.schema = options['schema'] || DEFAULT_SCHEMA this.indent = Math.max(1, (options['indent'] || 2)) this.noArrayIndent = options['noArrayIndent'] || false this.skipInvalid = options['skipInvalid'] || false this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']) this.styleMap = compileStyleMap(this.schema, options['styles'] || null) this.sortKeys = options['sortKeys'] || false this.lineWidth = options['lineWidth'] || 80 this.noRefs = options['noRefs'] || false this.noCompatMode = options['noCompatMode'] || false this.condenseFlow = options['condenseFlow'] || false this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE this.forceQuotes = options['forceQuotes'] || false this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null this.implicitTypes = this.schema.compiledImplicit this.explicitTypes = this.schema.compiledExplicit this.tag = null this.result = '' this.duplicates = [] this.usedDuplicates = null } // Indents every line in a string. Empty lines (\n only) are not indented. function indentString (string, spaces) { const ind = common.repeat(' ', spaces) let position = 0 let result = '' const length = string.length while (position < length) { let line const next = string.indexOf('\n', position) if (next === -1) { line = string.slice(position) position = length } else { line = string.slice(position, next + 1) position = next + 1 } if (line.length && line !== '\n') result += ind result += line } return result } function generateNextLine (state, level) { return '\n' + common.repeat(' ', state.indent * level) } function testImplicitResolving (state, str) { for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) { const type = state.implicitTypes[index] if (type.resolve(str)) { return true } } return false } // [33] s-white ::= s-space | s-tab function isWhitespace (c) { return c === CHAR_SPACE || c === CHAR_TAB } // Returns true if the character can be printed without escaping. // From YAML 1.2: "any allowed characters known to be non-printable // should also be escaped. [However,] This isn’t mandatory" // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. function isPrintable (c) { return (c >= 0x00020 && c <= 0x00007E) || ((c >= 0x000A1 && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) || ((c >= 0x0E000 && c <= 0x00FFFD) && c !== CHAR_BOM) || (c >= 0x10000 && c <= 0x10FFFF) } // [34] ns-char ::= nb-char - s-white // [27] nb-char ::= c-printable - b-char - c-byte-order-mark // [26] b-char ::= b-line-feed | b-carriage-return // Including s-white (for some reason, examples doesn't match specs in this aspect) // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark function isNsCharOrWhitespace (c) { return isPrintable(c) && c !== CHAR_BOM && // - b-char c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED } // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out // c = flow-in ⇒ ns-plain-safe-in // c = block-key ⇒ ns-plain-safe-out // c = flow-key ⇒ ns-plain-safe-in // [128] ns-plain-safe-out ::= ns-char // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:� - “#� ) // | ( /* An ns-char preceding */ “#� ) // | ( “:� /* Followed by an ns-plain-safe(c) */ ) function isPlainSafe (c, prev, inblock) { const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c) const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c) return ( ( // ns-plain-safe inblock // c = flow-in ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && // - c-flow-indicator c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET ) && // ns-plain-char c !== CHAR_SHARP && // false on '#' !(prev === CHAR_COLON && !cIsNsChar) ) || // false on ': ' (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#' (prev === CHAR_COLON && cIsNsChar) // change to true on ':[^ ]' } // Simplified test for values allowed as the first character in plain style. function isPlainSafeFirst (c) { // Uses a subset of ns-char - c-indicator // where ns-char = nb-char - s-white. // No support of ( ( “?� | “:� | “-� ) /* Followed by an ns-plain-safe(c)) */ ) part return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && // - s-white // - (c-indicator ::= // “-� | “?� | “:� | “,� | “[� | “]� | “{� | “}� c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && // | “#� | “&� | “*� | “!� | “|� | “=� | “>� | “'� | “"� c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && // | “%� | “@� | “`�) c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT } // Simplified test for values allowed as the last character in plain style. function isPlainSafeLast (c) { // just not whitespace or colon, it will be checked to be plain character later return !isWhitespace(c) && c !== CHAR_COLON } // Same as 'string'.codePointAt(pos), but works in older browsers. function codePointAt (string, pos) { const first = string.charCodeAt(pos) let second if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { second = string.charCodeAt(pos + 1) if (second >= 0xDC00 && second <= 0xDFFF) { // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000 } } return first } // Determines whether block indentation indicator is required. function needIndentIndicator (string) { const leadingSpaceRe = /^\n* / return leadingSpaceRe.test(string) } const STYLE_PLAIN = 1 const STYLE_SINGLE = 2 const STYLE_LITERAL = 3 const STYLE_FOLDED = 4 const STYLE_DOUBLE = 5 // Determines which scalar styles are possible and returns the preferred style. // lineWidth = -1 => no limit. // Pre-conditions: str.length > 0. // Post-conditions: // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). function chooseScalarStyle (string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { let i let char = 0 let prevChar = null let hasLineBreak = false let hasFoldableLine = false // only checked if shouldTrackWidth const shouldTrackWidth = lineWidth !== -1 let previousLineBreak = -1 // count the first line correctly let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1)) if (singleLineOnly || forceQuotes) { // Case: no block styles. // Check for disallowed characters to rule out plain and single. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i) if (!isPrintable(char)) { return STYLE_DOUBLE } plain = plain && isPlainSafe(char, prevChar, inblock) prevChar = char } } else { // Case: block styles permitted. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i) if (char === CHAR_LINE_FEED) { hasLineBreak = true // Check if any line can be folded. if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ') previousLineBreak = i } } else if (!isPrintable(char)) { return STYLE_DOUBLE } plain = plain && isPlainSafe(char, prevChar, inblock) prevChar = char } // in case the end is missing a \n hasFoldableLine = hasFoldableLine || (shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ')) } // Although every style can represent \n without escaping, prefer block styles // for multiline, since they're more readable and they don't add empty lines. // Also prefer folding a super-long line. if (!hasLineBreak && !hasFoldableLine) { // Strings interpretable as another type have to be quoted; // e.g. the string 'true' vs. the boolean true. if (plain && !forceQuotes && !testAmbiguousType(string)) { return STYLE_PLAIN } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE } // Edge case: block indentation indicator can only have one digit. if (indentPerLevel > 9 && needIndentIndicator(string)) { return STYLE_DOUBLE } // At this point we know block styles are valid. // Prefer literal style unless we want to fold. if (!forceQuotes) { return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE } // Note: line breaking/folding is implemented for only the folded style. // NB. We drop the last trailing newline (if any) of a returned block scalar // since the dumper adds its own newline. This always works: // • No ending newline => unaffected; already using strip "-" chomping. // • Ending newline => removed then restored. // Importantly, this keeps the "+" chomp indicator from gaining an extra line. function writeScalar (state, string, level, iskey, inblock) { state.dump = (function () { if (string.length === 0) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''" } if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'") } } const indent = state.indent * Math.max(1, level) // no 0-indent scalars // As indentation gets deeper, let the width decrease monotonically // to the lower bound min(state.lineWidth, 40). // Note that this implies // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. // state.lineWidth > 40 + state.indent: width decreases until the lower bound. // This behaves better than a constant minimum width which disallows narrower options, // or an indent threshold which causes the width to suddenly increase. const lineWidth = (state.lineWidth === -1) ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent) // Without knowing if keys are implicit/explicit, assume implicit for safety. const singleLineOnly = iskey || // No block styles in flow mode. (state.flowLevel > -1 && level >= state.flowLevel) function testAmbiguity (string) { return testImplicitResolving(state, string) } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { case STYLE_PLAIN: return string case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'" case STYLE_LITERAL: return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)) case STYLE_FOLDED: return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)) case STYLE_DOUBLE: return '"' + escapeString(string, lineWidth) + '"' default: throw new YAMLException('impossible error: invalid scalar style') } }()) } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. function blockHeader (string, indentPerLevel) { const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '' // note the special case: the string '\n' counts as a "trailing" empty line. const clip = string[string.length - 1] === '\n' const keep = clip && (string[string.length - 2] === '\n' || string === '\n') const chomp = keep ? '+' : (clip ? '' : '-') return indentIndicator + chomp + '\n' } // (See the note for writeScalar.) function dropEndingNewline (string) { return string[string.length - 1] === '\n' ? string.slice(0, -1) : string } // Note: a long line without a suitable break point will exceed the width limit. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. function foldString (string, width) { // In folded style, $k$ consecutive newlines output as $k+1$ newlines— // unless they're before or after a more-indented line, or at the very // beginning or end, in which case $k$ maps to $k$. // Therefore, parse each chunk as newline(s) followed by a content line. const lineRe = /(\n+)([^\n]*)/g // first line (possibly an empty line) let result = (function () { let nextLF = string.indexOf('\n') nextLF = nextLF !== -1 ? nextLF : string.length lineRe.lastIndex = nextLF return foldLine(string.slice(0, nextLF), width) }()) // If we haven't reached the first content line yet, don't add an extra \n. let prevMoreIndented = string[0] === '\n' || string[0] === ' ' let moreIndented // rest of the lines let match while ((match = lineRe.exec(string))) { const prefix = match[1] const line = match[2] moreIndented = (line[0] === ' ') result += prefix + ((!prevMoreIndented && !moreIndented && line !== '') ? '\n' : '') + foldLine(line, width) prevMoreIndented = moreIndented } return result } // Greedy line breaking. // Picks the longest line under the limit each time, // otherwise settles for the shortest line over the limit. // NB. More-indented lines *cannot* be folded, as that would add an extra \n. function foldLine (line, width) { if (line === '' || line[0] === ' ') return line // Since a more-indented line adds a \n, breaks can't be followed by a space. const breakRe = / [^ ]/g // note: the match index will always be <= length-2. let match // start is an inclusive index. end, curr, and next are exclusive. let start = 0 let end let curr = 0 let next = 0 let result = '' // Invariants: 0 <= start <= length-1. // 0 <= curr <= next <= max(0, length-2). curr - start <= width. // Inside the loop: // A match implies length >= 2, so curr and next are <= length-2. while ((match = breakRe.exec(line))) { next = match.index // maintain invariant: curr - start <= width if (next - start > width) { end = (curr > start) ? curr : next // derive end <= length-2 result += '\n' + line.slice(start, end) // skip the space that was output as \n start = end + 1 // derive start <= length-1 } curr = next } // By the invariants, start <= length-1, so there is something left over. // It is either the whole string or a part starting from non-whitespace. result += '\n' // Insert a break if the remainder is too long and there is a break available. if (line.length - start > width && curr > start) { result += line.slice(start, curr) + '\n' + line.slice(curr + 1) } else { result += line.slice(start) } return result.slice(1) // drop extra \n joiner } // Escapes a double-quoted string. function escapeString (string) { let result = '' let char = 0 for (let i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i) const escapeSeq = ESCAPE_SEQUENCES[char] if (!escapeSeq && isPrintable(char)) { result += string[i] if (char >= 0x10000) result += string[i + 1] } else { result += escapeSeq || encodeHex(char) } } return result } function writeFlowSequence (state, level, object) { let _result = '' const _tag = state.tag for (let index = 0, length = object.length; index < length; index += 1) { let value = object[index] if (state.replacer) { value = state.replacer.call(object, String(index), value) } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level, value, false, false) || (typeof value === 'undefined' && writeNode(state, level, null, false, false))) { if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '') _result += state.dump } } state.tag = _tag state.dump = '[' + _result + ']' } function writeBlockSequence (state, level, object, compact) { let _result = '' const _tag = state.tag for (let index = 0, length = object.length; index < length; index += 1) { let value = object[index] if (state.replacer) { value = state.replacer.call(object, String(index), value) } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level + 1, value, true, true, false, true) || (typeof value === 'undefined' && writeNode(state, level + 1, null, true, true, false, true))) { if (!compact || _result !== '') { _result += generateNextLine(state, level) } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += '-' } else { _result += '- ' } _result += state.dump } } state.tag = _tag state.dump = _result || '[]' // Empty sequence if no valid values. } function writeFlowMapping (state, level, object) { let _result = '' const _tag = state.tag const objectKeyList = Object.keys(object) for (let index = 0, length = objectKeyList.length; index < length; index += 1) { let pairBuffer = '' if (_result !== '') pairBuffer += ', ' if (state.condenseFlow) pairBuffer += '"' const objectKey = objectKeyList[index] let objectValue = object[objectKey] if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue) } if (!writeNode(state, level, objectKey, false, false)) { continue // Skip this pair because of invalid key; } if (state.dump.length > 1024) pairBuffer += '? ' pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ') if (!writeNode(state, level, objectValue, false, false)) { continue // Skip this pair because of invalid value. } pairBuffer += state.dump // Both key and value are valid. _result += pairBuffer } state.tag = _tag state.dump = '{' + _result + '}' } function writeBlockMapping (state, level, object, compact) { let _result = '' const _tag = state.tag const objectKeyList = Object.keys(object) // Allow sorting keys so that the output file is deterministic if (state.sortKeys === true) { // Default sorting objectKeyList.sort() } else if (typeof state.sortKeys === 'function') { // Custom sort function objectKeyList.sort(state.sortKeys) } else if (state.sortKeys) { // Something is wrong throw new YAMLException('sortKeys must be a boolean or a function') } for (let index = 0, length = objectKeyList.length; index < length; index += 1) { let pairBuffer = '' if (!compact || _result !== '') { pairBuffer += generateNextLine(state, level) } const objectKey = objectKeyList[index] let objectValue = object[objectKey] if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue) } if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue // Skip this pair because of invalid key. } const explicitPair = (state.tag !== null && state.tag !== '?') || (state.dump && state.dump.length > 1024) if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += '?' } else { pairBuffer += '? ' } } pairBuffer += state.dump if (explicitPair) { pairBuffer += generateNextLine(state, level) } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue // Skip this pair because of invalid value. } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ':' } else { pairBuffer += ': ' } pairBuffer += state.dump // Both key and value are valid. _result += pairBuffer } state.tag = _tag state.dump = _result || '{}' // Empty mapping if no valid pairs. } function detectType (state, object, explicit) { const typeList = explicit ? state.explicitTypes : state.implicitTypes for (let index = 0, length = typeList.length; index < length; index += 1) { const type = typeList[index] if ((type.instanceOf || type.predicate) && (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && (!type.predicate || type.predicate(object))) { if (explicit) { if (type.multi && type.representName) { state.tag = type.representName(object) } else { state.tag = type.tag } } else { state.tag = '?' } if (type.represent) { const style = state.styleMap[type.tag] || type.defaultStyle let _result if (_toString.call(type.represent) === '[object Function]') { _result = type.represent(object, style) } else if (_hasOwnProperty.call(type.represent, style)) { _result = type.represent[style](object, style) } else { throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style') } state.dump = _result } return true } } return false } // Serializes `object` and writes it to global `result`. // Returns true on success, or false on invalid object. // function writeNode (state, level, object, block, compact, iskey, isblockseq) { state.tag = null state.dump = object if (!detectType(state, object, false)) { detectType(state, object, true) } const type = _toString.call(state.dump) const inblock = block if (block) { block = (state.flowLevel < 0 || state.flowLevel > level) } const objectOrArray = type === '[object Object]' || type === '[object Array]' let duplicateIndex let duplicate if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object) duplicate = duplicateIndex !== -1 } if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { compact = false } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = '*ref_' + duplicateIndex } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true } if (type === '[object Object]') { if (block && (Object.keys(state.dump).length !== 0)) { writeBlockMapping(state, level, state.dump, compact) if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump } } else { writeFlowMapping(state, level, state.dump) if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump } } } else if (type === '[object Array]') { if (block && (state.dump.length !== 0)) { if (state.noArrayIndent && !isblockseq && level > 0) { writeBlockSequence(state, level - 1, state.dump, compact) } else { writeBlockSequence(state, level, state.dump, compact) } if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump } } else { writeFlowSequence(state, level, state.dump) if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump } } } else if (type === '[object String]') { if (state.tag !== '?') { writeScalar(state, state.dump, level, iskey, inblock) } } else if (type === '[object Undefined]') { return false } else { if (state.skipInvalid) return false throw new YAMLException('unacceptable kind of an object to dump ' + type) } if (state.tag !== null && state.tag !== '?') { // Need to encode all characters except those allowed by the spec: // // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ // [36] ns-hex-digit ::= ns-dec-digit // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-� // [39] ns-uri-char ::= “%� ns-hex-digit ns-hex-digit | ns-word-char | “#� // | “;� | “/� | “?� | “:� | “@� | “&� | “=� | “+� | “$� | “,� // | “_� | “.� | “!� | “~� | “*� | “'� | “(� | “)� | “[� | “]� // // Also need to encode '!' because it has special meaning (end of tag prefix). // let tagStr = encodeURI( state.tag[0] === '!' ? state.tag.slice(1) : state.tag ).replace(/!/g, '%21') if (state.tag[0] === '!') { tagStr = '!' + tagStr } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { tagStr = '!!' + tagStr.slice(18) } else { tagStr = '!<' + tagStr + '>' } state.dump = tagStr + ' ' + state.dump } } return true } function getDuplicateReferences (object, state) { const objects = [] const duplicatesIndexes = [] inspectNode(object, objects, duplicatesIndexes) const length = duplicatesIndexes.length for (let index = 0; index < length; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]) } state.usedDuplicates = new Array(length) } function inspectNode (object, objects, duplicatesIndexes) { if (object !== null && typeof object === 'object') { const index = objects.indexOf(object) if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) { duplicatesIndexes.push(index) } } else { objects.push(object) if (Array.isArray(object)) { for (let i = 0, length = object.length; i < length; i += 1) { inspectNode(object[i], objects, duplicatesIndexes) } } else { const objectKeyList = Object.keys(object) for (let i = 0, length = objectKeyList.length; i < length; i += 1) { inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes) } } } } } function dump (input, options) { options = options || {} const state = new State(options) if (!state.noRefs) getDuplicateReferences(input, state) let value = input if (state.replacer) { value = state.replacer.call({ '': value }, '', value) } if (writeNode(state, 0, value, true, true)) return state.dump + '\n' return '' } module.exports.dump = dump // YAML error class. http://stackoverflow.com/questions/8458984 // 'use strict' function formatError (exception, compact) { let where = '' const message = exception.reason || '(unknown reason)' if (!exception.mark) return message if (exception.mark.name) { where += 'in "' + exception.mark.name + '" ' } where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')' if (!compact && exception.mark.snippet) { where += '\n\n' + exception.mark.snippet } return message + ' ' + where } function YAMLException (reason, mark) { // Super constructor Error.call(this) this.name = 'YAMLException' this.reason = reason this.mark = mark this.message = formatError(this, false) // Include stack trace in error object if (Error.captureStackTrace) { // Chrome and NodeJS Error.captureStackTrace(this, this.constructor) } else { // FF, IE 10+ and Safari 6+. Fallback for others this.stack = (new Error()).stack || '' } } // Inherit from Error YAMLException.prototype = Object.create(Error.prototype) YAMLException.prototype.constructor = YAMLException YAMLException.prototype.toString = function toString (compact) { return this.name + ': ' + formatError(this, compact) } module.exports = YAMLException import yaml from '../index.js' const { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump } = yaml export { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump } export default yaml 'use strict' const common = require('./common') const YAMLException = require('./exception') const makeSnippet = require('./snippet') const DEFAULT_SCHEMA = require('./schema/default') const _hasOwnProperty = Object.prototype.hasOwnProperty const CONTEXT_FLOW_IN = 1 const CONTEXT_FLOW_OUT = 2 const CONTEXT_BLOCK_IN = 3 const CONTEXT_BLOCK_OUT = 4 const CHOMPING_CLIP = 1 const CHOMPING_STRIP = 2 const CHOMPING_KEEP = 3 // eslint-disable-next-line no-control-regex const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/ const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/ // eslint-disable-next-line no-useless-escape const PATTERN_FLOW_INDICATORS = /[,\[\]{}]/ // eslint-disable-next-line no-useless-escape const PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/ // eslint-disable-next-line no-useless-escape const PATTERN_TAG_URI = /^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i function _class (obj) { return Object.prototype.toString.call(obj) } function isEol (c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */) } function isWhiteSpace (c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) } function isWsOrEol (c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) || (c === 0x0A/* LF */) || (c === 0x0D/* CR */) } function isFlowIndicator (c) { return c === 0x2C/* , */ || c === 0x5B/* [ */ || c === 0x5D/* ] */ || c === 0x7B/* { */ || c === 0x7D/* } */ } function fromHexCode (c) { if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) { return c - 0x30 } const lc = c | 0x20 if ((lc >= 0x61/* a */) && (lc <= 0x66/* f */)) { return lc - 0x61 + 10 } return -1 } function escapedHexLen (c) { if (c === 0x78/* x */) { return 2 } if (c === 0x75/* u */) { return 4 } if (c === 0x55/* U */) { return 8 } return 0 } function fromDecimalCode (c) { if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) { return c - 0x30 } return -1 } function simpleEscapeSequence (c) { switch (c) { case 0x30/* 0 */: return '\x00' case 0x61/* a */: return '\x07' case 0x62/* b */: return '\x08' case 0x74/* t */: return '\x09' case 0x09/* Tab */: return '\x09' case 0x6E/* n */: return '\x0A' case 0x76/* v */: return '\x0B' case 0x66/* f */: return '\x0C' case 0x72/* r */: return '\x0D' case 0x65/* e */: return '\x1B' case 0x20/* Space */: return ' ' case 0x22/* " */: return '\x22' case 0x2F/* / */: return '/' case 0x5C/* \ */: return '\x5C' case 0x4E/* N */: return '\x85' case 0x5F/* _ */: return '\xA0' case 0x4C/* L */: return '\u2028' case 0x50/* P */: return '\u2029' default: return '' } } function charFromCodepoint (c) { if (c <= 0xFFFF) { return String.fromCharCode(c) } // Encode UTF-16 surrogate pair // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xD800, ((c - 0x010000) & 0x03FF) + 0xDC00 ) } // set a property of a literal object, while protecting against prototype pollution, // see https://github.com/nodeca/js-yaml/issues/164 for more details function setProperty (object, key, value) { // used for this specific key only because Object.defineProperty is slow if (key === '__proto__') { Object.defineProperty(object, key, { configurable: true, enumerable: true, writable: true, value: value }) } else { object[key] = value } } const simpleEscapeCheck = new Array(256) // integer, for fast access const simpleEscapeMap = new Array(256) for (let i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0 simpleEscapeMap[i] = simpleEscapeSequence(i) } function State (input, options) { this.input = input this.filename = options['filename'] || null this.schema = options['schema'] || DEFAULT_SCHEMA this.onWarning = options['onWarning'] || null // (Hidden) Remove? makes the loader to expect YAML 1.1 documents // if such documents have no explicit %YAML directive this.legacy = options['legacy'] || false this.json = options['json'] || false this.listener = options['listener'] || null this.maxDepth = typeof options['maxDepth'] === 'number' ? options['maxDepth'] : 100 this.maxMergeSeqLength = typeof options['maxMergeSeqLength'] === 'number' ? options['maxMergeSeqLength'] : 20 this.implicitTypes = this.schema.compiledImplicit this.typeMap = this.schema.compiledTypeMap this.length = input.length this.position = 0 this.line = 0 this.lineStart = 0 this.lineIndent = 0 this.depth = 0 // position of first leading tab in the current line, // used to make sure there are no tabs in the indentation this.firstTabInLine = -1 this.documents = [] this.anchorMapTransactions = [] /* this.version; this.checkLineBreaks; this.tagMap; this.anchorMap; this.tag; this.anchor; this.kind; this.result; */ } function generateError (state, message) { const mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart } mark.snippet = makeSnippet(mark) return new YAMLException(message, mark) } function throwError (state, message) { throw generateError(state, message) } function throwWarning (state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)) } } function storeAnchor (state, name, value) { const transactions = state.anchorMapTransactions if (transactions.length !== 0) { const transaction = transactions[transactions.length - 1] if (!_hasOwnProperty.call(transaction, name)) { transaction[name] = { existed: _hasOwnProperty.call(state.anchorMap, name), value: state.anchorMap[name] } } } state.anchorMap[name] = value } function beginAnchorTransaction (state) { state.anchorMapTransactions.push(Object.create(null)) } function commitAnchorTransaction (state) { const transaction = state.anchorMapTransactions.pop() const transactions = state.anchorMapTransactions if (transactions.length === 0) return const parent = transactions[transactions.length - 1] const names = Object.keys(transaction) for (let index = 0, length = names.length; index < length; index += 1) { const name = names[index] if (!_hasOwnProperty.call(parent, name)) { parent[name] = transaction[name] } } } function rollbackAnchorTransaction (state) { const transaction = state.anchorMapTransactions.pop() const names = Object.keys(transaction) for (let index = names.length - 1; index >= 0; index -= 1) { const entry = transaction[names[index]] if (entry.existed) { state.anchorMap[names[index]] = entry.value } else { delete state.anchorMap[names[index]] } } } function snapshotState (state) { return { position: state.position, line: state.line, lineStart: state.lineStart, lineIndent: state.lineIndent, firstTabInLine: state.firstTabInLine, tag: state.tag, anchor: state.anchor, kind: state.kind, result: state.result } } function restoreState (state, snapshot) { state.position = snapshot.position state.line = snapshot.line state.lineStart = snapshot.lineStart state.lineIndent = snapshot.lineIndent state.firstTabInLine = snapshot.firstTabInLine state.tag = snapshot.tag state.anchor = snapshot.anchor state.kind = snapshot.kind state.result = snapshot.result } const directiveHandlers = { YAML: function handleYamlDirective (state, name, args) { if (state.version !== null) { throwError(state, 'duplication of %YAML directive') } if (args.length !== 1) { throwError(state, 'YAML directive accepts exactly one argument') } const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]) if (match === null) { throwError(state, 'ill-formed argument of the YAML directive') } const major = parseInt(match[1], 10) const minor = parseInt(match[2], 10) if (major !== 1) { throwError(state, 'unacceptable YAML version of the document') } state.version = args[0] state.checkLineBreaks = (minor < 2) if (minor !== 1 && minor !== 2) { throwWarning(state, 'unsupported YAML version of the document') } }, TAG: function handleTagDirective (state, name, args) { let prefix if (args.length !== 2) { throwError(state, 'TAG directive accepts exactly two arguments') } const handle = args[0] prefix = args[1] if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, 'ill-formed tag handle (first argument) of the TAG directive') } if (_hasOwnProperty.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle') } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive') } try { prefix = decodeURIComponent(prefix) } catch (err) { throwError(state, 'tag prefix is malformed: ' + prefix) } state.tagMap[handle] = prefix } } function captureSegment (state, start, end, checkJson) { if (start < end) { const _result = state.input.slice(start, end) if (checkJson) { for (let _position = 0, _length = _result.length; _position < _length; _position += 1) { const _character = _result.charCodeAt(_position) if (!(_character === 0x09 || (_character >= 0x20 && _character <= 0x10FFFF))) { throwError(state, 'expected valid JSON character') } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, 'the stream contains non-printable characters') } state.result += _result } } function mergeMappings (state, destination, source, overridableKeys) { if (!common.isObject(source)) { throwError(state, 'cannot merge mappings; the provided source object is unacceptable') } const sourceKeys = Object.keys(source) for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { const key = sourceKeys[index] if (!_hasOwnProperty.call(destination, key)) { setProperty(destination, key, source[key]) overridableKeys[key] = true } } } function storeMappingPair (state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process // (deeply nested arrays that explode exponentially using aliases). if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode) for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, 'nested arrays are not supported inside keys') } if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { keyNode[index] = '[object Object]' } } } // Avoid code execution in load() via toString property // (still use its own toString for arrays, timestamps, // and whatever user schema extensions happen to have @@toStringTag) if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { keyNode = '[object Object]' } keyNode = String(keyNode) if (_result === null) { _result = {} } if (keyTag === 'tag:yaml.org,2002:merge') { if (Array.isArray(valueNode)) { if (valueNode.length > state.maxMergeSeqLength) { throwError(state, 'merge sequence length exceeded maxMergeSeqLength (' + state.maxMergeSeqLength + ')') } const seen = new Set() for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) { const src = valueNode[index] // Existing keys are not overridden on merge, so dedupe sources to // avoid redundant work on repeated aliases. if (seen.has(src)) continue seen.add(src) mergeMappings(state, _result, src, overridableKeys) } } else { mergeMappings(state, _result, valueNode, overridableKeys) } } else { if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) { state.line = startLine || state.line state.lineStart = startLineStart || state.lineStart state.position = startPos || state.position throwError(state, 'duplicated mapping key') } setProperty(_result, keyNode, valueNode) delete overridableKeys[keyNode] } return _result } function readLineBreak (state) { const ch = state.input.charCodeAt(state.position) if (ch === 0x0A/* LF */) { state.position++ } else if (ch === 0x0D/* CR */) { state.position++ if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { state.position++ } } else { throwError(state, 'a line break is expected') } state.line += 1 state.lineStart = state.position state.firstTabInLine = -1 } function skipSeparationSpace (state, allowComments, checkIndent) { let lineBreaks = 0 let ch = state.input.charCodeAt(state.position) while (ch !== 0) { while (isWhiteSpace(ch)) { if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { state.firstTabInLine = state.position } ch = state.input.charCodeAt(++state.position) } if (allowComments && ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position) } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0) } if (isEol(ch)) { readLineBreak(state) ch = state.input.charCodeAt(state.position) lineBreaks++ state.lineIndent = 0 while (ch === 0x20/* Space */) { state.lineIndent++ ch = state.input.charCodeAt(++state.position) } } else { break } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, 'deficient indentation') } return lineBreaks } function testDocumentSeparator (state) { let _position = state.position let ch = state.input.charCodeAt(_position) // Condition state.position === state.lineStart is tested // in parent on each call, for efficiency. No needs to test here again. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3 ch = state.input.charCodeAt(_position) if (ch === 0 || isWsOrEol(ch)) { return true } } return false } function writeFoldedLines (state, count) { if (count === 1) { state.result += ' ' } else if (count > 1) { state.result += common.repeat('\n', count - 1) } } function readPlainScalar (state, nodeIndent, withinFlowCollection) { let captureStart let captureEnd let hasPendingContent let _line let _lineStart let _lineIndent const _kind = state.kind const _result = state.result let ch = state.input.charCodeAt(state.position) if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 0x23/* # */ || ch === 0x26/* & */ || ch === 0x2A/* * */ || ch === 0x21/* ! */ || ch === 0x7C/* | */ || ch === 0x3E/* > */ || ch === 0x27/* ' */ || ch === 0x22/* " */ || ch === 0x25/* % */ || ch === 0x40/* @ */ || ch === 0x60/* ` */) { return false } if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { const following = state.input.charCodeAt(state.position + 1) if (isWsOrEol(following) || (withinFlowCollection && isFlowIndicator(following))) { return false } } state.kind = 'scalar' state.result = '' captureStart = captureEnd = state.position hasPendingContent = false while (ch !== 0) { if (ch === 0x3A/* : */) { const following = state.input.charCodeAt(state.position + 1) if (isWsOrEol(following) || (withinFlowCollection && isFlowIndicator(following))) { break } } else if (ch === 0x23/* # */) { const preceding = state.input.charCodeAt(state.position - 1) if (isWsOrEol(preceding)) { break } } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || (withinFlowCollection && isFlowIndicator(ch))) { break } else if (isEol(ch)) { _line = state.line _lineStart = state.lineStart _lineIndent = state.lineIndent skipSeparationSpace(state, false, -1) if (state.lineIndent >= nodeIndent) { hasPendingContent = true ch = state.input.charCodeAt(state.position) continue } else { state.position = captureEnd state.line = _line state.lineStart = _lineStart state.lineIndent = _lineIndent break } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false) writeFoldedLines(state, state.line - _line) captureStart = captureEnd = state.position hasPendingContent = false } if (!isWhiteSpace(ch)) { captureEnd = state.position + 1 } ch = state.input.charCodeAt(++state.position) } captureSegment(state, captureStart, captureEnd, false) if (state.result) { return true } state.kind = _kind state.result = _result return false } function readSingleQuotedScalar (state, nodeIndent) { let captureStart let captureEnd let ch = state.input.charCodeAt(state.position) if (ch !== 0x27/* ' */) { return false } state.kind = 'scalar' state.result = '' state.position++ captureStart = captureEnd = state.position while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x27/* ' */) { captureSegment(state, captureStart, state.position, true) ch = state.input.charCodeAt(++state.position) if (ch === 0x27/* ' */) { captureStart = state.position state.position++ captureEnd = state.position } else { return true } } else if (isEol(ch)) { captureSegment(state, captureStart, captureEnd, true) writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)) captureStart = captureEnd = state.position } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a single quoted scalar') } else { state.position++ if (!isWhiteSpace(ch)) { captureEnd = state.position } } } throwError(state, 'unexpected end of the stream within a single quoted scalar') } function readDoubleQuotedScalar (state, nodeIndent) { let captureStart let captureEnd let tmp let ch = state.input.charCodeAt(state.position) if (ch !== 0x22/* " */) { return false } state.kind = 'scalar' state.result = '' state.position++ captureStart = captureEnd = state.position while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x22/* " */) { captureSegment(state, captureStart, state.position, true) state.position++ return true } else if (ch === 0x5C/* \ */) { captureSegment(state, captureStart, state.position, true) ch = state.input.charCodeAt(++state.position) if (isEol(ch)) { skipSeparationSpace(state, false, nodeIndent) // TODO: rework to inline fn with no type cast? } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch] state.position++ } else if ((tmp = escapedHexLen(ch)) > 0) { let hexLength = tmp let hexResult = 0 for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position) if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp } else { throwError(state, 'expected hexadecimal character') } } state.result += charFromCodepoint(hexResult) state.position++ } else { throwError(state, 'unknown escape sequence') } captureStart = captureEnd = state.position } else if (isEol(ch)) { captureSegment(state, captureStart, captureEnd, true) writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)) captureStart = captureEnd = state.position } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a double quoted scalar') } else { state.position++ if (!isWhiteSpace(ch)) { captureEnd = state.position } } } throwError(state, 'unexpected end of the stream within a double quoted scalar') } function readFlowCollection (state, nodeIndent) { let readNext = true let _line let _lineStart let _pos const _tag = state.tag let _result const _anchor = state.anchor let terminator let isPair let isExplicitPair let isMapping const overridableKeys = Object.create(null) let keyNode let keyTag let valueNode let ch = state.input.charCodeAt(state.position) if (ch === 0x5B/* [ */) { terminator = 0x5D/* ] */ isMapping = false _result = [] } else if (ch === 0x7B/* { */) { terminator = 0x7D/* } */ isMapping = true _result = {} } else { return false } if (state.anchor !== null) { storeAnchor(state, state.anchor, _result) } ch = state.input.charCodeAt(++state.position) while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent) ch = state.input.charCodeAt(state.position) if (ch === terminator) { state.position++ state.tag = _tag state.anchor = _anchor state.kind = isMapping ? 'mapping' : 'sequence' state.result = _result return true } else if (!readNext) { throwError(state, 'missed comma between flow collection entries') } else if (ch === 0x2C/* , */) { // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 throwError(state, "expected the node content, but found ','") } keyTag = keyNode = valueNode = null isPair = isExplicitPair = false if (ch === 0x3F/* ? */) { const following = state.input.charCodeAt(state.position + 1) if (isWsOrEol(following)) { isPair = isExplicitPair = true state.position++ skipSeparationSpace(state, true, nodeIndent) } } _line = state.line // Save the current line. _lineStart = state.lineStart _pos = state.position composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true) keyTag = state.tag keyNode = state.result skipSeparationSpace(state, true, nodeIndent) ch = state.input.charCodeAt(state.position) if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { isPair = true ch = state.input.charCodeAt(++state.position) skipSeparationSpace(state, true, nodeIndent) composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true) valueNode = state.result } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos) } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)) } else { _result.push(keyNode) } skipSeparationSpace(state, true, nodeIndent) ch = state.input.charCodeAt(state.position) if (ch === 0x2C/* , */) { readNext = true ch = state.input.charCodeAt(++state.position) } else { readNext = false } } throwError(state, 'unexpected end of the stream within a flow collection') } function readBlockScalar (state, nodeIndent) { let folding let chomping = CHOMPING_CLIP let didReadContent = false let detectedIndent = false let textIndent = nodeIndent let emptyLines = 0 let atMoreIndented = false let tmp let ch = state.input.charCodeAt(state.position) if (ch === 0x7C/* | */) { folding = false } else if (ch === 0x3E/* > */) { folding = true } else { return false } state.kind = 'scalar' state.result = '' while (ch !== 0) { ch = state.input.charCodeAt(++state.position) if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { if (CHOMPING_CLIP === chomping) { chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP } else { throwError(state, 'repeat of a chomping mode identifier') } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one') } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1 detectedIndent = true } else { throwError(state, 'repeat of an indentation width identifier') } } else { break } } if (isWhiteSpace(ch)) { do { ch = state.input.charCodeAt(++state.position) } while (isWhiteSpace(ch)) if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position) } while (!isEol(ch) && (ch !== 0)) } } while (ch !== 0) { readLineBreak(state) state.lineIndent = 0 ch = state.input.charCodeAt(state.position) // eslint-disable-next-line no-unmodified-loop-condition while ((!detectedIndent || state.lineIndent < textIndent) && (ch === 0x20/* Space */)) { state.lineIndent++ ch = state.input.charCodeAt(++state.position) } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent } if (isEol(ch)) { emptyLines++ continue } if (!detectedIndent && textIndent === 0) { throwError(state, 'missing indentation for block scalar') } // End of the scalar. if (state.lineIndent < textIndent) { // Perform the chomping. if (chomping === CHOMPING_KEEP) { state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines) } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { // i.e. only if the scalar is not empty. state.result += '\n' } } // Break this `while` cycle and go to the funciton's epilogue. break } // Folded style: use fancy rules to handle line breaks. if (folding) { // Lines starting with white space characters (more-indented lines) are not folded. if (isWhiteSpace(ch)) { atMoreIndented = true // except for the first content line (cf. Example 8.1) state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines) // End of more-indented block. } else if (atMoreIndented) { atMoreIndented = false state.result += common.repeat('\n', emptyLines + 1) // Just one line break - perceive as the same line. } else if (emptyLines === 0) { if (didReadContent) { // i.e. only if we have already read some scalar content. state.result += ' ' } // Several line breaks - perceive as different lines. } else { state.result += common.repeat('\n', emptyLines) } // Literal style: just add exact number of line breaks between content lines. } else { // Keep all line breaks except the header line break. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines) } didReadContent = true detectedIndent = true emptyLines = 0 const captureStart = state.position while (!isEol(ch) && (ch !== 0)) { ch = state.input.charCodeAt(++state.position) } captureSegment(state, captureStart, state.position, false) } return true } function readBlockSequence (state, nodeIndent) { const _tag = state.tag const _anchor = state.anchor const _result = [] let detected = false // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false if (state.anchor !== null) { storeAnchor(state, state.anchor, _result) } let ch = state.input.charCodeAt(state.position) while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine throwError(state, 'tab characters must not be used in indentation') } if (ch !== 0x2D/* - */) { break } const following = state.input.charCodeAt(state.position + 1) if (!isWsOrEol(following)) { break } detected = true state.position++ if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null) ch = state.input.charCodeAt(state.position) continue } } const _line = state.line composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true) _result.push(state.result) skipSeparationSpace(state, true, -1) ch = state.input.charCodeAt(state.position) if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a sequence entry') } else if (state.lineIndent < nodeIndent) { break } } if (detected) { state.tag = _tag state.anchor = _anchor state.kind = 'sequence' state.result = _result return true } return false } function readBlockMapping (state, nodeIndent, flowIndent) { let allowCompact let _keyLine let _keyLineStart let _keyPos const _tag = state.tag const _anchor = state.anchor const _result = {} const overridableKeys = Object.create(null) let keyTag = null let keyNode = null let valueNode = null let atExplicitKey = false let detected = false // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false if (state.anchor !== null) { storeAnchor(state, state.anchor, _result) } let ch = state.input.charCodeAt(state.position) while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine throwError(state, 'tab characters must not be used in indentation') } const following = state.input.charCodeAt(state.position + 1) const _line = state.line // Save the current line. // // Explicit notation case. There are two separate blocks: // first for the key (denoted by "?") and second for the value (denoted by ":") // if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && isWsOrEol(following)) { if (ch === 0x3F/* ? */) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos) keyTag = keyNode = valueNode = null } detected = true atExplicitKey = true allowCompact = true } else if (atExplicitKey) { // i.e. 0x3A/* : */ === character after the explicit key. atExplicitKey = false allowCompact = true } else { throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line') } state.position += 1 ch = following // // Implicit notation case. Flow-style node as the key first, then ":", and the value. // } else { _keyLine = state.line _keyLineStart = state.lineStart _keyPos = state.position if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { // Neither implicit nor explicit notation. // Reading is done. Go to the epilogue. break } if (state.line === _line) { ch = state.input.charCodeAt(state.position) while (isWhiteSpace(ch)) { ch = state.input.charCodeAt(++state.position) } if (ch === 0x3A/* : */) { ch = state.input.charCodeAt(++state.position) if (!isWsOrEol(ch)) { throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping') } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos) keyTag = keyNode = valueNode = null } detected = true atExplicitKey = false allowCompact = false keyTag = state.tag keyNode = state.result } else if (detected) { throwError(state, 'can not read an implicit mapping pair; a colon is missed') } else { state.tag = _tag state.anchor = _anchor return true // Keep the result of `composeNode`. } } else if (detected) { throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key') } else { state.tag = _tag state.anchor = _anchor return true // Keep the result of `composeNode`. } } // // Common reading code for both explicit and implicit notations. // if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line _keyLineStart = state.lineStart _keyPos = state.position } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result } else { valueNode = state.result } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos) keyTag = keyNode = valueNode = null } skipSeparationSpace(state, true, -1) ch = state.input.charCodeAt(state.position) } if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a mapping entry') } else if (state.lineIndent < nodeIndent) { break } } // // Epilogue. // // Special case: last mapping's node contains only the key in explicit notation. if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos) } // Expose the resulting mapping. if (detected) { state.tag = _tag state.anchor = _anchor state.kind = 'mapping' state.result = _result } return detected } function readTagProperty (state) { let isVerbatim = false let isNamed = false let tagHandle let tagName let ch = state.input.charCodeAt(state.position) if (ch !== 0x21/* ! */) return false if (state.tag !== null) { throwError(state, 'duplication of a tag property') } ch = state.input.charCodeAt(++state.position) if (ch === 0x3C/* < */) { isVerbatim = true ch = state.input.charCodeAt(++state.position) } else if (ch === 0x21/* ! */) { isNamed = true tagHandle = '!!' ch = state.input.charCodeAt(++state.position) } else { tagHandle = '!' } let _position = state.position if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position) } while (ch !== 0 && ch !== 0x3E/* > */) if (state.position < state.length) { tagName = state.input.slice(_position, state.position) ch = state.input.charCodeAt(++state.position) } else { throwError(state, 'unexpected end of the stream within a verbatim tag') } } else { while (ch !== 0 && !isWsOrEol(ch)) { if (ch === 0x21/* ! */) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1) if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, 'named tag handle cannot contain such characters') } isNamed = true _position = state.position + 1 } else { throwError(state, 'tag suffix cannot contain exclamation marks') } } ch = state.input.charCodeAt(++state.position) } tagName = state.input.slice(_position, state.position) if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, 'tag suffix cannot contain flow indicator characters') } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, 'tag name cannot contain such characters: ' + tagName) } try { tagName = decodeURIComponent(tagName) } catch (err) { throwError(state, 'tag name is malformed: ' + tagName) } if (isVerbatim) { state.tag = tagName } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName } else if (tagHandle === '!') { state.tag = '!' + tagName } else if (tagHandle === '!!') { state.tag = 'tag:yaml.org,2002:' + tagName } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"') } return true } function readAnchorProperty (state) { let ch = state.input.charCodeAt(state.position) if (ch !== 0x26/* & */) return false if (state.anchor !== null) { throwError(state, 'duplication of an anchor property') } ch = state.input.charCodeAt(++state.position) const _position = state.position while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) { ch = state.input.charCodeAt(++state.position) } if (state.position === _position) { throwError(state, 'name of an anchor node must contain at least one character') } state.anchor = state.input.slice(_position, state.position) return true } function readAlias (state) { let ch = state.input.charCodeAt(state.position) if (ch !== 0x2A/* * */) return false ch = state.input.charCodeAt(++state.position) const _position = state.position while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) { ch = state.input.charCodeAt(++state.position) } if (state.position === _position) { throwError(state, 'name of an alias node must contain at least one character') } const alias = state.input.slice(_position, state.position) if (!_hasOwnProperty.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"') } state.result = state.anchorMap[alias] skipSeparationSpace(state, true, -1) return true } function tryReadBlockMappingFromProperty (state, propertyStart, nodeIndent, flowIndent) { const fallbackState = snapshotState(state) beginAnchorTransaction(state) restoreState(state, propertyStart) // Re-read the leading properties as part of the first implicit key, not as // properties of the current node. state.tag = null state.anchor = null state.kind = null state.result = null if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === 'mapping') { commitAnchorTransaction(state) return true } rollbackAnchorTransaction(state) restoreState(state, fallbackState) return false } function composeNode (state, parentIndent, nodeContext, allowToSeek, allowCompact) { let allowBlockScalars let allowBlockCollections let indentStatus = 1 // 1: this>parent, 0: this=parent, -1: this= state.maxDepth) { throwError(state, 'nesting exceeded maxDepth (' + state.maxDepth + ')') } state.depth += 1 if (state.listener !== null) { state.listener('open', state) } state.tag = null state.anchor = null state.kind = null state.result = null const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext if (allowToSeek) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true if (state.lineIndent > parentIndent) { indentStatus = 1 } else if (state.lineIndent === parentIndent) { indentStatus = 0 } else if (state.lineIndent < parentIndent) { indentStatus = -1 } } } if (indentStatus === 1) { while (true) { const ch = state.input.charCodeAt(state.position) const propertyState = snapshotState(state) // A duplicate property token after a line break can be the first key of // a nested block mapping, e.g. `!!map\n !!str key: value`. if (atNewLine && ((ch === 0x21/* ! */ && state.tag !== null) || (ch === 0x26/* & */ && state.anchor !== null))) { break } if (!readTagProperty(state) && !readAnchorProperty(state)) { break } if (propertyStart === null) { propertyStart = propertyState } if (skipSeparationSpace(state, true, -1)) { atNewLine = true allowBlockCollections = allowBlockStyles if (state.lineIndent > parentIndent) { indentStatus = 1 } else if (state.lineIndent === parentIndent) { indentStatus = 0 } else if (state.lineIndent < parentIndent) { indentStatus = -1 } } else { allowBlockCollections = false } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent } else { flowIndent = parentIndent + 1 } blockIndent = state.position - state.lineStart if (indentStatus === 1) { if ((allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent))) || readFlowCollection(state, flowIndent)) { hasContent = true } else { const ch = state.input.charCodeAt(state.position) if (propertyStart !== null && allowBlockStyles && !allowBlockCollections && ch !== 0x7C/* | */ && ch !== 0x3E/* > */ && tryReadBlockMappingFromProperty( state, propertyStart, propertyStart.position - propertyStart.lineStart, flowIndent )) { hasContent = true } else if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true } else if (readAlias(state)) { hasContent = true if (state.tag !== null || state.anchor !== null) { throwError(state, 'alias node should not have any properties') } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true if (state.tag === null) { state.tag = '?' } } if (state.anchor !== null) { storeAnchor(state, state.anchor, state.result) } } } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent) } } if (state.tag === null) { if (state.anchor !== null) { storeAnchor(state, state.anchor, state.result) } } else if (state.tag === '?') { // Implicit resolving is not allowed for non-scalar types, and '?' // non-specific tag is only automatically assigned to plain scalars. // // We only need to check kind conformity in case user explicitly assigns '?' // tag, for example like this: "! [0]" // if (state.result !== null && state.kind !== 'scalar') { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"') } for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex] if (type.resolve(state.result)) { // `state.result` updated in resolver if matched state.result = type.construct(state.result) state.tag = type.tag if (state.anchor !== null) { storeAnchor(state, state.anchor, state.result) } break } } } else if (state.tag !== '!') { if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag] } else { // looking for multi type type = null const typeList = state.typeMap.multi[state.kind || 'fallback'] for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex] break } } } if (!type) { throwError(state, 'unknown tag !<' + state.tag + '>') } if (state.result !== null && type.kind !== state.kind) { throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"') } if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag') } else { state.result = type.construct(state.result, state.tag) if (state.anchor !== null) { storeAnchor(state, state.anchor, state.result) } } } if (state.listener !== null) { state.listener('close', state) } state.depth -= 1 return state.tag !== null || state.anchor !== null || hasContent } function readDocument (state) { const documentStart = state.position let hasDirectives = false let ch state.version = null state.checkLineBreaks = state.legacy state.tagMap = Object.create(null) state.anchorMap = Object.create(null) while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1) ch = state.input.charCodeAt(state.position) if (state.lineIndent > 0 || ch !== 0x25/* % */) { break } hasDirectives = true ch = state.input.charCodeAt(++state.position) let _position = state.position while (ch !== 0 && !isWsOrEol(ch)) { ch = state.input.charCodeAt(++state.position) } const directiveName = state.input.slice(_position, state.position) const directiveArgs = [] if (directiveName.length < 1) { throwError(state, 'directive name must not be less than one character in length') } while (ch !== 0) { while (isWhiteSpace(ch)) { ch = state.input.charCodeAt(++state.position) } if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position) } while (ch !== 0 && !isEol(ch)) break } if (isEol(ch)) break _position = state.position while (ch !== 0 && !isWsOrEol(ch)) { ch = state.input.charCodeAt(++state.position) } directiveArgs.push(state.input.slice(_position, state.position)) } if (ch !== 0) readLineBreak(state) if (_hasOwnProperty.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs) } else { throwWarning(state, 'unknown document directive "' + directiveName + '"') } } skipSeparationSpace(state, true, -1) if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D/* - */ && state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { state.position += 3 skipSeparationSpace(state, true, -1) } else if (hasDirectives) { throwError(state, 'directives end mark is expected') } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true) skipSeparationSpace(state, true, -1) if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, 'non-ASCII line breaks are interpreted as content') } state.documents.push(state.result) if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 0x2E/* . */) { state.position += 3 skipSeparationSpace(state, true, -1) } return } if (state.position < (state.length - 1)) { throwError(state, 'end of the stream or a document separator is expected') } } function loadDocuments (input, options) { input = String(input) options = options || {} if (input.length !== 0) { // Add tailing `\n` if not exists if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { input += '\n' } // Strip BOM if (input.charCodeAt(0) === 0xFEFF) { input = input.slice(1) } } const state = new State(input, options) const nullpos = input.indexOf('\0') if (nullpos !== -1) { state.position = nullpos throwError(state, 'null byte is not allowed in input') } // Use 0 as string terminator. That significantly simplifies bounds check. state.input += '\0' while (state.input.charCodeAt(state.position) === 0x20/* Space */) { state.lineIndent += 1 state.position += 1 } while (state.position < (state.length - 1)) { readDocument(state) } return state.documents } function loadAll (input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator iterator = null } const documents = loadDocuments(input, options) if (typeof iterator !== 'function') { return documents } for (let index = 0, length = documents.length; index < length; index += 1) { iterator(documents[index]) } } function load (input, options) { const documents = loadDocuments(input, options) if (documents.length === 0) { return undefined } else if (documents.length === 1) { return documents[0] } throw new YAMLException('expected a single document in the stream, but found more') } module.exports.loadAll = loadAll module.exports.load = load 'use strict' const YAMLException = require('./exception') const Type = require('./type') function compileList (schema, name) { const result = [] schema[name].forEach(function (currentType) { let newIndex = result.length result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex } }) result[newIndex] = currentType }) return result } function compileMap (/* lists... */) { const result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } } function collectType (type) { if (type.multi) { result.multi[type.kind].push(type) result.multi['fallback'].push(type) } else { result[type.kind][type.tag] = result['fallback'][type.tag] = type } } for (let index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType) } return result } function Schema (definition) { return this.extend(definition) } Schema.prototype.extend = function extend (definition) { let implicit = [] let explicit = [] if (definition instanceof Type) { // Schema.extend(type) explicit.push(definition) } else if (Array.isArray(definition)) { // Schema.extend([ type1, type2, ... ]) explicit = explicit.concat(definition) } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) if (definition.implicit) implicit = implicit.concat(definition.implicit) if (definition.explicit) explicit = explicit.concat(definition.explicit) } else { throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + 'or a schema definition ({ implicit: [...], explicit: [...] })') } implicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.') } if (type.loadKind && type.loadKind !== 'scalar') { throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.') } if (type.multi) { throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.') } }) explicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.') } }) const result = Object.create(Schema.prototype) result.implicit = (this.implicit || []).concat(implicit) result.explicit = (this.explicit || []).concat(explicit) result.compiledImplicit = compileList(result, 'implicit') result.compiledExplicit = compileList(result, 'explicit') result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit) return result } module.exports = Schema // Standard YAML's Core schema. // http://www.yaml.org/spec/1.2/spec.html#id2804923 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, Core schema has no distinctions from JSON schema is JS-YAML. 'use strict' module.exports = require('./json') // JS-YAML's default schema for `safeLoad` function. // It is not described in the YAML specification. // // This schema is based on standard YAML's Core schema and includes most of // extra types described at YAML tag repository. (http://yaml.org/type/) 'use strict' module.exports = require('./core').extend({ implicit: [ require('../type/timestamp'), require('../type/merge') ], explicit: [ require('../type/binary'), require('../type/omap'), require('../type/pairs'), require('../type/set') ] }) // Standard YAML's Failsafe schema. // http://www.yaml.org/spec/1.2/spec.html#id2802346 'use strict' const Schema = require('../schema') module.exports = new Schema({ explicit: [ require('../type/str'), require('../type/seq'), require('../type/map') ] }) // Standard YAML's JSON schema. // http://www.yaml.org/spec/1.2/spec.html#id2803231 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, this schema is not such strict as defined in the YAML specification. // It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. 'use strict' module.exports = require('./failsafe').extend({ implicit: [ require('../type/null'), require('../type/bool'), require('../type/int'), require('../type/float') ] }) 'use strict' const common = require('./common') // get snippet for a single line, respecting maxLength function getLine (buffer, lineStart, lineEnd, position, maxLineLength) { let head = '' let tail = '' const maxHalfLength = Math.floor(maxLineLength / 2) - 1 if (position - lineStart > maxHalfLength) { head = ' ... ' lineStart = position - maxHalfLength + head.length } if (lineEnd - position > maxHalfLength) { tail = ' ...' lineEnd = position + maxHalfLength - tail.length } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, pos: position - lineStart + head.length // relative position } } function padStart (string, max) { return common.repeat(' ', max - string.length) + string } function makeSnippet (mark, options) { options = Object.create(options || null) if (!mark.buffer) return null if (!options.maxLength) options.maxLength = 79 if (typeof options.indent !== 'number') options.indent = 1 if (typeof options.linesBefore !== 'number') options.linesBefore = 3 if (typeof options.linesAfter !== 'number') options.linesAfter = 2 const re = /\r?\n|\r|\0/g const lineStarts = [0] const lineEnds = [] let match let foundLineNo = -1 while ((match = re.exec(mark.buffer))) { lineEnds.push(match.index) lineStarts.push(match.index + match[0].length) if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2 } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1 let result = '' const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3) for (let i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break const line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ) result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' + result } const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength) result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n' for (let i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break const line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ) result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' } return result.replace(/\n$/, '') } module.exports = makeSnippet 'use strict' const YAMLException = require('./exception') const TYPE_CONSTRUCTOR_OPTIONS = [ 'kind', 'multi', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'representName', 'defaultStyle', 'styleAliases' ] const YAML_NODE_KINDS = [ 'scalar', 'sequence', 'mapping' ] function compileStyleAliases (map) { const result = {} if (map !== null) { Object.keys(map).forEach(function (style) { map[style].forEach(function (alias) { result[String(alias)] = style }) }) } return result } function Type (tag, options) { options = options || {} Object.keys(options).forEach(function (name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.') } }) // TODO: Add tag format check. this.options = options // keep original options in case user wants to extend this type later this.tag = tag this.kind = options['kind'] || null this.resolve = options['resolve'] || function () { return true } this.construct = options['construct'] || function (data) { return data } this.instanceOf = options['instanceOf'] || null this.predicate = options['predicate'] || null this.represent = options['represent'] || null this.representName = options['representName'] || null this.defaultStyle = options['defaultStyle'] || null this.multi = options['multi'] || false this.styleAliases = compileStyleAliases(options['styleAliases'] || null) if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.') } } module.exports = Type 'use strict' const Type = require('../type') // [ 64, 65, 66 ] -> [ padding, CR, LF ] const BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r' function resolveYamlBinary (data) { if (data === null) return false let bitlen = 0 const max = data.length const map = BASE64_MAP // Convert one by one. for (let idx = 0; idx < max; idx++) { const code = map.indexOf(data.charAt(idx)) // Skip CR/LF if (code > 64) continue // Fail on illegal characters if (code < 0) return false bitlen += 6 } // If there are any bits left, source was corrupted return (bitlen % 8) === 0 } function constructYamlBinary (data) { const input = data.replace(/[\r\n=]/g, '') // remove CR/LF & padding to simplify scan const max = input.length const map = BASE64_MAP let bits = 0 const result = [] // Collect by 6*4 bits (3 bytes) for (let idx = 0; idx < max; idx++) { if ((idx % 4 === 0) && idx) { result.push((bits >> 16) & 0xFF) result.push((bits >> 8) & 0xFF) result.push(bits & 0xFF) } bits = (bits << 6) | map.indexOf(input.charAt(idx)) } // Dump tail const tailbits = (max % 4) * 6 if (tailbits === 0) { result.push((bits >> 16) & 0xFF) result.push((bits >> 8) & 0xFF) result.push(bits & 0xFF) } else if (tailbits === 18) { result.push((bits >> 10) & 0xFF) result.push((bits >> 2) & 0xFF) } else if (tailbits === 12) { result.push((bits >> 4) & 0xFF) } return new Uint8Array(result) } function representYamlBinary (object /*, style */) { let result = '' let bits = 0 const max = object.length const map = BASE64_MAP // Convert every three bytes to 4 ASCII characters. for (let idx = 0; idx < max; idx++) { if ((idx % 3 === 0) && idx) { result += map[(bits >> 18) & 0x3F] result += map[(bits >> 12) & 0x3F] result += map[(bits >> 6) & 0x3F] result += map[bits & 0x3F] } bits = (bits << 8) + object[idx] } // Dump tail const tail = max % 3 if (tail === 0) { result += map[(bits >> 18) & 0x3F] result += map[(bits >> 12) & 0x3F] result += map[(bits >> 6) & 0x3F] result += map[bits & 0x3F] } else if (tail === 2) { result += map[(bits >> 10) & 0x3F] result += map[(bits >> 4) & 0x3F] result += map[(bits << 2) & 0x3F] result += map[64] } else if (tail === 1) { result += map[(bits >> 2) & 0x3F] result += map[(bits << 4) & 0x3F] result += map[64] result += map[64] } return result } function isBinary (obj) { return Object.prototype.toString.call(obj) === '[object Uint8Array]' } module.exports = new Type('tag:yaml.org,2002:binary', { kind: 'scalar', resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }) 'use strict' const Type = require('../type') function resolveYamlBoolean (data) { if (data === null) return false const max = data.length return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')) } function constructYamlBoolean (data) { return data === 'true' || data === 'True' || data === 'TRUE' } function isBoolean (object) { return Object.prototype.toString.call(object) === '[object Boolean]' } module.exports = new Type('tag:yaml.org,2002:bool', { kind: 'scalar', resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function (object) { return object ? 'true' : 'false' }, uppercase: function (object) { return object ? 'TRUE' : 'FALSE' }, camelcase: function (object) { return object ? 'True' : 'False' } }, defaultStyle: 'lowercase' }) 'use strict' const common = require('../common') const Type = require('../type') const YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers '^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2 // special case, seems not from spec '|\\.[0-9]+(?:[eE][-+]?[0-9]+)?' + // .inf '|[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$') const YAML_FLOAT_SPECIAL_PATTERN = new RegExp( '^(?:' + // .inf '[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$') function resolveYamlFloat (data) { if (data === null) return false if (!YAML_FLOAT_PATTERN.test(data)) { return false } if (Number.isFinite(parseFloat(data, 10))) { return true } return YAML_FLOAT_SPECIAL_PATTERN.test(data) } function constructYamlFloat (data) { let value = data.toLowerCase() const sign = value[0] === '-' ? -1 : 1 if ('+-'.indexOf(value[0]) >= 0) { value = value.slice(1) } if (value === '.inf') { return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY } else if (value === '.nan') { return NaN } return sign * parseFloat(value, 10) } const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/ function representYamlFloat (object, style) { if (isNaN(object)) { switch (style) { case 'lowercase': return '.nan' case 'uppercase': return '.NAN' case 'camelcase': return '.NaN' } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case 'lowercase': return '.inf' case 'uppercase': return '.INF' case 'camelcase': return '.Inf' } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case 'lowercase': return '-.inf' case 'uppercase': return '-.INF' case 'camelcase': return '-.Inf' } } else if (common.isNegativeZero(object)) { return '-0.0' } const res = object.toString(10) // JS stringifier can build scientific format without dots: 5e-100, // while YAML requres dot: 5.e-100. Fix it with simple hack return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res } function isFloat (object) { return (Object.prototype.toString.call(object) === '[object Number]') && (object % 1 !== 0 || common.isNegativeZero(object)) } module.exports = new Type('tag:yaml.org,2002:float', { kind: 'scalar', resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: 'lowercase' }) 'use strict' const common = require('../common') const Type = require('../type') function isHexCode (c) { return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) || ((c >= 0x41/* A */) && (c <= 0x46/* F */)) || ((c >= 0x61/* a */) && (c <= 0x66/* f */)) } function isOctCode (c) { return ((c >= 0x30/* 0 */) && (c <= 0x37/* 7 */)) } function isDecCode (c) { return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) } function resolveYamlInteger (data) { if (data === null) return false const max = data.length let index = 0 let hasDigits = false if (!max) return false let ch = data[index] // sign if (ch === '-' || ch === '+') { ch = data[++index] } if (ch === '0') { // 0 if (index + 1 === max) return true ch = data[++index] // base 2, base 8, base 16 if (ch === 'b') { // base 2 index++ for (; index < max; index++) { ch = data[index] if (ch !== '0' && ch !== '1') return false hasDigits = true } return hasDigits && Number.isFinite(parseYamlInteger(data)) } if (ch === 'x') { // base 16 index++ for (; index < max; index++) { if (!isHexCode(data.charCodeAt(index))) return false hasDigits = true } return hasDigits && Number.isFinite(parseYamlInteger(data)) } if (ch === 'o') { // base 8 index++ for (; index < max; index++) { if (!isOctCode(data.charCodeAt(index))) return false hasDigits = true } return hasDigits && Number.isFinite(parseYamlInteger(data)) } } // base 10 (except 0) for (; index < max; index++) { if (!isDecCode(data.charCodeAt(index))) { return false } hasDigits = true } if (!hasDigits) return false return Number.isFinite(parseYamlInteger(data)) } function parseYamlInteger (data) { let value = data let sign = 1 let ch = value[0] if (ch === '-' || ch === '+') { if (ch === '-') sign = -1 value = value.slice(1) ch = value[0] } if (value === '0') return 0 if (ch === '0') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2) if (value[1] === 'x') return sign * parseInt(value.slice(2), 16) if (value[1] === 'o') return sign * parseInt(value.slice(2), 8) } return sign * parseInt(value, 10) } function constructYamlInteger (data) { return parseYamlInteger(data) } function isInteger (object) { return (Object.prototype.toString.call(object)) === '[object Number]' && (object % 1 === 0 && !common.isNegativeZero(object)) } module.exports = new Type('tag:yaml.org,2002:int', { kind: 'scalar', resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1) }, octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1) }, decimal: function (obj) { return obj.toString(10) }, hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1) } }, defaultStyle: 'decimal', styleAliases: { binary: [2, 'bin'], octal: [8, 'oct'], decimal: [10, 'dec'], hexadecimal: [16, 'hex'] } }) 'use strict' const Type = require('../type') module.exports = new Type('tag:yaml.org,2002:map', { kind: 'mapping', construct: function (data) { return data !== null ? data : {} } }) 'use strict' const Type = require('../type') function resolveYamlMerge (data) { return data === '<<' || data === null } module.exports = new Type('tag:yaml.org,2002:merge', { kind: 'scalar', resolve: resolveYamlMerge }) 'use strict' const Type = require('../type') function resolveYamlNull (data) { if (data === null) return true const max = data.length return (max === 1 && data === '~') || (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')) } function constructYamlNull () { return null } function isNull (object) { return object === null } module.exports = new Type('tag:yaml.org,2002:null', { kind: 'scalar', resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function () { return '~' }, lowercase: function () { return 'null' }, uppercase: function () { return 'NULL' }, camelcase: function () { return 'Null' }, empty: function () { return '' } }, defaultStyle: 'lowercase' }) 'use strict' const Type = require('../type') const _hasOwnProperty = Object.prototype.hasOwnProperty const _toString = Object.prototype.toString function resolveYamlOmap (data) { if (data === null) return true const objectKeys = [] const object = data for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index] let pairHasKey = false if (_toString.call(pair) !== '[object Object]') return false let pairKey for (pairKey in pair) { if (_hasOwnProperty.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true else return false } } if (!pairHasKey) return false if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey) else return false } return true } function constructYamlOmap (data) { return data !== null ? data : [] } module.exports = new Type('tag:yaml.org,2002:omap', { kind: 'sequence', resolve: resolveYamlOmap, construct: constructYamlOmap }) 'use strict' const Type = require('../type') const _toString = Object.prototype.toString function resolveYamlPairs (data) { if (data === null) return true const object = data const result = new Array(object.length) for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index] if (_toString.call(pair) !== '[object Object]') return false const keys = Object.keys(pair) if (keys.length !== 1) return false result[index] = [keys[0], pair[keys[0]]] } return true } function constructYamlPairs (data) { if (data === null) return [] const object = data const result = new Array(object.length) for (let index = 0, length = object.length; index < length; index += 1) { const pair = object[index] const keys = Object.keys(pair) result[index] = [keys[0], pair[keys[0]]] } return result } module.exports = new Type('tag:yaml.org,2002:pairs', { kind: 'sequence', resolve: resolveYamlPairs, construct: constructYamlPairs }) 'use strict' const Type = require('../type') module.exports = new Type('tag:yaml.org,2002:seq', { kind: 'sequence', construct: function (data) { return data !== null ? data : [] } }) 'use strict' const Type = require('../type') const _hasOwnProperty = Object.prototype.hasOwnProperty function resolveYamlSet (data) { if (data === null) return true const object = data for (const key in object) { if (_hasOwnProperty.call(object, key)) { if (object[key] !== null) return false } } return true } function constructYamlSet (data) { return data !== null ? data : {} } module.exports = new Type('tag:yaml.org,2002:set', { kind: 'mapping', resolve: resolveYamlSet, construct: constructYamlSet }) 'use strict' const Type = require('../type') module.exports = new Type('tag:yaml.org,2002:str', { kind: 'scalar', construct: function (data) { return data !== null ? data : '' } }) 'use strict' const Type = require('../type') const YAML_DATE_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9])' + // [2] month '-([0-9][0-9])$') // [3] day const YAML_TIMESTAMP_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [3] day '(?:[Tt]|[ \\t]+)' + // ... '([0-9][0-9]?)' + // [4] hour ':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [6] second '(?:\\.([0-9]*))?' + // [7] fraction '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tzHour '(?::([0-9][0-9]))?))?$') // [11] tzMinute function resolveYamlTimestamp (data) { if (data === null) return false if (YAML_DATE_REGEXP.exec(data) !== null) return true if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true return false } function constructYamlTimestamp (data) { let fraction = 0 let delta = null let match = YAML_DATE_REGEXP.exec(data) if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data) if (match === null) throw new Error('Date resolve error') // match: [1] year [2] month [3] day const year = +(match[1]) const month = +(match[2]) - 1 // JS month starts with 0 const day = +(match[3]) if (!match[4]) { // no hour return new Date(Date.UTC(year, month, day)) } // match: [4] hour [5] minute [6] second [7] fraction const hour = +(match[4]) const minute = +(match[5]) const second = +(match[6]) if (match[7]) { fraction = match[7].slice(0, 3) while (fraction.length < 3) { // milli-seconds fraction += '0' } fraction = +fraction } // match: [8] tz [9] tz_sign [10] tzHour [11] tzMinute if (match[9]) { const tzHour = +(match[10]) const tzMinute = +(match[11] || 0) delta = (tzHour * 60 + tzMinute) * 60000 // delta in mili-seconds if (match[9] === '-') delta = -delta } const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)) if (delta) date.setTime(date.getTime() - delta) return date } function representYamlTimestamp (object /*, style */) { return object.toISOString() } module.exports = new Type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }) { "name": "js-yaml", "version": "4.2.0", "description": "YAML 1.2 parser and serializer", "author": "Vladimir Zapparov ", "license": "MIT", "repository": "nodeca/js-yaml", "funding": [ { "type": "github", "url": "https://github.com/sponsors/puzrin" }, { "type": "github", "url": "https://github.com/sponsors/nodeca" } ], "files": [ "index.js", "lib/", "bin/", "dist/" ], "bin": { "js-yaml": "bin/js-yaml.js" }, "module": "./dist/js-yaml.mjs", "exports": { ".": { "import": "./dist/js-yaml.mjs", "require": "./index.js" }, "./package.json": "./package.json" }, "unpkg": "dist/js-yaml.min.js", "jsdelivr": "dist/js-yaml.min.js", "dependencies": { "argparse": "^2.0.1" }, "devDependencies": { "c8": "^11.0.0", "codemirror": "^5.65.21", "eslint": "^9.39.4", "fast-check": "^4.8.0", "gh-pages": "^6.3.0", "neostandard": "^0.13.0", "tinybench": "^6.0.2", "vite": "^8.0.14", "vite-plugin-node-polyfills": "^0.28.0", "vite-plugin-singlefile": "^2.3.3", "workerpool": "^10.0.2" } }extends: eslint:recommended env: node: true browser: true rules: block-scoped-var: 2 complexity: [2, 15] curly: [2, multi-or-nest, consistent] dot-location: [2, property] dot-notation: 2 indent: [2, 2, SwitchCase: 1] linebreak-style: [2, unix] new-cap: 2 no-console: [2, allow: [warn, error]] no-else-return: 2 no-eq-null: 2 no-fallthrough: 2 no-invalid-this: 2 no-return-assign: 2 no-shadow: 1 no-trailing-spaces: 2 no-use-before-define: [2, nofunc] quotes: [2, single, avoid-escape] semi: [2, always] strict: [2, global] valid-jsdoc: [2, requireReturn: false] no-control-regex: 0 MIT License Copyright (c) 2017 Evgeny Poberezkin 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. 'use strict'; var traverse = module.exports = function (schema, opts, cb) { // Legacy support for v0.3.1 and earlier. if (typeof opts == 'function') { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; var post = cb.post || function() {}; _traverse(opts, pre, post, schema, '', schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == 'object' && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i=0; i All JSON Schema documentation and descriptions are copyright (c): 2009 [draft-0] IETF Trust , Kris Zyp , and SitePen (USA) . 2009 [draft-1] IETF Trust , Kris Zyp , and SitePen (USA) . 2010 [draft-2] IETF Trust , Kris Zyp , and SitePen (USA) . 2010 [draft-3] IETF Trust , Kris Zyp , Gary Court , and SitePen (USA) . 2013 [draft-4] IETF Trust ), Francis Galiegue , Kris Zyp , Gary Court , and SitePen (USA) . 2018 [draft-7] IETF Trust , Austin Wright , Henry Andrews , Geraint Luff , and Cloudflare, Inc. . 2019 [draft-2019-09] IETF Trust , Austin Wright , Henry Andrews , Ben Hutton , and Greg Dennis . 2020 [draft-2020-12] IETF Trust , Austin Wright , Henry Andrews , Ben Hutton , and Greg Dennis . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // @generated // This code is automatically generated. Manual editing is not recommended. /* * BSD-2-Clause License * * Original source code is copyright (c) 2019-2025 Remy Rylan * * * Documentation and keyword descriptions are copyright (c) 2018 IETF Trust * , Austin Wright , Henry Andrews * , Geraint Luff , and Cloudflare, * Inc. . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ export const draft = "7"; export const $schema = "https://json-schema.org/draft-07/schema"; // ----------------------------------------------------------------------------- /** * Content encoding strategy enum. * * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) */ export var ContentEncoding; (function (ContentEncoding) { /** * Only US-ASCII characters, which use the lower 7 bits for each character. * * Each line must be less than 1,000 characters. */ ContentEncoding["7bit"] = "7bit"; /** * Allow extended ASCII characters which can use the 8th (highest) bit to * indicate special characters not available in 7bit. * * Each line must be less than 1,000 characters. */ ContentEncoding["8bit"] = "8bit"; /** * Useful for data that is mostly non-text. */ ContentEncoding["Base64"] = "base64"; /** * Same character set as 8bit, with no line length restriction. */ ContentEncoding["Binary"] = "binary"; /** * An extension token defined by a standards-track RFC and registered with * IANA. */ ContentEncoding["IETFToken"] = "ietf-token"; /** * Lines are limited to 76 characters, and line breaks are represented using * special characters that are escaped. */ ContentEncoding["QuotedPrintable"] = "quoted-printable"; /** * The two characters "X-" or "x-" followed, with no intervening white space, * by any token. */ ContentEncoding["XToken"] = "x-token"; })(ContentEncoding || (ContentEncoding = {})); /** * This enum provides well-known formats that apply to strings. */ export var Format; (function (Format) { /** * A string instance is valid against this attribute if it is a valid * representation according to the "full-date" production in * [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["Date"] = "date"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "date-time" production in * [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["DateTime"] = "date-time"; /** * A string instance is valid against this attribute if it is a valid Internet * email address as defined by [RFC 5322, section 3.4.1][RFC5322]. * * [RFC5322]: https://datatracker.ietf.org/doc/html/rfc5322 */ Format["Email"] = "email"; /** * As defined by [RFC 1034, section 3.1][RFC1034], including host names * produced using the Punycode algorithm specified in * [RFC 5891, section 4.4][RFC5891]. * * [RFC1034]: https://datatracker.ietf.org/doc/html/rfc1034 * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 */ Format["Hostname"] = "hostname"; /** * A string instance is valid against this attribute if it is a valid Internet * email address as defined by [RFC 6531][RFC6531]. * * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 */ Format["IDNEmail"] = "idn-email"; /** * As defined by either [RFC 1034, section 3.1][RFC1034] as for hostname, or * an internationalized hostname as defined by * [RFC 5890, section 2.3.2.3][RFC5890]. * * [RFC1034]: https://datatracker.ietf.org/doc/html/rfc1034 * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 */ Format["IDNHostname"] = "idn-hostname"; /** * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in * [RFC 2673, section 3.2][RFC2673]. * * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 */ Format["IPv4"] = "ipv4"; /** * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. * * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 */ Format["IPv6"] = "ipv6"; /** * A string instance is valid against this attribute if it is a valid IRI, * according to [RFC 3987][RFC3987]. * * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 */ Format["IRI"] = "iri"; /** * A string instance is valid against this attribute if it is a valid IRI * Reference (either an IRI or a relative-reference), according to * [RFC 3987][RFC3987]. * * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 */ Format["IRIReference"] = "iri-reference"; /** * A string instance is valid against this attribute if it is a valid JSON * string representation of a JSON Pointer, according to * [RFC 6901, section 5][RFC6901]. * * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 */ Format["JSONPointer"] = "json-pointer"; /** * A string instance is valid against this attribute if it is a valid JSON * string representation of a JSON Pointer fragment, according to * [RFC 6901, section 5][RFC6901]. * * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 */ Format["JSONPointerURIFragment"] = "json-pointer-uri-fragment"; /** * This attribute applies to string instances. * * A regular expression, which SHOULD be valid according to the * [ECMA-262][ecma262] regular expression dialect. * * Implementations that validate formats MUST accept at least the subset of * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] * section of this specification, and SHOULD accept all valid * [ECMA-262][ecma262] expressions. * * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ * [regexInterop]: https://json-schema.org/draft-07/json-schema-validation.html#regexInterop */ Format["RegEx"] = "regex"; /** * A string instance is valid against this attribute if it is a valid * [Relative JSON Pointer][relative-json-pointer]. * * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 */ Format["RelativeJSONPointer"] = "relative-json-pointer"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "time" production in [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["Time"] = "time"; /** * A string instance is valid against this attribute if it is a valid URI, * according to [RFC3986][RFC3986]. * * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 */ Format["URI"] = "uri"; /** * A string instance is valid against this attribute if it is a valid URI * Reference (either a URI or a relative-reference), according to * [RFC3986][RFC3986]. * * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 */ Format["URIReference"] = "uri-reference"; /** * A string instance is valid against this attribute if it is a valid URI * Template (of any level), according to [RFC6570][RFC6570]. * * Note that URI Templates may be used for IRIs; there is no separate IRI * Template specification. * * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 */ Format["URITemplate"] = "uri-template"; /** * UUID */ Format["UUID"] = "uuid"; })(Format || (Format = {})); /** * Enum consisting of simple type names for the `type` keyword */ export var TypeName; (function (TypeName) { /** * Value MUST be an array. */ TypeName["Array"] = "array"; /** * Value MUST be a boolean. */ TypeName["Boolean"] = "boolean"; /** * Value MUST be an integer, no floating point numbers are allowed. This is a * subset of the number type. */ TypeName["Integer"] = "integer"; /** * Value MUST be null. Note this is mainly for purpose of being able use union * types to define nullability. If this type is not included in a union, null * values are not allowed (the primitives listed above do not allow nulls on * their own). */ TypeName["Null"] = "null"; /** * Value MUST be a number, floating point numbers are allowed. */ TypeName["Number"] = "number"; /** * Value MUST be an object. */ TypeName["Object"] = "object"; /** * Value MUST be a string. */ TypeName["String"] = "string"; })(TypeName || (TypeName = {})); // ----------------------------------------------------------------------------- // Keywords // ----------------------------------------------------------------------------- export const keywords = [ "$comment", "$id", "$ref", "$schema", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "default", "definitions", "dependencies", "description", "else", "enum", "examples", "exclusiveMaximum", "exclusiveMinimum", "format", "if", "items", "maximum", "maxItems", "maxLength", "maxProperties", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "properties", "propertyNames", "readOnly", "required", "then", "title", "type", "uniqueItems", "writeOnly", ]; // @generated // This code is automatically generated. Manual editing is not recommended. /* * BSD-2-Clause License * * Original source code is copyright (c) 2025 Remy Rylan * * * Documentation and keyword descriptions are copyright (c) 2019 IETF Trust * , Austin Wright , Henry Andrews * , Ben Hutton , and Greg Dennis * . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ export const draft = "2019-09"; export const $schema = "https://json-schema.org/draft/2019-09/schema"; // ----------------------------------------------------------------------------- /** * Content encoding strategy enum. * * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) */ export var ContentEncoding; (function (ContentEncoding) { /** * Only US-ASCII characters, which use the lower 7 bits for each character. * * Each line must be less than 1,000 characters. */ ContentEncoding["7bit"] = "7bit"; /** * Allow extended ASCII characters which can use the 8th (highest) bit to * indicate special characters not available in 7bit. * * Each line must be less than 1,000 characters. */ ContentEncoding["8bit"] = "8bit"; /** * Useful for data that is mostly non-text. */ ContentEncoding["Base64"] = "base64"; /** * Same character set as 8bit, with no line length restriction. */ ContentEncoding["Binary"] = "binary"; /** * An extension token defined by a standards-track RFC and registered with * IANA. */ ContentEncoding["IETFToken"] = "ietf-token"; /** * Lines are limited to 76 characters, and line breaks are represented using * special characters that are escaped. */ ContentEncoding["QuotedPrintable"] = "quoted-printable"; /** * The two characters "X-" or "x-" followed, with no intervening white space, * by any token. */ ContentEncoding["XToken"] = "x-token"; })(ContentEncoding || (ContentEncoding = {})); /** * This enum provides well-known formats that apply to strings. */ export var Format; (function (Format) { /** * A string instance is valid against this attribute if it is a valid * representation according to the "full-date" production in * [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["Date"] = "date"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "date-time" production in * [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["DateTime"] = "date-time"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "duration" production. */ Format["Duration"] = "duration"; /** * A string instance is valid against this attribute if it is a valid Internet * email address as defined by [RFC 5322, section 3.4.1][RFC5322]. * * [RFC5322]: https://datatracker.ietf.org/doc/html/rfc5322 */ Format["Email"] = "email"; /** * As defined by [RFC 1123, section 2.1][RFC1123], including host names * produced using the Punycode algorithm specified in * [RFC 5891, section 4.4][RFC5891]. * * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 */ Format["Hostname"] = "hostname"; /** * A string instance is valid against this attribute if it is a valid Internet * email address as defined by [RFC 6531][RFC6531]. * * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 */ Format["IDNEmail"] = "idn-email"; /** * As defined by either [RFC 1123, section 2.1][RFC1123] as for hostname, or * an internationalized hostname as defined by * [RFC 5890, section 2.3.2.3][RFC5890]. * * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 */ Format["IDNHostname"] = "idn-hostname"; /** * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in * [RFC 2673, section 3.2][RFC2673]. * * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 */ Format["IPv4"] = "ipv4"; /** * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. * * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 */ Format["IPv6"] = "ipv6"; /** * A string instance is valid against this attribute if it is a valid IRI, * according to [RFC 3987][RFC3987]. * * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 */ Format["IRI"] = "iri"; /** * A string instance is valid against this attribute if it is a valid IRI * Reference (either an IRI or a relative-reference), according to * [RFC 3987][RFC3987]. * * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 */ Format["IRIReference"] = "iri-reference"; /** * A string instance is valid against this attribute if it is a valid JSON * string representation of a JSON Pointer, according to * [RFC 6901, section 5][RFC6901]. * * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 */ Format["JSONPointer"] = "json-pointer"; /** * A string instance is valid against this attribute if it is a valid JSON * string representation of a JSON Pointer fragment, according to * [RFC 6901, section 5][RFC6901]. * * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 */ Format["JSONPointerURIFragment"] = "json-pointer-uri-fragment"; /** * This attribute applies to string instances. * * A regular expression, which SHOULD be valid according to the * [ECMA-262][ecma262] regular expression dialect. * * Implementations that validate formats MUST accept at least the subset of * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] * section of this specification, and SHOULD accept all valid * [ECMA-262][ecma262] expressions. * * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ * [regexInterop]: https://json-schema.org/draft/2019-09/json-schema-validation.html#regexInterop */ Format["RegEx"] = "regex"; /** * A string instance is valid against this attribute if it is a valid * [Relative JSON Pointer][relative-json-pointer]. * * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 */ Format["RelativeJSONPointer"] = "relative-json-pointer"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "time" production in [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["Time"] = "time"; /** * A string instance is valid against this attribute if it is a valid URI, * according to [RFC3986][RFC3986]. * * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 */ Format["URI"] = "uri"; /** * A string instance is valid against this attribute if it is a valid URI * Reference (either a URI or a relative-reference), according to * [RFC3986][RFC3986]. * * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 */ Format["URIReference"] = "uri-reference"; /** * A string instance is valid against this attribute if it is a valid URI * Template (of any level), according to [RFC 6570][RFC6570]. * * Note that URI Templates may be used for IRIs; there is no separate IRI * Template specification. * * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 */ Format["URITemplate"] = "uri-template"; /** * A string instance is valid against this attribute if it is a valid string * representation of a UUID, according to [RFC 4122][RFC4122]. * * [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122 */ Format["UUID"] = "uuid"; })(Format || (Format = {})); /** * Enum consisting of simple type names for the `type` keyword */ export var TypeName; (function (TypeName) { /** * Value MUST be an array. */ TypeName["Array"] = "array"; /** * Value MUST be a boolean. */ TypeName["Boolean"] = "boolean"; /** * Value MUST be an integer, no floating point numbers are allowed. This is a * subset of the number type. */ TypeName["Integer"] = "integer"; /** * Value MUST be null. Note this is mainly for purpose of being able use union * types to define nullability. If this type is not included in a union, null * values are not allowed (the primitives listed above do not allow nulls on * their own). */ TypeName["Null"] = "null"; /** * Value MUST be a number, floating point numbers are allowed. */ TypeName["Number"] = "number"; /** * Value MUST be an object. */ TypeName["Object"] = "object"; /** * Value MUST be a string. */ TypeName["String"] = "string"; })(TypeName || (TypeName = {})); // ----------------------------------------------------------------------------- // Keywords // ----------------------------------------------------------------------------- export const keywords = [ "$anchor", "$comment", "$defs", "$id", "$recursiveAnchor", "$recursiveRef", "$ref", "$schema", "$vocabulary", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "contentSchema", "default", "definitions", "dependencies", "dependentRequired", "dependentSchemas", "deprecated", "description", "else", "enum", "examples", "exclusiveMaximum", "exclusiveMinimum", "format", "if", "items", "maxContains", "maximum", "maxItems", "maxLength", "maxProperties", "minContains", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "properties", "propertyNames", "readOnly", "required", "then", "title", "type", "unevaluatedItems", "unevaluatedProperties", "uniqueItems", "writeOnly", ]; // @generated // This code is automatically generated. Manual editing is not recommended. /* * BSD-2-Clause License * * Original source code is copyright (c) 2025 Remy Rylan * * * Documentation and keyword descriptions are copyright (c) 2020 IETF Trust * , Austin Wright , Henry Andrews * , Ben Hutton , and Greg Dennis * . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ export const draft = "2020-12"; export const $schema = "https://json-schema.org/draft/2020-12/schema"; // ----------------------------------------------------------------------------- /** * Content encoding strategy enum. * * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) */ export var ContentEncoding; (function (ContentEncoding) { /** * Only US-ASCII characters, which use the lower 7 bits for each character. * * Each line must be less than 1,000 characters. */ ContentEncoding["7bit"] = "7bit"; /** * Allow extended ASCII characters which can use the 8th (highest) bit to * indicate special characters not available in 7bit. * * Each line must be less than 1,000 characters. */ ContentEncoding["8bit"] = "8bit"; /** * Useful for data that is mostly non-text. */ ContentEncoding["Base64"] = "base64"; /** * Same character set as 8bit, with no line length restriction. */ ContentEncoding["Binary"] = "binary"; /** * An extension token defined by a standards-track RFC and registered with * IANA. */ ContentEncoding["IETFToken"] = "ietf-token"; /** * Lines are limited to 76 characters, and line breaks are represented using * special characters that are escaped. */ ContentEncoding["QuotedPrintable"] = "quoted-printable"; /** * The two characters "X-" or "x-" followed, with no intervening white space, * by any token. */ ContentEncoding["XToken"] = "x-token"; })(ContentEncoding || (ContentEncoding = {})); /** * This enum provides well-known formats that apply to strings. */ export var Format; (function (Format) { /** * A string instance is valid against this attribute if it is a valid * representation according to the "full-date" production in * [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["Date"] = "date"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "date-time" production in * [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["DateTime"] = "date-time"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "duration" production. */ Format["Duration"] = "duration"; /** * A string instance is valid against this attribute if it is a valid Internet * email address as defined by by the "Mailbox" ABNF rule in [RFC * 5321][RFC5322], section 4.1.2. * * [RFC5321]: https://datatracker.ietf.org/doc/html/rfc5321 */ Format["Email"] = "email"; /** * As defined by [RFC 1123, section 2.1][RFC1123], including host names * produced using the Punycode algorithm specified in * [RFC 5891, section 4.4][RFC5891]. * * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 */ Format["Hostname"] = "hostname"; /** * A string instance is valid against this attribute if it is a valid Internet * email address as defined by the extended "Mailbox" ABNF rule in * [RFC 6531][RFC6531], section 3.3. * * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 */ Format["IDNEmail"] = "idn-email"; /** * As defined by either [RFC 1123, section 2.1][RFC1123] as for hostname, or * an internationalized hostname as defined by * [RFC 5890, section 2.3.2.3][RFC5890]. * * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 */ Format["IDNHostname"] = "idn-hostname"; /** * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in * [RFC 2673, section 3.2][RFC2673]. * * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 */ Format["IPv4"] = "ipv4"; /** * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. * * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 */ Format["IPv6"] = "ipv6"; /** * A string instance is valid against this attribute if it is a valid IRI, * according to [RFC 3987][RFC3987]. * * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 */ Format["IRI"] = "iri"; /** * A string instance is valid against this attribute if it is a valid IRI * Reference (either an IRI or a relative-reference), according to * [RFC 3987][RFC3987]. * * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 */ Format["IRIReference"] = "iri-reference"; /** * A string instance is valid against this attribute if it is a valid JSON * string representation of a JSON Pointer, according to * [RFC 6901, section 5][RFC6901]. * * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 */ Format["JSONPointer"] = "json-pointer"; /** * A string instance is valid against this attribute if it is a valid JSON * string representation of a JSON Pointer fragment, according to * [RFC 6901, section 5][RFC6901]. * * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 */ Format["JSONPointerURIFragment"] = "json-pointer-uri-fragment"; /** * This attribute applies to string instances. * * A regular expression, which SHOULD be valid according to the * [ECMA-262][ecma262] regular expression dialect. * * Implementations that validate formats MUST accept at least the subset of * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] * section of this specification, and SHOULD accept all valid * [ECMA-262][ecma262] expressions. * * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ * [regexInterop]: https://json-schema.org/draft/2020-12/json-schema-validation.html#regexInterop */ Format["RegEx"] = "regex"; /** * A string instance is valid against this attribute if it is a valid * [Relative JSON Pointer][relative-json-pointer]. * * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 */ Format["RelativeJSONPointer"] = "relative-json-pointer"; /** * A string instance is valid against this attribute if it is a valid * representation according to the "time" production in [RFC 3339][RFC3339]. * * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 */ Format["Time"] = "time"; /** * A string instance is valid against this attribute if it is a valid URI, * according to [RFC3986][RFC3986]. * * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 */ Format["URI"] = "uri"; /** * A string instance is valid against this attribute if it is a valid URI * Reference (either a URI or a relative-reference), according to * [RFC3986][RFC3986]. * * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 */ Format["URIReference"] = "uri-reference"; /** * A string instance is valid against this attribute if it is a valid URI * Template (of any level), according to [RFC 6570][RFC6570]. * * Note that URI Templates may be used for IRIs; there is no separate IRI * Template specification. * * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 */ Format["URITemplate"] = "uri-template"; /** * A string instance is valid against this attribute if it is a valid string * representation of a UUID, according to [RFC 4122][RFC4122]. * * [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122 */ Format["UUID"] = "uuid"; })(Format || (Format = {})); /** * Enum consisting of simple type names for the `type` keyword */ export var TypeName; (function (TypeName) { /** * Value MUST be an array. */ TypeName["Array"] = "array"; /** * Value MUST be a boolean. */ TypeName["Boolean"] = "boolean"; /** * Value MUST be an integer, no floating point numbers are allowed. This is a * subset of the number type. */ TypeName["Integer"] = "integer"; /** * Value MUST be null. Note this is mainly for purpose of being able use union * types to define nullability. If this type is not included in a union, null * values are not allowed (the primitives listed above do not allow nulls on * their own). */ TypeName["Null"] = "null"; /** * Value MUST be a number, floating point numbers are allowed. */ TypeName["Number"] = "number"; /** * Value MUST be an object. */ TypeName["Object"] = "object"; /** * Value MUST be a string. */ TypeName["String"] = "string"; })(TypeName || (TypeName = {})); // ----------------------------------------------------------------------------- // Keywords // ----------------------------------------------------------------------------- export const keywords = [ "$anchor", "$comment", "$defs", "$dynamicAnchor", "$dynamicRef", "$id", "$ref", "$schema", "$vocabulary", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "contentSchema", "default", "definitions", "dependencies", "dependentRequired", "dependentSchemas", "deprecated", "description", "else", "enum", "examples", "exclusiveMaximum", "exclusiveMinimum", "format", "if", "items", "maxContains", "maximum", "maxItems", "maxLength", "maxProperties", "minContains", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "prefixItems", "properties", "propertyNames", "readOnly", "required", "then", "title", "type", "unevaluatedItems", "unevaluatedProperties", "uniqueItems", "writeOnly", ]; { "name": "json-schema-typed", "description": "JSON Schema TypeScript definitions with complete inline documentation.", "license": "BSD-2-Clause", "version": "8.0.2", "homepage": "https://github.com/RemyRylan/json-schema-typed/tree/main/dist/node", "repository": { "type": "git", "url": "https://github.com/RemyRylan/json-schema-typed.git" }, "author": { "name": "Remy Rylan", "url": "https://github.com/RemyRylan" }, "main": "./draft_2020_12.js", "types": "./draft_2020_12.d.ts", "type": "module", "exports": { ".": { "types": "./draft_2020_12.d.ts", "default": "./draft_2020_12.js" }, "./draft-07": { "types": "./draft_07.d.ts", "default": "./draft_07.js" }, "./draft-2019-09": { "types": "./draft_2019_09.d.ts", "default": "./draft_2019_09.js" }, "./draft-2020-12": { "types": "./draft_2020_12.d.ts", "default": "./draft_2020_12.js" } } }(The MIT License) Copyright (c) 2012-2015, JP Richardson 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. let _fs try { _fs = require('graceful-fs') } catch (_) { _fs = require('fs') } const universalify = require('universalify') const { stringify, stripBom } = require('./utils') async function _readFile (file, options = {}) { if (typeof options === 'string') { options = { encoding: options } } const fs = options.fs || _fs const shouldThrow = 'throws' in options ? options.throws : true let data = await universalify.fromCallback(fs.readFile)(file, options) data = stripBom(data) let obj try { obj = JSON.parse(data, options ? options.reviver : null) } catch (err) { if (shouldThrow) { err.message = `${file}: ${err.message}` throw err } else { return null } } return obj } const readFile = universalify.fromPromise(_readFile) function readFileSync (file, options = {}) { if (typeof options === 'string') { options = { encoding: options } } const fs = options.fs || _fs const shouldThrow = 'throws' in options ? options.throws : true try { let content = fs.readFileSync(file, options) content = stripBom(content) return JSON.parse(content, options.reviver) } catch (err) { if (shouldThrow) { err.message = `${file}: ${err.message}` throw err } else { return null } } } async function _writeFile (file, obj, options = {}) { const fs = options.fs || _fs const str = stringify(obj, options) await universalify.fromCallback(fs.writeFile)(file, str, options) } const writeFile = universalify.fromPromise(_writeFile) function writeFileSync (file, obj, options = {}) { const fs = options.fs || _fs const str = stringify(obj, options) // not sure if fs.writeFileSync returns anything, but just in case return fs.writeFileSync(file, str, options) } const jsonfile = { readFile, readFileSync, writeFile, writeFileSync } module.exports = jsonfile { "name": "jsonfile", "version": "6.1.0", "description": "Easily read/write JSON files.", "repository": { "type": "git", "url": "git@github.com:jprichardson/node-jsonfile.git" }, "author": "JP Richardson ", "license": "MIT", "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" }, "devDependencies": { "mocha": "^8.2.0", "rimraf": "^2.4.0", "standard": "^16.0.1" }, "main": "index.js", "files": [ "index.js", "utils.js" ] }function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) { const EOF = finalEOL ? EOL : '' const str = JSON.stringify(obj, replacer, spaces) return str.replace(/\n/g, EOL) + EOF } function stripBom (content) { // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified if (Buffer.isBuffer(content)) content = content.toString('utf8') return content.replace(/^\uFEFF/, '') } module.exports = { stringify, stripBom } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Lazy = void 0; class Lazy { constructor(creator) { this._value = null; this.creator = creator; } get hasValue() { return this.creator == null; } get value() { if (this.creator == null) { return this._value; } const result = this.creator(); this.value = result; return result; } set value(value) { this._value = value; this.creator = null; } } exports.Lazy = Lazy; //# sourceMappingURL=main.js.map{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;;AAAA,MAAa,IAAI;IAIf,YAAY,OAAyB;QAH7B,WAAM,GAAsB,IAAI,CAAA;QAItC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,OAAO,IAAI,IAAI,CAAA;IAC7B,CAAC;IAED,IAAI,KAAK;QACP,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI,EAAE;YACxB,OAAO,IAAI,CAAC,MAAQ,CAAA;SACrB;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,EAAE,CAAA;QAC7B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAA;QACnB,OAAO,MAAM,CAAA;IACf,CAAC;IAED,IAAI,KAAK,CAAC,KAAiB;QACzB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;QACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;IACrB,CAAC;CACF;AA1BD,oBA0BC","sourcesContent":["export class Lazy {\n private _value: Promise | null = null\n private creator: (() => Promise) | null\n\n constructor(creator: () => Promise) {\n this.creator = creator\n }\n\n get hasValue() {\n return this.creator == null\n }\n\n get value(): Promise {\n if (this.creator == null) {\n return this._value!!\n }\n\n const result = this.creator()\n this.value = result\n return result\n }\n\n set value(value: Promise) {\n this._value = value\n this.creator = null\n }\n}"]}{ "name": "lazy-val", "version": "1.0.5", "main": "out/main.js", "author": "Vladimir Krivosheev", "license": "MIT", "repository": "develar/lazy-val", "homepage": "https://github.com/develar/lazy-val", "files": [ "out" ], "devDependencies": { "typescript": "^4.2.4" }, "typings": "./out/main.d.ts" }Copyright jQuery Foundation and other contributors Based on Underscore.js, copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors This software consists of voluntary contributions made by many individuals. For exact contribution history, see the revision history available at https://github.com/lodash/lodash The following license applies to all parts of this software except as documented below: ==== 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. ==== Copyright and related rights for sample code are waived via CC0. Sample code is defined as all source code displayed within the prose of the documentation. CC0: http://creativecommons.org/publicdomain/zero/1.0/ ==== Files located in the node_modules and vendor directories are externally maintained libraries used by this software which have their own licenses; we recommend you read them, as their terms may differ from the terms above. /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } module.exports = escapeRegExp; { "name": "lodash.escaperegexp", "version": "4.1.2", "description": "The lodash method `_.escapeRegExp` exported as a module.", "homepage": "https://lodash.com/", "icon": "https://lodash.com/icon.svg", "license": "MIT", "author": "John-David Dalton (http://allyoucanleet.com/)", "repository": "lodash/lodash" }Copyright JS Foundation and other contributors Based on Underscore.js, copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors This software consists of voluntary contributions made by many individuals. For exact contribution history, see the revision history available at https://github.com/lodash/lodash The following license applies to all parts of this software except as documented below: ==== 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. ==== Copyright and related rights for sample code are waived via CC0. Sample code is defined as all source code displayed within the prose of the documentation. CC0: http://creativecommons.org/publicdomain/zero/1.0/ ==== Files located in the node_modules and vendor directories are externally maintained libraries used by this software which have their own licenses; we recommend you read them, as their terms may differ from the terms above. /** * Lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright JS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = Symbol ? Symbol.toStringTag : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = isEqual; { "name": "lodash.isequal", "version": "4.5.0", "description": "The Lodash method `_.isEqual` exported as a module.", "homepage": "https://lodash.com/", "icon": "https://lodash.com/icon.svg", "license": "MIT", "author": "John-David Dalton (http://allyoucanleet.com/)", "repository": "lodash/lodash" }const copyProperty = (to, from, property, ignoreNonConfigurable) => { // `Function#length` should reflect the parameters of `to` not `from` since we keep its body. // `Function#prototype` is non-writable and non-configurable so can never be modified. if (property === 'length' || property === 'prototype') { return; } // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here. if (property === 'arguments' || property === 'caller') { return; } const toDescriptor = Object.getOwnPropertyDescriptor(to, property); const fromDescriptor = Object.getOwnPropertyDescriptor(from, property); if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) { return; } Object.defineProperty(to, property, fromDescriptor); }; // `Object.defineProperty()` throws if the property exists, is not configurable and either: // - one its descriptors is changed // - it is non-writable and its value is changed const canCopyProperty = function (toDescriptor, fromDescriptor) { return toDescriptor === undefined || toDescriptor.configurable || ( toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value) ); }; const changePrototype = (to, from) => { const fromPrototype = Object.getPrototypeOf(from); if (fromPrototype === Object.getPrototypeOf(to)) { return; } Object.setPrototypeOf(to, fromPrototype); }; const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`; const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString'); const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected. // We use `bind()` instead of a closure for the same reason. // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times. const changeToString = (to, from, name) => { const withName = name === '' ? '' : `with ${name.trim()}() `; const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same` Object.defineProperty(newToString, 'name', toStringName); const {writable, enumerable, configurable} = toStringDescriptor; // We destructue to avoid a potential `get` descriptor. Object.defineProperty(to, 'toString', {value: newToString, writable, enumerable, configurable}); }; export default function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) { const {name} = to; for (const property of Reflect.ownKeys(from)) { copyProperty(to, from, property, ignoreNonConfigurable); } changePrototype(to, from); changeToString(to, from, name); return to; } MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "mimic-function", "version": "5.0.1", "description": "Make a function mimic another one", "license": "MIT", "repository": "sindresorhus/mimic-function", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "files": [ "index.js", "index.d.ts" ], "devDependencies": { "ava": "^5.3.1", "tsd": "^0.29.0", "xo": "^0.56.0" } }{ "all": true, "check-coverage": false, "reporter": ["text-summary", "text", "html", "json"], "lines": 86, "statements": 85.93, "functions": 82.43, "branches": 76.06, "exclude": [ "coverage", "example", "test" ] } This software is 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. 'use strict'; function hasKey(obj, keys) { var o = obj; keys.slice(0, -1).forEach(function (key) { o = o[key] || {}; }); var key = keys[keys.length - 1]; return key in o; } function isNumber(x) { if (typeof x === 'number') { return true; } if ((/^0x[0-9a-f]+$/i).test(x)) { return true; } return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x); } function isConstructorOrProto(obj, key) { return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__'; } module.exports = function (args, opts) { if (!opts) { opts = {}; } var flags = { bools: {}, strings: {}, unknownFn: null, }; if (typeof opts.unknown === 'function') { flags.unknownFn = opts.unknown; } if (typeof opts.boolean === 'boolean' && opts.boolean) { flags.allBools = true; } else { [].concat(opts.boolean).filter(Boolean).forEach(function (key) { flags.bools[key] = true; }); } var aliases = {}; function aliasIsBoolean(key) { return aliases[key].some(function (x) { return flags.bools[x]; }); } Object.keys(opts.alias || {}).forEach(function (key) { aliases[key] = [].concat(opts.alias[key]); aliases[key].forEach(function (x) { aliases[x] = [key].concat(aliases[key].filter(function (y) { return x !== y; })); }); }); [].concat(opts.string).filter(Boolean).forEach(function (key) { flags.strings[key] = true; if (aliases[key]) { [].concat(aliases[key]).forEach(function (k) { flags.strings[k] = true; }); } }); var defaults = opts.default || {}; var argv = { _: [] }; function argDefined(key, arg) { return (flags.allBools && (/^--[^=]+$/).test(arg)) || flags.strings[key] || flags.bools[key] || aliases[key]; } function setKey(obj, keys, value) { var o = obj; for (var i = 0; i < keys.length - 1; i++) { var key = keys[i]; if (isConstructorOrProto(o, key)) { return; } if (o[key] === undefined) { o[key] = {}; } if ( o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype ) { o[key] = {}; } if (o[key] === Array.prototype) { o[key] = []; } o = o[key]; } var lastKey = keys[keys.length - 1]; if (isConstructorOrProto(o, lastKey)) { return; } if ( o === Object.prototype || o === Number.prototype || o === String.prototype ) { o = {}; } if (o === Array.prototype) { o = []; } if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') { o[lastKey] = value; } else if (Array.isArray(o[lastKey])) { o[lastKey].push(value); } else { o[lastKey] = [o[lastKey], value]; } } function setArg(key, val, arg) { if (arg && flags.unknownFn && !argDefined(key, arg)) { if (flags.unknownFn(arg) === false) { return; } } var value = !flags.strings[key] && isNumber(val) ? Number(val) : val; setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), value); }); } Object.keys(flags.bools).forEach(function (key) { setArg(key, defaults[key] === undefined ? false : defaults[key]); }); var notFlags = []; if (args.indexOf('--') !== -1) { notFlags = args.slice(args.indexOf('--') + 1); args = args.slice(0, args.indexOf('--')); } for (var i = 0; i < args.length; i++) { var arg = args[i]; var key; var next; if ((/^--.+=/).test(arg)) { // Using [\s\S] instead of . because js doesn't support the // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); key = m[1]; var value = m[2]; if (flags.bools[key]) { value = value !== 'false'; } setArg(key, value, arg); } else if ((/^--no-.+/).test(arg)) { key = arg.match(/^--no-(.+)/)[1]; setArg(key, false, arg); } else if ((/^--.+/).test(arg)) { key = arg.match(/^--(.+)/)[1]; next = args[i + 1]; if ( next !== undefined && !(/^(-|--)[^-]/).test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true) ) { setArg(key, next, arg); i += 1; } else if ((/^(true|false)$/).test(next)) { setArg(key, next === 'true', arg); i += 1; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } else if ((/^-[^-]+/).test(arg)) { var letters = arg.slice(1, -1).split(''); var broken = false; for (var j = 0; j < letters.length; j++) { next = arg.slice(j + 2); if (next === '-') { setArg(letters[j], next, arg); continue; } if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') { setArg(letters[j], next.slice(1), arg); broken = true; break; } if ( (/[A-Za-z]/).test(letters[j]) && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next) ) { setArg(letters[j], next, arg); broken = true; break; } if (letters[j + 1] && letters[j + 1].match(/\W/)) { setArg(letters[j], arg.slice(j + 2), arg); broken = true; break; } else { setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); } } key = arg.slice(-1)[0]; if (!broken && key !== '-') { if ( args[i + 1] && !(/^(-|--)[^-]/).test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true) ) { setArg(key, args[i + 1], arg); i += 1; } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) { setArg(key, args[i + 1] === 'true', arg); i += 1; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } } else { if (!flags.unknownFn || flags.unknownFn(arg) !== false) { argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); } if (opts.stopEarly) { argv._.push.apply(argv._, args.slice(i + 1)); break; } } } Object.keys(defaults).forEach(function (k) { if (!hasKey(argv, k.split('.'))) { setKey(argv, k.split('.'), defaults[k]); (aliases[k] || []).forEach(function (x) { setKey(argv, x.split('.'), defaults[k]); }); } }); if (opts['--']) { argv['--'] = notFlags.slice(); } else { notFlags.forEach(function (k) { argv._.push(k); }); } return argv; }; { "name": "minimist", "version": "1.2.8", "description": "parse argument options", "main": "index.js", "devDependencies": { "@ljharb/eslint-config": "^21.0.1", "aud": "^2.0.2", "auto-changelog": "^2.4.0", "eslint": "=8.8.0", "in-publish": "^2.0.1", "npmignore": "^0.3.0", "nyc": "^10.3.2", "safe-publish-latest": "^2.0.0", "tape": "^5.6.3" }, "testling": { "files": "test/*.js", "browsers": [ "ie/6..latest", "ff/5", "firefox/latest", "chrome/10", "chrome/latest", "safari/5.1", "safari/latest", "opera/12" ] }, "repository": { "type": "git", "url": "git://github.com/minimistjs/minimist.git" }, "homepage": "https://github.com/minimistjs/minimist", "author": { "name": "James Halliday", "email": "mail@substack.net", "url": "http://substack.net" }, "funding": { "url": "https://github.com/sponsors/ljharb" }, "license": "MIT", "auto-changelog": { "output": "CHANGELOG.md", "template": "keepachangelog", "unreleased": false, "commitLimit": false, "backfillLimit": false, "hideCredit": true }, "publishConfig": { "ignore": [ ".github/workflows" ] } }Copyright 2010 James Halliday (mail@substack.net) This project is free software released under the MIT/X11 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. #!/usr/bin/env node var mkdirp = require('../'); var minimist = require('minimist'); var fs = require('fs'); var argv = minimist(process.argv.slice(2), { alias: { m: 'mode', h: 'help' }, string: [ 'mode' ] }); if (argv.help) { fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); return; } var paths = argv._.slice(); var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; (function next () { if (paths.length === 0) return; var p = paths.shift(); if (mode === undefined) mkdirp(p, cb) else mkdirp(p, mode, cb) function cb (err) { if (err) { console.error(err.message); process.exit(1); } else next(); } })(); 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 permission string. var path = require('path'); var fs = require('fs'); var _0777 = parseInt('0777', 8); module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; function mkdirP (p, opts, f, made) { if (typeof opts === 'function') { f = opts; opts = {}; } else if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 } if (!made) made = null; var cb = f || /* istanbul ignore next */ function () {}; p = path.resolve(p); xfs.mkdir(p, mode, function (er) { if (!er) { made = made || p; return cb(null, made); } switch (er.code) { case 'ENOENT': /* istanbul ignore if */ if (path.dirname(p) === p) return cb(er); mkdirP(path.dirname(p), opts, function (er, made) { /* istanbul ignore if */ if (er) cb(er, made); else mkdirP(p, opts, cb, made); }); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: xfs.stat(p, function (er2, stat) { // if the stat fails, then that's super weird. // let the original error be the failure reason. if (er2 || !stat.isDirectory()) cb(er, made) else cb(null, made); }); break; } }); } mkdirP.sync = function sync (p, opts, made) { if (!opts || typeof opts !== 'object') { opts = { mode: opts }; } var mode = opts.mode; var xfs = opts.fs || fs; if (mode === undefined) { mode = _0777 } if (!made) made = null; p = path.resolve(p); try { xfs.mkdirSync(p, mode); made = made || p; } catch (err0) { switch (err0.code) { case 'ENOENT' : made = sync(path.dirname(p), opts, made); sync(p, opts, made); break; // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. default: var stat; try { stat = xfs.statSync(p); } catch (err1) /* istanbul ignore next */ { throw err0; } /* istanbul ignore if */ if (!stat.isDirectory()) throw err0; break; } } return made; }; { "name": "mkdirp", "description": "Recursively mkdir, like `mkdir -p`", "version": "0.5.6", "publishConfig": { "tag": "legacy" }, "author": "James Halliday (http://substack.net)", "main": "index.js", "repository": { "type": "git", "url": "https://github.com/substack/node-mkdirp.git" }, "dependencies": { "minimist": "^1.2.6" }, "devDependencies": { "tap": "^16.0.1" }, "bin": "bin/cmd.js", "license": "MIT", "files": [ "bin", "index.js" ] }/** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } The MIT License (MIT) Copyright (c) 2020 Vercel, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "ms", "version": "2.1.3", "description": "Tiny millisecond conversion utility", "repository": "vercel/ms", "main": "./index", "files": [ "index.js" ], "lint-staged": { "*.js": [ "npm run lint", "prettier --single-quote --write", "git add" ] }, "license": "MIT", "devDependencies": { "eslint": "4.18.2", "expect.js": "0.3.1", "husky": "0.14.3", "lint-staged": "5.0.0", "mocha": "4.0.1", "prettier": "2.0.5" } }'use strict'; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; The MIT License (MIT) Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { "name": "path-is-absolute", "version": "1.0.1", "description": "Node.js 0.12 path.isAbsolute() ponyfill", "license": "MIT", "repository": "sindresorhus/path-is-absolute", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=0.10.0" }, "files": [ "index.js" ], "devDependencies": { "xo": "^0.16.0" } }'use strict'; var Module = require('module'); var path = require('path'); module.exports = function requireFromString(code, filename, opts) { if (typeof filename === 'object') { opts = filename; filename = undefined; } opts = opts || {}; filename = filename || ''; opts.appendPaths = opts.appendPaths || []; opts.prependPaths = opts.prependPaths || []; if (typeof code !== 'string') { throw new Error('code must be a string, not ' + typeof code); } var paths = Module._nodeModulePaths(path.dirname(filename)); var parent = module.parent; var m = new Module(filename, parent); m.filename = filename; m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths); m._compile(code, filename); var exports = m.exports; parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1); return exports; }; The MIT License (MIT) Copyright (c) Vsevolod Strukchinsky (github.com/floatdrop) 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. { "name": "require-from-string", "version": "2.0.2", "description": "Require module from string", "license": "MIT", "repository": "floatdrop/require-from-string", "author": { "name": "Vsevolod Strukchinsky", "email": "floatdrop@gmail.com", "url": "github.com/floatdrop" }, "engines": { "node": ">=0.10.0" }, "files": [ "index.js" ], "dependencies": {}, "devDependencies": { "mocha": "*" } }The ISC License Copyright (c) 2010-2024 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. ==== `String.fromCodePoint` by Mathias Bynens used according to terms of MIT License, as follows: Copyright (c) 2010-2024 Mathias Bynens 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. ;(function (sax) { // wrapper for non-node envs sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } sax.SAXParser = SAXParser sax.SAXStream = SAXStream sax.createStream = createStream // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), // since that's the earliest that a buffer overrun could occur. This way, checks are // as rare as required, but as often as necessary to ensure never crossing this bound. // Furthermore, buffers are only tested at most once per write(), so passing a very // large string into write() might have undesirable effects, but this is manageable by // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme // edge case, result in creating at most one complete copy of the string passed in. // Set to Infinity to have unlimited buffers. sax.MAX_BUFFER_LENGTH = 64 * 1024 var buffers = [ 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', 'procInstName', 'procInstBody', 'entity', 'attribName', 'attribValue', 'cdata', 'script' ] sax.EVENTS = [ 'text', 'processinginstruction', 'sgmldeclaration', 'doctype', 'comment', 'opentagstart', 'attribute', 'opentag', 'closetag', 'opencdata', 'cdata', 'closecdata', 'error', 'end', 'ready', 'script', 'opennamespace', 'closenamespace' ] function SAXParser (strict, opt) { if (!(this instanceof SAXParser)) { return new SAXParser(strict, opt) } var parser = this clearBuffers(parser) parser.q = parser.c = '' parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH parser.opt = opt || {} parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' parser.tags = [] parser.closed = parser.closedRoot = parser.sawRoot = false parser.tag = parser.error = null parser.strict = !!strict parser.noscript = !!(strict || parser.opt.noscript) parser.state = S.BEGIN parser.strictEntities = parser.opt.strictEntities parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) parser.attribList = [] // namespaces form a prototype chain. // it always points at the current tag, // which protos to its parent tag. if (parser.opt.xmlns) { parser.ns = Object.create(rootNS) } // disallow unquoted attribute values if not otherwise configured // and strict mode is true if (parser.opt.unquotedAttributeValues === undefined) { parser.opt.unquotedAttributeValues = !strict; } // mostly just for error reporting parser.trackPosition = parser.opt.position !== false if (parser.trackPosition) { parser.position = parser.line = parser.column = 0 } emit(parser, 'onready') } if (!Object.create) { Object.create = function (o) { function F () {} F.prototype = o var newf = new F() return newf } } if (!Object.keys) { Object.keys = function (o) { var a = [] for (var i in o) if (o.hasOwnProperty(i)) a.push(i) return a } } function checkBufferLength (parser) { var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) var maxActual = 0 for (var i = 0, l = buffers.length; i < l; i++) { var len = parser[buffers[i]].length if (len > maxAllowed) { // Text/cdata nodes can get big, and since they're buffered, // we can get here under normal conditions. // Avoid issues by emitting the text node now, // so at least it won't get any bigger. switch (buffers[i]) { case 'textNode': closeText(parser) break case 'cdata': emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' break case 'script': emitNode(parser, 'onscript', parser.script) parser.script = '' break default: error(parser, 'Max buffer length exceeded: ' + buffers[i]) } } maxActual = Math.max(maxActual, len) } // schedule the next check for the earliest possible buffer overrun. var m = sax.MAX_BUFFER_LENGTH - maxActual parser.bufferCheckPosition = m + parser.position } function clearBuffers (parser) { for (var i = 0, l = buffers.length; i < l; i++) { parser[buffers[i]] = '' } } function flushBuffers (parser) { closeText(parser) if (parser.cdata !== '') { emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' } if (parser.script !== '') { emitNode(parser, 'onscript', parser.script) parser.script = '' } } SAXParser.prototype = { end: function () { end(this) }, write: write, resume: function () { this.error = null; return this }, close: function () { return this.write(null) }, flush: function () { flushBuffers(this) } } var Stream try { Stream = require('stream').Stream } catch (ex) { Stream = function () {} } if (!Stream) Stream = function () {} var streamWraps = sax.EVENTS.filter(function (ev) { return ev !== 'error' && ev !== 'end' }) function createStream (strict, opt) { return new SAXStream(strict, opt) } function SAXStream (strict, opt) { if (!(this instanceof SAXStream)) { return new SAXStream(strict, opt) } Stream.apply(this) this._parser = new SAXParser(strict, opt) this.writable = true this.readable = true var me = this this._parser.onend = function () { me.emit('end') } this._parser.onerror = function (er) { me.emit('error', er) // if didn't throw, then means error was handled. // go ahead and clear error, so we can write again. me._parser.error = null } this._decoder = null streamWraps.forEach(function (ev) { Object.defineProperty(me, 'on' + ev, { get: function () { return me._parser['on' + ev] }, set: function (h) { if (!h) { me.removeAllListeners(ev) me._parser['on' + ev] = h return h } me.on(ev, h) }, enumerable: true, configurable: false }) }) } SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }) SAXStream.prototype.write = function (data) { if (typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function' && Buffer.isBuffer(data)) { if (!this._decoder) { var SD = require('string_decoder').StringDecoder this._decoder = new SD('utf8') } data = this._decoder.write(data) } this._parser.write(data.toString()) this.emit('data', data) return true } SAXStream.prototype.end = function (chunk) { if (chunk && chunk.length) { this.write(chunk) } this._parser.end() return true } SAXStream.prototype.on = function (ev, handler) { var me = this if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { me._parser['on' + ev] = function () { var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) args.splice(0, 0, ev) me.emit.apply(me, args) } } return Stream.prototype.on.call(me, ev, handler) } // this really needs to be replaced with character classes. // XML allows all manner of ridiculous numbers and digits. var CDATA = '[CDATA[' var DOCTYPE = 'DOCTYPE' var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } // http://www.w3.org/TR/REC-xml/#NT-NameStartChar // This implementation works on strings, a single character at a time // as such, it cannot ever support astral-plane characters (10000-EFFFF) // without a significant breaking change to either this parser, or the // JavaScript language. Implementation of an emoji-capable xml parser // is left as an exercise for the reader. var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ function isWhitespace (c) { return c === ' ' || c === '\n' || c === '\r' || c === '\t' } function isQuote (c) { return c === '"' || c === '\'' } function isAttribEnd (c) { return c === '>' || isWhitespace(c) } function isMatch (regex, c) { return regex.test(c) } function notMatch (regex, c) { return !isMatch(regex, c) } var S = 0 sax.STATE = { BEGIN: S++, // leading byte order mark or whitespace BEGIN_WHITESPACE: S++, // leading whitespace TEXT: S++, // general stuff TEXT_ENTITY: S++, // & and such. OPEN_WAKA: S++, // < SGML_DECL: S++, // SCRIPT: S++, //