diff --git a/README.md b/README.md index bedc7c3..ca96608 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Check out our [example repositories](https://github.com/githubocto?q=flat-demo&t ### Option 1: Flat Editor VSCode Extension -The easiest way to get a Flat Data action up and running is with the accompanying [Flat Editor VSCode Extension](https://marketplace.visualstudio.com/items?itemName=GitHubOCTO.flat) which helps you author Flat yml files. +The easiest way to get a Flat Data action up and running is with the accompanying [Flat Editor VSCode Extension](https://marketplace.visualstudio.com/items?itemName=GitHubOCTO.flat) which helps you author Flat yml files. To use it, [install the extension](https://marketplace.visualstudio.com/items?itemName=GitHubOCTO.flat) and then invoke `Flat Editor` from the command palette within VSCode (Mac: ⌘⇧P, Others:ctrl-shift-P). @@ -85,13 +85,25 @@ These two modes are exclusive; you cannot mix settings for these two in one Flat #### `http_url` -A URL from which to fetch data. Specifying this input puts Flat into `http` mode. +A URL from which to fetch data. Specifying this input puts Flat into `http` mode. This can be any endpoint: a json, csv, png, zip, xlsx, etc. +#### `authorization` (optional) + +A string used for authorizing the HTTP request. The value of this field is passed in as a header w/ the `authorization` key. + +For example, if this field is set to `Bearer abc123` then the following header is sent with each request: + +```json +{ + "Authorization": "Bearer abc123" +} +``` + #### `downloaded_filename` -The name of the file to store data fetched by Flat. +The name of the file to store data fetched by Flat. In `http` mode this can be anything. This can be any endpoint: a json, csv, txt, png, zip, xlsx, etc. file @@ -115,14 +127,13 @@ A URI-style database connection string. Flat will use this connection string to > > If you're using the [flat-vscode extension](https://github.com/githubocto/flat-vscode), this is handled for you. - #### `sql_queryfile` The pathname of the file containing the SQL query that will be issued to the database. Defaults to `.github/workflows/query.sql`. This path is relative to the root of your repo. #### `downloaded_filename` -The name of the file to store data fetched by Flat. +The name of the file to store data fetched by Flat. In `sql` mode this should be one of `csv` or `json`. SQL query results will be serialized to disk in the specified format. diff --git a/dist/LICENSE b/dist/LICENSE index 0a26fa9..db0b4d0 100644 --- a/dist/LICENSE +++ b/dist/LICENSE @@ -15,15 +15,6 @@ MIT @actions/io MIT -The MIT License (MIT) - -Copyright 2019 GitHub - -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. @azure/ms-rest-azure-env MIT @@ -100,47 +91,6 @@ MIT SOFTWARE -@js-joda/core -BSD-3-Clause -BSD License - -For js-joda software - -Copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of js-joda nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -@tediousjs/connection-string -MIT - @vercel/ncc MIT Copyright 2018 ZEIT, Inc. @@ -406,6 +356,32 @@ Apache-2.0 limitations under the License. +ajv +MIT +The MIT License (MIT) + +Copyright (c) 2015-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. + + + ansi-regex MIT The MIT License (MIT) @@ -496,6 +472,32 @@ Permission to use, copy, modify, and/or distribute this software for any purpose 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. +asn1 +MIT +Copyright (c) 2011 Mark Cavage, All rights reserved. + +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 + + +assert-plus +MIT + async MIT Copyright (c) 2010-2018 Caolan McMahon @@ -544,6 +546,87 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +aws-sign2 +Apache-2.0 +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +aws4 +MIT +Copyright 2013 Michael Hart (michael.hart.au@gmail.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. + + axios MIT Copyright (c) 2014-present Matt Zabriskie @@ -592,6 +675,76 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +bcrypt-pbkdf +BSD-3-Clause +The Blowfish portions are under the following license: + +Blowfish block cipher for OpenBSD +Copyright 1997 Niels Provos +All rights reserved. + +Implementation advice by David Mazieres . + +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. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 bcrypt_pbkdf portions are under the following license: + +Copyright (c) 2013 Ted Unangst + +Permission to use, copy, modify, and 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. + + + +Performance improvements (Javascript-specific): + +Copyright 2016, Joyent Inc +Author: Alex Wilson + +Permission to use, copy, modify, and 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. + + bignumber.js MIT The MIT Licence. @@ -624,7 +777,7 @@ MIT The MIT License (MIT) ===================== -Copyright (c) 2013-2019 bl contributors +Copyright (c) 2013-2018 bl contributors ---------------------------------- *bl contributors listed at * @@ -677,6 +830,37 @@ Redistribution and use in source and binary forms, with or without modification, 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. +caseless +Apache-2.0 +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +1. Definitions. +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. +END OF TERMS AND CONDITIONS + chalk MIT MIT License @@ -1234,6 +1418,30 @@ 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. +ecc-jsbn +MIT +The MIT License (MIT) + +Copyright (c) 2014 Jeremie Miller + +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. + ecdsa-sig-formatter Apache-2.0 Apache License @@ -1439,19 +1647,119 @@ Apache License limitations under the License. -follow-redirects +extend MIT -Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh +The MIT License (MIT) -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: +Copyright (c) 2014 Stefan Thomas -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +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. + + + +extsprintf +MIT +Copyright (c) 2012, Joyent, Inc. All rights reserved. + +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 + + +fast-deep-equal +MIT +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. + + +fast-json-stable-stringify +MIT +This software is released under the MIT license: + +Copyright (c) 2017 Evgeny Poberezkin +Copyright (c) 2013 James Halliday + +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. + + +follow-redirects +MIT +Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh + +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, @@ -1461,6 +1769,64 @@ 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. +forever-agent +Apache-2.0 +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + form-data MIT Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors @@ -1573,6 +1939,36 @@ under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/ +har-schema +ISC +Copyright (c) 2015, Ahmad Nassri + +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. + + +har-validator +MIT +MIT License + +Copyright (c) 2018 Ahmad Nassri + +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. + + has-flag MIT MIT License @@ -1637,6 +2033,28 @@ 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. +http-signature +MIT +Copyright Joyent, Inc. All rights reserved. +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. + + iconv-lite MIT Copyright (c) 2011 Alexander Shtuchkin @@ -1701,7 +2119,7 @@ PERFORMANCE OF THIS SOFTWARE. -ip-regex +is-fullwidth-code-point MIT The MIT License (MIT) @@ -1726,34 +2144,46 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -is-fullwidth-code-point +is-typedarray MIT -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) +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: +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 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. +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. isarray MIT +isstream +MIT +The MIT License (MIT) +===================== + +Copyright (c) 2015 Rod Vagg +--------------------------- + +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. + + js-yaml MIT (The MIT License) @@ -1959,6 +2389,119 @@ Apache-2.0 END OF TERMS AND CONDITIONS +jsbn +MIT +Licensing +--------- + +This software is covered under the following copyright: + +/* + * Copyright (c) 2003-2005 Tom Wu + * All Rights Reserved. + * + * 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" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ + +Address all questions regarding this license to: + + Tom Wu + tjw@cs.Stanford.EDU + +json-schema +AFLv2.1 + +json-schema-traverse +MIT +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. + + +json-stringify-safe +ISC +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. + + +jsprim +MIT +Copyright (c) 2012, Joyent, Inc. All rights reserved. + +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 + + jwa MIT Copyright (c) 2013 Brian J. Brennan @@ -2166,68 +2709,17 @@ Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors 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. - - -native-duplexpair -MIT -The MIT License (MIT) - -Copyright (c) 2017 Anna Henningsen - -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. - - - -node-abort-controller -MIT -MIT License - -Copyright (c) 2019 Steve Faulkner - -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. + 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. -node-fetch +native-duplexpair MIT The MIT License (MIT) -Copyright (c) 2016 David Frank +Copyright (c) 2017 Anna Henningsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -2343,6 +2835,64 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +oauth-sign +Apache-2.0 +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + object-assign MIT The MIT License (MIT) @@ -2527,11 +3077,21 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +performance-now +MIT +Copyright (c) 2013 Braveg1rl + +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. + pg MIT MIT License -Copyright (c) 2010 - 2021 Brian Carlson +Copyright (c) 2010 - 2020 Brian Carlson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -2622,7 +3182,7 @@ pg-protocol MIT MIT License -Copyright (c) 2010 - 2021 Brian Carlson +Copyright (c) 2010 - 2020 Brian Carlson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -2785,6 +3345,38 @@ The above copyright notice and this permission notice shall be included in all c 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. +qs +BSD-3-Clause +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * 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/hapijs/qs/graphs/contributors + + readable-stream MIT Node.js is licensed for use as follows: @@ -2894,24 +3486,63 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any END OF TERMS AND CONDITIONS -rfdc -MIT -Copyright 2019 "David Mark Clements " +request +Apache-2.0 +Apache License + +Version 2.0, January 2004 -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: +http://www.apache.org/licenses/ -The above copyright notice and this permission notice shall be included in all copies or substantial portions -of the Software. +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -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. +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS rimraf ISC @@ -3233,6 +3864,28 @@ Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors THE SOFTWARE. +sshpk +MIT +Copyright Joyent, Inc. All rights reserved. +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. + + string-width MIT The MIT License (MIT) @@ -3455,6 +4108,92 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +tunnel-agent +Apache-2.0 +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +tweetnacl +Unlicense +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to + + typeorm MIT @@ -3484,6 +4223,21 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +uri-js +BSD-2-Clause +Copyright 2011 Gary Court. 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 GARY COURT "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 GARY COURT 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. + +The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court. + + util-deprecate MIT (The MIT License) @@ -3537,6 +4291,29 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +verror +MIT +Copyright (c) 2016, Joyent, Inc. All rights reserved. + +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 + + wide-align ISC Copyright (c) 2015, Rebecca Turner diff --git a/dist/index.js b/dist/index.js index eccd78a..076d73c 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,4 +1,5 @@ -require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap +require('./sourcemap-register.js');module.exports = +/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 53597: @@ -226,7 +227,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isSQLConfig = exports.isHTTPConfig = exports.getConfig = void 0; const core = __importStar(__nccwpck_require__(42186)); -const z = __importStar(__nccwpck_require__(63301)); +const z = __importStar(__nccwpck_require__(30489)); const FormatEnum = z.enum(['csv', 'json']); const CommonConfigSchema = z.object({ downloaded_filename: z.string(), @@ -516,27 +517,14 @@ run().catch(error => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; const os = __importStar(__nccwpck_require__(12087)); const utils_1 = __nccwpck_require__(5278); /** @@ -615,25 +603,6 @@ function escapeProperty(s) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -643,8 +612,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __nccwpck_require__(87351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); @@ -711,9 +686,7 @@ function addPath(inputPath) { } exports.addPath = addPath; /** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. + * Gets the value of an input. The value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. @@ -724,34 +697,9 @@ function getInput(name, options) { if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } - if (options && options.trimWhitespace === false) { - return val; - } return val.trim(); } exports.getInput = getInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * @@ -760,7 +708,6 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { - process.stdout.write(os.EOL); command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; @@ -902,27 +849,14 @@ exports.getState = getState; "use strict"; // For internal use, subject to change. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__nccwpck_require__(35747)); @@ -953,7 +887,6 @@ exports.issueCommand = issueCommand; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandValue = void 0; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string @@ -1644,18 +1577,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); const assert_1 = __nccwpck_require__(42357); -const fs = __importStar(__nccwpck_require__(35747)); -const path = __importStar(__nccwpck_require__(85622)); +const fs = __nccwpck_require__(35747); +const path = __nccwpck_require__(85622); _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; exports.IS_WINDOWS = process.platform === 'win32'; function exists(fsPath) { @@ -1853,18 +1779,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const childProcess = __importStar(__nccwpck_require__(63129)); -const path = __importStar(__nccwpck_require__(85622)); +const childProcess = __nccwpck_require__(63129); +const path = __nccwpck_require__(85622); const util_1 = __nccwpck_require__(31669); -const ioUtil = __importStar(__nccwpck_require__(81962)); +const ioUtil = __nccwpck_require__(81962); const exec = util_1.promisify(childProcess.exec); /** * Copies a file or folder. @@ -2032,73 +1951,58 @@ function which(tool, check) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } - return result; } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ''; - }); -} -exports.which = which; -/** - * Returns a list of all occurrences of the given tool on the system path. - * - * @returns Promise the paths of the tool - */ -function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // build the list of extensions to try - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { - for (const extension of process.env['PATHEXT'].split(path.delimiter)) { - if (extension) { - extensions.push(extension); + try { + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env.PATHEXT) { + for (const extension of process.env.PATHEXT.split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } } } - } - // if it's rooted, return it if exists. otherwise return empty. - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return filePath; + } + return ''; } - return []; - } - // if any path separators, return empty - if (tool.includes(path.sep)) { - return []; - } - // build the list of directories - // - // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, - // it feels like we should not do this. Checking the current directory seems like more of a use - // case of a shell, and the which() function exposed by the toolkit should strive for consistency - // across platforms. - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); + // if any path separators, return empty + if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) { + return ''; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } } } - } - // find all matches - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); + // return the first match + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions); + if (filePath) { + return filePath; + } } + return ''; + } + catch (err) { + throw new Error(`which failed with message ${err.message}`); } - return matches; }); } -exports.findInPath = findInPath; +exports.which = which; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); @@ -2256,7 +2160,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.windows.net/", batchResourceId: "https://batch.core.windows.net/", activeDirectoryGraphApiVersion: "2013-04-05", - storageEndpointSuffix: "core.windows.net", + storageEndpointSuffix: ".core.windows.net", keyVaultDnsSuffix: ".vault.azure.net", azureDataLakeStoreFileSystemEndpointSuffix: "azuredatalakestore.net", azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "azuredatalakeanalytics.net", @@ -2276,7 +2180,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.chinacloudapi.cn/", activeDirectoryGraphApiVersion: "2013-04-05", batchResourceId: "https://batch.chinacloudapi.cn/", - storageEndpointSuffix: "core.chinacloudapi.cn", + storageEndpointSuffix: ".core.chinacloudapi.cn", keyVaultDnsSuffix: ".vault.azure.cn", // TODO: add dns suffixes for the china cloud for datalake store and datalake analytics once they are defined. azureDataLakeStoreFileSystemEndpointSuffix: "N/A", @@ -2297,7 +2201,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.windows.net/", batchResourceId: "https://batch.core.usgovcloudapi.net/", activeDirectoryGraphApiVersion: "2013-04-05", - storageEndpointSuffix: "core.usgovcloudapi.net", + storageEndpointSuffix: ".core.usgovcloudapi.net", keyVaultDnsSuffix: ".vault.usgovcloudapi.net", azureDataLakeStoreFileSystemEndpointSuffix: "N/A", azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "N/A", @@ -2317,7 +2221,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.cloudapi.de/", batchResourceId: "https://batch.microsoftazure.de/", activeDirectoryGraphApiVersion: "2013-04-05", - storageEndpointSuffix: "core.cloudapi.de", + storageEndpointSuffix: ".core.cloudapi.de", keyVaultDnsSuffix: ".vault.microsoftazure.de", azureDataLakeStoreFileSystemEndpointSuffix: "N/A", azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "N/A", @@ -2351,16 +2255,16 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var uuidv4 = _interopDefault(__nccwpck_require__(20621)); -var tslib = __nccwpck_require__(4351); +var axios = _interopDefault(__nccwpck_require__(96545)); +var stream = __nccwpck_require__(92413); +var FormData = _interopDefault(__nccwpck_require__(64334)); var tough = __nccwpck_require__(68930); +var tunnel = __nccwpck_require__(74294); var http = __nccwpck_require__(98605); var https = __nccwpck_require__(57211); -var node_fetch = _interopDefault(__nccwpck_require__(80467)); -var FormData = _interopDefault(__nccwpck_require__(69970)); -var stream = __nccwpck_require__(92413); -var tunnel = __nccwpck_require__(74294); var xml2js = __nccwpck_require__(66189); var os = __nccwpck_require__(12087); +var tslib = __nccwpck_require__(75636); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. @@ -2370,24 +2274,6 @@ var os = __nccwpck_require__(12087); function getHeaderKey(headerName) { return headerName.toLowerCase(); } -function isHttpHeadersLike(object) { - if (!object || typeof object !== "object") { - return false; - } - if (typeof object.rawHeaders === "function" && - typeof object.clone === "function" && - typeof object.get === "function" && - typeof object.set === "function" && - typeof object.contains === "function" && - typeof object.remove === "function" && - typeof object.headersArray === "function" && - typeof object.headerValues === "function" && - typeof object.headerNames === "function" && - typeof object.toJson === "function") { - return true; - } - return false; -} /** * A collection of HTTP header key/value pairs. */ @@ -2407,10 +2293,7 @@ var HttpHeaders = /** @class */ (function () { * @param headerValue The value of the header to set. */ HttpHeaders.prototype.set = function (headerName, headerValue) { - this._headersMap[getHeaderKey(headerName)] = { - name: headerName, - value: headerValue.toString(), - }; + this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() }; }; /** * Get the header value for the provided header name, or undefined if no header exists in this @@ -2517,7 +2400,7 @@ function encodeString(value) { function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length - var bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); + var bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer); return bufferValue.toString("base64"); } /** @@ -2536,7 +2419,7 @@ var Constants = { * @const * @type {string} */ - msRestVersion: "2.5.0", + msRestVersion: "1.11.2", /** * Specifies HTTP. * @@ -2565,14 +2448,6 @@ var Constants = { * @type {string} */ HTTPS_PROXY: "HTTPS_PROXY", - /** - * Specifies NO Proxy. - */ - NO_PROXY: "NO_PROXY", - /** - * Specifies ALL Proxy. - */ - ALL_PROXY: "ALL_PROXY", HttpConstants: { /** * Http Verbs @@ -2587,11 +2462,11 @@ var Constants = { POST: "POST", MERGE: "MERGE", HEAD: "HEAD", - PATCH: "PATCH", + PATCH: "PATCH" }, StatusCodes: { - TooManyRequests: 429, - }, + TooManyRequests: 429 + } }, /** * Defines constants for use with HTTP headers. @@ -2620,18 +2495,15 @@ var Constants = { * @const * @type {string} */ - USER_AGENT: "User-Agent", - }, + USER_AGENT: "User-Agent" + } }; // Copyright (c) Microsoft Corporation. All rights reserved. /** * A constant that indicates whether the environment is node.js or browser based. */ -var isNode = typeof process !== "undefined" && - !!process.version && - !!process.versions && - !!process.versions.node; +var isNode = (typeof process !== "undefined") && !!process.version && !!process.versions && !!process.versions.node; /** * Encodes an URI. * @@ -2795,15 +2667,6 @@ function isDuration(value) { function replaceAll(value, searchValue, replaceValue) { return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); } -/** - * Determines whether the given enity is a basic/primitive type - * (string, number, boolean, null, undefined). - * @param value Any entity - * @return boolean - true is it is primitive type, false otherwise. - */ -function isPrimitiveType(value) { - return (typeof value !== "object" && typeof value !== "function") || value === null; -} // Copyright (c) Microsoft Corporation. All rights reserved. var Serializer = /** @class */ (function () { @@ -2816,7 +2679,7 @@ var Serializer = /** @class */ (function () { var failValidation = function (constraintName, constraintValue) { throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); }; - if (mapper.constraints && value != undefined) { + if (mapper.constraints && (value != undefined)) { var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems; if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); @@ -2845,14 +2708,10 @@ var Serializer = /** @class */ (function () { if (MultipleOf != undefined && value % MultipleOf !== 0) { failValidation("MultipleOf", MultipleOf); } - if (Pattern) { - var pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; - if (typeof value !== "string" || value.match(pattern) === null) { - failValidation("Pattern", Pattern); - } + if (Pattern && value.match(Pattern) === null) { + failValidation("Pattern", Pattern); } - if (UniqueItems && - value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + if (UniqueItems && value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { failValidation("UniqueItems", UniqueItems); } } @@ -2874,10 +2733,10 @@ var Serializer = /** @class */ (function () { if (!objectName) { objectName = mapper.serializedName; } - if (mapperType.match(/^Sequence$/gi) !== null) { + if (mapperType.match(/^Sequence$/ig) !== null) { payload = []; } - if (mapper.isConstant) { + if (object == undefined && (mapper.defaultValue != undefined || mapper.isConstant)) { object = mapper.defaultValue; } // This table of allowed values should help explain @@ -2905,32 +2764,32 @@ var Serializer = /** @class */ (function () { else { // Validate Constraints if any this.validateConstraints(mapper, object, objectName); - if (mapperType.match(/^any$/gi) !== null) { + if (mapperType.match(/^any$/ig) !== null) { payload = object; } - else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/gi) !== null) { + else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) { payload = serializeBasicTypes(mapperType, objectName, object); } - else if (mapperType.match(/^Enum$/gi) !== null) { + else if (mapperType.match(/^Enum$/ig) !== null) { var enumMapper = mapper; payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); } - else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/gi) !== null) { + else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) { payload = serializeDateTypes(mapperType, object, objectName); } - else if (mapperType.match(/^ByteArray$/gi) !== null) { + else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = serializeByteArrayType(objectName, object); } - else if (mapperType.match(/^Base64Url$/gi) !== null) { + else if (mapperType.match(/^Base64Url$/ig) !== null) { payload = serializeBase64UrlType(objectName, object); } - else if (mapperType.match(/^Sequence$/gi) !== null) { + else if (mapperType.match(/^Sequence$/ig) !== null) { payload = serializeSequenceType(this, mapper, object, objectName); } - else if (mapperType.match(/^Dictionary$/gi) !== null) { + else if (mapperType.match(/^Dictionary$/ig) !== null) { payload = serializeDictionaryType(this, mapper, object, objectName); } - else if (mapperType.match(/^Composite$/gi) !== null) { + else if (mapperType.match(/^Composite$/ig) !== null) { payload = serializeCompositeType(this, mapper, object, objectName); } } @@ -2955,10 +2814,6 @@ var Serializer = /** @class */ (function () { // so let's do the more user-friendly thing and return an empty list. responseBody = []; } - // specifically check for undefined as default value can be a falsey value `0, "", false, null` - if (mapper.defaultValue !== undefined) { - responseBody = mapper.defaultValue; - } return responseBody; } var payload; @@ -2966,7 +2821,7 @@ var Serializer = /** @class */ (function () { if (!objectName) { objectName = mapper.serializedName; } - if (mapperType.match(/^Composite$/gi) !== null) { + if (mapperType.match(/^Composite$/ig) !== null) { payload = deserializeCompositeType(this, mapper, responseBody, objectName); } else { @@ -2980,13 +2835,13 @@ var Serializer = /** @class */ (function () { responseBody = responseBody["_"]; } } - if (mapperType.match(/^Number$/gi) !== null) { + if (mapperType.match(/^Number$/ig) !== null) { payload = parseFloat(responseBody); if (isNaN(payload)) { payload = responseBody; } } - else if (mapperType.match(/^Boolean$/gi) !== null) { + else if (mapperType.match(/^Boolean$/ig) !== null) { if (responseBody === "true") { payload = true; } @@ -2997,25 +2852,25 @@ var Serializer = /** @class */ (function () { payload = responseBody; } } - else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/gi) !== null) { + else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) { payload = responseBody; } - else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/gi) !== null) { + else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) { payload = new Date(responseBody); } - else if (mapperType.match(/^UnixTime$/gi) !== null) { + else if (mapperType.match(/^UnixTime$/ig) !== null) { payload = unixTimeToDate(responseBody); } - else if (mapperType.match(/^ByteArray$/gi) !== null) { + else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = decodeString(responseBody); } - else if (mapperType.match(/^Base64Url$/gi) !== null) { + else if (mapperType.match(/^Base64Url$/ig) !== null) { payload = base64UrlToByteArray(responseBody); } - else if (mapperType.match(/^Sequence$/gi) !== null) { + else if (mapperType.match(/^Sequence$/ig) !== null) { payload = deserializeSequenceType(this, mapper, responseBody, objectName); } - else if (mapperType.match(/^Dictionary$/gi) !== null) { + else if (mapperType.match(/^Dictionary$/ig) !== null) { payload = deserializeDictionaryType(this, mapper, responseBody, objectName); } } @@ -3028,7 +2883,7 @@ var Serializer = /** @class */ (function () { }()); function trimEnd(str, ch) { var len = str.length; - while (len - 1 >= 0 && str[len - 1] === ch) { + while ((len - 1) >= 0 && str[len - 1] === ch) { --len; } return str.substr(0, len); @@ -3093,27 +2948,27 @@ function unixTimeToDate(n) { } function serializeBasicTypes(typeName, objectName, value) { if (value !== null && value !== undefined) { - if (typeName.match(/^Number$/gi) !== null) { + if (typeName.match(/^Number$/ig) !== null) { if (typeof value !== "number") { throw new Error(objectName + " with value " + value + " must be of type number."); } } - else if (typeName.match(/^String$/gi) !== null) { + else if (typeName.match(/^String$/ig) !== null) { if (typeof value.valueOf() !== "string") { throw new Error(objectName + " with value \"" + value + "\" must be of type string."); } } - else if (typeName.match(/^Uuid$/gi) !== null) { + else if (typeName.match(/^Uuid$/ig) !== null) { if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid."); } } - else if (typeName.match(/^Boolean$/gi) !== null) { + else if (typeName.match(/^Boolean$/ig) !== null) { if (typeof value !== "boolean") { throw new Error(objectName + " with value " + value + " must be of type boolean."); } } - else if (typeName.match(/^Stream$/gi) !== null) { + else if (typeName.match(/^Stream$/ig) !== null) { var objectType = typeof value; if (objectType !== "string" && objectType !== "function" && @@ -3161,31 +3016,28 @@ function serializeBase64UrlType(objectName, value) { } function serializeDateTypes(typeName, value, objectName) { if (value != undefined) { - if (typeName.match(/^Date$/gi) !== null) { + if (typeName.match(/^Date$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); } - value = - value instanceof Date - ? value.toISOString().substring(0, 10) - : new Date(value).toISOString().substring(0, 10); + value = (value instanceof Date) ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); } - else if (typeName.match(/^DateTime$/gi) !== null) { + else if (typeName.match(/^DateTime$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); } - value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + value = (value instanceof Date) ? value.toISOString() : new Date(value).toISOString(); } - else if (typeName.match(/^DateTimeRfc1123$/gi) !== null) { + else if (typeName.match(/^DateTimeRfc1123$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format."); } - value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString(); } - else if (typeName.match(/^UnixTime$/gi) !== null) { + else if (typeName.match(/^UnixTime$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " + @@ -3193,7 +3045,7 @@ function serializeDateTypes(typeName, value, objectName) { } value = dateToUnixTime(value); } - else if (typeName.match(/^TimeSpan$/gi) !== null) { + else if (typeName.match(/^TimeSpan$/ig) !== null) { if (!isDuration(value)) { throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\"."); } @@ -3287,7 +3139,7 @@ function serializeCompositeType(serializer, mapper, object, objectName) { for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) { var pathName = paths_1[_c]; var childObject = parentObject[pathName]; - if (childObject == undefined && object[key] != undefined) { + if ((childObject == undefined) && (object[key] != undefined)) { parentObject[pathName] = {}; } parentObject = parentObject[pathName]; @@ -3299,9 +3151,7 @@ function serializeCompositeType(serializer, mapper, object, objectName) { : objectName; var toSerialize = object[key]; var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator && - polymorphicDiscriminator.clientName === key && - toSerialize == undefined) { + if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) { toSerialize = mapper.serializedName; } var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName); @@ -3402,18 +3252,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName) } propertyInstance = res; var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; - // checking that the model property name (key)(ex: "fishtype") and the - // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") - // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") - // is a better approach. The generator is not consistent with escaping '\.' in the - // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator - // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However, - // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and - // the transformation of model property name (ex: "fishtype") is done consistently. - // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. - if (polymorphicDiscriminator && - key === polymorphicDiscriminator.clientName && - propertyInstance == undefined) { + if (polymorphicDiscriminator && propertyMapper.serializedName === polymorphicDiscriminator.serializedName && propertyInstance == undefined) { propertyInstance = mapper.serializedName; } var serializedValue = void 0; @@ -3422,7 +3261,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName) propertyInstance = responseBody[key]; instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); } - else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { + else if (propertyInstance !== undefined) { serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); instance[key] = serializedValue; } @@ -3448,9 +3287,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName) else if (responseBody) { for (var _e = 0, _f = Object.keys(responseBody); _e < _f.length; _e++) { var key = _f[_e]; - if (instance[key] === undefined && - !handledPropertyNames.includes(key) && - !isSpecialXmlProperty(key)) { + if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) { instance[key] = responseBody[key]; } } @@ -3515,14 +3352,12 @@ function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyNam return mapper; } function getPolymorphicDiscriminatorRecursively(serializer, mapper) { - return (mapper.type.polymorphicDiscriminator || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)); + return mapper.type.polymorphicDiscriminator + || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) + || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className); } function getPolymorphicDiscriminatorSafely(serializer, typeName) { - return (typeName && - serializer.modelMappers[typeName] && - serializer.modelMappers[typeName].type.polymorphicDiscriminator); + return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator); } // TODO: why is this here? function serializeObject(toSerialize) { @@ -3578,25 +3413,10 @@ var MapperType = strEnum([ "String", "Stream", "TimeSpan", - "UnixTime", + "UnixTime" ]); // Copyright (c) Microsoft Corporation. All rights reserved. -function isWebResourceLike(object) { - if (typeof object !== "object") { - return false; - } - if (typeof object.url === "string" && - typeof object.method === "string" && - typeof object.headers === "object" && - isHttpHeadersLike(object.headers) && - typeof object.validateRequestProperties === "function" && - typeof object.prepare === "function" && - typeof object.clone === "function") { - return true; - } - return false; -} /** * Creates a new WebResource object. * @@ -3606,11 +3426,11 @@ function isWebResourceLike(object) { * @constructor */ var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings, redirectLimit) { + function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings) { this.streamResponseBody = streamResponseBody; this.url = url || ""; this.method = method || "GET"; - this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); + this.headers = (headers instanceof HttpHeaders ? headers : new HttpHeaders(headers)); this.body = body; this.query = query; this.formData = undefined; @@ -3622,7 +3442,6 @@ var WebResource = /** @class */ (function () { this.proxySettings = proxySettings; this.keepAlive = keepAlive; this.agentSettings = agentSettings; - this.redirectLimit = redirectLimit; } /** * Validates that the required properties such as method, url, headers["Content-Type"], @@ -3652,14 +3471,13 @@ var WebResource = /** @class */ (function () { if (options.url && options.pathTemplate) { throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them."); } - if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") && - (options.url == undefined || typeof options.url.valueOf() !== "string")) { + if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") && (options.url == undefined || typeof options.url.valueOf() !== "string")) { throw new Error("Please provide exactly one of options.pathTemplate or options.url."); } // set the url if it is provided. if (options.url) { if (typeof options.url !== "string") { - throw new Error('options.url must be of type "string".'); + throw new Error("options.url must be of type \"string\"."); } this.url = options.url; } @@ -3667,10 +3485,7 @@ var WebResource = /** @class */ (function () { if (options.method) { var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; if (validMethods.indexOf(options.method.toUpperCase()) === -1) { - throw new Error('The provided method "' + - options.method + - '" is invalid. Supported HTTP methods are: ' + - JSON.stringify(validMethods)); + throw new Error("The provided method \"" + options.method + "\" is invalid. Supported HTTP methods are: " + JSON.stringify(validMethods)); } } this.method = options.method.toUpperCase(); @@ -3678,16 +3493,14 @@ var WebResource = /** @class */ (function () { if (options.pathTemplate) { var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters; if (typeof pathTemplate_1 !== "string") { - throw new Error('options.pathTemplate must be of type "string".'); + throw new Error("options.pathTemplate must be of type \"string\"."); } if (!options.baseUrl) { options.baseUrl = "https://management.azure.com"; } var baseUrl = options.baseUrl; - var url_1 = baseUrl + - (baseUrl.endsWith("/") ? "" : "/") + - (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1); - var segments = url_1.match(/({\w*\s*\w*})/gi); + var url_1 = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1); + var segments = url_1.match(/({\w*\s*\w*})/ig); if (segments && segments.length) { if (!pathParameters_1) { throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided."); @@ -3695,9 +3508,7 @@ var WebResource = /** @class */ (function () { segments.forEach(function (item) { var pathParamName = item.slice(1, -1); var pathParam = pathParameters_1[pathParamName]; - if (pathParam === null || - pathParam === undefined || - !(typeof pathParam === "string" || typeof pathParam === "object")) { + if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) { throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName + (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") + ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") + @@ -3806,8 +3617,6 @@ var WebResource = /** @class */ (function () { this.abortSignal = options.abortSignal; this.onDownloadProgress = options.onDownloadProgress; this.onUploadProgress = options.onUploadProgress; - this.redirectLimit = options.redirectLimit; - this.streamResponseBody = options.streamResponseBody; return this; }; /** @@ -3815,7 +3624,7 @@ var WebResource = /** @class */ (function () { * @returns {WebResource} The clone of this WebResource HTTP request object. */ WebResource.prototype.clone = function () { - var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings, this.redirectLimit); + var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings); if (this.formData) { result.formData = this.formData; } @@ -3833,979 +3642,6 @@ var WebResource = /** @class */ (function () { return WebResource; }()); -/** - * @author Toru Nagashima - * @copyright 2015 Toru Nagashima. All rights reserved. - * See LICENSE file in root directory for full license. - */ -/** - * @typedef {object} PrivateData - * @property {EventTarget} eventTarget The event target. - * @property {{type:string}} event The original event object. - * @property {number} eventPhase The current event phase. - * @property {EventTarget|null} currentTarget The current event target. - * @property {boolean} canceled The flag to prevent default. - * @property {boolean} stopped The flag to stop propagation. - * @property {boolean} immediateStopped The flag to stop propagation immediately. - * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. - * @property {number} timeStamp The unix time. - * @private - */ - -/** - * Private data for event wrappers. - * @type {WeakMap} - * @private - */ -const privateData = new WeakMap(); - -/** - * Cache for wrapper classes. - * @type {WeakMap} - * @private - */ -const wrappers = new WeakMap(); - -/** - * Get private data. - * @param {Event} event The event object to get private data. - * @returns {PrivateData} The private data of the event. - * @private - */ -function pd(event) { - const retv = privateData.get(event); - console.assert( - retv != null, - "'this' is expected an Event object, but got", - event - ); - return retv -} - -/** - * https://dom.spec.whatwg.org/#set-the-canceled-flag - * @param data {PrivateData} private data. - */ -function setCancelFlag(data) { - if (data.passiveListener != null) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error( - "Unable to preventDefault inside passive event listener invocation.", - data.passiveListener - ); - } - return - } - if (!data.event.cancelable) { - return - } - - data.canceled = true; - if (typeof data.event.preventDefault === "function") { - data.event.preventDefault(); - } -} - -/** - * @see https://dom.spec.whatwg.org/#interface-event - * @private - */ -/** - * The event wrapper. - * @constructor - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Event|{type:string}} event The original event to wrap. - */ -function Event(eventTarget, event) { - privateData.set(this, { - eventTarget, - event, - eventPhase: 2, - currentTarget: eventTarget, - canceled: false, - stopped: false, - immediateStopped: false, - passiveListener: null, - timeStamp: event.timeStamp || Date.now(), - }); - - // https://heycam.github.io/webidl/#Unforgeable - Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); - - // Define accessors - const keys = Object.keys(event); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in this)) { - Object.defineProperty(this, key, defineRedirectDescriptor(key)); - } - } -} - -// Should be enumerable, but class methods are not enumerable. -Event.prototype = { - /** - * The type of this event. - * @type {string} - */ - get type() { - return pd(this).event.type - }, - - /** - * The target of this event. - * @type {EventTarget} - */ - get target() { - return pd(this).eventTarget - }, - - /** - * The target of this event. - * @type {EventTarget} - */ - get currentTarget() { - return pd(this).currentTarget - }, - - /** - * @returns {EventTarget[]} The composed path of this event. - */ - composedPath() { - const currentTarget = pd(this).currentTarget; - if (currentTarget == null) { - return [] - } - return [currentTarget] - }, - - /** - * Constant of NONE. - * @type {number} - */ - get NONE() { - return 0 - }, - - /** - * Constant of CAPTURING_PHASE. - * @type {number} - */ - get CAPTURING_PHASE() { - return 1 - }, - - /** - * Constant of AT_TARGET. - * @type {number} - */ - get AT_TARGET() { - return 2 - }, - - /** - * Constant of BUBBLING_PHASE. - * @type {number} - */ - get BUBBLING_PHASE() { - return 3 - }, - - /** - * The target of this event. - * @type {number} - */ - get eventPhase() { - return pd(this).eventPhase - }, - - /** - * Stop event bubbling. - * @returns {void} - */ - stopPropagation() { - const data = pd(this); - - data.stopped = true; - if (typeof data.event.stopPropagation === "function") { - data.event.stopPropagation(); - } - }, - - /** - * Stop event bubbling. - * @returns {void} - */ - stopImmediatePropagation() { - const data = pd(this); - - data.stopped = true; - data.immediateStopped = true; - if (typeof data.event.stopImmediatePropagation === "function") { - data.event.stopImmediatePropagation(); - } - }, - - /** - * The flag to be bubbling. - * @type {boolean} - */ - get bubbles() { - return Boolean(pd(this).event.bubbles) - }, - - /** - * The flag to be cancelable. - * @type {boolean} - */ - get cancelable() { - return Boolean(pd(this).event.cancelable) - }, - - /** - * Cancel this event. - * @returns {void} - */ - preventDefault() { - setCancelFlag(pd(this)); - }, - - /** - * The flag to indicate cancellation state. - * @type {boolean} - */ - get defaultPrevented() { - return pd(this).canceled - }, - - /** - * The flag to be composed. - * @type {boolean} - */ - get composed() { - return Boolean(pd(this).event.composed) - }, - - /** - * The unix time of this event. - * @type {number} - */ - get timeStamp() { - return pd(this).timeStamp - }, - - /** - * The target of this event. - * @type {EventTarget} - * @deprecated - */ - get srcElement() { - return pd(this).eventTarget - }, - - /** - * The flag to stop event bubbling. - * @type {boolean} - * @deprecated - */ - get cancelBubble() { - return pd(this).stopped - }, - set cancelBubble(value) { - if (!value) { - return - } - const data = pd(this); - - data.stopped = true; - if (typeof data.event.cancelBubble === "boolean") { - data.event.cancelBubble = true; - } - }, - - /** - * The flag to indicate cancellation state. - * @type {boolean} - * @deprecated - */ - get returnValue() { - return !pd(this).canceled - }, - set returnValue(value) { - if (!value) { - setCancelFlag(pd(this)); - } - }, - - /** - * Initialize this event object. But do nothing under event dispatching. - * @param {string} type The event type. - * @param {boolean} [bubbles=false] The flag to be possible to bubble up. - * @param {boolean} [cancelable=false] The flag to be possible to cancel. - * @deprecated - */ - initEvent() { - // Do nothing. - }, -}; - -// `constructor` is not enumerable. -Object.defineProperty(Event.prototype, "constructor", { - value: Event, - configurable: true, - writable: true, -}); - -// Ensure `event instanceof window.Event` is `true`. -if (typeof window !== "undefined" && typeof window.Event !== "undefined") { - Object.setPrototypeOf(Event.prototype, window.Event.prototype); - - // Make association for wrappers. - wrappers.set(window.Event.prototype, Event); -} - -/** - * Get the property descriptor to redirect a given property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to redirect the property. - * @private - */ -function defineRedirectDescriptor(key) { - return { - get() { - return pd(this).event[key] - }, - set(value) { - pd(this).event[key] = value; - }, - configurable: true, - enumerable: true, - } -} - -/** - * Get the property descriptor to call a given method property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to call the method property. - * @private - */ -function defineCallDescriptor(key) { - return { - value() { - const event = pd(this).event; - return event[key].apply(event, arguments) - }, - configurable: true, - enumerable: true, - } -} - -/** - * Define new wrapper class. - * @param {Function} BaseEvent The base wrapper class. - * @param {Object} proto The prototype of the original event. - * @returns {Function} The defined wrapper class. - * @private - */ -function defineWrapper(BaseEvent, proto) { - const keys = Object.keys(proto); - if (keys.length === 0) { - return BaseEvent - } - - /** CustomEvent */ - function CustomEvent(eventTarget, event) { - BaseEvent.call(this, eventTarget, event); - } - - CustomEvent.prototype = Object.create(BaseEvent.prototype, { - constructor: { value: CustomEvent, configurable: true, writable: true }, - }); - - // Define accessors. - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in BaseEvent.prototype)) { - const descriptor = Object.getOwnPropertyDescriptor(proto, key); - const isFunc = typeof descriptor.value === "function"; - Object.defineProperty( - CustomEvent.prototype, - key, - isFunc - ? defineCallDescriptor(key) - : defineRedirectDescriptor(key) - ); - } - } - - return CustomEvent -} - -/** - * Get the wrapper class of a given prototype. - * @param {Object} proto The prototype of the original event to get its wrapper. - * @returns {Function} The wrapper class. - * @private - */ -function getWrapper(proto) { - if (proto == null || proto === Object.prototype) { - return Event - } - - let wrapper = wrappers.get(proto); - if (wrapper == null) { - wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); - wrappers.set(proto, wrapper); - } - return wrapper -} - -/** - * Wrap a given event to management a dispatching. - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Object} event The event to wrap. - * @returns {Event} The wrapper instance. - * @private - */ -function wrapEvent(eventTarget, event) { - const Wrapper = getWrapper(Object.getPrototypeOf(event)); - return new Wrapper(eventTarget, event) -} - -/** - * Get the immediateStopped flag of a given event. - * @param {Event} event The event to get. - * @returns {boolean} The flag to stop propagation immediately. - * @private - */ -function isStopped(event) { - return pd(event).immediateStopped -} - -/** - * Set the current event phase of a given event. - * @param {Event} event The event to set current target. - * @param {number} eventPhase New event phase. - * @returns {void} - * @private - */ -function setEventPhase(event, eventPhase) { - pd(event).eventPhase = eventPhase; -} - -/** - * Set the current target of a given event. - * @param {Event} event The event to set current target. - * @param {EventTarget|null} currentTarget New current target. - * @returns {void} - * @private - */ -function setCurrentTarget(event, currentTarget) { - pd(event).currentTarget = currentTarget; -} - -/** - * Set a passive listener of a given event. - * @param {Event} event The event to set current target. - * @param {Function|null} passiveListener New passive listener. - * @returns {void} - * @private - */ -function setPassiveListener(event, passiveListener) { - pd(event).passiveListener = passiveListener; -} - -/** - * @typedef {object} ListenerNode - * @property {Function} listener - * @property {1|2|3} listenerType - * @property {boolean} passive - * @property {boolean} once - * @property {ListenerNode|null} next - * @private - */ - -/** - * @type {WeakMap>} - * @private - */ -const listenersMap = new WeakMap(); - -// Listener types -const CAPTURE = 1; -const BUBBLE = 2; -const ATTRIBUTE = 3; - -/** - * Check whether a given value is an object or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an object. - */ -function isObject(x) { - return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax -} - -/** - * Get listeners. - * @param {EventTarget} eventTarget The event target to get. - * @returns {Map} The listeners. - * @private - */ -function getListeners(eventTarget) { - const listeners = listenersMap.get(eventTarget); - if (listeners == null) { - throw new TypeError( - "'this' is expected an EventTarget object, but got another value." - ) - } - return listeners -} - -/** - * Get the property descriptor for the event attribute of a given event. - * @param {string} eventName The event name to get property descriptor. - * @returns {PropertyDescriptor} The property descriptor. - * @private - */ -function defineEventAttributeDescriptor(eventName) { - return { - get() { - const listeners = getListeners(this); - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - return node.listener - } - node = node.next; - } - return null - }, - - set(listener) { - if (typeof listener !== "function" && !isObject(listener)) { - listener = null; // eslint-disable-line no-param-reassign - } - const listeners = getListeners(this); - - // Traverse to the tail while removing old value. - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - // Remove old value. - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - node = node.next; - } - - // Add new value. - if (listener !== null) { - const newNode = { - listener, - listenerType: ATTRIBUTE, - passive: false, - once: false, - next: null, - }; - if (prev === null) { - listeners.set(eventName, newNode); - } else { - prev.next = newNode; - } - } - }, - configurable: true, - enumerable: true, - } -} - -/** - * Define an event attribute (e.g. `eventTarget.onclick`). - * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. - * @param {string} eventName The event name to define. - * @returns {void} - */ -function defineEventAttribute(eventTargetPrototype, eventName) { - Object.defineProperty( - eventTargetPrototype, - `on${eventName}`, - defineEventAttributeDescriptor(eventName) - ); -} - -/** - * Define a custom EventTarget with event attributes. - * @param {string[]} eventNames Event names for event attributes. - * @returns {EventTarget} The custom EventTarget. - * @private - */ -function defineCustomEventTarget(eventNames) { - /** CustomEventTarget */ - function CustomEventTarget() { - EventTarget.call(this); - } - - CustomEventTarget.prototype = Object.create(EventTarget.prototype, { - constructor: { - value: CustomEventTarget, - configurable: true, - writable: true, - }, - }); - - for (let i = 0; i < eventNames.length; ++i) { - defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); - } - - return CustomEventTarget -} - -/** - * EventTarget. - * - * - This is constructor if no arguments. - * - This is a function which returns a CustomEventTarget constructor if there are arguments. - * - * For example: - * - * class A extends EventTarget {} - * class B extends EventTarget("message") {} - * class C extends EventTarget("message", "error") {} - * class D extends EventTarget(["message", "error"]) {} - */ -function EventTarget() { - /*eslint-disable consistent-return */ - if (this instanceof EventTarget) { - listenersMap.set(this, new Map()); - return - } - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return defineCustomEventTarget(arguments[0]) - } - if (arguments.length > 0) { - const types = new Array(arguments.length); - for (let i = 0; i < arguments.length; ++i) { - types[i] = arguments[i]; - } - return defineCustomEventTarget(types) - } - throw new TypeError("Cannot call a class as a function") - /*eslint-enable consistent-return */ -} - -// Should be enumerable, but class methods are not enumerable. -EventTarget.prototype = { - /** - * Add a given listener to this event target. - * @param {string} eventName The event name to add. - * @param {Function} listener The listener to add. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - addEventListener(eventName, listener, options) { - if (listener == null) { - return - } - if (typeof listener !== "function" && !isObject(listener)) { - throw new TypeError("'listener' should be a function or an object.") - } - - const listeners = getListeners(this); - const optionsIsObj = isObject(options); - const capture = optionsIsObj - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - const newNode = { - listener, - listenerType, - passive: optionsIsObj && Boolean(options.passive), - once: optionsIsObj && Boolean(options.once), - next: null, - }; - - // Set it as the first node if the first node is null. - let node = listeners.get(eventName); - if (node === undefined) { - listeners.set(eventName, newNode); - return - } - - // Traverse to the tail while checking duplication.. - let prev = null; - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - // Should ignore duplication. - return - } - prev = node; - node = node.next; - } - - // Add it. - prev.next = newNode; - }, - - /** - * Remove a given listener from this event target. - * @param {string} eventName The event name to remove. - * @param {Function} listener The listener to remove. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - removeEventListener(eventName, listener, options) { - if (listener == null) { - return - } - - const listeners = getListeners(this); - const capture = isObject(options) - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - return - } - - prev = node; - node = node.next; - } - }, - - /** - * Dispatch a given event. - * @param {Event|{type:string}} event The event to dispatch. - * @returns {boolean} `false` if canceled. - */ - dispatchEvent(event) { - if (event == null || typeof event.type !== "string") { - throw new TypeError('"event.type" should be a string.') - } - - // If listeners aren't registered, terminate. - const listeners = getListeners(this); - const eventName = event.type; - let node = listeners.get(eventName); - if (node == null) { - return true - } - - // Since we cannot rewrite several properties, so wrap object. - const wrappedEvent = wrapEvent(this, event); - - // This doesn't process capturing phase and bubbling phase. - // This isn't participating in a tree. - let prev = null; - while (node != null) { - // Remove this listener if it's once - if (node.once) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - // Call this listener - setPassiveListener( - wrappedEvent, - node.passive ? node.listener : null - ); - if (typeof node.listener === "function") { - try { - node.listener.call(this, wrappedEvent); - } catch (err) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error(err); - } - } - } else if ( - node.listenerType !== ATTRIBUTE && - typeof node.listener.handleEvent === "function" - ) { - node.listener.handleEvent(wrappedEvent); - } - - // Break if `event.stopImmediatePropagation` was called. - if (isStopped(wrappedEvent)) { - break - } - - node = node.next; - } - setPassiveListener(wrappedEvent, null); - setEventPhase(wrappedEvent, 0); - setCurrentTarget(wrappedEvent, null); - - return !wrappedEvent.defaultPrevented - }, -}; - -// `constructor` is not enumerable. -Object.defineProperty(EventTarget.prototype, "constructor", { - value: EventTarget, - configurable: true, - writable: true, -}); - -// Ensure `eventTarget instanceof window.EventTarget` is `true`. -if ( - typeof window !== "undefined" && - typeof window.EventTarget !== "undefined" -) { - Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); -} - -/** - * @author Toru Nagashima - * See LICENSE file in root directory for full license. - */ - -/** - * The signal class. - * @see https://dom.spec.whatwg.org/#abortsignal - */ -class AbortSignal extends EventTarget { - /** - * AbortSignal cannot be constructed directly. - */ - constructor() { - super(); - throw new TypeError("AbortSignal cannot be constructed directly"); - } - /** - * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. - */ - get aborted() { - const aborted = abortedFlags.get(this); - if (typeof aborted !== "boolean") { - throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); - } - return aborted; - } -} -defineEventAttribute(AbortSignal.prototype, "abort"); -/** - * Create an AbortSignal object. - */ -function createAbortSignal() { - const signal = Object.create(AbortSignal.prototype); - EventTarget.call(signal); - abortedFlags.set(signal, false); - return signal; -} -/** - * Abort a given signal. - */ -function abortSignal(signal) { - if (abortedFlags.get(signal) !== false) { - return; - } - abortedFlags.set(signal, true); - signal.dispatchEvent({ type: "abort" }); -} -/** - * Aborted flag for each instances. - */ -const abortedFlags = new WeakMap(); -// Properties should be enumerable. -Object.defineProperties(AbortSignal.prototype, { - aborted: { enumerable: true }, -}); -// `toString()` should return `"[object AbortSignal]"` -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortSignal", - }); -} - -/** - * The AbortController. - * @see https://dom.spec.whatwg.org/#abortcontroller - */ -class AbortController { - /** - * Initialize this controller. - */ - constructor() { - signals.set(this, createAbortSignal()); - } - /** - * Returns the `AbortSignal` object associated with this object. - */ - get signal() { - return getSignal(this); - } - /** - * Abort and signal to any observers that the associated activity is to be aborted. - */ - abort() { - abortSignal(getSignal(this)); - } -} -/** - * Associated signals. - */ -const signals = new WeakMap(); -/** - * Get the associated signal of a given controller. - */ -function getSignal(controller) { - const signal = signals.get(controller); - if (signal == null) { - throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); - } - return signal; -} -// Properties should be enumerable. -Object.defineProperties(AbortController.prototype, { - signal: { enumerable: true }, - abort: { enumerable: true }, -}); -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortController", - }); -} - // Copyright (c) Microsoft Corporation. All rights reserved. var RestError = /** @class */ (function (_super) { tslib.__extends(RestError, _super); @@ -4825,212 +3661,6 @@ var RestError = /** @class */ (function (_super) { return RestError; }(Error)); -// Copyright (c) Microsoft Corporation. All rights reserved. -var FetchHttpClient = /** @class */ (function () { - function FetchHttpClient() { - } - FetchHttpClient.prototype.sendRequest = function (httpRequest) { - return tslib.__awaiter(this, void 0, void 0, function () { - var abortController, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, loadedBytes_1, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, _b, _c, onDownloadProgress_1, responseBody, loadedBytes_2, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - if (!httpRequest && typeof httpRequest !== "object") { - throw new Error("'httpRequest' (WebResource) cannot be null or undefined and must be of type object."); - } - abortController = new AbortController(); - if (httpRequest.abortSignal) { - if (httpRequest.abortSignal.aborted) { - throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); - } - abortListener = function (event) { - if (event.type === "abort") { - abortController.abort(); - } - }; - httpRequest.abortSignal.addEventListener("abort", abortListener); - } - if (httpRequest.timeout) { - setTimeout(function () { - abortController.abort(); - }, httpRequest.timeout); - } - if (httpRequest.formData) { - formData = httpRequest.formData; - requestForm_1 = new FormData(); - appendFormValue = function (key, value) { - // value function probably returns a stream so we can provide a fresh stream on each retry - if (typeof value === "function") { - value = value(); - } - if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) { - requestForm_1.append(key, value.value, value.options); - } - else { - requestForm_1.append(key, value); - } - }; - for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { - formKey = _a[_i]; - formValue = formData[formKey]; - if (Array.isArray(formValue)) { - for (j = 0; j < formValue.length; j++) { - appendFormValue(formKey, formValue[j]); - } - } - else { - appendFormValue(formKey, formValue); - } - } - httpRequest.body = requestForm_1; - httpRequest.formData = undefined; - contentType = httpRequest.headers.get("Content-Type"); - if (contentType && contentType.indexOf("multipart/form-data") !== -1) { - if (typeof requestForm_1.getBoundary === "function") { - httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary()); - } - else { - // browser will automatically apply a suitable content-type header - httpRequest.headers.remove("Content-Type"); - } - } - } - body = httpRequest.body - ? typeof httpRequest.body === "function" - ? httpRequest.body() - : httpRequest.body - : undefined; - if (httpRequest.onUploadProgress && httpRequest.body) { - loadedBytes_1 = 0; - uploadReportStream = new stream.Transform({ - transform: function (chunk, _encoding, callback) { - loadedBytes_1 += chunk.length; - httpRequest.onUploadProgress({ loadedBytes: loadedBytes_1 }); - callback(undefined, chunk); - }, - }); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } - else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - return [4 /*yield*/, this.prepareRequest(httpRequest)]; - case 1: - platformSpecificRequestInit = _d.sent(); - requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController.signal, redirect: "manual" }, platformSpecificRequestInit); - _d.label = 2; - case 2: - _d.trys.push([2, 8, 9, 10]); - return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; - case 3: - response = _d.sent(); - headers = parseHeaders(response.headers); - _b = { - headers: headers, - request: httpRequest, - status: response.status, - readableStreamBody: httpRequest.streamResponseBody - ? response.body - : undefined - }; - if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5]; - return [4 /*yield*/, response.text()]; - case 4: - _c = _d.sent(); - return [3 /*break*/, 6]; - case 5: - _c = undefined; - _d.label = 6; - case 6: - operationResponse = (_b.bodyAsText = _c, - _b.redirected = response.redirected, - _b.url = response.url, - _b); - onDownloadProgress_1 = httpRequest.onDownloadProgress; - if (onDownloadProgress_1) { - responseBody = response.body || undefined; - if (isReadableStream(responseBody)) { - loadedBytes_2 = 0; - downloadReportStream = new stream.Transform({ - transform: function (chunk, _encoding, callback) { - loadedBytes_2 += chunk.length; - onDownloadProgress_1({ loadedBytes: loadedBytes_2 }); - callback(undefined, chunk); - }, - }); - responseBody.pipe(downloadReportStream); - operationResponse.readableStreamBody = downloadReportStream; - } - else { - length_1 = parseInt(headers.get("Content-Length")) || undefined; - if (length_1) { - // Calling callback for non-stream response for consistency with browser - onDownloadProgress_1({ loadedBytes: length_1 }); - } - } - } - return [4 /*yield*/, this.processRequest(operationResponse)]; - case 7: - _d.sent(); - return [2 /*return*/, operationResponse]; - case 8: - error_1 = _d.sent(); - fetchError = error_1; - if (fetchError.code === "ENOTFOUND") { - throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); - } - else if (fetchError.type === "aborted") { - throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); - } - throw fetchError; - case 9: - // clean up event listener - if (httpRequest.abortSignal && abortListener) { - uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); - } - downloadStreamDone = Promise.resolve(); - if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { - downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody); - } - Promise.all([uploadStreamDone, downloadStreamDone]) - .then(function () { - var _a; - (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); - return; - }) - .catch(function (_e) { }); - } - return [7 /*endfinally*/]; - case 10: return [2 /*return*/]; - } - }); - }); - }; - return FetchHttpClient; -}()); -function isReadableStream(body) { - return body && typeof body.pipe === "function"; -} -function isStreamComplete(stream) { - return new Promise(function (resolve) { - stream.on("close", resolve); - stream.on("end", resolve); - stream.on("error", resolve); - }); -} -function parseHeaders(headers) { - var httpHeaders = new HttpHeaders(); - headers.forEach(function (value, key) { - httpHeaders.set(key, value); - }); - return httpHeaders; -} - // Copyright (c) Microsoft Corporation. All rights reserved. /** * A class that handles the query portion of a URLBuilder. @@ -5123,6 +3753,11 @@ var URLQuery = /** @class */ (function () { break; case "ParameterValue": switch (currentCharacter) { + case "=": + parameterName = ""; + parameterValue = ""; + currentState = "Invalid"; + break; case "&": result.set(parameterName, parameterValue); parameterName = ""; @@ -5134,6 +3769,11 @@ var URLQuery = /** @class */ (function () { break; } break; + case "Invalid": + if (currentCharacter === "&") { + currentState = "ParameterName"; + } + break; default: throw new Error("Unrecognized URLQuery parse state: " + currentState); } @@ -5215,12 +3855,8 @@ var URLBuilder = /** @class */ (function () { this._path = undefined; } else { - var schemeIndex = path.indexOf("://"); - if (schemeIndex !== -1) { - var schemeStart = path.lastIndexOf("/", schemeIndex); - // Make sure to only grab the URL part of the path before setting the state back to SCHEME - // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" - this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); + if (path.indexOf("://") !== -1) { + this.set(path, "SCHEME"); } else { this.set(path, "PATH"); @@ -5392,9 +4028,9 @@ var URLToken = /** @class */ (function () { */ function isAlphaNumericCharacter(character) { var characterCode = character.charCodeAt(0); - return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || - (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || - (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */); + return (48 /* '0' */ <= characterCode && characterCode <= 57 /* '9' */) || + (65 /* 'A' */ <= characterCode && characterCode <= 90 /* 'Z' */) || + (97 /* 'a' */ <= characterCode && characterCode <= 122 /* 'z' */); } /** * A class that tokenizes URL strings. @@ -5621,65 +4257,76 @@ function nextQuery(tokenizer) { } // Copyright (c) Microsoft Corporation. All rights reserved. -function createProxyAgent(requestUrl, proxySettings, headers) { - var tunnelOptions = { - proxy: { - host: URLBuilder.parse(proxySettings.host).getHost(), - port: proxySettings.port, - headers: (headers && headers.rawHeaders()) || {}, - }, - }; - if (proxySettings.username && proxySettings.password) { - tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password; - } - var requestScheme = URLBuilder.parse(requestUrl).getScheme() || ""; - var isRequestHttps = requestScheme.toLowerCase() === "https"; - var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || ""; - var isProxyHttps = proxyScheme.toLowerCase() === "https"; - var proxyAgent = { - isHttps: isRequestHttps, - agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions), - }; - return proxyAgent; -} -function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { - if (isRequestHttps && isProxyHttps) { - return tunnel.httpsOverHttps(tunnelOptions); - } - else if (isRequestHttps && !isProxyHttps) { - return tunnel.httpsOverHttp(tunnelOptions); - } - else if (!isRequestHttps && isProxyHttps) { - return tunnel.httpOverHttps(tunnelOptions); - } - else { - return tunnel.httpOverHttp(tunnelOptions); - } -} - -// Copyright (c) Microsoft Corporation. All rights reserved. -var NodeFetchHttpClient = /** @class */ (function (_super) { - tslib.__extends(NodeFetchHttpClient, _super); - function NodeFetchHttpClient() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); - return _this; +var axiosInstance = axios.create(); +// This hack is still required with 0.19.0 version of axios since axios tries to merge the +// Content-Type header from it's config[""] where the method name is lower-case, +// into the request header. It could be possible that the Content-Type header is not present +// in the original request and this would create problems while creating the signature for +// storage data plane sdks. +axiosInstance.interceptors.request.use(function (config) { return (tslib.__assign(tslib.__assign({}, config), { method: config.method && config.method.toUpperCase() })); }); +// keepalive agents are reused across instances to provide maximum socket reuse for +// outbound requests +var keepaliveAgents = { + http: new http.Agent({ keepAlive: true }), + https: new https.Agent({ keepAlive: true }), +}; +/** + * A HttpClient implementation that uses axios to send HTTP requests. + */ +var AxiosHttpClient = /** @class */ (function () { + function AxiosHttpClient() { + this.cookieJar = new tough.CookieJar(); } - NodeFetchHttpClient.prototype.fetch = function (input, init) { + AxiosHttpClient.prototype.sendRequest = function (httpRequest) { return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, node_fetch(input, init)]; - }); - }); - }; - NodeFetchHttpClient.prototype.prepareRequest = function (httpRequest) { - return tslib.__awaiter(this, void 0, void 0, function () { - var requestInit, cookieString, _a, httpAgent, httpsAgent, tunnel, options, agent; + var formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, cookieString, abortSignal, abortListener, cancelToken, rawHeaders, httpRequestBody, axiosBody, onUploadProgress, loadedBytes_1, uploadReportStream, res, config, _b, httpAgent, httpsAgent, agent, err_1, axiosErr, headers, onDownloadProgress, responseBody, loadedBytes_2, downloadReportStream, length_1, operationResponse, setCookieHeader_1; var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - requestInit = {}; + if (typeof httpRequest !== "object") { + throw new Error("httpRequest (WebResource) cannot be null or undefined and must be of type object."); + } + if (httpRequest.formData) { + formData = httpRequest.formData; + requestForm_1 = new FormData(); + appendFormValue = function (key, value) { + // value function probably returns a stream so we can provide a fresh stream on each retry + if (typeof value === "function") { + value = value(); + } + if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) { + requestForm_1.append(key, value.value, value.options); + } + else { + requestForm_1.append(key, value); + } + }; + for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { + formKey = _a[_i]; + formValue = formData[formKey]; + if (Array.isArray(formValue)) { + for (j = 0; j < formValue.length; j++) { + appendFormValue(formKey, formValue[j]); + } + } + else { + appendFormValue(formKey, formValue); + } + } + httpRequest.body = requestForm_1; + httpRequest.formData = undefined; + contentType = httpRequest.headers.get("Content-Type"); + if (contentType && contentType.indexOf("multipart/form-data") !== -1) { + if (typeof requestForm_1.getBoundary === "function") { + httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary()); + } + else { + // browser will automatically apply a suitable content-type header + httpRequest.headers.remove("Content-Type"); + } + } + } if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2]; return [4 /*yield*/, new Promise(function (resolve, reject) { _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) { @@ -5692,52 +4339,149 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { }); })]; case 1: - cookieString = _b.sent(); + cookieString = _c.sent(); httpRequest.headers.set("Cookie", cookieString); - _b.label = 2; + _c.label = 2; case 2: + abortSignal = httpRequest.abortSignal; + if (abortSignal && abortSignal.aborted) { + throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); + } + cancelToken = abortSignal && new axios.CancelToken(function (canceler) { + abortListener = function () { return canceler(); }; + abortSignal.addEventListener("abort", abortListener); + }); + rawHeaders = httpRequest.headers.rawHeaders(); + httpRequestBody = httpRequest.body; + axiosBody = + // Workaround for https://github.com/axios/axios/issues/755 + // tslint:disable-next-line:no-null-keyword + typeof httpRequestBody === "undefined" ? null : + typeof httpRequestBody === "function" ? httpRequestBody() : + httpRequestBody; + onUploadProgress = httpRequest.onUploadProgress; + if (onUploadProgress && axiosBody) { + loadedBytes_1 = 0; + uploadReportStream = new stream.Transform({ + transform: function (chunk, _encoding, callback) { + loadedBytes_1 += chunk.length; + onUploadProgress({ loadedBytes: loadedBytes_1 }); + callback(undefined, chunk); + } + }); + if (isReadableStream(axiosBody)) { + axiosBody.pipe(uploadReportStream); + } + else { + uploadReportStream.end(axiosBody); + } + axiosBody = uploadReportStream; + } + _c.label = 3; + case 3: + _c.trys.push([3, 5, 6, 7]); + config = { + method: httpRequest.method, + url: httpRequest.url, + headers: rawHeaders, + data: axiosBody, + transformResponse: function (data) { return data; }, + validateStatus: function () { return true; }, + // Workaround for https://github.com/axios/axios/issues/1362 + maxContentLength: Infinity, + responseType: httpRequest.streamResponseBody ? "stream" : "text", + cancelToken: cancelToken, + timeout: httpRequest.timeout, + proxy: false + }; if (httpRequest.agentSettings) { - _a = httpRequest.agentSettings, httpAgent = _a.http, httpsAgent = _a.https; - if (httpsAgent && httpRequest.url.startsWith("https")) { - requestInit.agent = httpsAgent; + _b = httpRequest.agentSettings, httpAgent = _b.http, httpsAgent = _b.https; + if (httpsAgent) { + config.httpsAgent = httpsAgent; } - else if (httpAgent) { - requestInit.agent = httpAgent; + if (httpAgent) { + config.httpAgent = httpAgent; } } else if (httpRequest.proxySettings) { - tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); - requestInit.agent = tunnel.agent; + agent = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); + if (agent.isHttps) { + config.httpsAgent = agent.agent; + } + else { + config.httpAgent = agent.agent; + } } if (httpRequest.keepAlive === true) { - if (requestInit.agent) { - requestInit.agent.keepAlive = true; + if (config.httpAgent) { + config.httpAgent.keepAlive = true; } else { - options = { keepAlive: true }; - agent = httpRequest.url.startsWith("https") - ? new https.Agent(options) - : new http.Agent(options); - requestInit.agent = agent; + config.httpAgent = keepaliveAgents.http; + } + if (config.httpsAgent) { + config.httpsAgent.keepAlive = true; + } + else { + config.httpsAgent = keepaliveAgents.https; } } - return [2 /*return*/, requestInit]; - } - }); - }); - }; - NodeFetchHttpClient.prototype.processRequest = function (operationResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var setCookieHeader_1; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.cookieJar) return [3 /*break*/, 2]; + return [4 /*yield*/, axiosInstance.request(config)]; + case 4: + res = _c.sent(); + return [3 /*break*/, 7]; + case 5: + err_1 = _c.sent(); + if (err_1 instanceof axios.Cancel) { + throw new RestError(err_1.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + } + else { + axiosErr = err_1; + throw new RestError(axiosErr.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + } + return [3 /*break*/, 7]; + case 6: + if (abortSignal && abortListener) { + abortSignal.removeEventListener("abort", abortListener); + } + return [7 /*endfinally*/]; + case 7: + headers = new HttpHeaders(res.headers); + onDownloadProgress = httpRequest.onDownloadProgress; + responseBody = res.data; + if (onDownloadProgress) { + if (isReadableStream(responseBody)) { + loadedBytes_2 = 0; + downloadReportStream = new stream.Transform({ + transform: function (chunk, _encoding, callback) { + loadedBytes_2 += chunk.length; + onDownloadProgress({ loadedBytes: loadedBytes_2 }); + callback(undefined, chunk); + } + }); + responseBody.pipe(downloadReportStream); + responseBody = downloadReportStream; + } + else { + length_1 = parseInt(headers.get("Content-Length")) || responseBody.length || undefined; + if (length_1) { + // Calling callback for non-stream response for consistency with browser + onDownloadProgress({ loadedBytes: length_1 }); + } + } + } + operationResponse = { + request: httpRequest, + status: res.status, + headers: headers, + readableStreamBody: httpRequest.streamResponseBody ? responseBody : undefined, + bodyAsText: httpRequest.streamResponseBody ? undefined : responseBody + }; + if (!this.cookieJar) return [3 /*break*/, 9]; setCookieHeader_1 = operationResponse.headers.get("Set-Cookie"); - if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 2]; + if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 9]; return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.cookieJar.setCookie(setCookieHeader_1, operationResponse.request.url, { ignoreError: true }, function (err) { + _this.cookieJar.setCookie(setCookieHeader_1, httpRequest.url, function (err) { if (err) { reject(err); } @@ -5746,16 +4490,56 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { } }); })]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; + case 8: + _c.sent(); + _c.label = 9; + case 9: return [2 /*return*/, operationResponse]; } }); }); }; - return NodeFetchHttpClient; -}(FetchHttpClient)); + return AxiosHttpClient; +}()); +function isReadableStream(body) { + return typeof body.pipe === "function"; +} +function createProxyAgent(requestUrl, proxySettings, headers) { + var tunnelOptions = { + proxy: { + host: URLBuilder.parse(proxySettings.host).getHost(), + port: proxySettings.port, + headers: (headers && headers.rawHeaders()) || {} + } + }; + if ((proxySettings.username && proxySettings.password)) { + tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password; + } + var requestScheme = URLBuilder.parse(requestUrl).getScheme() || ""; + var isRequestHttps = requestScheme.toLowerCase() === "https"; + var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || ""; + var isProxyHttps = proxyScheme.toLowerCase() === "https"; + var proxyAgent = { + isHttps: isRequestHttps, + agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) + }; + return proxyAgent; +} +function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { + if (isRequestHttps && isProxyHttps) { + return tunnel.httpsOverHttps(tunnelOptions); + } + else if (isRequestHttps && !isProxyHttps) { + return tunnel.httpsOverHttp(tunnelOptions); + } + else if (!isRequestHttps && isProxyHttps) { + return tunnel.httpOverHttps(tunnelOptions); + } + else { + return tunnel.httpOverHttp(tunnelOptions); + } +} + +// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved. (function (HttpPipelineLogLevel) { @@ -5777,6 +4561,49 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO"; })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {})); +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * A static-key-based credential that supports updating + * the underlying key value. + */ +var AzureKeyCredential = /** @class */ (function () { + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key - The initial value of the key to use in authentication + */ + function AzureKeyCredential(key) { + if (!key) { + throw new Error("key must be a non-empty string"); + } + this._key = key; + } + Object.defineProperty(AzureKeyCredential.prototype, "key", { + /** + * The value of the key to be used in authentication + */ + get: function () { + return this._key; + }, + enumerable: false, + configurable: true + }); + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used + */ + AzureKeyCredential.prototype.update = function (newKey) { + this._key = newKey; + }; + return AzureKeyCredential; +}()); + // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** @@ -5796,6 +4623,8 @@ function isTokenCredential(credential) { (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); } +// Copyright (c) Microsoft Corporation. + // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. /** @@ -5825,8 +4654,7 @@ function isStreamOperation(operationSpec) { var result = false; for (var statusCode in operationSpec.responses) { var operationResponse = operationSpec.responses[statusCode]; - if (operationResponse.bodyMapper && - operationResponse.bodyMapper.type.name === MapperType.Stream) { + if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { result = true; break; } @@ -5837,10 +4665,12 @@ function isStreamOperation(operationSpec) { // Copyright (c) Microsoft Corporation. All rights reserved. function stringifyXML(obj, opts) { var builder = new xml2js.Builder({ + explicitArray: false, + explicitCharkey: false, rootName: (opts || {}).rootName, renderOpts: { - pretty: false, - }, + pretty: false + } }); return builder.buildObject(obj); } @@ -5848,7 +4678,7 @@ function parseXML(str) { var xmlParser = new xml2js.Parser({ explicitArray: false, explicitCharkey: false, - explicitRoot: false, + explicitRoot: false }); return new Promise(function (resolve, reject) { if (!str) { @@ -5905,9 +4735,9 @@ var RequestPolicyOptions = /** @class */ (function () { * @returns Whether or not a log with the provided log level should be logged. */ RequestPolicyOptions.prototype.shouldLog = function (logLevel) { - return (!!this._logger && + return !!this._logger && logLevel !== exports.HttpPipelineLogLevel.OFF && - logLevel <= this._logger.minimumLogLevel); + logLevel <= this._logger.minimumLogLevel; }; /** * Attempt to log the provided message to the provided logger. If no logger was provided or if @@ -5932,7 +4762,7 @@ function deserializationPolicy(deserializationContentTypes) { return { create: function (nextPolicy, options) { return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options); - }, + } }; } var defaultJsonContentTypes = ["application/json", "text/json"]; @@ -5945,21 +4775,15 @@ var DeserializationPolicy = /** @class */ (function (_super) { tslib.__extends(DeserializationPolicy, _super); function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) { var _this = _super.call(this, nextPolicy, options) || this; - _this.jsonContentTypes = - (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; - _this.xmlContentTypes = - (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; + _this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes; + _this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes; return _this; } DeserializationPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { var _this = this; return tslib.__generator(this, function (_a) { - return [2 /*return*/, this._nextPolicy - .sendRequest(request) - .then(function (response) { - return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); - })]; + return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })]; }); }); }; @@ -6002,12 +4826,9 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { if (operationSpec && operationSpec.responses) { var statusCode = parsedResponse.status; var expectedStatusCodes = Object.keys(operationSpec.responses); - var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"); + var hasNoExpectedStatusCodes = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); var responseSpec = getOperationResponse(parsedResponse); - var isExpectedStatusCode = hasNoExpectedStatusCodes - ? 200 <= statusCode && statusCode < 300 - : !!responseSpec; + var isExpectedStatusCode = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec; if (!isExpectedStatusCode) { var defaultResponseSpec = operationSpec.responses.default; if (defaultResponseSpec) { @@ -6022,8 +4843,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { try { if (parsedErrorResponse) { var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper; - if (defaultResponseBodyMapper && - defaultResponseBodyMapper.serializedName === "CloudError") { + if (defaultResponseBodyMapper && defaultResponseBodyMapper.serializedName === "CloudError") { if (parsedErrorResponse.error) { parsedErrorResponse = parsedErrorResponse.error; } @@ -6046,12 +4866,10 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { } if (defaultResponseBodyMapper) { var valueToDeserialize = parsedErrorResponse; - if (operationSpec.isXML && - defaultResponseBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof parsedErrorResponse === "object" - ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName] - : []; + if (operationSpec.isXML && defaultResponseBodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = typeof parsedErrorResponse === "object" + ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName] + : []; } error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body"); } @@ -6067,10 +4885,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { if (responseSpec.bodyMapper) { var valueToDeserialize = parsedResponse.parsedBody; if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof valueToDeserialize === "object" - ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] - : []; + valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : []; } try { parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody"); @@ -6105,11 +4920,8 @@ function parse(jsonContentTypes, xmlContentTypes, operationResponse) { if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) { var text_1 = operationResponse.bodyAsText; var contentType = operationResponse.headers.get("Content-Type") || ""; - var contentComponents = !contentType - ? [] - : contentType.split(";").map(function (component) { return component.toLowerCase(); }); - if (contentComponents.length === 0 || - contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) { + var contentComponents = !contentType ? [] : contentType.split(";").map(function (component) { return component.toLowerCase(); }); + if (contentComponents.length === 0 || contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) { return new Promise(function (resolve) { operationResponse.parsedBody = JSON.parse(text_1); resolve(operationResponse); @@ -6132,7 +4944,7 @@ function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, max return { create: function (nextPolicy, options) { return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); - }, + } }; } var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; @@ -6148,7 +4960,7 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { /** * @constructor * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain. - * @param {RequestPolicyOptionsLike} options The options for this RequestPolicy. + * @param {RequestPolicyOptions} options The options for this RequestPolicy. * @param {number} [retryCount] The client retry count. * @param {number} [retryInterval] The client retry interval, in milliseconds. * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds. @@ -6156,23 +4968,16 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { */ function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { var _this = _super.call(this, nextPolicy, options) || this; - function isNumber(n) { - return typeof n === "number"; - } + function isNumber(n) { return typeof n === "number"; } _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - _this.minRetryInterval = isNumber(minRetryInterval) - ? minRetryInterval - : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - _this.maxRetryInterval = isNumber(maxRetryInterval) - ? maxRetryInterval - : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + _this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + _this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; return _this; } ExponentialRetryPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request.clone()) + return this._nextPolicy.sendRequest(request.clone()) .then(function (response) { return retry(_this, request, response); }) .catch(function (error) { return retry(_this, request, error.response, undefined, error); }); }; @@ -6187,10 +4992,7 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { * @return {boolean} True if the operation qualifies for a retry; false otherwise. */ function shouldRetry(policy, statusCode, retryData) { - if (statusCode == undefined || - (statusCode < 500 && statusCode !== 408) || - statusCode === 501 || - statusCode === 505) { + if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) { return false; } var currentCount; @@ -6198,9 +5000,9 @@ function shouldRetry(policy, statusCode, retryData) { throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null."); } else { - currentCount = retryData && retryData.retryCount; + currentCount = (retryData && retryData.retryCount); } - return currentCount < policy.retryCount; + return (currentCount < policy.retryCount); } /** * Updates the retry data for the next attempt. @@ -6213,7 +5015,7 @@ function updateRetryData(policy, retryData, err) { if (!retryData) { retryData = { retryCount: 0, - retryInterval: 0, + retryInterval: 0 }; } if (err) { @@ -6258,7 +5060,7 @@ function generateClientRequestIdPolicy(requestIdHeaderName) { return { create: function (nextPolicy, options) { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); - }, + } }; } var GenerateClientRequestIdPolicy = /** @class */ (function (_super) { @@ -6284,11 +5086,11 @@ function getDefaultUserAgentKey() { function getPlatformSpecificData() { var runtimeInfo = { key: "Node", - value: process.version, + value: process.version }; var osInfo = { key: "OS", - value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")", + value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")" }; return [runtimeInfo, osInfo]; } @@ -6297,19 +5099,17 @@ function getPlatformSpecificData() { function getRuntimeInfo() { var msRestRuntime = { key: "ms-rest-js", - value: Constants.msRestVersion, + value: Constants.msRestVersion }; return [msRestRuntime]; } function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) { if (keySeparator === void 0) { keySeparator = " "; } if (valueSeparator === void 0) { valueSeparator = "/"; } - return telemetryInfo - .map(function (info) { + return telemetryInfo.map(function (info) { var value = info.value ? "" + valueSeparator + info.value : ""; return "" + info.key + value; - }) - .join(keySeparator); + }).join(keySeparator); } var getDefaultUserAgentHeaderName = getDefaultUserAgentKey; function getDefaultUserAgentValue() { @@ -6319,14 +5119,12 @@ function getDefaultUserAgentValue() { return userAgent; } function userAgentPolicy(userAgentData) { - var key = !userAgentData || userAgentData.key == undefined ? getDefaultUserAgentKey() : userAgentData.key; - var value = !userAgentData || userAgentData.value == undefined - ? getDefaultUserAgentValue() - : userAgentData.value; + var key = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key; + var value = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value; return { create: function (nextPolicy, options) { return new UserAgentPolicy(nextPolicy, options, key, value); - }, + } }; } var UserAgentPolicy = /** @class */ (function (_super) { @@ -6355,16 +5153,12 @@ var UserAgentPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); // Copyright (c) Microsoft Corporation. All rights reserved. -var DefaultRedirectOptions = { - handleRedirects: true, - maxRetries: 20, -}; function redirectPolicy(maximumRetries) { if (maximumRetries === void 0) { maximumRetries = 20; } return { create: function (nextPolicy, options) { return new RedirectPolicy(nextPolicy, options, maximumRetries); - }, + } }; } var RedirectPolicy = /** @class */ (function (_super) { @@ -6377,9 +5171,7 @@ var RedirectPolicy = /** @class */ (function (_super) { } RedirectPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request) - .then(function (response) { return handleRedirect(_this, response, 0); }); + return this._nextPolicy.sendRequest(request).then(function (response) { return handleRedirect(_this, response, 0); }); }; return RedirectPolicy; }(BaseRequestPolicy)); @@ -6387,46 +5179,28 @@ function handleRedirect(policy, response, currentRetries) { var request = response.request, status = response.status; var locationHeader = response.headers.get("location"); if (locationHeader && - (status === 300 || - (status === 301 && ["GET", "HEAD"].includes(request.method)) || - (status === 302 && ["GET", "POST", "HEAD"].includes(request.method)) || - (status === 303 && "POST" === request.method) || - status === 307) && - ((request.redirectLimit !== undefined && currentRetries < request.redirectLimit) || - (request.redirectLimit === undefined && currentRetries < policy.maxRetries))) { + (status === 300 || status === 307 || (status === 303 && request.method === "POST")) && + (!policy.maxRetries || currentRetries < policy.maxRetries)) { var builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); request.url = builder.toString(); - // POST request with Status code 302 and 303 should be converted into a + // POST request with Status code 303 should be converted into a // redirected GET request if the redirect url is present in the location header - // reference: https://tools.ietf.org/html/rfc7231#page-57 && https://fetch.spec.whatwg.org/#http-redirect-fetch - if ((status === 302 || status === 303) && request.method === "POST") { + if (status === 303) { request.method = "GET"; - delete request.body; } - return policy._nextPolicy - .sendRequest(request) - .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); }) - .then(function (res) { return recordRedirect(res, request.url); }); + return policy._nextPolicy.sendRequest(request) + .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); }); } return Promise.resolve(response); } -function recordRedirect(response, redirect) { - // This is called as the recursive calls to handleRedirect() unwind, - // only record the deepest/last redirect - if (!response.redirected) { - response.redirected = true; - response.url = redirect; - } - return response; -} function rpRegistrationPolicy(retryTimeout) { if (retryTimeout === void 0) { retryTimeout = 30; } return { create: function (nextPolicy, options) { return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); - }, + } }; } var RPRegistrationPolicy = /** @class */ (function (_super) { @@ -6439,8 +5213,7 @@ var RPRegistrationPolicy = /** @class */ (function (_super) { } RPRegistrationPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request.clone()) + return this._nextPolicy.sendRequest(request.clone()) .then(function (response) { return registerIfNeeded(_this, request, response); }); }; return RPRegistrationPolicy; @@ -6450,7 +5223,7 @@ function registerIfNeeded(policy, request, response) { var rpName = checkRPNotRegisteredError(response.bodyAsText); if (rpName) { var urlPrefix = extractSubscriptionUrl(request.url); - return (registerRP(policy, urlPrefix, rpName, request) + return registerRP(policy, urlPrefix, rpName, request) // Autoregistration of ${provider} failed for some reason. We will not return this error // instead will return the initial response with 409 status code back to the user. // do nothing here as we are returning the original response at the end of this method. @@ -6463,14 +5236,14 @@ function registerIfNeeded(policy, request, response) { return policy._nextPolicy.sendRequest(request.clone()); } return response; - })); + }); } } return Promise.resolve(response); } /** * Reuses the headers of the original request and url (if specified). - * @param {WebResourceLike} originalRequest The original request + * @param {WebResource} originalRequest The original request * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false. * @returns {object} A new request object with desired headers. */ @@ -6502,11 +5275,8 @@ function checkRPNotRegisteredError(body) { catch (err) { // do nothing; } - if (responseBody && - responseBody.error && - responseBody.error.message && - responseBody.error.code && - responseBody.error.code === "MissingSubscriptionRegistration") { + if (responseBody && responseBody.error && responseBody.error.message && + responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") { var matchRes = responseBody.error.message.match(/.*'(.*)'/i); if (matchRes) { result = matchRes.pop(); @@ -6523,7 +5293,7 @@ function checkRPNotRegisteredError(body) { */ function extractSubscriptionUrl(url) { var result; - var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); + var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//ig); if (matchRes && matchRes[0]) { result = matchRes[0]; } @@ -6537,7 +5307,7 @@ function extractSubscriptionUrl(url) { * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ * @param {string} provider The provider name to be registered. - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. * @param {registrationCallback} callback The callback that handles the RP registration */ @@ -6547,7 +5317,8 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { var reqOptions = getRequestEssentials(originalRequest); reqOptions.method = "POST"; reqOptions.url = postUrl; - return policy._nextPolicy.sendRequest(reqOptions).then(function (response) { + return policy._nextPolicy.sendRequest(reqOptions) + .then(function (response) { if (response.status !== 200) { throw new Error("Autoregistration of " + provider + " failed. Please try registering manually."); } @@ -6559,7 +5330,7 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { * Polling will happen till the registrationState property of the response body is "Registered". * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. * @param {string} url The request url for polling - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. * @returns {Promise} True if RP Registration is successful. */ @@ -6573,8 +5344,7 @@ function getRegistrationStatus(policy, url, originalRequest) { return true; } else { - return delay(policy._retryTimeout * 1000) - .then(function () { return getRegistrationStatus(policy, url, originalRequest); }); + return delay(policy._retryTimeout * 1000).then(function () { return getRegistrationStatus(policy, url, originalRequest); }); } }); } @@ -6584,7 +5354,7 @@ function signingPolicy(authenticationProvider) { return { create: function (nextPolicy, options) { return new SigningPolicy(nextPolicy, options, authenticationProvider); - }, + } }; } var SigningPolicy = /** @class */ (function (_super) { @@ -6599,9 +5369,7 @@ var SigningPolicy = /** @class */ (function (_super) { }; SigningPolicy.prototype.sendRequest = function (request) { var _this = this; - return this.signRequest(request).then(function (nextRequest) { - return _this._nextPolicy.sendRequest(nextRequest); - }); + return this.signRequest(request).then(function (nextRequest) { return _this._nextPolicy.sendRequest(nextRequest); }); }; return SigningPolicy; }(BaseRequestPolicy)); @@ -6611,7 +5379,7 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max return { create: function (nextPolicy, options) { return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); - }, + } }; } /** @@ -6633,23 +5401,14 @@ var SystemErrorRetryPolicy = /** @class */ (function (_super) { _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT; - _this.retryInterval = - typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL; - _this.minRetryInterval = - typeof minRetryInterval === "number" - ? minRetryInterval - : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - _this.maxRetryInterval = - typeof maxRetryInterval === "number" - ? maxRetryInterval - : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + _this.retryInterval = typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL; + _this.minRetryInterval = typeof minRetryInterval === "number" ? minRetryInterval : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + _this.maxRetryInterval = typeof maxRetryInterval === "number" ? maxRetryInterval : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL; return _this; } SystemErrorRetryPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request.clone()) - .catch(function (error) { return retry$1(_this, request, error.response, error); }); + return this._nextPolicy.sendRequest(request.clone()).then(function (response) { return retry$1(_this, request, response); }); }; return SystemErrorRetryPolicy; }(BaseRequestPolicy)); @@ -6666,9 +5425,9 @@ function shouldRetry$1(policy, retryData) { throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null."); } else { - currentCount = retryData && retryData.retryCount; + currentCount = (retryData && retryData.retryCount); } - return currentCount < policy.retryCount; + return (currentCount < policy.retryCount); } /** * Updates the retry data for the next attempt. @@ -6680,7 +5439,7 @@ function updateRetryData$1(policy, retryData, err) { if (!retryData) { retryData = { retryCount: 0, - retryInterval: 0, + retryInterval: 0 }; } if (err) { @@ -6693,47 +5452,31 @@ function updateRetryData$1(policy, retryData, err) { retryData.retryCount++; // Adjust retry interval var incrementDelta = Math.pow(2, retryData.retryCount) - 1; - var boundedRandDelta = policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 0.4)); + var boundedRandDelta = policy.retryInterval * 0.8 + + Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8)); incrementDelta *= boundedRandDelta; retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval); return retryData; } -function retry$1(policy, request, operationResponse, err, retryData) { - return tslib.__awaiter(this, void 0, void 0, function () { - var error_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - retryData = updateRetryData$1(policy, retryData, err); - if (!(err && - err.code && - shouldRetry$1(policy, retryData) && - (err.code === "ETIMEDOUT" || - err.code === "ESOCKETTIMEDOUT" || - err.code === "ECONNREFUSED" || - err.code === "ECONNRESET" || - err.code === "ENOENT"))) return [3 /*break*/, 5]; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, delay(retryData.retryInterval)]; - case 2: - _a.sent(); - return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())]; - case 3: - error_1 = _a.sent(); - return [2 /*return*/, retry$1(policy, request, operationResponse, error_1, retryData)]; - case 4: return [3 /*break*/, 6]; - case 5: - if (err) { - // If the operation failed in the end, return all errors instead of just the last one - return [2 /*return*/, Promise.reject(retryData.error)]; - } - return [2 /*return*/, operationResponse]; - case 6: return [2 /*return*/]; - } - }); - }); +function retry$1(policy, request, operationResponse, retryData, err) { + retryData = updateRetryData$1(policy, retryData, err); + if (err && err.code && shouldRetry$1(policy, retryData) && + (err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || + err.code === "ECONNRESET" || err.code === "ENOENT")) { + // If previous operation ended with an error and the policy allows a retry, do that + return delay(retryData.retryInterval) + .then(function () { return policy._nextPolicy.sendRequest(request.clone()); }) + .then(function (res) { return retry$1(policy, request, res, retryData, err); }) + .catch(function (err) { return retry$1(policy, request, operationResponse, retryData, err); }); + } + else { + if (err != undefined) { + // If the operation failed in the end, return all errors instead of just the last one + err = retryData.error; + return Promise.reject(err); + } + return Promise.resolve(operationResponse); + } } // Copyright (c) Microsoft Corporation. All rights reserved. @@ -6750,7 +5493,7 @@ function agentPolicy(agentSettings) { return { create: function (nextPolicy, options) { return new AgentPolicy(nextPolicy, options, agentSettings); - }, + } }; } var AgentPolicy = /** @class */ (function (_super) { @@ -6770,101 +5513,23 @@ var AgentPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); // Copyright (c) Microsoft Corporation. All rights reserved. -/** - * @internal - */ -var noProxyList = loadNoProxy(); -var byPassedList = new Map(); -/** - * @internal - */ -function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } - else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; - } - return undefined; -} function loadEnvironmentProxyValue() { if (!process) { return undefined; } - var httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); - var allProxy = getEnvironmentValue(Constants.ALL_PROXY); - var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; -} -// Check whether the host of a given `uri` is in the noProxyList. -// If there's a match, any request sent to the same host won't have the proxy settings set. -// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 -function isBypassed(uri) { - if (noProxyList.length === 0) { - return false; - } - var host = URLBuilder.parse(uri).getHost(); - if (byPassedList.has(host)) { - return byPassedList.get(host); + if (process.env[Constants.HTTPS_PROXY]) { + return process.env[Constants.HTTPS_PROXY]; } - var isBypassedFlag = false; - for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var pattern = noProxyList_1[_i]; - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } - else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } - } - } - else { - if (host === pattern) { - isBypassedFlag = true; - } - } + else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) { + return process.env[Constants.HTTPS_PROXY.toLowerCase()]; } - byPassedList.set(host, isBypassedFlag); - return isBypassedFlag; -} -/** - * @internal - */ -function loadNoProxy() { - var noProxy = getEnvironmentValue(Constants.NO_PROXY); - if (noProxy) { - return noProxy - .split(",") - .map(function (item) { return item.trim(); }) - .filter(function (item) { return item.length; }); + else if (process.env[Constants.HTTP_PROXY]) { + return process.env[Constants.HTTP_PROXY]; } - return []; -} -/** - * @internal - */ -function extractAuthFromUrl(url) { - var atIndex = url.indexOf("@"); - if (atIndex === -1) { - return { urlWithoutAuth: url }; + else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) { + return process.env[Constants.HTTP_PROXY.toLowerCase()]; } - var schemeIndex = url.indexOf("://"); - var authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; - var auth = url.substring(authStart, atIndex); - var colonIndex = auth.indexOf(":"); - var hasPassword = colonIndex !== -1; - var username = hasPassword ? auth.substring(0, colonIndex) : auth; - var password = hasPassword ? auth.substring(colonIndex + 1) : undefined; - var urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); - return { - username: username, - password: password, - urlWithoutAuth: urlWithoutAuth, - }; + return undefined; } function getDefaultProxySettings(proxyUrl) { if (!proxyUrl) { @@ -6873,24 +5538,17 @@ function getDefaultProxySettings(proxyUrl) { return undefined; } } - var _a = extractAuthFromUrl(proxyUrl), username = _a.username, password = _a.password, urlWithoutAuth = _a.urlWithoutAuth; - var parsedUrl = URLBuilder.parse(urlWithoutAuth); - var schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; + var parsedUrl = URLBuilder.parse(proxyUrl); return { - host: schema + parsedUrl.getHost(), - port: Number.parseInt(parsedUrl.getPort() || "80"), - username: username, - password: password, + host: parsedUrl.getScheme() + "://" + parsedUrl.getHost(), + port: Number.parseInt(parsedUrl.getPort() || "80") }; } function proxyPolicy(proxySettings) { - if (!proxySettings) { - proxySettings = getDefaultProxySettings(); - } return { create: function (nextPolicy, options) { return new ProxyPolicy(nextPolicy, options, proxySettings); - }, + } }; } var ProxyPolicy = /** @class */ (function (_super) { @@ -6901,7 +5559,7 @@ var ProxyPolicy = /** @class */ (function (_super) { return _this; } ProxyPolicy.prototype.sendRequest = function (request) { - if (!request.proxySettings && !isBypassed(request.url)) { + if (!request.proxySettings) { request.proxySettings = this.proxySettings; } return this._nextPolicy.sendRequest(request); @@ -6911,13 +5569,11 @@ var ProxyPolicy = /** @class */ (function (_super) { // Copyright (c) Microsoft Corporation. All rights reserved. var StatusCodes = Constants.HttpConstants.StatusCodes; -var DEFAULT_RETRY_COUNT = 3; -function throttlingRetryPolicy(maxRetries) { - if (maxRetries === void 0) { maxRetries = DEFAULT_RETRY_COUNT; } +function throttlingRetryPolicy() { return { create: function (nextPolicy, options) { - return new ThrottlingRetryPolicy(nextPolicy, options, maxRetries); - }, + return new ThrottlingRetryPolicy(nextPolicy, options); + } }; } /** @@ -6928,9 +5584,9 @@ function throttlingRetryPolicy(maxRetries) { */ var ThrottlingRetryPolicy = /** @class */ (function (_super) { tslib.__extends(ThrottlingRetryPolicy, _super); - function ThrottlingRetryPolicy(nextPolicy, options, retryLimit) { + function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) { var _this = _super.call(this, nextPolicy, options) || this; - _this.retryLimit = retryLimit; + _this._handleResponse = _handleResponse || _this._defaultResponseHandler; return _this; } ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) { @@ -6938,33 +5594,29 @@ var ThrottlingRetryPolicy = /** @class */ (function (_super) { var _this = this; return tslib.__generator(this, function (_a) { return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) { - return _this.retry(httpRequest, response, 0); + if (response.status !== StatusCodes.TooManyRequests) { + return response; + } + else { + return _this._handleResponse(httpRequest, response); + } })]; }); }); }; - ThrottlingRetryPolicy.prototype.retry = function (httpRequest, httpResponse, retryCount) { + ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) { return tslib.__awaiter(this, void 0, void 0, function () { - var retryAfterHeader, delayInMs, res; + var retryAfterHeader, delayInMs; + var _this = this; return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (httpResponse.status !== StatusCodes.TooManyRequests) { - return [2 /*return*/, httpResponse]; - } - retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); - if (!(retryAfterHeader && retryCount < this.retryLimit)) return [3 /*break*/, 3]; - delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); - if (!delayInMs) return [3 /*break*/, 3]; - return [4 /*yield*/, delay(delayInMs)]; - case 1: - _a.sent(); - return [4 /*yield*/, this._nextPolicy.sendRequest(httpRequest)]; - case 2: - res = _a.sent(); - return [2 /*return*/, this.retry(httpRequest, res, retryCount + 1)]; - case 3: return [2 /*return*/, httpResponse]; + retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); + if (retryAfterHeader) { + delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); + if (delayInMs) { + return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })]; + } } + return [2 /*return*/, httpResponse]; }); }); }; @@ -7022,6 +5674,7 @@ var AzureIdentityCredentialAdapter = /** @class */ (function () { else { throw new Error("Could find token for scope"); } + return [2 /*return*/]; } }); }); @@ -7070,7 +5723,7 @@ var ServiceClient = /** @class */ (function () { throw new Error("credentials argument needs to implement signRequest method"); } this._withCredentials = options.withCredentials || false; - this._httpClient = options.httpClient || new NodeFetchHttpClient(); + this._httpClient = options.httpClient || new AxiosHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); var requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { @@ -7096,7 +5749,7 @@ var ServiceClient = /** @class */ (function () { } var httpRequest; try { - if (isWebResourceLike(options)) { + if (options instanceof WebResource) { options.validateRequestProperties(); httpRequest = options; } @@ -7169,30 +5822,20 @@ var ServiceClient = /** @class */ (function () { } } } - else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || - queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { + else { queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); } } if (!queryParameter.skipEncoding) { if (Array.isArray(queryParameterValue)) { for (var index in queryParameterValue) { - if (queryParameterValue[index] !== undefined && - queryParameterValue[index] !== null) { - queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); - } + queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); } } else { queryParameterValue = encodeURIComponent(queryParameterValue); } } - if (queryParameter.collectionFormat != undefined && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); } } @@ -7208,8 +5851,7 @@ var ServiceClient = /** @class */ (function () { var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); if (headerValue != undefined) { headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); - var headerCollectionPrefix = headerParameter.mapper - .headerCollectionPrefix; + var headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix; if (headerCollectionPrefix) { for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) { var key = _g[_f]; @@ -7217,8 +5859,7 @@ var ServiceClient = /** @class */ (function () { } } else { - httpRequest.headers.set(headerParameter.mapper.serializedName || - getPathStringFromParameter(headerParameter), headerValue); + httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue); } } } @@ -7248,9 +5889,8 @@ var ServiceClient = /** @class */ (function () { if (httpRequest.streamResponseBody == undefined) { httpRequest.streamResponseBody = isStreamOperation(operationSpec); } - result = this.sendRequest(httpRequest).then(function (res) { - return flattenResponse(res, operationSpec.responses[res.status]); - }); + result = this.sendRequest(httpRequest) + .then(function (res) { return flattenResponse(res, operationSpec.responses[res.status]); }); } catch (error) { result = Promise.reject(error); @@ -7282,9 +5922,7 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName }); } else if (!isStream) { - httpRequest.body = stringifyXML(httpRequest.body, { - rootName: xmlName || serializedName, - }); + httpRequest.body = stringifyXML(httpRequest.body, { rootName: xmlName || serializedName }); } } else if (!isStream) { @@ -7342,10 +5980,7 @@ function createDefaultRequestPolicyFactories(credentials, options) { if (userAgentHeaderName && userAgentHeaderValue) { factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); } - var redirectOptions = tslib.__assign(tslib.__assign({}, DefaultRedirectOptions), options.redirectOptions); - if (redirectOptions.handleRedirects) { - factories.push(redirectPolicy(redirectOptions.maxRetries)); - } + factories.push(redirectPolicy()); factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout)); if (!options.noRetryPolicy) { factories.push(exponentialRetryPolicy()); @@ -7382,9 +6017,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu } var useDefaultValue = false; if (!propertySearchResult.propertyFound) { - useDefaultValue = - parameterMapper.required || - (parameterPath[0] === "options" && parameterPath.length === 2); + useDefaultValue = parameterMapper.required || (parameterPath[0] === "options" && parameterPath.length === 2); } value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; } @@ -7438,7 +6071,7 @@ function flattenResponse(_response, responseSpec) { var bodyMapper = responseSpec && responseSpec.bodyMapper; var addOperationResponse = function (obj) { return Object.defineProperty(obj, "_response", { - value: _response, + value: _response }); }; if (bodyMapper) { @@ -7446,12 +6079,14 @@ function flattenResponse(_response, responseSpec) { if (typeName === "Stream") { return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); } - var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; + var modelProperties_1 = typeName === "Composite" && bodyMapper.type.modelProperties || {}; var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; }); if (typeName === "Sequence" || isPageableResponse) { - // We're expecting a sequece(array) make sure that the response body is in the + // We're expecting a sequence(array) make sure that the response body is in the // correct format, if not make it an empty array [] - var parsedBody = Array.isArray(_response.parsedBody) ? _response.parsedBody : []; + var parsedBody = Array.isArray(_response.parsedBody) + ? _response.parsedBody + : []; var arrayResponse = tslib.__spreadArrays(parsedBody); for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) { var key = _a[_i]; @@ -7472,9 +6107,7 @@ function flattenResponse(_response, responseSpec) { return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); } } - if (bodyMapper || - _response.request.method === "HEAD" || - isPrimitiveType(_response.parsedBody)) { + if (bodyMapper || _response.request.method === "HEAD") { // primitive body types and HEAD booleans return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { body: _response.parsedBody })); } @@ -7487,7 +6120,7 @@ function logPolicy(logger) { return { create: function (nextPolicy, options) { return new LogPolicy(nextPolicy, options, logger); - }, + } }; } var LogPolicy = /** @class */ (function (_super) { @@ -7538,8 +6171,8 @@ var TokenCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @return {Promise} The signed request object. + * @param {WebResource} webResource The WebResource to be signed. + * @return {Promise} The signed request object. */ TokenCredentials.prototype.signRequest = function (webResource) { if (!webResource.headers) @@ -7578,8 +6211,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @returns {Promise} The signed request object. + * @param {WebResource} webResource The WebResource to be signed. + * @returns {Promise} The signed request object. */ BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { var credentials = this.userName + ":" + this.password; @@ -7661,8 +6294,8 @@ var TopicCredentials = /** @class */ (function (_super) { } var options = { inHeader: { - "aeg-sas-key": topicKey, - }, + "aeg-sas-key": topicKey + } }; _this = _super.call(this, options) || this; return _this; @@ -7686,8 +6319,8 @@ var DomainCredentials = /** @class */ (function (_super) { } var options = { inHeader: { - "aeg-sas-key": domainKey, - }, + "aeg-sas-key": domainKey + } }; _this = _super.call(this, options) || this; return _this; @@ -7695,562 +6328,55 @@ var DomainCredentials = /** @class */ (function (_super) { return DomainCredentials; }(ApiKeyCredentials)); -exports.ApiKeyCredentials = ApiKeyCredentials; -exports.AzureIdentityCredentialAdapter = AzureIdentityCredentialAdapter; -exports.BaseRequestPolicy = BaseRequestPolicy; -exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials; -exports.Constants = Constants; -exports.DefaultHttpClient = NodeFetchHttpClient; -exports.DomainCredentials = DomainCredentials; +// Copyright (c) Microsoft Corporation. All rights reserved. + +exports.WebResource = WebResource; +exports.DefaultHttpClient = AxiosHttpClient; exports.HttpHeaders = HttpHeaders; -exports.MapperType = MapperType; -exports.RequestPolicyOptions = RequestPolicyOptions; exports.RestError = RestError; -exports.Serializer = Serializer; exports.ServiceClient = ServiceClient; -exports.TokenCredentials = TokenCredentials; -exports.TopicCredentials = TopicCredentials; -exports.URLBuilder = URLBuilder; -exports.URLQuery = URLQuery; -exports.WebResource = WebResource; -exports.agentPolicy = agentPolicy; -exports.applyMixins = applyMixins; -exports.delay = delay; -exports.deserializationPolicy = deserializationPolicy; -exports.deserializeResponseBody = deserializeResponseBody; -exports.encodeUri = encodeUri; -exports.executePromisesSequentially = executePromisesSequentially; -exports.exponentialRetryPolicy = exponentialRetryPolicy; exports.flattenResponse = flattenResponse; +exports.Constants = Constants; +exports.logPolicy = logPolicy; +exports.BaseRequestPolicy = BaseRequestPolicy; +exports.RequestPolicyOptions = RequestPolicyOptions; exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy; -exports.generateUuid = generateUuid; +exports.exponentialRetryPolicy = exponentialRetryPolicy; +exports.systemErrorRetryPolicy = systemErrorRetryPolicy; +exports.throttlingRetryPolicy = throttlingRetryPolicy; exports.getDefaultProxySettings = getDefaultProxySettings; -exports.getDefaultUserAgentValue = getDefaultUserAgentValue; -exports.isDuration = isDuration; -exports.isNode = isNode; -exports.isValidUuid = isValidUuid; -exports.logPolicy = logPolicy; -exports.promiseToCallback = promiseToCallback; -exports.promiseToServiceCallback = promiseToServiceCallback; exports.proxyPolicy = proxyPolicy; exports.redirectPolicy = redirectPolicy; -exports.serializeObject = serializeObject; exports.signingPolicy = signingPolicy; +exports.userAgentPolicy = userAgentPolicy; +exports.getDefaultUserAgentValue = getDefaultUserAgentValue; +exports.deserializationPolicy = deserializationPolicy; +exports.deserializeResponseBody = deserializeResponseBody; +exports.MapperType = MapperType; +exports.Serializer = Serializer; +exports.serializeObject = serializeObject; exports.stripRequest = stripRequest; exports.stripResponse = stripResponse; -exports.systemErrorRetryPolicy = systemErrorRetryPolicy; -exports.throttlingRetryPolicy = throttlingRetryPolicy; -exports.userAgentPolicy = userAgentPolicy; +exports.delay = delay; +exports.executePromisesSequentially = executePromisesSequentially; +exports.generateUuid = generateUuid; +exports.encodeUri = encodeUri; +exports.promiseToCallback = promiseToCallback; +exports.promiseToServiceCallback = promiseToServiceCallback; +exports.isValidUuid = isValidUuid; +exports.applyMixins = applyMixins; +exports.isNode = isNode; +exports.isDuration = isDuration; +exports.URLBuilder = URLBuilder; +exports.URLQuery = URLQuery; +exports.TokenCredentials = TokenCredentials; +exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials; +exports.ApiKeyCredentials = ApiKeyCredentials; +exports.TopicCredentials = TopicCredentials; +exports.DomainCredentials = DomainCredentials; //# sourceMappingURL=msRest.node.js.map -/***/ }), - -/***/ 69970: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var CombinedStream = __nccwpck_require__(85443); -var util = __nccwpck_require__(31669); -var path = __nccwpck_require__(85622); -var http = __nccwpck_require__(98605); -var https = __nccwpck_require__(57211); -var parseUrl = __nccwpck_require__(78835).parse; -var fs = __nccwpck_require__(35747); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var populate = __nccwpck_require__(53647); - -// Public API -module.exports = FormData; - -// make it a Stream -util.inherits(FormData, CombinedStream); - -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream - */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); - - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } -} - -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function(field, value, options) { - - options = options || {}; - - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } - - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } - - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } - - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - - append(header); - append(value); - append(footer); - - // pass along options.knownLength - this._trackLength(header, value, options); -}; - -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; - - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } - - this._valueLength += valueLength; - - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; - - // empty or either doesn't have path or not an http response - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { - return; - } - - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; - -FormData.prototype._lengthRetriever = function(value, callback) { - - if (value.hasOwnProperty('fd')) { - - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { - - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); - - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { - - var fileSize; - - if (err) { - callback(err); - return; - } - - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); - - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); - } -}; - -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } - - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; - - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } - - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; - } - - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } - - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } - } - - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; - -FormData.prototype._getContentDisposition = function(value, options) { - - var filename - , contentDisposition - ; - - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } - - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } - - return contentDisposition; -}; - -FormData.prototype._getContentType = function(value, options) { - - // use custom content-type above all - var contentType = options.contentType; - - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } - - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } - - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } - - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } - - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } - - return contentType; -}; - -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; - - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } - - next(footer); - }.bind(this); -}; - -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; - -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; - - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - - return formHeaders; -}; - -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } - - return this._boundary; -}; - -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); - - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); - } - - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); - } - } - } - - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; - -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - - this._boundary = boundary; -}; - -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; - - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } - - return knownLength; -}; - -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; - - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } - - return hasKnownLength; -}; - -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; - - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } - - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; - } - - values.forEach(function(length) { - knownLength += length; - }); - - cb(null, knownLength); - }); -}; - -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; - - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { - - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - - // use custom params - } else { - - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; - } - } - - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); - - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } - - // get content length and fire away - this.getLength(function(err, length) { - if (err) { - this._error(err); - return; - } - - // add content length - request.setHeader('Content-Length', length); - - this.pipe(request); - if (cb) { - request.on('error', cb); - request.on('response', cb.bind(this, null)); - } - }.bind(this)); - - return request; -}; - -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; - -FormData.prototype.toString = function () { - return '[object FormData]'; -}; - - -/***/ }), - -/***/ 53647: -/***/ ((module) => { - -// populates missing values -module.exports = function(dst, src) { - - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); - - return dst; -}; - - /***/ }), /***/ 68930: @@ -8288,9 +6414,9 @@ module.exports = function(dst, src) { * POSSIBILITY OF SUCH DAMAGE. */ +var net = __nccwpck_require__(11631); var urlParse = __nccwpck_require__(78835).parse; var util = __nccwpck_require__(31669); -var ipRegex = __nccwpck_require__(29233)({ exact: true }); var pubsuffix = __nccwpck_require__(23005); var Store = __nccwpck_require__(5340)/* .Store */ .y; var MemoryCookieStore = __nccwpck_require__(96868)/* .MemoryCookieStore */ .m; @@ -8579,7 +6705,7 @@ function domainMatch(str, domStr, canonicalize) { /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ /* "* The string is a host name (i.e., not an IP address)." */ - if (ipRegex.test(str)) { + if (net.isIP(str)) { return false; } @@ -9266,17 +7392,11 @@ CookieJar.prototype.setCookie = function(cookie, url, options, cb) { } // S5.3 step 1 - if (typeof(cookie) === 'string' || cookie instanceof String) { + if (!(cookie instanceof Cookie)) { cookie = Cookie.parse(cookie, { loose: loose }); - if (!cookie) { - err = new Error("Cookie failed to parse"); - return cb(options.ignoreError ? null : err); - } } - else if (!(cookie instanceof Cookie)) { - // If you're seeing this error, and are passing in a Cookie object, - // it *might* be a Cookie object from another loaded version of tough-cookie. - err = new Error("First argument to setCookie must be a Cookie object or string"); + if (!cookie) { + err = new Error("Cookie failed to parse"); return cb(options.ignoreError ? null : err); } @@ -10204,7 +8324,7 @@ Store.prototype.getAllCookies = function(cb) { /***/ ((module) => { // generated by genversion -module.exports = '3.0.1' +module.exports = '2.5.0' /***/ }), @@ -10318,15 +8438,15 @@ class ApplicationTokenCertificateCredentials extends applicationTokenCredentials * Creates a new ApplicationTokenCredentials object. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for detailed instructions on creating an Azure Active Directory application. - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. - * @param certificate - A PEM encoded certificate private key. - * @param thumbprint - A hex encoded thumbprint of the certificate. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * @constructor + * @param {string} clientId The active directory application client id. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. + * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {Environment} [environment] The azure environment to authenticate with. + * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal. */ constructor(clientId, domain, certificate, thumbprint, tokenAudience, environment, tokenCache) { if (!certificate || typeof certificate.valueOf() !== "string") { @@ -10341,16 +8461,17 @@ class ApplicationTokenCertificateCredentials extends applicationTokenCredentials } /** * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL. - * @returns A promise that resolves to TokenResponse and rejects with an Error. + * @returns {Promise} A promise that resolves to TokenResponse and rejects with an Error. */ getToken() { return __awaiter(this, void 0, void 0, function* () { try { - return yield this.getTokenFromCache(); + const tokenResponse = yield this.getTokenFromCache(); + return tokenResponse; } catch (error) { if (error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { - throw error; + return Promise.reject(error); } return new Promise((resolve, reject) => { const resource = this.getActiveDirectoryResourceId(); @@ -10373,7 +8494,7 @@ class ApplicationTokenCertificateCredentials extends applicationTokenCredentials * @param clientId The active directory application client id also known as the SPN (ServicePrincipal Name). * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param certificateStringOrFilePath - A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example: + * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example: * - CertificateString: "-----BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n\n-----END CERTIFICATE-----\n" * - CertificateFilePath: **Absolute** file path of the .pem file. * @param domain The domain or tenant id containing this application. @@ -10382,7 +8503,8 @@ class ApplicationTokenCertificateCredentials extends applicationTokenCredentials * @returns ApplicationTokenCertificateCredentials */ static create(clientId, certificateStringOrFilePath, domain, options) { - if (!certificateStringOrFilePath || typeof certificateStringOrFilePath.valueOf() !== "string") { + if (!certificateStringOrFilePath || + typeof certificateStringOrFilePath.valueOf() !== "string") { throw new Error("'certificateStringOrFilePath' must be a non empty string."); } if (!certificateStringOrFilePath.startsWith("-----BEGIN")) { @@ -10428,14 +8550,14 @@ class ApplicationTokenCredentials extends applicationTokenCredentialsBase_1.Appl * Creates a new ApplicationTokenCredentials object. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for detailed instructions on creating an Azure Active Directory application. - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. - * @param secret - The authentication secret for the application. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * @constructor + * @param {string} clientId The active directory application client id. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} secret The authentication secret for the application. + * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {Environment} [environment] The azure environment to authenticate with. + * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal. */ constructor(clientId, domain, secret, tokenAudience, environment, tokenCache) { if (!secret || typeof secret.valueOf() !== "string") { @@ -10446,16 +8568,18 @@ class ApplicationTokenCredentials extends applicationTokenCredentialsBase_1.Appl } /** * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL. - * @returns A promise that resolves to TokenResponse and rejects with an Error. + * @returns {Promise} A promise that resolves to TokenResponse and rejects with an Error. */ getToken() { return __awaiter(this, void 0, void 0, function* () { try { - return yield this.getTokenFromCache(); + const tokenResponse = yield this.getTokenFromCache(); + return tokenResponse; } catch (error) { - if (error.message && error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { - throw error; + if (error.message && + error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { + return Promise.reject(error); } const resource = this.getActiveDirectoryResourceId(); return new Promise((resolve, reject) => { @@ -10501,13 +8625,13 @@ class ApplicationTokenCredentialsBase extends tokenCredentialsBase_1.TokenCreden * Creates a new ApplicationTokenCredentials object. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for detailed instructions on creating an Azure Active Directory application. - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * @constructor + * @param {string} clientId The active directory application client id. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {Environment} [environment] The azure environment to authenticate with. + * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal. */ constructor(clientId, domain, tokenAudience, environment, tokenCache) { super(clientId, domain, tokenAudience, environment, tokenCache); @@ -10517,27 +8641,29 @@ class ApplicationTokenCredentialsBase extends tokenCredentialsBase_1.TokenCreden getTokenFromCache: { get: () => super.getTokenFromCache } }); return __awaiter(this, void 0, void 0, function* () { + const self = this; // a thin wrapper over the base implementation. try get token from cache, additionaly clean up cache if required. try { - return yield _super.getTokenFromCache.call(this, undefined); + const tokenResponse = yield _super.getTokenFromCache.call(this, undefined); + return Promise.resolve(tokenResponse); } catch (error) { // Remove the stale token from the tokencache. ADAL gives the same error message "Entry not found in cache." // for entry not being present in the cache and for accessToken being expired in the cache. We do not want the token cache // to contain the expired token, we clean it up here. - const status = yield this.removeInvalidItemsFromCache({ - _clientId: this.clientId + const status = yield self.removeInvalidItemsFromCache({ + _clientId: self.clientId }); if (status.result) { - throw error; + return Promise.reject(error); } const message = status && status.details && status.details.message ? status.details.message : status.details; - throw new Error(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR + + return Promise.reject(new Error(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR + " : " + "critical failure while removing expired token for service principal from token cache. " + - message); + message)); } }); } @@ -10546,22 +8672,24 @@ class ApplicationTokenCredentialsBase extends tokenCredentialsBase_1.TokenCreden * Rather we resolve with an object that says the result is false and error information is provided in * the details property of the resolved object. This is done to do better error handling in the above function * where removeInvalidItemsFromCache() is called. - * @param query - The query to be used for finding the token for service principal from the cache - * @returns resultObject with more info. + * @param {object} query The query to be used for finding the token for service principal from the cache + * @returns {result: boolean, details?: Error} resultObject with more info. */ removeInvalidItemsFromCache(query) { const self = this; - return new Promise((resolve) => { + return new Promise(resolve => { self.tokenCache.find(query, (error, entries) => { if (error) { return resolve({ result: false, details: error }); } if (entries && entries.length > 0) { - return self.tokenCache.remove(entries, (err) => { - if (err) { - return resolve({ result: false, details: err }); - } - return resolve({ result: true }); + return new Promise(resolve => { + return self.tokenCache.remove(entries, (err) => { + if (err) { + return resolve({ result: false, details: err }); + } + return resolve({ result: true }); + }); }); } else { @@ -10625,7 +8753,7 @@ class AzureCliCredentials { /** * Tries to get the new token from Azure CLI, if the token has expired or the subscription has * changed else uses the cached accessToken. - * @returns The tokenResponse (tokenType and accessToken are the two important properties). + * @return The tokenResponse (tokenType and accessToken are the two important properties). */ getToken() { return __awaiter(this, void 0, void 0, function* () { @@ -10659,7 +8787,7 @@ class AzureCliCredentials { return __awaiter(this, void 0, void 0, function* () { const tokenResponse = yield this.getToken(); webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`); - return webResource; + return Promise.resolve(webResource); }); } _hasTokenExpired() { @@ -10667,8 +8795,7 @@ class AzureCliCredentials { const now = Math.floor(Date.now() / 1000); if (this.tokenInfo.expiresOn && this.tokenInfo.expiresOn instanceof Date && - Math.floor(this.tokenInfo.expiresOn.getTime() / 1000) - now > - this._tokenRenewalMarginInSeconds) { + Math.floor(this.tokenInfo.expiresOn.getTime() / 1000) - now > this._tokenRenewalMarginInSeconds) { result = false; } return result; @@ -10679,13 +8806,9 @@ class AzureCliCredentials { _parseToken() { try { const base64Url = this.tokenInfo.accessToken.split(".")[1]; - const base64 = decodeURIComponent(Buffer.from(base64Url, "base64") - .toString("binary") - .split("") - .map((c) => { + const base64 = decodeURIComponent(Buffer.from(base64Url, "base64").toString("binary").split("").map((c) => { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); - }) - .join("")); + }).join("")); return JSON.parse(base64); } catch (err) { @@ -10698,10 +8821,10 @@ class AzureCliCredentials { newResource = newResource.slice(0, -1); if (currentResource.endsWith("/")) currentResource = currentResource.slice(0, -1); - return ((newResource === "https://management.core.windows.net" && + return (newResource === "https://management.core.windows.net" && currentResource === "https://management.azure.com") || (newResource === "https://management.azure.com" && - currentResource === "https://management.core.windows.net")); + currentResource === "https://management.core.windows.net"); } _hasResourceChanged() { const parsedToken = this._parseToken(); @@ -10710,7 +8833,9 @@ class AzureCliCredentials { const currentResource = parsedToken.aud && parsedToken.aud.endsWith("/") ? parsedToken.aud.slice(0, -1) : parsedToken.aud; - const newResource = this.resource.endsWith("/") ? this.resource.slice(0, -1) : this.resource; + const newResource = this.resource.endsWith("/") + ? this.resource.slice(0, -1) + : this.resource; const result = this._isAzureResourceManagerEndpoint(newResource, currentResource) ? false : currentResource !== newResource; @@ -10723,21 +8848,20 @@ class AzureCliCredentials { static getAccessToken(options = {}) { return __awaiter(this, void 0, void 0, function* () { try { - const cmdArguments = ["account", "get-access-token"]; + let cmd = "account get-access-token"; if (options.subscriptionIdOrName) { - cmdArguments.push("-s"); - cmdArguments.push(options.subscriptionIdOrName); + cmd += ` -s "${options.subscriptionIdOrName}"`; } if (options.resource) { - cmdArguments.push("--resource"); - cmdArguments.push(options.resource); + cmd += ` --resource ${options.resource}`; } - const result = yield login_1.execAz(cmdArguments); + const result = yield login_1.execAz(cmd); result.expiresOn = new Date(result.expiresOn); return result; } catch (err) { - const message = `An error occurred while getting credentials from ` + `Azure CLI: ${err.stack}`; + const message = `An error occurred while getting credentials from ` + + `Azure CLI: ${err.stack}`; throw new Error(message); } }); @@ -10749,17 +8873,15 @@ class AzureCliCredentials { */ static getSubscription(subscriptionIdOrName) { return __awaiter(this, void 0, void 0, function* () { - if (subscriptionIdOrName && - (typeof subscriptionIdOrName !== "string" || !subscriptionIdOrName.length)) { + if (subscriptionIdOrName && (typeof subscriptionIdOrName !== "string" || !subscriptionIdOrName.length)) { throw new Error("'subscriptionIdOrName' must be a non-empty string."); } try { - const cmdArguments = ["account", "show"]; + let cmd = "account show"; if (subscriptionIdOrName) { - cmdArguments.push("-s"); - cmdArguments.push(subscriptionIdOrName); + cmd += ` -s "${subscriptionIdOrName}"`; } - const result = yield login_1.execAz(cmdArguments); + const result = yield login_1.execAz(cmd); return result; } catch (err) { @@ -10777,7 +8899,7 @@ class AzureCliCredentials { static setDefaultSubscription(subscriptionIdOrName) { return __awaiter(this, void 0, void 0, function* () { try { - yield login_1.execAz(["account", "set", "-s", subscriptionIdOrName]); + yield login_1.execAz(`account set -s ${subscriptionIdOrName}`); } catch (err) { const message = `An error occurred while setting the current subscription from ` + @@ -10794,14 +8916,14 @@ class AzureCliCredentials { return __awaiter(this, void 0, void 0, function* () { let subscriptionList = []; try { - const cmdArguments = ["account", "list"]; + let cmd = "account list"; if (options.all) { - cmdArguments.push(" --all"); + cmd += " --all"; } if (options.refresh) { - cmdArguments.push("--refresh"); + cmd += "--refresh"; } - subscriptionList = yield login_1.execAz(cmdArguments); + subscriptionList = yield login_1.execAz(cmd); if (subscriptionList && subscriptionList.length) { for (const sub of subscriptionList) { if (sub.cloudName) { @@ -10860,16 +8982,16 @@ class DeviceTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase * When this credential is used, the script will provide a url and code. The user needs to copy the url and the code, paste it * in a browser and authenticate over there. If successful, the script will get the access token. * - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. Default value is "common" - * @param username - The user name for account in the form: "user@example.com". - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * @constructor + * @param {string} [clientId] The active directory application client id. + * @param {string} [domain] The domain or tenant id containing this application. Default value is "common" + * @param {string} [username] The user name for account in the form: "user@example.com". + * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param environment - The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud". - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {Environment} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud". + * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal. */ constructor(clientId, domain, username, tokenAudience, environment, tokenCache) { if (!username) { @@ -11002,40 +9124,36 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); const msiTokenCredentials_1 = __nccwpck_require__(6182); const ms_rest_js_1 = __nccwpck_require__(30812); /** - * Provides information about managed service identity token credentials in an App Service environment. + * @class MSIAppServiceTokenCredentials */ class MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { /** * Creates an instance of MSIAppServiceTokenCredentials. - * @param options.msiEndpoint - The local URL from which your app can request tokens. - * Unless this property is specified, any of the two environment variables `IDENTITY_ENDPOINT` or `MSI_ENDPOINT` will be used as the default value. - * @param options.msiSecret - The secret used in communication between your code and the local MSI agent. - * Unless this property is specified, any of the two environment variables `IDENTITY_SECRET` or `MSI_SECRET` will be used as the default value. - * @param options.resource - The resource uri or token audience for which the token is needed. + * @param {string} [options.msiEndpoint] - The local URL from which your app can request tokens. + * Either provide this parameter or set the environment variable `MSI_ENDPOINT`. + * For example: `MSI_ENDPOINT="http://127.0.0.1:41741/MSI/token/"` + * @param {string} [options.msiSecret] - The secret used in communication between your code and the local MSI agent. + * Either provide this parameter or set the environment variable `MSI_SECRET`. + * For example: `MSI_SECRET="69418689F1E342DD946CB82994CDA3CB"` + * @param {string} [options.resource] - The resource uri or token audience for which the token is needed. * For e.g. it can be: * - resource management endpoint "https://management.azure.com/" (default) * - management endpoint "https://management.core.windows.net/" - * @param options.msiApiVersion - The api-version of the local MSI agent. Default value is "2017-09-01". - * @param options.clientId - The clientId of the managed identity you would like the token for. Required, if - * your app service has user-assigned managed identities. + * @param {string} [options.msiApiVersion] - The api-version of the local MSI agent. Default value is "2017-09-01". */ constructor(options) { if (!options) options = {}; super(options); - options.msiEndpoint = - options.msiEndpoint || process.env["IDENTITY_ENDPOINT"] || process.env["MSI_ENDPOINT"]; - options.msiSecret = - options.msiSecret || process.env["IDENTITY_SECRET"] || process.env["MSI_SECRET"]; - if (!options.msiEndpoint || - (options.msiEndpoint && typeof options.msiEndpoint.valueOf() !== "string")) { + options.msiEndpoint = options.msiEndpoint || process.env["MSI_ENDPOINT"]; + options.msiSecret = options.msiSecret || process.env["MSI_SECRET"]; + if (!options.msiEndpoint || (options.msiEndpoint && typeof options.msiEndpoint.valueOf() !== "string")) { throw new Error('Either provide "msiEndpoint" as a property of the "options" object ' + - 'or set the environment variable "IDENTITY_ENDPOINT" or "MSI_ENDPOINT" and it must be of type "string".'); + 'or set the environment variable "MSI_ENDPOINT" and it must be of type "string".'); } - if (!options.msiSecret || - (options.msiSecret && typeof options.msiSecret.valueOf() !== "string")) { + if (!options.msiSecret || (options.msiSecret && typeof options.msiSecret.valueOf() !== "string")) { throw new Error('Either provide "msiSecret" as a property of the "options" object ' + - 'or set the environment variable "IDENTITY_SECRET" or "MSI_SECRET" and it must be of type "string".'); + 'or set the environment variable "MSI_SECRET" and it must be of type "string".'); } if (!options.msiApiVersion) { options.msiApiVersion = "2017-09-01"; @@ -11046,20 +9164,21 @@ class MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCreden this.msiEndpoint = options.msiEndpoint; this.msiSecret = options.msiSecret; this.msiApiVersion = options.msiApiVersion; - this.clientId = options.clientId; } /** * Prepares and sends a GET request to a service endpoint indicated by the app service, which responds with the access token. - * @returns Promise with the tokenResponse (tokenType and accessToken are the two important properties). + * @return {Promise} Promise with the tokenResponse (tokenType and accessToken are the two important properties). */ getToken() { return __awaiter(this, void 0, void 0, function* () { const reqOptions = this.prepareRequestOptions(); - const opRes = yield this._httpClient.sendRequest(reqOptions); + let opRes; + let result; + opRes = yield this._httpClient.sendRequest(reqOptions); if (opRes.bodyAsText === undefined || opRes.bodyAsText.indexOf("ExceptionMessage") !== -1) { throw new Error(`MSI: Failed to retrieve a token from "${reqOptions.url}" with an error: ${opRes.bodyAsText}`); } - const result = this.parseTokenResponse(opRes.bodyAsText); + result = this.parseTokenResponse(opRes.bodyAsText); if (!result.tokenType) { throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`); } @@ -11071,15 +9190,12 @@ class MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCreden } prepareRequestOptions() { const endpoint = this.msiEndpoint.endsWith("/") ? this.msiEndpoint : `${this.msiEndpoint}/`; + const resource = encodeURIComponent(this.resource); + const getUrl = `${endpoint}?resource=${resource}&api-version=${this.msiApiVersion}`; const reqOptions = { - url: endpoint, + url: getUrl, headers: { - secret: this.msiSecret - }, - queryParameters: { - resource: this.resource, - "api-version": this.msiApiVersion, - clientid: this.clientId + "secret": this.msiSecret }, method: "GET" }; @@ -11111,14 +9227,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); const ms_rest_js_1 = __nccwpck_require__(30812); const authConstants_1 = __nccwpck_require__(26700); /** - * Provides information about managed service identity token credentials. + * @class MSITokenCredentials - Provides information about managed service identity token credentials. * This object can only be used to acquire token on a virtual machine provisioned in Azure with managed service identity. */ class MSITokenCredentials { /** * Creates an instance of MSITokenCredentials. - * @param options - Optional parameters - * @param options.resource - The resource uri or token audience for which the token is needed. + * @param {object} [options] - Optional parameters + * @param {string} [options.resource] - The resource uri or token audience for which the token is needed. * For e.g. it can be: * - resource management endpoint "https://management.azure.com/"(default) * - management endpoint "https://management.core.windows.net/" @@ -11138,8 +9254,8 @@ class MSITokenCredentials { /** * Parses a tokenResponse json string into a object, and converts properties on the first level to camelCase. * This method tries to standardize the tokenResponse - * @param body - A json string - * @returns The tokenResponse (tokenType and accessToken are the two important properties). + * @param {string} body A json string + * @return {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties). */ parseTokenResponse(body) { // Docs show different examples of possible MSI responses for different services. https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/overview @@ -11177,7 +9293,7 @@ class MSITokenCredentials { if (typeof parsedBody["expires_on"] === "string") { // possibly a Date string '09/14/2017 00:00:00 PM +00:00' if (parsedBody["expires_on"].includes(":") || parsedBody["expires_on"].includes("/")) { - parsedBody.expiresOn = new Date(parseInt(parsedBody["expires_on"], 10)); + parsedBody.expiresOn = new Date(parsedBody["expires_on"], 10); } else { // normal number as a string '1504130527' @@ -11191,14 +9307,14 @@ class MSITokenCredentials { /** * Signs a request with the Authentication header. * - * @param webResource - The WebResource to be signed. - * @returns Promise with signed WebResource. + * @param {webResource} The WebResource to be signed. + * @return {Promise} Promise with signed WebResource. */ signRequest(webResource) { return __awaiter(this, void 0, void 0, function* () { const tokenResponse = yield this.getToken(); webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`); - return webResource; + return Promise.resolve(webResource); }); } } @@ -11226,7 +9342,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); const msiTokenCredentials_1 = __nccwpck_require__(6182); const ms_rest_js_1 = __nccwpck_require__(30812); /** - * Provides information about managed service identity token credentials on a virtual machine provisioned in Azure. + * @class MSIVmTokenCredentials */ class MSIVmTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { constructor(options) { @@ -11261,13 +9377,15 @@ class MSIVmTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { } /** * Prepares and sends a POST request to a service endpoint hosted on the Azure VM, which responds with the access token. - * @returns Promise with the tokenResponse (tokenType and accessToken are the two important properties). + * @return {Promise} Promise with the tokenResponse (tokenType and accessToken are the two important properties). */ getToken() { return __awaiter(this, void 0, void 0, function* () { const reqOptions = this.prepareRequestOptions(); - const opRes = yield this._httpClient.sendRequest(reqOptions); - const result = this.parseTokenResponse(opRes.bodyAsText); + let opRes; + let result; + opRes = yield this._httpClient.sendRequest(reqOptions); + result = this.parseTokenResponse(opRes.bodyAsText); if (!result.tokenType) { throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`); } @@ -11282,15 +9400,15 @@ class MSIVmTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { url: this.msiEndpoint, headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", - Metadata: "true" + "Metadata": "true" }, method: this.httpMethod, queryParameters: { "api-version": this.apiVersion, - resource: this.resource, - object_id: this.objectId, - client_id: this.clientId, - mi_res_id: this.identityId + "resource": this.resource, + "object_id": this.objectId, + "client_id": this.clientId, + "mi_res_id": this.identityId } }; const webResource = new ms_rest_js_1.WebResource(); @@ -11335,17 +9453,12 @@ class TokenCredentialsBase { throw new Error("domain must be a non empty string."); } if (this.tokenAudience === "graph" && this.domain.toLowerCase() === "common") { - throw new Error(`${'If the tokenAudience is specified as "graph" then "domain" cannot be defaulted to "common" tenant.\ - It must be the actual tenant (preferably a string in a guid format).'}`); + throw new Error(`${"If the tokenAudience is specified as \"graph\" then \"domain\" cannot be defaulted to \"commmon\" tenant.\ + It must be the actual tenant (preferrably a string in a guid format)."}`); } const authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain; this.authContext = new adal_node_1.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache); } - setDomain(domain) { - this.domain = domain; - const authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain; - this.authContext = new adal_node_1.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache); - } getActiveDirectoryResourceId() { let resource = this.environment.activeDirectoryResourceId; if (this.tokenAudience) { @@ -11377,13 +9490,15 @@ class TokenCredentialsBase { /** * Signs a request with the Authentication header. * - * @param webResource - The WebResource to be signed. + * @param {webResource} The WebResource to be signed. + * @param {function(error)} callback The callback function. + * @return {undefined} */ signRequest(webResource) { return __awaiter(this, void 0, void 0, function* () { const tokenResponse = yield this.getToken(); webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`); - return webResource; + return Promise.resolve(webResource); }); } } @@ -11413,17 +9528,17 @@ class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase { /** * Creates a new UserTokenCredentials object. * - * - * @param clientId - The active directory application client id. + * @constructor + * @param {string} clientId The active directory application client id. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param domain - The domain or tenant id containing this application. - * @param username - The user name for the Organization Id account. - * @param password - The password for the Organization Id account. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} username The user name for the Organization Id account. + * @param {string} password The password for the Organization Id account. + * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). + * @param {Environment} [environment] The azure environment to authenticate with. + * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal. */ constructor(clientId, domain, username, password, tokenAudience, environment, tokenCache) { if (!clientId || typeof clientId.valueOf() !== "string") { @@ -11445,12 +9560,13 @@ class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase { crossCheckUserNameWithToken(username, userIdFromToken) { // to maintain the casing consistency between "azureprofile.json" and token cache. (RD 1996587) // use the "userId" here, which should be the same with "username" except the casing. - return username.toLowerCase() === userIdFromToken.toLowerCase(); + return (username.toLowerCase() === userIdFromToken.toLowerCase()); } /** * Tries to get the token from cache initially. If that is unsuccessful then it tries to get the token from ADAL. - * - * @returns The tokenResponse (tokenType and accessToken are the two important properties). + * @returns {Promise} + * {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties). + * @memberof UserTokenCredentials */ getToken() { return __awaiter(this, void 0, void 0, function* () { @@ -11473,7 +9589,7 @@ class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase { return resolve(tokenResponse); } else { - return reject(`The userId "${tokenResponse.userId}" in access token doesn't match the username "${self.username}" provided during authentication.`); + return reject(`The userId "${tokenResponse.userId}" in access token doesn"t match the username "${self.username}" provided during authentication.`); } }); }); @@ -11516,7 +9632,7 @@ const subscriptionUtils_1 = __nccwpck_require__(47813); const msiVmTokenCredentials_1 = __nccwpck_require__(73287); const msiAppServiceTokenCredentials_1 = __nccwpck_require__(68376); /** - * Urls for management plane token + * @constant {Array} managementPlaneTokenAudiences - Urls for management plane token * audience across different azure environments. */ const managementPlaneTokenAudiences = [ @@ -11551,21 +9667,19 @@ if (process.env["AZURE_ADAL_LOGGING_ENABLED"]) { * Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants. * This method is applicable only for organizational ids that are not 2FA enabled otherwise please use interactive login. * - * When using personal accounts, the `domain` property in the `options` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. - * - * @param username - The user name for the Organization Id account. - * @param password - The password for the Organization Id account. - * @param options - Object representing optional parameters. - * @param options.clientId - The active directory application client id. + * @param {string} username The user name for the Organization Id account. + * @param {string} password The password for the Organization Id account. + * @param {object} [options] Object representing optional parameters. + * @param {string} [options.clientId] The active directory application client id. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param options.tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param options.domain - The domain or tenant Id containing this application. Default value "common". - * @param options.environment - The azure environment to authenticate with. - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). + * @param {string} [options.domain] The domain or tenant id containing this application. Default value "common". + * @param {Environment} [options.environment] The azure environment to authenticate with. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @returns A Promise that resolves to AuthResponse, which contains `credentials` and an optional `subscriptions` array, and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withUsernamePasswordWithAuthResponse(username, password, options) { return __awaiter(this, void 0, void 0, function* () { @@ -11581,35 +9695,38 @@ function withUsernamePasswordWithAuthResponse(username, password, options) { if (!options.environment) { options.environment = ms_rest_azure_env_1.Environment.AzureCloud; } - const creds = new userTokenCredentials_1.UserTokenCredentials(options.clientId, options.domain, username, password, options.tokenAudience, options.environment, options.tokenCache); - const tokenResponse = yield creds.getToken(); - // The token cache gets propulated for all the tenants as a part of building the tenantList. - let tenantList = yield subscriptionUtils_1.buildTenantList(creds); - if (tenantList.length === 0 && tokenResponse.tenantId) { - tenantList = [tokenResponse.tenantId]; + let creds; + let tenantList = []; + let subscriptionList = []; + try { + creds = new userTokenCredentials_1.UserTokenCredentials(options.clientId, options.domain, username, password, options.tokenAudience, options.environment); + yield creds.getToken(); + // The token cache gets propulated for all the tenants as a part of building the tenantList. + tenantList = yield subscriptionUtils_1.buildTenantList(creds); + subscriptionList = yield _getSubscriptions(creds, tenantList, options.tokenAudience); + } + catch (err) { + return Promise.reject(err); } - const subscriptionList = yield _getSubscriptions(creds, tenantList, options.tokenAudience); - return { credentials: creds, subscriptions: subscriptionList }; + return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); }); } exports.withUsernamePasswordWithAuthResponse = withUsernamePasswordWithAuthResponse; /** - * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrincipalId/clientId across all the applicable tenants. + * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants. * - * When using personal accounts, the `domain` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. - * - * @param clientId - The active directory application client Id also known as the SPN (ServicePrincipal Name). + * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name). * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param secret - The application secret for the service principal. - * @param domain - The domain or tenant Id containing this application. - * @param options - Object representing optional parameters. - * @param options.tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param options.environment - The azure environment to authenticate with. - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {string} secret The application secret for the service principal. + * @param {string} domain The domain or tenant id containing this application. + * @param {object} [options] Object representing optional parameters. + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). + * @param {Environment} [options.environment] The azure environment to authenticate with. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options) { return __awaiter(this, void 0, void 0, function* () { @@ -11619,32 +9736,37 @@ function withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, op if (!options.environment) { options.environment = ms_rest_azure_env_1.Environment.AzureCloud; } - const creds = new applicationTokenCredentials_1.ApplicationTokenCredentials(clientId, domain, secret, options.tokenAudience, options.environment, options.tokenCache); - yield creds.getToken(); - const subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); - return { credentials: creds, subscriptions: subscriptionList }; + let creds; + let subscriptionList = []; + try { + creds = new applicationTokenCredentials_1.ApplicationTokenCredentials(clientId, domain, secret, options.tokenAudience, options.environment); + yield creds.getToken(); + subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); + } + catch (err) { + return Promise.reject(err); + } + return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); }); } exports.withServicePrincipalSecretWithAuthResponse = withServicePrincipalSecretWithAuthResponse; /** - * Provides an ApplicationTokenCertificateCredentials object and the list of subscriptions associated with that servicePrincipalId/clientId across all the applicable tenants. + * Provides an ApplicationTokenCertificateCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants. * - * When using personal accounts, the `domain` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. - * - * @param clientId - The active directory application client Id also known as the SPN (ServicePrincipal Name). + * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name). * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param certificateStringOrFilePath - A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example: + * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example: * - CertificateString: "-----BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n\n-----END CERTIFICATE-----\n" * - CertificateFilePath: **Absolute** file path of the .pem file. - * @param domain - The domain or tenant Id containing this application. - * @param options - Object representing optional parameters. - * @param options.tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param options.environment - The azure environment to authenticate with. - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {string} domain The domain or tenant id containing this application. + * @param {object} [options] Object representing optional parameters. + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). + * @param {Environment} [options.environment] The azure environment to authenticate with. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options) { return __awaiter(this, void 0, void 0, function* () { @@ -11654,10 +9776,17 @@ function withServicePrincipalCertificateWithAuthResponse(clientId, certificateSt if (!options.environment) { options.environment = ms_rest_azure_env_1.Environment.AzureCloud; } - const creds = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials.create(clientId, certificateStringOrFilePath, domain, options); - yield creds.getToken(); - const subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); - return { credentials: creds, subscriptions: subscriptionList }; + let creds; + let subscriptionList = []; + try { + creds = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials.create(clientId, certificateStringOrFilePath, domain, options); + yield creds.getToken(); + subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); + } + catch (err) { + return Promise.reject(err); + } + return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); }); } exports.withServicePrincipalCertificateWithAuthResponse = withServicePrincipalCertificateWithAuthResponse; @@ -11702,7 +9831,7 @@ function foundManagementEndpointUrl(authFileUrl, envUrl) { } authFileUrl = authFileUrl.endsWith("/") ? authFileUrl.slice(0, -1) : authFileUrl; envUrl = envUrl.endsWith("/") ? envUrl.slice(0, -1) : envUrl; - return authFileUrl.toLowerCase() === envUrl.toLowerCase(); + return (authFileUrl.toLowerCase() === envUrl.toLowerCase()); } /** * Before using this method please install az cli from https://github.com/Azure/azure-cli/releases. Then execute `az ad sp create-for-rbac --sdk-auth > ${yourFilename.json}`. @@ -11720,14 +9849,14 @@ function foundManagementEndpointUrl(authFileUrl, envUrl) { * the subscriptionId from the auth file to the user provided environment variable in the options * parameter or the default "AZURE_SUBSCRIPTION_ID". * - * @param options - Optional parameters - * @param options.filePath - Absolute file path to the auth file. If not provided + * @param {object} [options] - Optional parameters + * @param {string} [options.filePath] - Absolute file path to the auth file. If not provided * then please set the environment variable AZURE_AUTH_LOCATION. - * @param options.subscriptionEnvVariableName - The subscriptionId environment variable + * @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable * name. Default is "AZURE_SUBSCRIPTION_ID". - * @param optionalCallback - The optional callback. + * @param {function} [optionalCallback] The optional callback. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withAuthFileWithAuthResponse(options) { return __awaiter(this, void 0, void 0, function* () { @@ -11737,13 +9866,18 @@ function withAuthFileWithAuthResponse(options) { const subscriptionEnvVariableName = options.subscriptionEnvVariableName || "AZURE_SUBSCRIPTION_ID"; if (!filePath) { const msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${authConstants_1.AuthConstants.AZURE_AUTH_LOCATION}.`; - throw new Error(msg); + return Promise.reject(new Error(msg)); } let content, credsObj = {}; const optionsForSp = {}; - content = fs_1.readFileSync(filePath, { encoding: "utf8" }); - credsObj = JSON.parse(content); - validateAuthFileContent(credsObj, filePath); + try { + content = fs_1.readFileSync(filePath, { encoding: "utf8" }); + credsObj = JSON.parse(content); + validateAuthFileContent(credsObj, filePath); + } + catch (err) { + return Promise.reject(err); + } if (!credsObj.managementEndpointUrl) { credsObj.managementEndpointUrl = credsObj.resourceManagerEndpointUrl; } @@ -11776,7 +9910,7 @@ function withAuthFileWithAuthResponse(options) { const keys = Object.keys(credsObj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; - if (key.match(/^(clientId|clientSecret|clientCertificate|subscriptionId|tenantId)$/gi) === null) { + if (key.match(/^(clientId|clientSecret|clientCertificate|subscriptionId|tenantId)$/ig) === null) { if (key === "activeDirectoryEndpointUrl" && !key.endsWith("/")) { envParams[key] = credsObj[key] + "/"; } @@ -11801,36 +9935,38 @@ function withAuthFileWithAuthResponse(options) { } exports.withAuthFileWithAuthResponse = withAuthFileWithAuthResponse; /** - * Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants. + * Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a + * DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants. * - * When using personal accounts, the `domain` property in the `options` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. + * @param {object} [options] Object representing optional parameters. * - * @param options - Object representing optional parameters. - * - * @param options.clientId - The active directory application client id. + * @param {string} [options.clientId] The active directory application client id. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. * - * @param options.tokenAudience - The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided - * then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferably in a guid format). + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided + * then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format). * - * @param options.domain - The domain or tenant Id containing this application. Default value is "common". + * @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common". * - * @param options.environment - The azure environment to authenticate with. Default environment is "Public Azure". + * @param {Environment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure". * - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @param options.language - The language code specifying how the message should be localized to. Default value "en-us". + * @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us". * - * @param options.userCodeResponseLogger - A logger that logs the user code response message required for interactive login. When + * @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When * this option is specified the usercode response message will not be logged to console. * - * @param optionalCallback - The optional callback. + * @param {function} [optionalCallback] The optional callback. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withInteractiveWithAuthResponse(options) { return __awaiter(this, void 0, void 0, function* () { + if (!options) { + options = {}; + } if (!options) { options = {}; } @@ -11863,6 +9999,8 @@ function withInteractiveWithAuthResponse(options) { const authorityUrl = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain; const authContext = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache); interactiveOptions.context = authContext; + let userCodeResponse; + let creds; function tryAcquireToken(interactiveOptions, resolve, reject) { authContext.acquireUserCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, interactiveOptions.language, (err, userCodeRes) => { if (err) { @@ -11872,44 +10010,46 @@ function withInteractiveWithAuthResponse(options) { }, 1000); } else { - reject(err); + return reject(err); } - return; } + userCodeResponse = userCodeRes; if (interactiveOptions.userCodeResponseLogger) { - interactiveOptions.userCodeResponseLogger(userCodeRes.message); + interactiveOptions.userCodeResponseLogger(userCodeResponse.message); } else { - console.log(userCodeRes.message); + console.log(userCodeResponse.message); } - return resolve(userCodeRes); + return resolve(userCodeResponse); }); } const getUserCode = new Promise((resolve, reject) => { return tryAcquireToken(interactiveOptions, resolve, reject); }); - const userCodeResponse = yield getUserCode; - const creds = yield new Promise((resolve, reject) => { - return authContext.acquireTokenWithDeviceCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, userCodeResponse, (error, tokenResponse) => { - if (error) { - return reject(error); - } - const response = tokenResponse; - interactiveOptions.userName = response.userId; - interactiveOptions.authorizationScheme = response.tokenType; - let creds; - try { - creds = new deviceTokenCredentials_1.DeviceTokenCredentials(interactiveOptions.clientId, interactiveOptions.domain, interactiveOptions.userName, interactiveOptions.tokenAudience, interactiveOptions.environment, interactiveOptions.tokenCache); - } - catch (err) { - return reject(err); - } - return resolve(creds); + return getUserCode.then(() => { + return new Promise((resolve, reject) => { + return authContext.acquireTokenWithDeviceCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, userCodeResponse, (error, tokenResponse) => { + if (error) { + return reject(error); + } + interactiveOptions.userName = tokenResponse.userId; + interactiveOptions.authorizationScheme = tokenResponse.tokenType; + try { + creds = new deviceTokenCredentials_1.DeviceTokenCredentials(interactiveOptions.clientId, interactiveOptions.domain, interactiveOptions.userName, interactiveOptions.tokenAudience, interactiveOptions.environment, interactiveOptions.tokenCache); + } + catch (err) { + return reject(err); + } + return resolve(creds); + }); }); + }).then((creds) => { + return subscriptionUtils_1.buildTenantList(creds); + }).then((tenants) => { + return _getSubscriptions(creds, tenants, interactiveOptions.tokenAudience); + }).then((subscriptions) => { + return Promise.resolve({ credentials: creds, subscriptions: subscriptions }); }); - const tenants = yield subscriptionUtils_1.buildTenantList(creds); - const subscriptions = yield _getSubscriptions(creds, tenants, interactiveOptions.tokenAudience); - return { credentials: creds, subscriptions: subscriptions }; }); } exports.withInteractiveWithAuthResponse = withInteractiveWithAuthResponse; @@ -11921,7 +10061,9 @@ function withAuthFile(options, callback) { const cb = callback; if (!callback) { return withAuthFileWithAuthResponse(options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -11942,7 +10084,9 @@ function interactive(options, callback) { const cb = callback; if (!callback) { return withInteractiveWithAuthResponse(options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -11963,7 +10107,9 @@ function withServicePrincipalSecret(clientId, secret, domain, options, callback) const cb = callback; if (!callback) { return withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -11984,7 +10130,9 @@ function withServicePrincipalCertificate(clientId, certificateStringOrFilePath, const cb = callback; if (!callback) { return withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -12005,7 +10153,9 @@ function withUsernamePassword(username, password, options, callback) { const cb = callback; if (!callback) { return withUsernamePasswordWithAuthResponse(username, password, options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -12023,31 +10173,33 @@ exports.withUsernamePassword = withUsernamePassword; */ function _getSubscriptions(creds, tenants, tokenAudience) { if (tokenAudience && - !managementPlaneTokenAudiences.some((item) => { - return item === tokenAudience.toLowerCase(); - })) { - return Promise.resolve([]); + !managementPlaneTokenAudiences.some((item) => { return item === tokenAudience.toLowerCase(); })) { + return Promise.resolve(([])); } return subscriptionUtils_1.getSubscriptionsFromTenants(creds, tenants); } /** * Initializes MSITokenCredentials class and calls getToken and returns a token response. * - * @param domain - - required. The tenant id. - * @param options - - Optional parameters - * @param options.port - port on which the MSI service is running on the host VM. Default port is 50342 - * @param options.resource - The resource uri or token audience for which the token is needed. Default - "https://management.azure.com/" - * @param options.aadEndpoint - The add endpoint for authentication. default - "https://login.microsoftonline.com" - * @param callback - - the callback function. + * @param {string} domain - required. The tenant id. + * @param {object} options - Optional parameters + * @param {string} [options.port] - port on which the MSI service is running on the host VM. Default port is 50342 + * @param {string} [options.resource] - The resource uri or token audience for which the token is needed. Default - "https://management.azure.com/" + * @param {string} [options.aadEndpoint] - The add endpoint for authentication. default - "https://login.microsoftonline.com" + * @param {any} callback - the callback function. */ function _withMSI(options) { - return __awaiter(this, void 0, void 0, function* () { - if (!options) { - options = {}; - } + if (!options) { + options = {}; + } + return new Promise((resolve, reject) => { const creds = new msiVmTokenCredentials_1.MSIVmTokenCredentials(options); - yield creds.getToken(); - return creds; + creds.getToken().then((_tokenResponse) => { + // We ignore the token response, it's put in the cache. + return resolve(creds); + }).catch(error => { + reject(error); + }); }); } function loginWithVmMSI(options, callback) { @@ -12073,13 +10225,17 @@ exports.loginWithVmMSI = loginWithVmMSI; * Private method */ function _withAppServiceMSI(options) { - return __awaiter(this, void 0, void 0, function* () { - if (!options) { - options = {}; - } + if (!options) { + options = {}; + } + return new Promise((resolve, reject) => { const creds = new msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials(options); - yield creds.getToken(); - return creds; + creds.getToken().then((_tokenResponse) => { + // We ignore the token response, it's put in the cache. + return resolve(creds); + }).catch(error => { + reject(error); + }); }); } function loginWithAppServiceMSI(options, callback) { @@ -12104,13 +10260,12 @@ exports.loginWithAppServiceMSI = loginWithAppServiceMSI; /** * Executes the azure cli command and returns the result. It will be `undefined` if the command did * not return anything or a `JSON object` if the command did return something. - * @param cmdArguments Arguments to the az cli command to execute. + * @param cmd The az cli command to execute. */ -function execAz(cmdArguments) { +function execAz(cmd) { return __awaiter(this, void 0, void 0, function* () { - const azCmd = process.platform === "win32" ? "az.cmd" : "az"; return new Promise((resolve, reject) => { - child_process_1.execFile(azCmd, [...cmdArguments, "--out", "json"], { encoding: "utf8" }, (error, stdout) => { + child_process_1.exec(`az ${cmd} --out json`, { encoding: "utf8" }, (error, stdout) => { if (error) { return reject(error); } @@ -12119,8 +10274,8 @@ function execAz(cmdArguments) { return resolve(JSON.parse(stdout)); } catch (err) { - const msg = `An error occurred while parsing the output "${stdout}", of ` + - `the cmd az "${cmdArguments}": ${err.stack}.`; + const msg = `An error occured while parsing the output "${stdout}", of ` + + `the cmd "${cmd}": ${err.stack}.`; return reject(new Error(msg)); } } @@ -12162,8 +10317,6 @@ var userTokenCredentials_1 = __nccwpck_require__(14502); exports.UserTokenCredentials = userTokenCredentials_1.UserTokenCredentials; var authConstants_1 = __nccwpck_require__(26700); exports.AuthConstants = authConstants_1.AuthConstants; -var subscriptionUtils_1 = __nccwpck_require__(47813); -exports.buildTenantList = subscriptionUtils_1.buildTenantList; var azureCliCredentials_1 = __nccwpck_require__(38909); exports.AzureCliCredentials = azureCliCredentials_1.AzureCliCredentials; var login_1 = __nccwpck_require__(29325); @@ -12204,31 +10357,35 @@ const applicationTokenCredentialsBase_1 = __nccwpck_require__(60968); const authConstants_1 = __nccwpck_require__(26700); /** * Builds an array of tenantIds. - * @param credentials - The credentials. - * @param apiVersion - default value 2016-06-01 - * @returns A promise that resolves to an array of tenantIds and rejects with an error. + * @param {TokenCredentialsBase} credentials The credentials. + * @param {string} apiVersion default value 2016-06-01 + * @returns {Promise} resolves to an array of tenantIds and rejects with an error. */ function buildTenantList(credentials, apiVersion = "2016-06-01") { return __awaiter(this, void 0, void 0, function* () { if (credentials.domain && credentials.domain !== authConstants_1.AuthConstants.AAD_COMMON_TENANT) { - return [credentials.domain]; + return Promise.resolve([credentials.domain]); } const client = new msRest.ServiceClient(credentials); const baseUrl = credentials.environment.resourceManagerEndpointUrl; const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}tenants?api-version=${apiVersion}`; const req = { url: reqUrl, - method: "GET" + method: "GET", }; - const res = yield client.sendRequest(req); + let res; + try { + res = yield client.sendRequest(req); + } + catch (err) { + return Promise.reject(err); + } const result = []; - if (res.status < 300) { - const tenants = res.parsedBody; - for (const tenant of tenants.value) { - result.push(tenant.tenantId); - } + const tenants = res.parsedBody; + for (const tenant in tenants.value) { + result.push(tenant.tenantId); } - return result; + return Promise.resolve(result); }); } exports.buildTenantList = buildTenantList; @@ -12252,9 +10409,15 @@ function getSubscriptionsFromTenants(credentials, tenantList, apiVersion = "2016 const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}subscriptions?api-version=${apiVersion}`; const req = { url: reqUrl, - method: "GET" + method: "GET", }; - const res = yield client.sendRequest(req); + let res; + try { + res = yield client.sendRequest(req); + } + catch (err) { + return Promise.reject(err); + } const subscriptionList = res.parsedBody.value; subscriptions = subscriptions.concat(subscriptionList.map((s) => { s.tenantId = tenant; @@ -12270,7 +10433,7 @@ function getSubscriptionsFromTenants(credentials, tenantList, apiVersion = "2016 } // Reset the original domain. credentials.domain = originalDomain; - return subscriptions; + return Promise.resolve(subscriptions); }); } exports.getSubscriptionsFromTenants = getSubscriptionsFromTenants; @@ -12287,175391 +10450,179454 @@ exports.getSubscriptionsFromTenants = getSubscriptionsFromTenants; // Licensed under the MIT License. See License.txt in the project root for license information. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AuthConstants = { - AAD_COMMON_TENANT: "common", - DEFAULT_ADAL_CLIENT_ID: "04b07795-8ddb-461a-bbee-02f9e1bf7b46", - SDK_INTERNAL_ERROR: "SDK_INTERNAL_ERROR", - DEFAULT_LANGUAGE: "en-us", - AZURE_AUTH_LOCATION: "AZURE_AUTH_LOCATION", - RESOURCE_MANAGER_ENDPOINT: "https://management.azure.com/" + "AAD_COMMON_TENANT": "common", + "DEFAULT_ADAL_CLIENT_ID": "04b07795-8ddb-461a-bbee-02f9e1bf7b46", + "SDK_INTERNAL_ERROR": "SDK_INTERNAL_ERROR", + "DEFAULT_LANGUAGE": "en-us", + "AZURE_AUTH_LOCATION": "AZURE_AUTH_LOCATION", + "RESOURCE_MANAGER_ENDPOINT": "https://management.azure.com/" }; //# sourceMappingURL=authConstants.js.map /***/ }), -/***/ 22709: -/***/ (function(__unused_webpack_module, exports) { - -//! @version @js-joda/core - 3.2.0 -//! @copyright (c) 2015-present, Philipp Thürwächter, Pattrick Hüper & js-joda contributors -//! @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos -//! @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - function createErrorType(name, init, superErrorClass) { - if (superErrorClass === void 0) { - superErrorClass = Error; - } - - function JsJodaException(message) { - if (!Error.captureStackTrace) { - this.stack = new Error().stack; - } else { - Error.captureStackTrace(this, this.constructor); - } - - this.message = message; - init && init.apply(this, arguments); - - this.toString = function () { - return this.name + ": " + this.message; - }; - } - - JsJodaException.prototype = Object.create(superErrorClass.prototype); - JsJodaException.prototype.name = name; - JsJodaException.prototype.constructor = JsJodaException; - return JsJodaException; - } - - var DateTimeException = createErrorType('DateTimeException', messageWithCause); - var DateTimeParseException = createErrorType('DateTimeParseException', messageForDateTimeParseException); - var UnsupportedTemporalTypeException = createErrorType('UnsupportedTemporalTypeException', null, DateTimeException); - var ArithmeticException = createErrorType('ArithmeticException'); - var IllegalArgumentException = createErrorType('IllegalArgumentException'); - var IllegalStateException = createErrorType('IllegalStateException'); - var NullPointerException = createErrorType('NullPointerException'); - - function messageWithCause(message, cause) { - if (cause === void 0) { - cause = null; - } - - var msg = message || this.name; - - if (cause !== null && cause instanceof Error) { - msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n'; - } - - this.message = msg; - } - - function messageForDateTimeParseException(message, text, index, cause) { - if (text === void 0) { - text = ''; - } - - if (index === void 0) { - index = 0; - } - - if (cause === void 0) { - cause = null; - } - - var msg = message || this.name; - msg += ': ' + text + ', at index: ' + index; - - if (cause !== null && cause instanceof Error) { - msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n'; - } +/***/ 48566: +/***/ ((module, exports) => { - this.message = msg; +module.exports = exports = abbrev.abbrev = abbrev - this.parsedString = function () { - return text; - }; +abbrev.monkeyPatch = monkeyPatch - this.errorIndex = function () { - return index; - }; - } +function monkeyPatch () { + Object.defineProperty(Array.prototype, 'abbrev', { + value: function () { return abbrev(this) }, + enumerable: false, configurable: true, writable: true + }) - function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; - } + Object.defineProperty(Object.prototype, 'abbrev', { + value: function () { return abbrev(Object.keys(this)) }, + enumerable: false, configurable: true, writable: true + }) +} - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } +function abbrev (list) { + if (arguments.length !== 1 || !Array.isArray(list)) { + list = Array.prototype.slice.call(arguments, 0) + } + for (var i = 0, l = list.length, args = [] ; i < l ; i ++) { + args[i] = typeof list[i] === "string" ? list[i] : String(list[i]) + } - return self; - } + // sort them lexicographically, so that they're next to their nearest kin + args = args.sort(lexSort) - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - function assert(assertion, msg, error) { - if (!assertion) { - if (error) { - throw new error(msg); - } else { - throw new Error(msg); - } - } - } - function requireNonNull(value, parameterName) { - if (value == null) { - throw new NullPointerException(parameterName + ' must not be null'); + // walk through each, seeing how much it has in common with the next and previous + var abbrevs = {} + , prev = "" + for (var i = 0, l = args.length ; i < l ; i ++) { + var current = args[i] + , next = args[i + 1] || "" + , nextMatches = true + , prevMatches = true + if (current === next) continue + for (var j = 0, cl = current.length ; j < cl ; j ++) { + var curChar = current.charAt(j) + nextMatches = nextMatches && curChar === next.charAt(j) + prevMatches = prevMatches && curChar === prev.charAt(j) + if (!nextMatches && !prevMatches) { + j ++ + break } - - return value; } - function requireInstance(value, _class, parameterName) { - if (!(value instanceof _class)) { - throw new IllegalArgumentException(parameterName + ' must be an instance of ' + (_class.name ? _class.name : _class) + (value && value.constructor && value.constructor.name ? ', but is ' + value.constructor.name : '')); - } - - return value; + prev = current + if (j === cl) { + abbrevs[current] = current + continue } - function abstractMethodFail(methodName) { - throw new TypeError('abstract method "' + methodName + '" is not implemented'); + for (var a = current.substr(0, j) ; j <= cl ; j ++) { + abbrevs[a] = current + a += current.charAt(j) } + } + return abbrevs +} - var assert$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - assert: assert, - requireNonNull: requireNonNull, - requireInstance: requireInstance, - abstractMethodFail: abstractMethodFail - }); - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var MAX_SAFE_INTEGER = 9007199254740991; - var MIN_SAFE_INTEGER = -9007199254740991; - var MathUtil = function () { - function MathUtil() {} - - MathUtil.intDiv = function intDiv(x, y) { - var r = x / y; - r = MathUtil.roundDown(r); - return MathUtil.safeZero(r); - }; - - MathUtil.intMod = function intMod(x, y) { - var r = x - MathUtil.intDiv(x, y) * y; - r = MathUtil.roundDown(r); - return MathUtil.safeZero(r); - }; - - MathUtil.roundDown = function roundDown(r) { - if (r < 0) { - return Math.ceil(r); - } else { - return Math.floor(r); - } - }; - - MathUtil.floorDiv = function floorDiv(x, y) { - var r = Math.floor(x / y); - return MathUtil.safeZero(r); - }; - - MathUtil.floorMod = function floorMod(x, y) { - var r = x - MathUtil.floorDiv(x, y) * y; - return MathUtil.safeZero(r); - }; - - MathUtil.safeAdd = function safeAdd(x, y) { - MathUtil.verifyInt(x); - MathUtil.verifyInt(y); - - if (x === 0) { - return MathUtil.safeZero(y); - } - - if (y === 0) { - return MathUtil.safeZero(x); - } - - var r = MathUtil.safeToInt(x + y); - - if (r === x || r === y) { - throw new ArithmeticException('Invalid addition beyond MAX_SAFE_INTEGER!'); - } - - return r; - }; - - MathUtil.safeSubtract = function safeSubtract(x, y) { - MathUtil.verifyInt(x); - MathUtil.verifyInt(y); - - if (x === 0 && y === 0) { - return 0; - } else if (x === 0) { - return MathUtil.safeZero(-1 * y); - } else if (y === 0) { - return MathUtil.safeZero(x); - } - - return MathUtil.safeToInt(x - y); - }; - - MathUtil.safeMultiply = function safeMultiply(x, y) { - MathUtil.verifyInt(x); - MathUtil.verifyInt(y); - - if (x === 1) { - return MathUtil.safeZero(y); - } - - if (y === 1) { - return MathUtil.safeZero(x); - } - - if (x === 0 || y === 0) { - return 0; - } - - var r = MathUtil.safeToInt(x * y); - - if (r / y !== x || x === MIN_SAFE_INTEGER && y === -1 || y === MIN_SAFE_INTEGER && x === -1) { - throw new ArithmeticException('Multiplication overflows: ' + x + ' * ' + y); - } - - return r; - }; - - MathUtil.parseInt = function (_parseInt) { - function parseInt(_x) { - return _parseInt.apply(this, arguments); - } - - parseInt.toString = function () { - return _parseInt.toString(); - }; - - return parseInt; - }(function (value) { - var r = parseInt(value); - return MathUtil.safeToInt(r); - }); - - MathUtil.safeToInt = function safeToInt(value) { - MathUtil.verifyInt(value); - return MathUtil.safeZero(value); - }; - - MathUtil.verifyInt = function verifyInt(value) { - if (value == null) { - throw new ArithmeticException("Invalid value: '" + value + "', using null or undefined as argument"); - } - - if (isNaN(value)) { - throw new ArithmeticException('Invalid int value, using NaN as argument'); - } - - if (value % 1 !== 0) { - throw new ArithmeticException("Invalid value: '" + value + "' is a float"); - } - - if (value > MAX_SAFE_INTEGER || value < MIN_SAFE_INTEGER) { - throw new ArithmeticException('Calculation overflows an int: ' + value); - } - }; - - MathUtil.safeZero = function safeZero(value) { - return value === 0 ? 0 : +value; - }; - - MathUtil.compareNumbers = function compareNumbers(a, b) { - if (a < b) { - return -1; - } - - if (a > b) { - return 1; - } - - return 0; - }; - - MathUtil.smi = function smi(int) { - return int >>> 1 & 0x40000000 | int & 0xBFFFFFFF; - }; - - MathUtil.hash = function hash(number) { - if (number !== number || number === Infinity) { - return 0; - } - - var result = number; - - while (number > 0xFFFFFFFF) { - number /= 0xFFFFFFFF; - result ^= number; - } - - return MathUtil.smi(result); - }; - - MathUtil.hashCode = function hashCode() { - var result = 17; - - for (var _len = arguments.length, numbers = new Array(_len), _key = 0; _key < _len; _key++) { - numbers[_key] = arguments[_key]; - } - - for (var _i = 0, _numbers = numbers; _i < _numbers.length; _i++) { - var n = _numbers[_i]; - result = (result << 5) - result + MathUtil.hash(n); - } - - return MathUtil.hash(result); - }; - - return MathUtil; - }(); - MathUtil.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER; - MathUtil.MIN_SAFE_INTEGER = MIN_SAFE_INTEGER; - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var Enum = function () { - function Enum(name) { - this._name = name; - } - - var _proto = Enum.prototype; - - _proto.equals = function equals(other) { - return this === other; - }; - - _proto.toString = function toString() { - return this._name; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return Enum; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalAmount = function () { - function TemporalAmount() {} - - var _proto = TemporalAmount.prototype; - - _proto.get = function get(unit) { - abstractMethodFail('get'); - }; - - _proto.units = function units() { - abstractMethodFail('units'); - }; - - _proto.addTo = function addTo(temporal) { - abstractMethodFail('addTo'); - }; - - _proto.subtractFrom = function subtractFrom(temporal) { - abstractMethodFail('subtractFrom'); - }; - - return TemporalAmount; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalUnit = function () { - function TemporalUnit() {} - - var _proto = TemporalUnit.prototype; - - _proto.duration = function duration() { - abstractMethodFail('duration'); - }; - - _proto.isDurationEstimated = function isDurationEstimated() { - abstractMethodFail('isDurationEstimated'); - }; - - _proto.isDateBased = function isDateBased() { - abstractMethodFail('isDateBased'); - }; - - _proto.isTimeBased = function isTimeBased() { - abstractMethodFail('isTimeBased'); - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - abstractMethodFail('isSupportedBy'); - }; - - _proto.addTo = function addTo(dateTime, periodToAdd) { - abstractMethodFail('addTo'); - }; - - _proto.between = function between(temporal1, temporal2) { - abstractMethodFail('between'); - }; - - return TemporalUnit; - }(); - - var Duration = function (_TemporalAmount) { - _inheritsLoose(Duration, _TemporalAmount); - - function Duration(seconds, nanos) { - var _this; - - _this = _TemporalAmount.call(this) || this; - _this._seconds = MathUtil.safeToInt(seconds); - _this._nanos = MathUtil.safeToInt(nanos); - return _this; - } - - Duration.ofDays = function ofDays(days) { - return Duration._create(MathUtil.safeMultiply(days, LocalTime.SECONDS_PER_DAY), 0); - }; - - Duration.ofHours = function ofHours(hours) { - return Duration._create(MathUtil.safeMultiply(hours, LocalTime.SECONDS_PER_HOUR), 0); - }; - - Duration.ofMinutes = function ofMinutes(minutes) { - return Duration._create(MathUtil.safeMultiply(minutes, LocalTime.SECONDS_PER_MINUTE), 0); - }; - - Duration.ofSeconds = function ofSeconds(seconds, nanoAdjustment) { - if (nanoAdjustment === void 0) { - nanoAdjustment = 0; - } - - var secs = MathUtil.safeAdd(seconds, MathUtil.floorDiv(nanoAdjustment, LocalTime.NANOS_PER_SECOND)); - var nos = MathUtil.floorMod(nanoAdjustment, LocalTime.NANOS_PER_SECOND); - return Duration._create(secs, nos); - }; - - Duration.ofMillis = function ofMillis(millis) { - var secs = MathUtil.intDiv(millis, 1000); - var mos = MathUtil.intMod(millis, 1000); - - if (mos < 0) { - mos += 1000; - secs--; - } - - return Duration._create(secs, mos * 1000000); - }; - - Duration.ofNanos = function ofNanos(nanos) { - var secs = MathUtil.intDiv(nanos, LocalTime.NANOS_PER_SECOND); - var nos = MathUtil.intMod(nanos, LocalTime.NANOS_PER_SECOND); - - if (nos < 0) { - nos += LocalTime.NANOS_PER_SECOND; - secs--; - } - - return this._create(secs, nos); - }; - - Duration.of = function of(amount, unit) { - return Duration.ZERO.plus(amount, unit); - }; - - Duration.from = function from(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount); - var duration = Duration.ZERO; - amount.units().forEach(function (unit) { - duration = duration.plus(amount.get(unit), unit); - }); - return duration; - }; - - Duration.between = function between(startInclusive, endExclusive) { - requireNonNull(startInclusive, 'startInclusive'); - requireNonNull(endExclusive, 'endExclusive'); - var secs = startInclusive.until(endExclusive, ChronoUnit.SECONDS); - var nanos = 0; - - if (startInclusive.isSupported(ChronoField.NANO_OF_SECOND) && endExclusive.isSupported(ChronoField.NANO_OF_SECOND)) { - try { - var startNos = startInclusive.getLong(ChronoField.NANO_OF_SECOND); - nanos = endExclusive.getLong(ChronoField.NANO_OF_SECOND) - startNos; - - if (secs > 0 && nanos < 0) { - nanos += LocalTime.NANOS_PER_SECOND; - } else if (secs < 0 && nanos > 0) { - nanos -= LocalTime.NANOS_PER_SECOND; - } else if (secs === 0 && nanos !== 0) { - var adjustedEnd = endExclusive.with(ChronoField.NANO_OF_SECOND, startNos); - secs = startInclusive.until(adjustedEnd, ChronoUnit.SECONDS); - } - } catch (e) {} - } - - return this.ofSeconds(secs, nanos); - }; - - Duration.parse = function parse(text) { - requireNonNull(text, 'text'); - var PATTERN = new RegExp('([-+]?)P(?:([-+]?[0-9]+)D)?(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?', 'i'); - var matches = PATTERN.exec(text); - - if (matches !== null) { - if ('T' === matches[3] === false) { - var negate = '-' === matches[1]; - var dayMatch = matches[2]; - var hourMatch = matches[4]; - var minuteMatch = matches[5]; - var secondMatch = matches[6]; - var fractionMatch = matches[7]; - - if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) { - var daysAsSecs = Duration._parseNumber(text, dayMatch, LocalTime.SECONDS_PER_DAY, 'days'); - - var hoursAsSecs = Duration._parseNumber(text, hourMatch, LocalTime.SECONDS_PER_HOUR, 'hours'); - - var minsAsSecs = Duration._parseNumber(text, minuteMatch, LocalTime.SECONDS_PER_MINUTE, 'minutes'); - - var seconds = Duration._parseNumber(text, secondMatch, 1, 'seconds'); - - var negativeSecs = secondMatch != null && secondMatch.charAt(0) === '-'; +function lexSort (a, b) { + return a === b ? 0 : a > b ? 1 : -1 +} - var nanos = Duration._parseFraction(text, fractionMatch, negativeSecs ? -1 : 1); - try { - return Duration._create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos); - } catch (ex) { - throw new DateTimeParseException('Text cannot be parsed to a Duration: overflow', text, 0, ex); - } - } - } - } +/***/ }), - throw new DateTimeParseException('Text cannot be parsed to a Duration', text, 0); - }; +/***/ 35894: +/***/ ((module, exports, __nccwpck_require__) => { - Duration._parseNumber = function _parseNumber(text, parsed, multiplier, errorText) { - if (parsed == null) { - return 0; - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); + +var ac = __nccwpck_require__(69775); +var authParams = __nccwpck_require__(74854); +var logging = __nccwpck_require__(92288); +var MemoryCache = __nccwpck_require__(92474); + +exports = {}; + +exports.Logging = logging.Logging; +exports.AuthenticationContext = ac.AuthenticationContext; +exports.setGlobalADALOptions = ac.setGlobalADALOptions; +exports.getGlobalADALOptions = ac.getGlobalADALOptions; +exports.MemoryCache = MemoryCache; +_.extend(exports, authParams); + +/** + * Creates a new AuthenticationContext object. By default the authority will be checked against + * a list of known Azure Active Directory authorities. If the authority is not recognized as + * one of these well known authorities then token acquisition will fail. This behavior can be + * turned off via the validateAuthority parameter below. + * @function + * @param {string} authority A URL that identifies a token authority. + * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. + * @returns {AuthenticationContext} A new authentication context. + */ +exports.createAuthenticationContext = function(authority, validateAuthority) { + return new ac.AuthenticationContext(authority, validateAuthority); +}; + +module.exports = exports; - try { - if (parsed[0] === '+') { - parsed = parsed.substring(1); - } - return MathUtil.safeMultiply(parseFloat(parsed), multiplier); - } catch (ex) { - throw new DateTimeParseException('Text cannot be parsed to a Duration: ' + errorText, text, 0, ex); - } - }; +/***/ }), - Duration._parseFraction = function _parseFraction(text, parsed, negate) { - if (parsed == null || parsed.length === 0) { - return 0; - } +/***/ 62432: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - parsed = (parsed + '000000000').substring(0, 9); - return parseFloat(parsed) * negate; - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var constants = __nccwpck_require__(10282); + +var UserCodeResponseFields = constants.UserCodeResponseFields; + +var argumentValidation = { + /** + * Throws if the passed in parameter is not a string. + * @param {string} param The parameter to validate. + * @param {string} name The name of the parameter being validated. + * @throws {Error} If the parameter is not a valid string. + */ + validateStringParameter : function(param, name) { + if (!param) { + throw new Error('The ' + name + ' parameter is required.'); + } + if (!_.isString(param)) { + throw new Error('The ' + name + ' parameter must be of type String.'); + } + }, + + /** + * Validates that the callback passed in {@link AuthenticationContext.acquireToken} is a function + * @param {AcquireTokenCallback} callback + * @throws {Error} If the callback parameter is not a function + */ + validateCallbackType : function(callback) { + if (!callback || !_.isFunction(callback)) { + throw new Error('acquireToken requires a function callback parameter.'); + } + }, + + validateUserCodeInfo : function(userCodeInfo) { + if (!userCodeInfo){ + throw new Error('The userCodeInfo parameter is required'); + } + + if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.DEVICE_CODE)){ + throw new Error('The userCodeInfo is missing device_code'); + } + + if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.INTERVAL)){ + throw new Error('The userCodeInfo is missing interval'); + } + + if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.EXPIRES_IN)){ + throw new Error('The userCodeInfo is missing expires_in'); + } + } +}; + +module.exports = argumentValidation; - Duration._create = function _create() { - if (arguments.length <= 2) { - return Duration._createSecondsNanos(arguments[0], arguments[1]); - } else { - return Duration._createNegateDaysHoursMinutesSecondsNanos(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); - } - }; - Duration._createNegateDaysHoursMinutesSecondsNanos = function _createNegateDaysHoursMinutesSecondsNanos(negate, daysAsSecs, hoursAsSecs, minsAsSecs, secs, nanos) { - var seconds = MathUtil.safeAdd(daysAsSecs, MathUtil.safeAdd(hoursAsSecs, MathUtil.safeAdd(minsAsSecs, secs))); +/***/ }), - if (negate) { - return Duration.ofSeconds(seconds, nanos).negated(); - } +/***/ 69775: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return Duration.ofSeconds(seconds, nanos); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var argument = __nccwpck_require__(62432); +var Authority = __nccwpck_require__(19270)/* .Authority */ .W; +var TokenRequest = __nccwpck_require__(21178); +var CodeRequest = __nccwpck_require__(66576); +var createLogContext = __nccwpck_require__(92288).createLogContext; +var MemoryCache = __nccwpck_require__(92474); +var util = __nccwpck_require__(5336); +var constants = __nccwpck_require__(10282); + +var globalADALOptions = {}; +var globalCache = new MemoryCache(); + + +/** + * This function is used to add or remove entries from a TokenCache + * @typedef {function} ModifyCacheFunction + * @param {Array} entries An array of entries to either add or remove from the TokenCache + * @param {function} callback A callback function to call when the add or remove operation is complete. + * This function can take a single error argument. + */ + +/** + * This function is called by a TokenCache when a find operation completes. + * @callback TokenCacheFindCallback + * @param {Error} [err] If an error occurred during the find operation then it should be passed here. + * @param {Array} [entries] If the find operation was succesful then the matched entries should be returned here. + */ + +/** + * This function is called by ADAL to query a TokenCache. The query parameter is + * a flat object which must be compared against entries in the cache. An entry + * matches if it has all of the fields in the query and the values of those fields match + * the values in the query. A matched object may have more fields than the query object. + * @typedef {function} FindCacheFunction + * @param {object} query This object should be compared to cache entries and matches should be returned. + * @param {TokenCacheFindCallback} callback This callback should be called when the find operation is complete. + */ + +/** + * This is an interface that can be implemented to provide custom token cache persistence. + * @public + * @class TokenCache + * @property {ModifyCacheFunction} add Called by ADAL when entries should be added to the cache. + * @property {ModifyCacheFunction} remove Called by ADAL when entries should be removed from the cache. + * @property {FindCacheFunction} find Called when ADAL needs to find entries in the cache. + */ + + +/** + * Creates a new AuthenticationContext object. By default the authority will be checked against + * a list of known Azure Active Directory authorities. If the authority is not recognized as + * one of these well known authorities then token acquisition will fail. This behavior can be + * turned off via the validateAuthority parameter below. + * @constructor + * @param {string} authority A URL that identifies a token authority. + * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. + * @param {TokenCache} [cache] Sets the token cache used by this AuthenticationContext instance. If this parameter is not set + * then a default, in memory cache is used. The default in memory cache is global to the process and is + * shared by all AuthenticationContexts that are created with an empty cache parameter. To control the + * scope and lifetime of a cache you can either create a {@link MemoryCache} instance and pass it when + * constructing an AuthenticationContext or implement a custom {@link TokenCache} and pass that. Cache + * instances passed at AuthenticationContext construction time are only used by that instance of + * the AuthenticationContext and are not shared unless it has been manually passed during the + * construction of other AuthenticationContexts. + * + */ +function AuthenticationContext(authority, validateAuthority, cache) { + var validate = (validateAuthority === undefined || validateAuthority === null || validateAuthority); + + this._authority = new Authority(authority, validate); + this._oauth2client = null; + this._correlationId = null; + this._callContext = { options : globalADALOptions }; + this._cache = cache || globalCache; + this._tokenRequestWithUserCode = {}; +} + +/** + * Gets the authority url this AuthenticationContext was constructed with. + * @instance + * @memberOf AuthenticationContext + * @type {string} + * @name authority + */ +Object.defineProperty(AuthenticationContext.prototype, 'authority', { + get: function () { + return this._authority.url; + } +}); + +/** + * Gets/Sets the correlation id that will be used for the next acquireToken request. + * @instance + * @memberOf AuthenticationContext + * @type {string} + * @name correlationId + */ +Object.defineProperty(AuthenticationContext.prototype, 'correlationId', { + get: function () { + return this._correlationId; + }, + set: function (id) { + this._correlationId = id; + } +}); + +/** + * Get/Sets options that are applied to requests generated by this AuthenticationContext instance. + * @instance + * @memberOf AuthenticationContext + * @type {object} + * @name options + */ +Object.defineProperty(AuthenticationContext.prototype, 'options', { + get: function() { + return this._callContext.options; + }, + set: function (value) { + this._callContext.options = value; + } +}); + +/** + * Get the token cache used by this AuthenticationContext instance. + * @instance + * @memberOf AuthenticationContext + * @type {object} + * @name cache + */ +Object.defineProperty(AuthenticationContext.prototype, 'cache', { + get: function() { + return this._cache; + }, +}); + +/** + * This will be returned in case the OAuth 2 service returns an error. + * @typedef ErrorResponse + * @property {string} [error] A server error. + * @property {string} [errorDescription] A description of the error returned. + */ + +/** + * Contains tokens and metadata upon successful completion of an acquireToken call. + * @typedef TokenResponse + * @property {string} tokenType The type of token returned. + * @property {string} accessToken The returned access token. + * @property {string} [refreshToken] A refresh token. + * @property {Date} [createdOn] The date on which the access token was created. + * @property {Date} expiresOn The Date on which the access token expires. + * @property {int} expiresIn The amount of time, in seconds, for which the token is valid. + * @property {string} [userId] An id for the user. May be a displayable value if is_user_id_displayable is true. + * @property {bool} [isUserIdDisplayable] Indicates whether the user_id property will be meaningful if displayed to a user. + * @property {string} [tenantId] The identifier of the tenant under which the access token was issued. + * @property {string} [givenName] The given name of the principal represented by the access token. + * @property {string} [familyName] The family name of the principal represented by the access token. + * @property {string} [identityProvider] Identifies the identity provider that issued the access token. + */ + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback AcquireTokenCallback + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {TokenResponse|ErrorResponse} [response] On a succesful request returns a {@link TokenResposne}. + */ + +/** + * This function implements code that is common to all acquireToken flows. + * @private + * @param {AcquireTokenCallback} callback + * @param {Function} tokenFunction This is the function to call to actually acquire the token after common flow has completed. + */ +AuthenticationContext.prototype._acquireToken = function(callback, tokenFunction) { + var self = this; + this._callContext._logContext = createLogContext(this.correlationId); + this._authority.validate(this._callContext, function(err) { + if (err) { + callback(err); + return; + } + tokenFunction.call(self); + }); +}; + +AuthenticationContext.prototype._acquireUserCode = function (callback, codeFunction) { + var self = this; + this._callContext._logContext = createLogContext(this.correlationId); + this._authority.validate(this._callContext, function (err) { + if (err) { + callback(err); + return; + } + + codeFunction.call(self); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} [userId] The username of the user on behalf this application is authenticating. + * @param {string} [clientId] The OAuth client id of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireToken = function(resource, userId, clientId, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenFromCacheWithRefresh(userId, callback); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} username The username of the user on behalf this application is authenticating. + * @param {string} password The password of the user named in the username parameter. + * @param {string} clientId The OAuth client id of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithUsernamePassword = function(resource, username, password, clientId, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(username, 'username'); + argument.validateStringParameter(password, 'password'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenWithUsernamePassword(username, password, callback); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} clientSecret The OAuth client secret of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithClientCredentials = function(resource, clientId, clientSecret, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(clientId, 'clientId'); + argument.validateStringParameter(clientSecret, 'clientSecret'); + } catch (err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenWithClientCredentials(clientSecret, callback); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} authorizationCode An authorization code returned from a client. + * @param {string} redirectUri The redirect uri that was used in the authorize call. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} clientSecret The OAuth client secret of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithAuthorizationCode = function(authorizationCode, redirectUri, resource, clientId, clientSecret, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(authorizationCode, 'authorizationCode'); + argument.validateStringParameter(redirectUri, 'redirectUri'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, redirectUri); + tokenRequest.getTokenWithAuthorizationCode(authorizationCode, clientSecret, callback); + }); +}; + +/** + * Gets a new access token via a previously issued refresh token. + * @param {string} refreshToken A refresh token returned in a tokne response from a previous invocation of acquireToken. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} [clientSecret] The OAuth client secret of the calling application. (Note: this parameter is a late addition. + * This parameter may be ommitted entirely so that applications built before this change will continue + * to work unchanged.) + * @param {string} resource The OAuth resource for which a token is being request. This parameter is optional and can be set to null. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithRefreshToken = function(refreshToken, clientId, clientSecret, resource, callback) { + // Fix up the arguments. Older clients may pass fewer arguments as the clientSecret paramter did not always exist. + // The code needs to make adjustments for those clients. + var clientSecretPresent = (5 === arguments.length); + var actualClientSecret = clientSecretPresent ? clientSecret : null; + var actualCallback = clientSecretPresent ? arguments[4] : arguments[3]; + var actualResource = clientSecretPresent ? arguments[3] : arguments[2]; + + argument.validateCallbackType(actualCallback); + try { + argument.validateStringParameter(refreshToken, 'refreshToken'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, actualResource); + tokenRequest.getTokenWithRefreshToken(refreshToken, actualClientSecret, actualCallback); + }); +}; + +/** + * Gets a new access token using via a certificate credential. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithClientCertificate = function(resource, clientId, certificate, thumbprint, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(certificate, 'certificate'); + argument.validateStringParameter(thumbprint, 'thumbprint'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenWithCertificate(certificate, thumbprint, callback); + }); +}; + +/** + * Gets the userCodeInfo which contains user_code, device_code for authenticating user on device. + * @param {string} resource A URI that identifies the resource for which the device_code and user_code is valid for. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} language The language code specifying how the message should be localized to. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireUserCode = function(resource, clientId, language, callback) { + argument.validateCallbackType(callback); + + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(clientId, 'clientId'); + } catch (err) { + callback(err); + return; + } + + this._acquireUserCode(callback, function () { + var codeRequest = new CodeRequest(this._callContext, this, clientId, resource); + codeRequest.getUserCodeInfo(language, callback); + }); +}; + +/** + * Gets a new access token using via a device code. + * @note This method doesn't look up the cache, it only stores the returned token into cache. To look up cache before making a new request, + * please use acquireToken. + * @param {string} clientId The OAuth client id of the calling application. + * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithDeviceCode = function(resource, clientId, userCodeInfo, callback){ + argument.validateCallbackType(callback); + + try{ + argument.validateUserCodeInfo(userCodeInfo); + } catch (err) { + callback(err); + return; + } + + var self = this; + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, null); + self._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]] = tokenRequest; + tokenRequest.getTokenWithDeviceCode(userCodeInfo, callback); + }) +}; + +/** + * Cancels the polling request to get token with device code. + * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.cancelRequestToGetTokenWithDeviceCode = function (userCodeInfo, callback) { + argument.validateCallbackType(callback); + + try { + argument.validateUserCodeInfo(userCodeInfo); + } catch (err) { + callback(err); + return; + } + + if (!this._tokenRequestWithUserCode || !this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]) { + callback(new Error('No acquireTokenWithDeviceCodeRequest existed to be cancelled')); + return; + } + + var tokenRequestToBeCancelled = this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]; + tokenRequestToBeCancelled.cancelTokenRequestWithDeviceCode(); + + delete this._tokenRequestWithUserCode[constants.UserCodeResponseFields.DEVICE_CODE]; +}; + +var exports = { + AuthenticationContext : AuthenticationContext, + setGlobalADALOptions : function(options) { + globalADALOptions = options; + }, + getGlobalADALOptions : function() { + return globalADALOptions; + } +}; + +util.adalInit(); +module.exports = exports; - Duration._createSecondsNanos = function _createSecondsNanos(seconds, nanoAdjustment) { - if (seconds === void 0) { - seconds = 0; - } - if (nanoAdjustment === void 0) { - nanoAdjustment = 0; - } +/***/ }), - if (seconds === 0 && nanoAdjustment === 0) { - return Duration.ZERO; - } +/***/ 74854: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return new Duration(seconds, nanoAdjustment); - }; - - var _proto = Duration.prototype; - - _proto.get = function get(unit) { - if (unit === ChronoUnit.SECONDS) { - return this._seconds; - } else if (unit === ChronoUnit.NANOS) { - return this._nanos; - } else { - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } - }; - - _proto.units = function units() { - return [ChronoUnit.SECONDS, ChronoUnit.NANOS]; - }; - - _proto.isZero = function isZero() { - return this._seconds === 0 && this._nanos === 0; - }; - - _proto.isNegative = function isNegative() { - return this._seconds < 0; - }; - - _proto.seconds = function seconds() { - return this._seconds; - }; - - _proto.nano = function nano() { - return this._nanos; - }; - - _proto.withSeconds = function withSeconds(seconds) { - return Duration._create(seconds, this._nanos); - }; - - _proto.withNanos = function withNanos(nanoOfSecond) { - ChronoField.NANO_OF_SECOND.checkValidIntValue(nanoOfSecond); - return Duration._create(this._seconds, nanoOfSecond); - }; - - _proto.plusDuration = function plusDuration(duration) { - requireNonNull(duration, 'duration'); - return this.plus(duration.seconds(), duration.nano()); - }; - - _proto.plus = function plus(durationOrNumber, unitOrNumber) { - if (arguments.length === 1) { - return this.plusDuration(durationOrNumber); - } else if (arguments.length === 2 && unitOrNumber instanceof TemporalUnit) { - return this.plusAmountUnit(durationOrNumber, unitOrNumber); - } else { - return this.plusSecondsNanos(durationOrNumber, unitOrNumber); - } - }; - - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); - - if (unit === ChronoUnit.DAYS) { - return this.plusSecondsNanos(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_DAY), 0); - } - - if (unit.isDurationEstimated()) { - throw new UnsupportedTemporalTypeException('Unit must not have an estimated duration'); - } - - if (amountToAdd === 0) { - return this; - } - - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); - - case ChronoUnit.MICROS: - return this.plusSecondsNanos(MathUtil.intDiv(amountToAdd, 1000000 * 1000) * 1000, MathUtil.intMod(amountToAdd, 1000000 * 1000) * 1000); - - case ChronoUnit.MILLIS: - return this.plusMillis(amountToAdd); - - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); - } - - return this.plusSecondsNanos(MathUtil.safeMultiply(unit.duration().seconds(), amountToAdd), 0); - } - - var duration = unit.duration().multipliedBy(amountToAdd); - return this.plusSecondsNanos(duration.seconds(), duration.nano()); - }; - - _proto.plusDays = function plusDays(daysToAdd) { - return this.plusSecondsNanos(MathUtil.safeMultiply(daysToAdd, LocalTime.SECONDS_PER_DAY), 0); - }; - - _proto.plusHours = function plusHours(hoursToAdd) { - return this.plusSecondsNanos(MathUtil.safeMultiply(hoursToAdd, LocalTime.SECONDS_PER_HOUR), 0); - }; - - _proto.plusMinutes = function plusMinutes(minutesToAdd) { - return this.plusSecondsNanos(MathUtil.safeMultiply(minutesToAdd, LocalTime.SECONDS_PER_MINUTE), 0); - }; - - _proto.plusSeconds = function plusSeconds(secondsToAdd) { - return this.plusSecondsNanos(secondsToAdd, 0); - }; - - _proto.plusMillis = function plusMillis(millisToAdd) { - return this.plusSecondsNanos(MathUtil.intDiv(millisToAdd, 1000), MathUtil.intMod(millisToAdd, 1000) * 1000000); - }; - - _proto.plusNanos = function plusNanos(nanosToAdd) { - return this.plusSecondsNanos(0, nanosToAdd); - }; - - _proto.plusSecondsNanos = function plusSecondsNanos(secondsToAdd, nanosToAdd) { - requireNonNull(secondsToAdd, 'secondsToAdd'); - requireNonNull(nanosToAdd, 'nanosToAdd'); - - if (secondsToAdd === 0 && nanosToAdd === 0) { - return this; - } - - var epochSec = MathUtil.safeAdd(this._seconds, secondsToAdd); - epochSec = MathUtil.safeAdd(epochSec, MathUtil.intDiv(nanosToAdd, LocalTime.NANOS_PER_SECOND)); - nanosToAdd = MathUtil.intMod(nanosToAdd, LocalTime.NANOS_PER_SECOND); - var nanoAdjustment = MathUtil.safeAdd(this._nanos, nanosToAdd); - return Duration.ofSeconds(epochSec, nanoAdjustment); - }; - - _proto.minus = function minus(durationOrNumber, unit) { - if (arguments.length === 1) { - return this.minusDuration(durationOrNumber); - } else { - return this.minusAmountUnit(durationOrNumber, unit); - } - }; - - _proto.minusDuration = function minusDuration(duration) { - requireNonNull(duration, 'duration'); - var secsToSubtract = duration.seconds(); - var nanosToSubtract = duration.nano(); - - if (secsToSubtract === MIN_SAFE_INTEGER) { - return this.plus(MAX_SAFE_INTEGER, -nanosToSubtract); - } - - return this.plus(-secsToSubtract, -nanosToSubtract); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - return amountToSubtract === MIN_SAFE_INTEGER ? this.plusAmountUnit(MAX_SAFE_INTEGER, unit) : this.plusAmountUnit(-amountToSubtract, unit); - }; - - _proto.minusDays = function minusDays(daysToSubtract) { - return daysToSubtract === MIN_SAFE_INTEGER ? this.plusDays(MAX_SAFE_INTEGER) : this.plusDays(-daysToSubtract); - }; - - _proto.minusHours = function minusHours(hoursToSubtract) { - return hoursToSubtract === MIN_SAFE_INTEGER ? this.plusHours(MAX_SAFE_INTEGER) : this.plusHours(-hoursToSubtract); - }; - - _proto.minusMinutes = function minusMinutes(minutesToSubtract) { - return minutesToSubtract === MIN_SAFE_INTEGER ? this.plusMinutes(MAX_SAFE_INTEGER) : this.plusMinutes(-minutesToSubtract); - }; - - _proto.minusSeconds = function minusSeconds(secondsToSubtract) { - return secondsToSubtract === MIN_SAFE_INTEGER ? this.plusSeconds(MAX_SAFE_INTEGER) : this.plusSeconds(-secondsToSubtract); - }; - - _proto.minusMillis = function minusMillis(millisToSubtract) { - return millisToSubtract === MIN_SAFE_INTEGER ? this.plusMillis(MAX_SAFE_INTEGER) : this.plusMillis(-millisToSubtract); - }; - - _proto.minusNanos = function minusNanos(nanosToSubtract) { - return nanosToSubtract === MIN_SAFE_INTEGER ? this.plusNanos(MAX_SAFE_INTEGER) : this.plusNanos(-nanosToSubtract); - }; - - _proto.multipliedBy = function multipliedBy(multiplicand) { - if (multiplicand === 0) { - return Duration.ZERO; - } - - if (multiplicand === 1) { - return this; - } - - var secs = MathUtil.safeMultiply(this._seconds, multiplicand); - var nos = MathUtil.safeMultiply(this._nanos, multiplicand); - secs = secs + MathUtil.intDiv(nos, LocalTime.NANOS_PER_SECOND); - nos = MathUtil.intMod(nos, LocalTime.NANOS_PER_SECOND); - return Duration.ofSeconds(secs, nos); - }; - - _proto.dividedBy = function dividedBy(divisor) { - if (divisor === 0) { - throw new ArithmeticException('Cannot divide by zero'); - } - - if (divisor === 1) { - return this; - } - - var secs = MathUtil.intDiv(this._seconds, divisor); - var secsMod = MathUtil.roundDown((this._seconds / divisor - secs) * LocalTime.NANOS_PER_SECOND); - var nos = MathUtil.intDiv(this._nanos, divisor); - nos = secsMod + nos; - return Duration.ofSeconds(secs, nos); - }; - - _proto.negated = function negated() { - return this.multipliedBy(-1); - }; - - _proto.abs = function abs() { - return this.isNegative() ? this.negated() : this; - }; - - _proto.addTo = function addTo(temporal) { - requireNonNull(temporal, 'temporal'); - - if (this._seconds !== 0) { - temporal = temporal.plus(this._seconds, ChronoUnit.SECONDS); - } - - if (this._nanos !== 0) { - temporal = temporal.plus(this._nanos, ChronoUnit.NANOS); - } - - return temporal; - }; - - _proto.subtractFrom = function subtractFrom(temporal) { - requireNonNull(temporal, 'temporal'); - - if (this._seconds !== 0) { - temporal = temporal.minus(this._seconds, ChronoUnit.SECONDS); - } - - if (this._nanos !== 0) { - temporal = temporal.minus(this._nanos, ChronoUnit.NANOS); - } - - return temporal; - }; - - _proto.toDays = function toDays() { - return MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_DAY); - }; - - _proto.toHours = function toHours() { - return MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_HOUR); - }; - - _proto.toMinutes = function toMinutes() { - return MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_MINUTE); - }; - - _proto.toMillis = function toMillis() { - var millis = Math.round(MathUtil.safeMultiply(this._seconds, 1000)); - millis = MathUtil.safeAdd(millis, MathUtil.intDiv(this._nanos, 1000000)); - return millis; - }; - - _proto.toNanos = function toNanos() { - var totalNanos = MathUtil.safeMultiply(this._seconds, LocalTime.NANOS_PER_SECOND); - totalNanos = MathUtil.safeAdd(totalNanos, this._nanos); - return totalNanos; - }; - - _proto.compareTo = function compareTo(otherDuration) { - requireNonNull(otherDuration, 'otherDuration'); - requireInstance(otherDuration, Duration, 'otherDuration'); - var cmp = MathUtil.compareNumbers(this._seconds, otherDuration.seconds()); - - if (cmp !== 0) { - return cmp; - } - - return this._nanos - otherDuration.nano(); - }; - - _proto.equals = function equals(otherDuration) { - if (this === otherDuration) { - return true; - } - - if (otherDuration instanceof Duration) { - return this.seconds() === otherDuration.seconds() && this.nano() === otherDuration.nano(); - } - - return false; - }; - - _proto.toString = function toString() { - if (this === Duration.ZERO) { - return 'PT0S'; - } - - var hours = MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_HOUR); - var minutes = MathUtil.intDiv(MathUtil.intMod(this._seconds, LocalTime.SECONDS_PER_HOUR), LocalTime.SECONDS_PER_MINUTE); - var secs = MathUtil.intMod(this._seconds, LocalTime.SECONDS_PER_MINUTE); - var rval = 'PT'; - - if (hours !== 0) { - rval += hours + 'H'; - } - - if (minutes !== 0) { - rval += minutes + 'M'; - } - - if (secs === 0 && this._nanos === 0 && rval.length > 2) { - return rval; - } - - if (secs < 0 && this._nanos > 0) { - if (secs === -1) { - rval += '-0'; - } else { - rval += secs + 1; - } - } else { - rval += secs; - } - - if (this._nanos > 0) { - rval += '.'; - var nanoString; - - if (secs < 0) { - nanoString = '' + (2 * LocalTime.NANOS_PER_SECOND - this._nanos); - } else { - nanoString = '' + (LocalTime.NANOS_PER_SECOND + this._nanos); - } - - nanoString = nanoString.slice(1, nanoString.length); - rval += nanoString; - - while (rval.charAt(rval.length - 1) === '0') { - rval = rval.slice(0, rval.length - 1); - } - } - - rval += 'S'; - return rval; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return Duration; - }(TemporalAmount); - function _init() { - Duration.ZERO = new Duration(0, 0); - } - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE.md in the root directory of this source tree) - */ - var YearConstants = function YearConstants() {}; - function _init$1() { - YearConstants.MIN_VALUE = -999999; - YearConstants.MAX_VALUE = 999999; - } - - var ChronoUnit = function (_TemporalUnit) { - _inheritsLoose(ChronoUnit, _TemporalUnit); - - function ChronoUnit(name, estimatedDuration) { - var _this; - - _this = _TemporalUnit.call(this) || this; - _this._name = name; - _this._duration = estimatedDuration; - return _this; - } - - var _proto = ChronoUnit.prototype; - - _proto.duration = function duration() { - return this._duration; - }; - - _proto.isDurationEstimated = function isDurationEstimated() { - return this.isDateBased() || this === ChronoUnit.FOREVER; - }; - - _proto.isDateBased = function isDateBased() { - return this.compareTo(ChronoUnit.DAYS) >= 0 && this !== ChronoUnit.FOREVER; - }; - - _proto.isTimeBased = function isTimeBased() { - return this.compareTo(ChronoUnit.DAYS) < 0; - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - if (this === ChronoUnit.FOREVER) { - return false; - } - - try { - temporal.plus(1, this); - return true; - } catch (e) { - try { - temporal.plus(-1, this); - return true; - } catch (e2) { - return false; - } - } - }; - - _proto.addTo = function addTo(temporal, amount) { - return temporal.plus(amount, this); - }; - - _proto.between = function between(temporal1, temporal2) { - return temporal1.until(temporal2, this); - }; - - _proto.toString = function toString() { - return this._name; - }; - - _proto.compareTo = function compareTo(other) { - return this.duration().compareTo(other.duration()); - }; - - return ChronoUnit; - }(TemporalUnit); - function _init$2() { - ChronoUnit.NANOS = new ChronoUnit('Nanos', Duration.ofNanos(1)); - ChronoUnit.MICROS = new ChronoUnit('Micros', Duration.ofNanos(1000)); - ChronoUnit.MILLIS = new ChronoUnit('Millis', Duration.ofNanos(1000000)); - ChronoUnit.SECONDS = new ChronoUnit('Seconds', Duration.ofSeconds(1)); - ChronoUnit.MINUTES = new ChronoUnit('Minutes', Duration.ofSeconds(60)); - ChronoUnit.HOURS = new ChronoUnit('Hours', Duration.ofSeconds(3600)); - ChronoUnit.HALF_DAYS = new ChronoUnit('HalfDays', Duration.ofSeconds(43200)); - ChronoUnit.DAYS = new ChronoUnit('Days', Duration.ofSeconds(86400)); - ChronoUnit.WEEKS = new ChronoUnit('Weeks', Duration.ofSeconds(7 * 86400)); - ChronoUnit.MONTHS = new ChronoUnit('Months', Duration.ofSeconds(31556952 / 12)); - ChronoUnit.YEARS = new ChronoUnit('Years', Duration.ofSeconds(31556952)); - ChronoUnit.DECADES = new ChronoUnit('Decades', Duration.ofSeconds(31556952 * 10)); - ChronoUnit.CENTURIES = new ChronoUnit('Centuries', Duration.ofSeconds(31556952 * 100)); - ChronoUnit.MILLENNIA = new ChronoUnit('Millennia', Duration.ofSeconds(31556952 * 1000)); - ChronoUnit.ERAS = new ChronoUnit('Eras', Duration.ofSeconds(31556952 * (YearConstants.MAX_VALUE + 1))); - ChronoUnit.FOREVER = new ChronoUnit('Forever', Duration.ofSeconds(MathUtil.MAX_SAFE_INTEGER, 999999999)); - } - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - - var TemporalField = function () { - function TemporalField() {} - - var _proto = TemporalField.prototype; - - _proto.isDateBased = function isDateBased() { - abstractMethodFail('isDateBased'); - }; - - _proto.isTimeBased = function isTimeBased() { - abstractMethodFail('isTimeBased'); - }; - - _proto.baseUnit = function baseUnit() { - abstractMethodFail('baseUnit'); - }; - - _proto.rangeUnit = function rangeUnit() { - abstractMethodFail('rangeUnit'); - }; - - _proto.range = function range() { - abstractMethodFail('range'); - }; - - _proto.rangeRefinedBy = function rangeRefinedBy(temporal) { - abstractMethodFail('rangeRefinedBy'); - }; - - _proto.getFrom = function getFrom(temporal) { - abstractMethodFail('getFrom'); - }; - - _proto.adjustInto = function adjustInto(temporal, newValue) { - abstractMethodFail('adjustInto'); - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - abstractMethodFail('isSupportedBy'); - }; - - _proto.displayName = function displayName() { - abstractMethodFail('displayName'); - }; - - _proto.equals = function equals(other) { - abstractMethodFail('equals'); - }; - - _proto.name = function name() { - abstractMethodFail('name'); - }; - - return TemporalField; - }(); - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ValueRange = function () { - function ValueRange(minSmallest, minLargest, maxSmallest, maxLargest) { - assert(!(minSmallest > minLargest), 'Smallest minimum value \'' + minSmallest + '\' must be less than largest minimum value \'' + minLargest + '\'', IllegalArgumentException); - assert(!(maxSmallest > maxLargest), 'Smallest maximum value \'' + maxSmallest + '\' must be less than largest maximum value \'' + maxLargest + '\'', IllegalArgumentException); - assert(!(minLargest > maxLargest), 'Minimum value \'' + minLargest + '\' must be less than maximum value \'' + maxLargest + '\'', IllegalArgumentException); - this._minSmallest = minSmallest; - this._minLargest = minLargest; - this._maxLargest = maxLargest; - this._maxSmallest = maxSmallest; - } - - var _proto = ValueRange.prototype; - - _proto.isFixed = function isFixed() { - return this._minSmallest === this._minLargest && this._maxSmallest === this._maxLargest; - }; - - _proto.minimum = function minimum() { - return this._minSmallest; - }; - - _proto.largestMinimum = function largestMinimum() { - return this._minLargest; - }; - - _proto.maximum = function maximum() { - return this._maxLargest; - }; - - _proto.smallestMaximum = function smallestMaximum() { - return this._maxSmallest; - }; - - _proto.isValidValue = function isValidValue(value) { - return this.minimum() <= value && value <= this.maximum(); - }; - - _proto.checkValidValue = function checkValidValue(value, field) { - var msg; - - if (!this.isValidValue(value)) { - if (field != null) { - msg = 'Invalid value for ' + field + ' (valid values ' + this.toString() + '): ' + value; - } else { - msg = 'Invalid value (valid values ' + this.toString() + '): ' + value; - } - - return assert(false, msg, DateTimeException); - } - - return value; - }; - - _proto.checkValidIntValue = function checkValidIntValue(value, field) { - if (this.isValidIntValue(value) === false) { - throw new DateTimeException('Invalid int value for ' + field + ': ' + value); - } - - return value; - }; - - _proto.isValidIntValue = function isValidIntValue(value) { - return this.isIntValue() && this.isValidValue(value); - }; - - _proto.isIntValue = function isIntValue() { - return this.minimum() >= MathUtil.MIN_SAFE_INTEGER && this.maximum() <= MathUtil.MAX_SAFE_INTEGER; - }; - - _proto.equals = function equals(other) { - if (other === this) { - return true; - } - - if (other instanceof ValueRange) { - return this._minSmallest === other._minSmallest && this._minLargest === other._minLargest && this._maxSmallest === other._maxSmallest && this._maxLargest === other._maxLargest; - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._minSmallest, this._minLargest, this._maxSmallest, this._maxLargest); - }; - - _proto.toString = function toString() { - var str = this.minimum() + (this.minimum() !== this.largestMinimum() ? '/' + this.largestMinimum() : ''); - str += ' - '; - str += this.smallestMaximum() + (this.smallestMaximum() !== this.maximum() ? '/' + this.maximum() : ''); - return str; - }; - - ValueRange.of = function of() { - if (arguments.length === 2) { - return new ValueRange(arguments[0], arguments[0], arguments[1], arguments[1]); - } else if (arguments.length === 3) { - return new ValueRange(arguments[0], arguments[0], arguments[1], arguments[2]); - } else if (arguments.length === 4) { - return new ValueRange(arguments[0], arguments[1], arguments[2], arguments[3]); - } else { - return assert(false, 'Invalid number of arguments ' + arguments.length, IllegalArgumentException); - } - }; - - return ValueRange; - }(); - - var ChronoField = function (_TemporalField) { - _inheritsLoose(ChronoField, _TemporalField); - - ChronoField.byName = function byName(fieldName) { - for (var prop in ChronoField) { - if (ChronoField[prop]) { - if (ChronoField[prop] instanceof ChronoField && ChronoField[prop].name() === fieldName) { - return ChronoField[prop]; - } - } - } - }; - - function ChronoField(name, baseUnit, rangeUnit, range) { - var _this; - - _this = _TemporalField.call(this) || this; - _this._name = name; - _this._baseUnit = baseUnit; - _this._rangeUnit = rangeUnit; - _this._range = range; - return _this; - } - - var _proto = ChronoField.prototype; - - _proto.name = function name() { - return this._name; - }; - - _proto.baseUnit = function baseUnit() { - return this._baseUnit; - }; - - _proto.rangeUnit = function rangeUnit() { - return this._rangeUnit; - }; - - _proto.range = function range() { - return this._range; - }; - - _proto.displayName = function displayName() { - return this.toString(); - }; - - _proto.checkValidValue = function checkValidValue(value) { - return this.range().checkValidValue(value, this); - }; - - _proto.checkValidIntValue = function checkValidIntValue(value) { - return this.range().checkValidIntValue(value, this); - }; - - _proto.isDateBased = function isDateBased() { - var dateBased = this === ChronoField.DAY_OF_WEEK || this === ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH || this === ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR || this === ChronoField.DAY_OF_MONTH || this === ChronoField.DAY_OF_YEAR || this === ChronoField.EPOCH_DAY || this === ChronoField.ALIGNED_WEEK_OF_MONTH || this === ChronoField.ALIGNED_WEEK_OF_YEAR || this === ChronoField.MONTH_OF_YEAR || this === ChronoField.YEAR_OF_ERA || this === ChronoField.YEAR || this === ChronoField.ERA; - return dateBased; - }; - - _proto.isTimeBased = function isTimeBased() { - var timeBased = this === ChronoField.NANO_OF_SECOND || this === ChronoField.NANO_OF_DAY || this === ChronoField.MICRO_OF_SECOND || this === ChronoField.MICRO_OF_DAY || this === ChronoField.MILLI_OF_SECOND || this === ChronoField.MILLI_OF_DAY || this === ChronoField.SECOND_OF_MINUTE || this === ChronoField.SECOND_OF_DAY || this === ChronoField.MINUTE_OF_HOUR || this === ChronoField.MINUTE_OF_DAY || this === ChronoField.HOUR_OF_AMPM || this === ChronoField.CLOCK_HOUR_OF_AMPM || this === ChronoField.HOUR_OF_DAY || this === ChronoField.CLOCK_HOUR_OF_DAY || this === ChronoField.AMPM_OF_DAY; - return timeBased; - }; - - _proto.rangeRefinedBy = function rangeRefinedBy(temporal) { - return temporal.range(this); - }; - - _proto.getFrom = function getFrom(temporal) { - return temporal.getLong(this); - }; - - _proto.toString = function toString() { - return this.name(); - }; - - _proto.equals = function equals(other) { - return this === other; - }; - - _proto.adjustInto = function adjustInto(temporal, newValue) { - return temporal.with(this, newValue); - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(this); - }; - - return ChronoField; - }(TemporalField); - function _init$3() { - ChronoField.NANO_OF_SECOND = new ChronoField('NanoOfSecond', ChronoUnit.NANOS, ChronoUnit.SECONDS, ValueRange.of(0, 999999999)); - ChronoField.NANO_OF_DAY = new ChronoField('NanoOfDay', ChronoUnit.NANOS, ChronoUnit.DAYS, ValueRange.of(0, 86400 * 1000000000 - 1)); - ChronoField.MICRO_OF_SECOND = new ChronoField('MicroOfSecond', ChronoUnit.MICROS, ChronoUnit.SECONDS, ValueRange.of(0, 999999)); - ChronoField.MICRO_OF_DAY = new ChronoField('MicroOfDay', ChronoUnit.MICROS, ChronoUnit.DAYS, ValueRange.of(0, 86400 * 1000000 - 1)); - ChronoField.MILLI_OF_SECOND = new ChronoField('MilliOfSecond', ChronoUnit.MILLIS, ChronoUnit.SECONDS, ValueRange.of(0, 999)); - ChronoField.MILLI_OF_DAY = new ChronoField('MilliOfDay', ChronoUnit.MILLIS, ChronoUnit.DAYS, ValueRange.of(0, 86400 * 1000 - 1)); - ChronoField.SECOND_OF_MINUTE = new ChronoField('SecondOfMinute', ChronoUnit.SECONDS, ChronoUnit.MINUTES, ValueRange.of(0, 59)); - ChronoField.SECOND_OF_DAY = new ChronoField('SecondOfDay', ChronoUnit.SECONDS, ChronoUnit.DAYS, ValueRange.of(0, 86400 - 1)); - ChronoField.MINUTE_OF_HOUR = new ChronoField('MinuteOfHour', ChronoUnit.MINUTES, ChronoUnit.HOURS, ValueRange.of(0, 59)); - ChronoField.MINUTE_OF_DAY = new ChronoField('MinuteOfDay', ChronoUnit.MINUTES, ChronoUnit.DAYS, ValueRange.of(0, 24 * 60 - 1)); - ChronoField.HOUR_OF_AMPM = new ChronoField('HourOfAmPm', ChronoUnit.HOURS, ChronoUnit.HALF_DAYS, ValueRange.of(0, 11)); - ChronoField.CLOCK_HOUR_OF_AMPM = new ChronoField('ClockHourOfAmPm', ChronoUnit.HOURS, ChronoUnit.HALF_DAYS, ValueRange.of(1, 12)); - ChronoField.HOUR_OF_DAY = new ChronoField('HourOfDay', ChronoUnit.HOURS, ChronoUnit.DAYS, ValueRange.of(0, 23)); - ChronoField.CLOCK_HOUR_OF_DAY = new ChronoField('ClockHourOfDay', ChronoUnit.HOURS, ChronoUnit.DAYS, ValueRange.of(1, 24)); - ChronoField.AMPM_OF_DAY = new ChronoField('AmPmOfDay', ChronoUnit.HALF_DAYS, ChronoUnit.DAYS, ValueRange.of(0, 1)); - ChronoField.DAY_OF_WEEK = new ChronoField('DayOfWeek', ChronoUnit.DAYS, ChronoUnit.WEEKS, ValueRange.of(1, 7)); - ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH = new ChronoField('AlignedDayOfWeekInMonth', ChronoUnit.DAYS, ChronoUnit.WEEKS, ValueRange.of(1, 7)); - ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR = new ChronoField('AlignedDayOfWeekInYear', ChronoUnit.DAYS, ChronoUnit.WEEKS, ValueRange.of(1, 7)); - ChronoField.DAY_OF_MONTH = new ChronoField('DayOfMonth', ChronoUnit.DAYS, ChronoUnit.MONTHS, ValueRange.of(1, 28, 31), 'day'); - ChronoField.DAY_OF_YEAR = new ChronoField('DayOfYear', ChronoUnit.DAYS, ChronoUnit.YEARS, ValueRange.of(1, 365, 366)); - ChronoField.EPOCH_DAY = new ChronoField('EpochDay', ChronoUnit.DAYS, ChronoUnit.FOREVER, ValueRange.of(Math.floor(YearConstants.MIN_VALUE * 365.25), Math.floor(YearConstants.MAX_VALUE * 365.25))); - ChronoField.ALIGNED_WEEK_OF_MONTH = new ChronoField('AlignedWeekOfMonth', ChronoUnit.WEEKS, ChronoUnit.MONTHS, ValueRange.of(1, 4, 5)); - ChronoField.ALIGNED_WEEK_OF_YEAR = new ChronoField('AlignedWeekOfYear', ChronoUnit.WEEKS, ChronoUnit.YEARS, ValueRange.of(1, 53)); - ChronoField.MONTH_OF_YEAR = new ChronoField('MonthOfYear', ChronoUnit.MONTHS, ChronoUnit.YEARS, ValueRange.of(1, 12), 'month'); - ChronoField.PROLEPTIC_MONTH = new ChronoField('ProlepticMonth', ChronoUnit.MONTHS, ChronoUnit.FOREVER, ValueRange.of(YearConstants.MIN_VALUE * 12, YearConstants.MAX_VALUE * 12 + 11)); - ChronoField.YEAR_OF_ERA = new ChronoField('YearOfEra', ChronoUnit.YEARS, ChronoUnit.FOREVER, ValueRange.of(1, YearConstants.MAX_VALUE, YearConstants.MAX_VALUE + 1)); - ChronoField.YEAR = new ChronoField('Year', ChronoUnit.YEARS, ChronoUnit.FOREVER, ValueRange.of(YearConstants.MIN_VALUE, YearConstants.MAX_VALUE), 'year'); - ChronoField.ERA = new ChronoField('Era', ChronoUnit.ERAS, ChronoUnit.FOREVER, ValueRange.of(0, 1)); - ChronoField.INSTANT_SECONDS = new ChronoField('InstantSeconds', ChronoUnit.SECONDS, ChronoUnit.FOREVER, ValueRange.of(MIN_SAFE_INTEGER, MAX_SAFE_INTEGER)); - ChronoField.OFFSET_SECONDS = new ChronoField('OffsetSeconds', ChronoUnit.SECONDS, ChronoUnit.FOREVER, ValueRange.of(-18 * 3600, 18 * 3600)); - } - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalQueries = function () { - function TemporalQueries() {} - - TemporalQueries.zoneId = function zoneId() { - return TemporalQueries.ZONE_ID; - }; - - TemporalQueries.chronology = function chronology() { - return TemporalQueries.CHRONO; - }; - - TemporalQueries.precision = function precision() { - return TemporalQueries.PRECISION; - }; - - TemporalQueries.zone = function zone() { - return TemporalQueries.ZONE; - }; - - TemporalQueries.offset = function offset() { - return TemporalQueries.OFFSET; - }; - - TemporalQueries.localDate = function localDate() { - return TemporalQueries.LOCAL_DATE; - }; - - TemporalQueries.localTime = function localTime() { - return TemporalQueries.LOCAL_TIME; - }; - - return TemporalQueries; - }(); - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalAccessor = function () { - function TemporalAccessor() {} - - var _proto = TemporalAccessor.prototype; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.zoneId() || _query === TemporalQueries.chronology() || _query === TemporalQueries.precision()) { - return null; - } - - return _query.queryFrom(this); - }; - - _proto.get = function get(field) { - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; - - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (this.isSupported(field)) { - return field.range(); - } - - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.rangeRefinedBy(this); - }; - - return TemporalAccessor; - }(); - - var TemporalQuery = function (_Enum) { - _inheritsLoose(TemporalQuery, _Enum); - - function TemporalQuery() { - return _Enum.apply(this, arguments) || this; - } - - var _proto = TemporalQuery.prototype; - - _proto.queryFrom = function queryFrom(temporal) { - abstractMethodFail('queryFrom'); - }; - - return TemporalQuery; - }(Enum); - function createTemporalQuery(name, queryFromFunction) { - var ExtendedTemporalQuery = function (_TemporalQuery) { - _inheritsLoose(ExtendedTemporalQuery, _TemporalQuery); - - function ExtendedTemporalQuery() { - return _TemporalQuery.apply(this, arguments) || this; - } - - return ExtendedTemporalQuery; - }(TemporalQuery); - - ExtendedTemporalQuery.prototype.queryFrom = queryFromFunction; - return new ExtendedTemporalQuery(name); - } - - var DayOfWeek = function (_TemporalAccessor) { - _inheritsLoose(DayOfWeek, _TemporalAccessor); - - function DayOfWeek(ordinal, name) { - var _this; - - _this = _TemporalAccessor.call(this) || this; - _this._ordinal = ordinal; - _this._name = name; - return _this; - } - - var _proto = DayOfWeek.prototype; - - _proto.ordinal = function ordinal() { - return this._ordinal; - }; - - _proto.name = function name() { - return this._name; - }; - - DayOfWeek.values = function values() { - return ENUMS.slice(); - }; - - DayOfWeek.valueOf = function valueOf(name) { - var ordinal = 0; - - for (ordinal; ordinal < ENUMS.length; ordinal++) { - if (ENUMS[ordinal].name() === name) { - break; - } - } - - return DayOfWeek.of(ordinal + 1); - }; - - DayOfWeek.of = function of(dayOfWeek) { - if (dayOfWeek < 1 || dayOfWeek > 7) { - throw new DateTimeException('Invalid value for DayOfWeek: ' + dayOfWeek); - } - - return ENUMS[dayOfWeek - 1]; - }; - - DayOfWeek.from = function from(temporal) { - assert(temporal != null, 'temporal', NullPointerException); - - if (temporal instanceof DayOfWeek) { - return temporal; - } - - try { - return DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); - } catch (ex) { - if (ex instanceof DateTimeException) { - throw new DateTimeException('Unable to obtain DayOfWeek from TemporalAccessor: ' + temporal + ', type ' + (temporal.constructor != null ? temporal.constructor.name : ''), ex); - } else { - throw ex; - } - } - }; - - _proto.value = function value() { - return this._ordinal + 1; - }; - - _proto.displayName = function displayName(style, locale) { - throw new IllegalArgumentException('Pattern using (localized) text not implemented yet!'); - }; - - _proto.isSupported = function isSupported(field) { - if (field instanceof ChronoField) { - return field === ChronoField.DAY_OF_WEEK; - } - - return field != null && field.isSupportedBy(this); - }; - - _proto.range = function range(field) { - if (field === ChronoField.DAY_OF_WEEK) { - return field.range(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.rangeRefinedBy(this); - }; - - _proto.get = function get(field) { - if (field === ChronoField.DAY_OF_WEEK) { - return this.value(); - } - - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; - - _proto.getLong = function getLong(field) { - if (field === ChronoField.DAY_OF_WEEK) { - return this.value(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.getFrom(this); - }; - - _proto.plus = function plus(days) { - var amount = MathUtil.floorMod(days, 7); - return ENUMS[MathUtil.floorMod(this._ordinal + (amount + 7), 7)]; - }; - - _proto.minus = function minus(days) { - return this.plus(-1 * MathUtil.floorMod(days, 7)); - }; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.precision()) { - return ChronoUnit.DAYS; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.chronology() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } - - assert(_query != null, 'query', NullPointerException); - return _query.queryFrom(this); - }; - - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - return temporal.with(ChronoField.DAY_OF_WEEK, this.value()); - }; - - _proto.equals = function equals(other) { - return this === other; - }; - - _proto.toString = function toString() { - return this._name; - }; - - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, DayOfWeek, 'other'); - return this._ordinal - other._ordinal; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return DayOfWeek; - }(TemporalAccessor); - var ENUMS; - function _init$4() { - DayOfWeek.MONDAY = new DayOfWeek(0, 'MONDAY'); - DayOfWeek.TUESDAY = new DayOfWeek(1, 'TUESDAY'); - DayOfWeek.WEDNESDAY = new DayOfWeek(2, 'WEDNESDAY'); - DayOfWeek.THURSDAY = new DayOfWeek(3, 'THURSDAY'); - DayOfWeek.FRIDAY = new DayOfWeek(4, 'FRIDAY'); - DayOfWeek.SATURDAY = new DayOfWeek(5, 'SATURDAY'); - DayOfWeek.SUNDAY = new DayOfWeek(6, 'SUNDAY'); - DayOfWeek.FROM = createTemporalQuery('DayOfWeek.FROM', function (temporal) { - return DayOfWeek.from(temporal); - }); - ENUMS = [DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY]; - } - - var Month = function (_TemporalAccessor) { - _inheritsLoose(Month, _TemporalAccessor); - - function Month(value, name) { - var _this; - - _this = _TemporalAccessor.call(this) || this; - _this._value = MathUtil.safeToInt(value); - _this._name = name; - return _this; - } - - var _proto = Month.prototype; - - _proto.value = function value() { - return this._value; - }; - - _proto.ordinal = function ordinal() { - return this._value - 1; - }; - - _proto.name = function name() { - return this._name; - }; - - _proto.displayName = function displayName(style, locale) { - throw new IllegalArgumentException('Pattern using (localized) text not implemented yet!'); - }; - - _proto.isSupported = function isSupported(field) { - if (null === field) { - return false; - } - - if (field instanceof ChronoField) { - return field === ChronoField.MONTH_OF_YEAR; - } - - return field != null && field.isSupportedBy(this); - }; - - _proto.get = function get(field) { - if (field === ChronoField.MONTH_OF_YEAR) { - return this.value(); - } - - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; - - _proto.getLong = function getLong(field) { - if (field === ChronoField.MONTH_OF_YEAR) { - return this.value(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.getFrom(this); - }; - - _proto.plus = function plus(months) { - var amount = MathUtil.intMod(months, 12) + 12; - var newMonthVal = MathUtil.intMod(this.value() + amount, 12); - newMonthVal = newMonthVal === 0 ? 12 : newMonthVal; - return Month.of(newMonthVal); - }; - - _proto.minus = function minus(months) { - return this.plus(-1 * MathUtil.intMod(months, 12)); - }; - - _proto.length = function length(leapYear) { - switch (this) { - case Month.FEBRUARY: - return leapYear ? 29 : 28; - - case Month.APRIL: - case Month.JUNE: - case Month.SEPTEMBER: - case Month.NOVEMBER: - return 30; - - default: - return 31; - } - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + + +var request = __nccwpck_require__(48699); + +var argument = __nccwpck_require__(62432); +var log = __nccwpck_require__(92288); +var util = __nccwpck_require__(5336); +var HttpErrorCode = __nccwpck_require__(10282).HttpError; + +/* + * Constants + */ +var consts = { + AUTHORIZATION_URI : 'authorization_uri', + RESOURCE : 'resource', + WWW_AUTHENTICATE_HEADER : 'www-authenticate' +}; + +/** + * The AuthenticationParameters class holds the parameters that are parsed from an OAuth challenge + * in the www-authenticate header. + * @constructor + * @param {string} authorizationUri The URI of an authority that can issues tokens for the + * resource that issued the challenge. + * @param {string} resource The resource for a which a token should be requested from the authority. + */ +function AuthenticationParameters(authorizationUri, resource) { + this._authorizationUri = authorizationUri; + this._resource = resource; +} + +/** + * The URI of an authority that can issues tokens for the resource that issued the challenge. + * @instance + * @memberOf AuthenticationParameters + * @type {string} + * @name authorizationUri + */ +Object.defineProperty(AuthenticationParameters.prototype, 'authorizationUri', { + get : function() { + return this._authorizationUri; + } +}); + +/** + * The resource for a which a token should be requested from the authority. + * This property may be undefined if the resource was not returned in the challenge. + * @instance + * @memberOf AuthenticationParameters + * @type {string} + * @name authorizationUri + */ +Object.defineProperty(AuthenticationParameters.prototype, 'resource', { + get : function() { + return this._resource; + } +}); + +var exports = {}; + +// The 401 challenge is a standard defined in RFC6750, which is based in part on RFC2617. +// The challenge has the following form. +// WWW-Authenticate : Bearer authorization_uri="https://login.windows.net/mytenant.com/oauth2/authorize",Resource_id="00000002-0000-0000-c000-000000000000" + +// This regex is used to validate the structure of the challenge header. +// Match whole structure: ^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$ +// ^ Start at the beginning of the string. +// \s*Bearer\s+ Match 'Bearer' surrounded by one or more amount of whitespace. +// ([^,\s="]+?) This cpatures the key which is composed of any characters except comma, whitespace or a quotes. +// = Match the = sign. +// "([^"]*?)" Captures the value can be any number of non quote characters. At this point only the first key value pair as been captured. +// \s* There can be any amount of white space after the first key value pair. +// ( Start a capture group to retrieve the rest of the key value pairs that are separated by commas. +// \s* There can be any amount of whitespace before the comma. +// , There must be a comma. +// \s* There can be any amount of whitespace after the comma. +// (([^,\s="]+?) This will capture the key that comes after the comma. It's made of a series of any character excpet comma, whitespace or quotes. +// = Match the equal sign between the key and value. +// " Match the opening quote of the value. +// ([^"]*?) This will capture the value which can be any number of non quote characters. +// " Match the values closing quote. +// \s* There can be any amount of whitespace before the next comma. +// )* Close the capture group for key value pairs. There can be any number of these. +// $ The rest of the string can be whitespace but nothing else up to the end of the string. +// +// +// In other some other languages the regex above would be all that was needed. However, in JavaScript the RegExp object does not +// return all of the captures in one go. So the regex above needs to be broken up so that captures can be retrieved +// iteratively. +// + +function parseChallenge(challenge) { + // This regex checks the structure of the whole challenge header. The complete + // header needs to be checked for validity before we can be certain that + // we will succeed in pulling out the individual parts. + var bearerChallengeStructureValidation = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$/; + + // This regex pulls out the key and value from the very first pair. + var firstKeyValuePairRegex = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*/; + + // This regex is used to pull out all of the key value pairs after the first one. + // All of these begin with a comma. + var allOtherKeyValuePairRegex = /(?:,\s*([^,\s="]+?)="([^"]*?)"\s*)/g; + + + if (!bearerChallengeStructureValidation.test(challenge)) { + throw new Error('The challenge is not parseable as an RFC6750 OAuth2 challenge'); + } + + var challengeParameters = {}; + for(var match = firstKeyValuePairRegex.exec(challenge); + match; + match = allOtherKeyValuePairRegex.exec(challenge)) { + + challengeParameters[match[1]] = match[2]; + } + + return challengeParameters; +} + +exports.AuthenticationParameters = AuthenticationParameters; + +/** + * Creates an {@link AuthenticationParameters} object from the contents of a + * www-authenticate header received from a HTTP 401 response from a resource server. + * @param {string} challenge The content fo the www-authenticate header. + * @return {AuthenticationParameters} An AuthenticationParameters object containing the parsed values from the header. + */ +exports.createAuthenticationParametersFromHeader = function(challenge) { + argument.validateStringParameter(challenge, 'challenge'); + + var challengeParameters = parseChallenge(challenge); + + var authorizationUri = challengeParameters[consts.AUTHORIZATION_URI]; + if (!authorizationUri) { + throw new Error('Could not find \'authorization_uri\' in challenge header.'); + } + + var resource = challengeParameters[consts.RESOURCE]; + + return new AuthenticationParameters(authorizationUri, resource); +}; + +/** + * Create an {@link AuthenticationParameters} object from a node http.IncomingMessage + * object that was created as a result of a request to a resource server. This function + * expects the response to contain a HTTP 401 error code with a www-authenticate + * header. + * @param {http.IncomingMessage} response A response from a http request to a resource server. + * @return {AuthenticationParameters} + */ +exports.createAuthenticationParametersFromResponse = function(response) { + if (!response) { + throw new Error('Mising required parameter: response'); + } + + if (!response.statusCode) { + throw new Error('The response parameter does not have the expected HTTP statusCode field'); + } + + if (HttpErrorCode.UNAUTHORIZED !== response.statusCode) { + throw new Error('The response status code does not correspond to an OAuth challenge. ' + + 'The statusCode is expected to be 401 but is: ' + response.statusCode); + } + + if (!response.headers) { + throw new Error('There were no headers found in the response.'); + } + + var challenge = response.headers[consts.WWW_AUTHENTICATE_HEADER]; + if (!challenge) { + throw new Error('The response does not contain a WWW-Authenticate header that can be used to determine the authority_uri and resource.'); + } + + return exports.createAuthenticationParametersFromHeader(challenge); +}; + +function validateUrlObject(url) { + if (!url || !url.href) { + throw new Error('Parameter is of wrong type: url'); + } +} + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback CreateAuthenticationParametersCallback + * @memberOf AuthenticationContext + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {AuthenticationParameters} [parameters] On a succesful request returns a {@link AuthenticationParameters}. + */ + +/** + * Creates an {@link AuthenticationParameters} object by sending a get request + * to the url passed to this function, and parsing the resulting http 401 + * response. + * @param {string|url} url The url of a resource server. + * @param {AuthenticationParameters} callback Called on error or request completion. + * @param {string} [correlationId] An optional correlationId to pass along with the request and to include in any logs. + */ +exports.createAuthenticationParametersFromUrl = function(url, callback, correlationId) { + argument.validateCallbackType(callback); + try { + if (!url) { + callback(new Error('Missing required parameter: url')); + return; + } + var challengeUrl; + if ('string' === typeof(url)) { + challengeUrl = url; + } else { + validateUrlObject(url); + challengeUrl = url.href; + } + + var logContext = log.createLogContext(correlationId); + var logger = new log.Logger('AuthenticationParameters', logContext); + + logger.verbose('Attempting to retrieve authentication parameters'); + logger.verbose('Attempting to retrieve authentication parameters from: ' + challengeUrl, true); + var options = util.createRequestOptions( { _callContext : { _logContext: logContext } } ); + request.get(challengeUrl, options, function(err, response) { + if (err) { + logger.error('Authentication parameters http get failed.', err, true); + callback(err); + return; + } + var parameters; + try { + parameters = exports.createAuthenticationParametersFromResponse(response); + } catch(creationErr) { + logger.error('Unable to parse response in to authentication paramaters.', creationErr, true); + callback(creationErr); + return; + } + callback(null, parameters); + }); + } catch(err) { + callback(err); + return; + } +}; + +module.exports = exports; - _proto.minLength = function minLength() { - switch (this) { - case Month.FEBRUARY: - return 28; +/***/ }), - case Month.APRIL: - case Month.JUNE: - case Month.SEPTEMBER: - case Month.NOVEMBER: - return 30; +/***/ 19270: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - default: - return 31; - } - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var request = __nccwpck_require__(48699); +var url = __nccwpck_require__(78835); +var _ = __nccwpck_require__(83571); + +var AADConstants = __nccwpck_require__(10282).AADConstants; +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +/** +* Constructs an Authority object with a specific authority URL. +* @private +* @constructor +* @param {string} authorityUrl A URL that identifies a token authority. +* @param {bool} validateAuthority Indicates whether the Authority url should be validated as an actual AAD +* authority. The default is true. +*/ +function Authority(authorityUrl, validateAuthority) { + this._log = null; + this._url = url.parse(authorityUrl); + this._validateAuthorityUrl(); + + this._validated = !validateAuthority; + this._host = null; + this._tenant = null; + this._parseAuthority(); + + this._authorizationEndpoint = null; + this._tokenEndpoint = null; + this._deviceCodeEndpoint = null; + this._isAdfsAuthority = (this._tenant.toLowerCase() === "adfs"); +} + +/** + * The URL of the authority + * @instance + * @type {string} + * @memberOf Authority + * @name url + */ +Object.defineProperty(Authority.prototype, 'url', { + get: function() { + return url.format(this._url); + } +}); + +/** + * The token endpoint that the authority uses as discovered by instance discovery. + * @instance + * @type {string} + * @memberOf Authority + * @name tokenEndpoint + */ +Object.defineProperty(Authority.prototype, 'tokenEndpoint', { + get: function() { + return this._tokenEndpoint; + } +}); + +Object.defineProperty(Authority.prototype, 'deviceCodeEndpoint', { + get: function() { + return this._deviceCodeEndpoint; + } +}); + +/** + * Checks the authority url to ensure that it meets basic requirements such as being over SSL. If it does not then + * this method will throw if any of the checks fail. + * @private + * @throws {Error} If the authority url fails to pass any validation checks. + */ +Authority.prototype._validateAuthorityUrl = function() { + if (this._url.protocol !== 'https:') { + throw new Error('The authority url must be an https endpoint.'); + } + + if (this._url.query) { + throw new Error('The authority url must not have a query string.'); + } +}; + +/** + * Parse the authority to get the tenant name. The rest of the + * URL is thrown away in favor of one of the endpoints from the validation doc. + * @private + */ +Authority.prototype._parseAuthority = function() { + this._host = this._url.host; + + var pathParts = this._url.pathname.split('/'); + this._tenant = pathParts[1]; + + if (!this._tenant) { + throw new Error('Could not determine tenant.'); + } +}; + +/** + * Performs instance discovery based on a simple match against well known authorities. + * @private + * @return {bool} Returns true if the authority is recognized. + */ +Authority.prototype._performStaticInstanceDiscovery = function() { + this._log.verbose('Performing static instance discovery'); + + var hostIndex = _.indexOf(AADConstants.WELL_KNOWN_AUTHORITY_HOSTS, this._url.hostname); + var found = hostIndex > -1; + + if (found) { + this._log.verbose('Authority validated via static instance discovery.'); + } + + return found; +}; + +Authority.prototype._createAuthorityUrl = function() { + return 'https://' + this._url.host + '/' + encodeURIComponent(this._tenant) + AADConstants.AUTHORIZE_ENDPOINT_PATH; +}; + +/** + * Creates an instance discovery endpoint url for the specific authority that this object represents. + * @private + * @param {string} authorityHost The host name of a well known authority. + * @return {URL} The constructed endpoint url. + */ +Authority.prototype._createInstanceDiscoveryEndpointFromTemplate = function(authorityHost) { + var discoveryEndpoint = AADConstants.INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE; + discoveryEndpoint = discoveryEndpoint.replace('{authorize_host}', authorityHost); + discoveryEndpoint = discoveryEndpoint.replace('{authorize_endpoint}', encodeURIComponent(this._createAuthorityUrl())); + return url.parse(discoveryEndpoint); +}; + +/** + * Performs instance discovery via a network call to well known authorities. + * @private + * @param {Authority.InstanceDiscoveryCallback} callback The callback function. If succesful, + * this function calls the callback with the + * tenantDiscoveryEndpoint returned by the + * server. + */ +Authority.prototype._performDynamicInstanceDiscovery = function(callback) { + try { + var self = this; + var discoveryEndpoint = this._createInstanceDiscoveryEndpointFromTemplate(AADConstants.WORLD_WIDE_AUTHORITY); + + var getOptions = util.createRequestOptions(self); + + this._log.verbose('Attempting instance discover'); + this._log.verbose('Attempting instance discover at: ' + url.format(discoveryEndpoint), true); + request.get(discoveryEndpoint, getOptions, util.createRequestHandler('Instance Discovery', this._log, callback, + function(response, body) { + var discoveryResponse = JSON.parse(body); + + if (discoveryResponse['tenant_discovery_endpoint']) { + callback(null, discoveryResponse['tenant_discovery_endpoint']); + } else { + callback(self._log.createError('Failed to parse instance discovery response')); + } + }) + ); + } catch(e) { + callback(e); + } +}; + +/** + * @callback InstanceDiscoveryCallback + * @private + * @memberOf Authority + * @param {Error} err If an error occurs during instance discovery then it will be returned here. + * @param {string} tenantDiscoveryEndpoint If instance discovery is successful then this will contain the + * tenantDiscoveryEndpoint associated with the authority. + */ + +/** + * Determines whether the authority is recognized as a trusted AAD authority. + * @private + * @param {Authority.InstanceDiscoveryCallback} callback The callback function. + */ +Authority.prototype._validateViaInstanceDiscovery = function(callback) { + if (this._performStaticInstanceDiscovery()) { + callback(); + } else { + this._performDynamicInstanceDiscovery(callback); + } +}; + +/** + * @callback GetOauthEndpointsCallback + * @private + * @memberOf Authority + * @param {Error} error An error if one occurred. + */ + +/** + * Given a tenant discovery endpoint this method will attempt to discover the token endpoint. If the + * tenant discovery endpoint is unreachable for some reason then it will fall back to a algorithmic generation of the + * token endpoint url. + * @private + * @param {string} tenantDiscoveryEndpoint The url of the tenant discovery endpoint for this authority. + * @param {Authority.GetOauthEndpointsCallback} callback The callback function. + */ +Authority.prototype._getOAuthEndpoints = function(tenantDiscoveryEndpoint, callback) { + if (this._tokenEndpoint && this._deviceCodeEndpoint) { + callback(); + return; + } else { + // fallback to the well known token endpoint path. + if (!this._tokenEndpoint){ + this._tokenEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.TOKEN_ENDPOINT_PATH; + } + + if (!this._deviceCodeEndpoint){ + this._deviceCodeEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.DEVICE_ENDPOINT_PATH; + } + + callback(); + return; + } +}; + +/** + * @callback ValidateCallback + * @memberOf Authority + */ + +/** + * Perform validation on the authority represented by this object. In addition to simple validation + * the oauth token endpoint will be retrieved. + * @param {Authority.ValidateCallback} callback The callback function. + */ +Authority.prototype.validate = function(callContext, callback) { + this._log = new Logger('Authority', callContext._logContext); + this._callContext = callContext; + var self = this; + + if (!this._validated) { + this._log.verbose('Performing instance discovery'); + this._log.verbose('Performing instance discovery: ' + url.format(this._url), true); + this._validateViaInstanceDiscovery(function(err, tenantDiscoveryEndpoint) { + if (err) + { + callback(err); + } else { + self._validated = true; + self._getOAuthEndpoints(tenantDiscoveryEndpoint, callback); + return; + } + }); + } else { + this._log.verbose('Instance discovery/validation has either already been completed or is turned off'); + this._log.verbose('Instance discovery/validation has either already been completed or is turned off: ' + url.format(this._url), true); + this._getOAuthEndpoints(null, callback); + return; + } +}; + +module.exports.W = Authority; - _proto.maxLength = function maxLength() { - switch (this) { - case Month.FEBRUARY: - return 29; - case Month.APRIL: - case Month.JUNE: - case Month.SEPTEMBER: - case Month.NOVEMBER: - return 30; +/***/ }), - default: - return 31; - } - }; +/***/ 38289: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.firstDayOfYear = function firstDayOfYear(leapYear) { - var leap = leapYear ? 1 : 0; - - switch (this) { - case Month.JANUARY: - return 1; - - case Month.FEBRUARY: - return 32; - - case Month.MARCH: - return 60 + leap; - - case Month.APRIL: - return 91 + leap; - - case Month.MAY: - return 121 + leap; - - case Month.JUNE: - return 152 + leap; - - case Month.JULY: - return 182 + leap; - - case Month.AUGUST: - return 213 + leap; - - case Month.SEPTEMBER: - return 244 + leap; - - case Month.OCTOBER: - return 274 + leap; - - case Month.NOVEMBER: - return 305 + leap; - - case Month.DECEMBER: - default: - return 335 + leap; - } - }; - - _proto.firstMonthOfQuarter = function firstMonthOfQuarter() { - switch (this) { - case Month.JANUARY: - case Month.FEBRUARY: - case Month.MARCH: - return Month.JANUARY; - - case Month.APRIL: - case Month.MAY: - case Month.JUNE: - return Month.APRIL; - - case Month.JULY: - case Month.AUGUST: - case Month.SEPTEMBER: - return Month.JULY; - - case Month.OCTOBER: - case Month.NOVEMBER: - case Month.DECEMBER: - default: - return Month.OCTOBER; - } - }; - - _proto.query = function query(_query) { - assert(_query != null, 'query() parameter must not be null', DateTimeException); - - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.MONTHS; - } - - return _TemporalAccessor.prototype.query.call(this, _query); - }; - - _proto.toString = function toString() { - switch (this) { - case Month.JANUARY: - return 'JANUARY'; - - case Month.FEBRUARY: - return 'FEBRUARY'; - - case Month.MARCH: - return 'MARCH'; - - case Month.APRIL: - return 'APRIL'; - - case Month.MAY: - return 'MAY'; - - case Month.JUNE: - return 'JUNE'; - - case Month.JULY: - return 'JULY'; - - case Month.AUGUST: - return 'AUGUST'; - - case Month.SEPTEMBER: - return 'SEPTEMBER'; - - case Month.OCTOBER: - return 'OCTOBER'; - - case Month.NOVEMBER: - return 'NOVEMBER'; - - case Month.DECEMBER: - return 'DECEMBER'; - - default: - return 'unknown Month, value: ' + this.value(); - } - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.MONTH_OF_YEAR, this.value()); - }; - - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, Month, 'other'); - return this._value - other._value; - }; - - _proto.equals = function equals(other) { - return this === other; - }; - - Month.valueOf = function valueOf(name) { - var ordinal = 0; - - for (ordinal; ordinal < MONTHS.length; ordinal++) { - if (MONTHS[ordinal].name() === name) { - break; - } - } - - return Month.of(ordinal + 1); - }; - - Month.values = function values() { - return MONTHS.slice(); - }; - - Month.of = function of(month) { - if (month < 1 || month > 12) { - assert(false, 'Invalid value for MonthOfYear: ' + month, DateTimeException); - } - - return MONTHS[month - 1]; - }; - - Month.from = function from(temporal) { - if (temporal instanceof Month) { - return temporal; - } - - try { - return Month.of(temporal.get(ChronoField.MONTH_OF_YEAR)); - } catch (ex) { - throw new DateTimeException('Unable to obtain Month from TemporalAccessor: ' + temporal + ' of type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : ''), ex); - } - }; - - return Month; - }(TemporalAccessor); - var MONTHS; - function _init$5() { - Month.JANUARY = new Month(1, 'JANUARY'); - Month.FEBRUARY = new Month(2, 'FEBRUARY'); - Month.MARCH = new Month(3, 'MARCH'); - Month.APRIL = new Month(4, 'APRIL'); - Month.MAY = new Month(5, 'MAY'); - Month.JUNE = new Month(6, 'JUNE'); - Month.JULY = new Month(7, 'JULY'); - Month.AUGUST = new Month(8, 'AUGUST'); - Month.SEPTEMBER = new Month(9, 'SEPTEMBER'); - Month.OCTOBER = new Month(10, 'OCTOBER'); - Month.NOVEMBER = new Month(11, 'NOVEMBER'); - Month.DECEMBER = new Month(12, 'DECEMBER'); - MONTHS = [Month.JANUARY, Month.FEBRUARY, Month.MARCH, Month.APRIL, Month.MAY, Month.JUNE, Month.JULY, Month.AUGUST, Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER, Month.DECEMBER]; - } - - var PATTERN = /([-+]?)P(?:([-+]?[0-9]+)Y)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)W)?(?:([-+]?[0-9]+)D)?/; - var Period = function (_TemporalAmount) { - _inheritsLoose(Period, _TemporalAmount); - - function Period(years, months, days) { - var _this; - - _this = _TemporalAmount.call(this) || this; - - var _years = MathUtil.safeToInt(years); - - var _months = MathUtil.safeToInt(months); - - var _days = MathUtil.safeToInt(days); - - if (_years === 0 && _months === 0 && _days === 0) { - if (!Period.ZERO) { - _this._years = _years; - _this._months = _months; - _this._days = _days; - Period.ZERO = _assertThisInitialized(_this); - } - - return Period.ZERO || _assertThisInitialized(_this); - } - - _this._years = _years; - _this._months = _months; - _this._days = _days; - return _this; - } - - Period.ofYears = function ofYears(years) { - return Period.create(years, 0, 0); - }; - - Period.ofMonths = function ofMonths(months) { - return Period.create(0, months, 0); - }; - - Period.ofWeeks = function ofWeeks(weeks) { - return Period.create(0, 0, MathUtil.safeMultiply(weeks, 7)); - }; - - Period.ofDays = function ofDays(days) { - return Period.create(0, 0, days); - }; - - Period.of = function of(years, months, days) { - return Period.create(years, months, days); - }; - - Period.from = function from(amount) { - if (amount instanceof Period) { - return amount; - } - - requireNonNull(amount, 'amount'); - var years = 0; - var months = 0; - var days = 0; - var units = amount.units(); - - for (var i = 0; i < units.length; i++) { - var unit = units[i]; - var unitAmount = amount.get(unit); - - if (unit === ChronoUnit.YEARS) { - years = MathUtil.safeToInt(unitAmount); - } else if (unit === ChronoUnit.MONTHS) { - months = MathUtil.safeToInt(unitAmount); - } else if (unit === ChronoUnit.DAYS) { - days = MathUtil.safeToInt(unitAmount); - } else { - throw new DateTimeException('Unit must be Years, Months or Days, but was ' + unit); - } - } - - return Period.create(years, months, days); - }; - - Period.between = function between(startDate, endDate) { - requireNonNull(startDate, 'startDate'); - requireNonNull(endDate, 'endDate'); - requireInstance(startDate, LocalDate, 'startDate'); - requireInstance(endDate, LocalDate, 'endDate'); - return startDate.until(endDate); - }; - - Period.parse = function parse(text) { - requireNonNull(text, 'text'); - - try { - return Period._parse(text); - } catch (ex) { - if (ex instanceof ArithmeticException) { - throw new DateTimeParseException('Text cannot be parsed to a Period', text, 0, ex); - } else { - throw ex; - } - } - }; - - Period._parse = function _parse(text) { - var matches = PATTERN.exec(text); - - if (matches != null) { - var negate = '-' === matches[1] ? -1 : 1; - var yearMatch = matches[2]; - var monthMatch = matches[3]; - var weekMatch = matches[4]; - var dayMatch = matches[5]; - - if (yearMatch != null || monthMatch != null || weekMatch != null || dayMatch != null) { - var years = Period._parseNumber(text, yearMatch, negate); - - var months = Period._parseNumber(text, monthMatch, negate); - - var weeks = Period._parseNumber(text, weekMatch, negate); - - var days = Period._parseNumber(text, dayMatch, negate); - - days = MathUtil.safeAdd(days, MathUtil.safeMultiply(weeks, 7)); - return Period.create(years, months, days); - } - } - - throw new DateTimeParseException('Text cannot be parsed to a Period', text, 0); - }; - - Period._parseNumber = function _parseNumber(text, str, negate) { - if (str == null) { - return 0; - } - - var val = MathUtil.parseInt(str); - return MathUtil.safeMultiply(val, negate); - }; - - Period.create = function create(years, months, days) { - return new Period(years, months, days); - }; - - var _proto = Period.prototype; - - _proto.units = function units() { - return [ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS]; - }; - - _proto.chronology = function chronology() { - return IsoChronology.INSTANCE; - }; - - _proto.get = function get(unit) { - if (unit === ChronoUnit.YEARS) { - return this._years; - } - - if (unit === ChronoUnit.MONTHS) { - return this._months; - } - - if (unit === ChronoUnit.DAYS) { - return this._days; - } - - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - }; - - _proto.isZero = function isZero() { - return this === Period.ZERO; - }; - - _proto.isNegative = function isNegative() { - return this._years < 0 || this._months < 0 || this._days < 0; - }; - - _proto.years = function years() { - return this._years; - }; - - _proto.months = function months() { - return this._months; - }; - - _proto.days = function days() { - return this._days; - }; - - _proto.withYears = function withYears(years) { - if (years === this._years) { - return this; - } - - return Period.create(years, this._months, this._days); - }; - - _proto.withMonths = function withMonths(months) { - if (months === this._months) { - return this; - } - - return Period.create(this._years, months, this._days); - }; - - _proto.withDays = function withDays(days) { - if (days === this._days) { - return this; - } - - return Period.create(this._years, this._months, days); - }; - - _proto.plus = function plus(amountToAdd) { - var amount = Period.from(amountToAdd); - return Period.create(MathUtil.safeAdd(this._years, amount._years), MathUtil.safeAdd(this._months, amount._months), MathUtil.safeAdd(this._days, amount._days)); - }; - - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } - - return Period.create(MathUtil.safeToInt(MathUtil.safeAdd(this._years, yearsToAdd)), this._months, this._days); - }; - - _proto.plusMonths = function plusMonths(monthsToAdd) { - if (monthsToAdd === 0) { - return this; - } - - return Period.create(this._years, MathUtil.safeToInt(MathUtil.safeAdd(this._months, monthsToAdd)), this._days); - }; - - _proto.plusDays = function plusDays(daysToAdd) { - if (daysToAdd === 0) { - return this; - } - - return Period.create(this._years, this._months, MathUtil.safeToInt(MathUtil.safeAdd(this._days, daysToAdd))); - }; - - _proto.minus = function minus(amountToSubtract) { - var amount = Period.from(amountToSubtract); - return Period.create(MathUtil.safeSubtract(this._years, amount._years), MathUtil.safeSubtract(this._months, amount._months), MathUtil.safeSubtract(this._days, amount._days)); - }; - - _proto.minusYears = function minusYears(yearsToSubtract) { - return this.plusYears(-1 * yearsToSubtract); - }; - - _proto.minusMonths = function minusMonths(monthsToSubtract) { - return this.plusMonths(-1 * monthsToSubtract); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + + +var _ = __nccwpck_require__(83571); +var crypto = __nccwpck_require__(76417); +__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. + +var Logger = __nccwpck_require__(92288).Logger; +var constants = __nccwpck_require__(10282); +var cacheConstants = constants.Cache; +var TokenResponseFields = constants.TokenResponseFields; + +// TODO: remove this. +// There is a PM requirement that developers be able to look in to the cache and manipulate the cache based on +// the parameters (authority, resource, clientId, userId), in any combination. They must be able find, add, and remove +// tokens based on those parameters. Any default cache that the API supplies must allow for this query pattern. +// This has the following implications: +// The developer must not be required to calculate any special fields, such as hashes or unique keys. +// +// The default cache implementation can not include optimizations that break the previous requirement. +// This means that we can only do complete scans of the data and equality can only be calculated based on +// equality of all of the individual fields. +// +// The cache interface can not make any assumption about the query efficency of the cache nor can +// it help in optimizing those queries. +// +// There is no simple sorting optimization, rather a series of indexes, and index intersection would +// be necessary. +// +// If for some reason the developer tries to update the cache with a new entry that may be a refresh +// token, they will not know that they need to update all of the refresh tokens or they may get strange +// behavior. +// +// Related to the above, there is no definition of a coherent cache. And if there was there would be +// no way for our API to enforce it. What about duplicates? +// +// there be a single cache entry per (authority, resource, clientId) +// tuple, with no special tokens (i.e. MRRT tokens) +// Required cache operations +// + +// Constants +var METADATA_CLIENTID = '_clientId'; +var METADATA_AUTHORITY = '_authority'; + +function nop(placeHolder, callback) { + callback(); +} + +/* + * This is a place holder cache that does nothing. + */ +var nopCache = { + add : nop, + addMany : nop, + remove : nop, + removeMany : nop, + find : nop +}; + +function createTokenHash(token) { + var hashAlg = crypto.createHash(cacheConstants.HASH_ALGORITHM); + hashAlg.update(token, 'utf8'); + return hashAlg.digest('base64'); +} + +function createTokenIdMessage(entry) { + var accessTokenHash = createTokenHash(entry[TokenResponseFields.ACCESS_TOKEN]); + var message = 'AccessTokenId: ' + accessTokenHash; + if (entry[TokenResponseFields.REFRESH_TOKEN]) { + var refreshTokenHash = createTokenHash(entry[TokenResponseFields.REFRESH_TOKEN]); + message += ', RefreshTokenId: ' + refreshTokenHash; + } + return message; +} + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback RefreshEntryFunction + * @memberOf CacheDriver + * @param {object} tokenResponse A token response to refresh. + * @param {string} [resource] The resource for which to obtain the token if it is different from the original token. + * @param {AcquireTokenCallback} callback Called on completion with an error or a new entry to add to the cache. + */ + +/** + * Constructs a new CacheDriver object. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} authority + * @param {TokenCache} [cache] A token cache to use. If none is passed then the CacheDriver instance + * will not cache. + * @param {RefreshEntryFunction} refreshFunction + */ +function CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) { + this._callContext = callContext; + this._log = new Logger('CacheDriver', callContext._logContext); + this._authority = authority; + this._resource = resource; + this._clientId = clientId; + this._cache = cache || nopCache; + this._refreshFunction = refreshFunction; +} + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback QueryCallback + * @memberOf CacheDriver + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {Array} [response] On a succesful request returns an array of matched entries. + */ + +/** + * The cache driver query function. Ensures that all queries are authority specific. + * @param {object} query A query object. Can contain a clientId or userId or both. + * @param {QueryCallback} callback + */ +CacheDriver.prototype._find = function(query, callback) { + this._cache.find(query, callback); +}; + +/** + * Queries for all entries that might satisfy a request for a cached token. + * @param {object} query A query object. Can contain a clientId or userId or both. + * @param {QueryCallback} callback + */ +CacheDriver.prototype._getPotentialEntries = function(query, callback) { + var self = this; + var potentialEntriesQuery = {}; + + if (query.clientId) { + potentialEntriesQuery[METADATA_CLIENTID] = query.clientId; + } + if (query.userId) { + potentialEntriesQuery[TokenResponseFields.USER_ID] = query.userId; + } + + this._log.verbose('Looking for potential cache entries:'); + this._log.verbose(JSON.stringify(potentialEntriesQuery), true); + this._find(potentialEntriesQuery, function(err, entries) { + self._log.verbose('Found ' + entries.length + ' potential entries.'); + callback(err, entries); + return; + }); +}; + +/** + * Finds all multi resource refresh tokens in the cache. + * Refresh token is bound to userId, clientId. + * @param {QueryCallback} callback + */ +CacheDriver.prototype._findMRRTTokensForUser = function(user, callback) { + this._find({ isMRRT : true, userId : user, _clientId : this._clientId}, callback); +}; + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback SingleEntryCallback + * @memberOf CacheDriver + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {object} [response] On a succesful request returns a single cache entry. + */ + + +/** + * Finds a single entry that matches the query. If multiple entries are found that satisfy the query + * then an error will be returned. + * @param {object} query A query object. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._loadSingleEntryFromCache = function(query, callback) { + var self = this; + this._getPotentialEntries(query, function(err, potentialEntries) { + if (err) { + callback(err); + return; + } + + var returnVal; + var isResourceTenantSpecific; + + if (potentialEntries && 0 < potentialEntries.length) { + var resourceTenantSpecificEntries = _.where(potentialEntries, { resource : self._resource, _authority : self._authority }); + + if (!resourceTenantSpecificEntries || 0 === resourceTenantSpecificEntries.length) { + self._log.verbose('No resource specific cache entries found.'); + + // There are no resource specific entries. Find an MRRT token. + var mrrtTokens = _.where(potentialEntries, { isMRRT : true }); + if (mrrtTokens && mrrtTokens.length > 0) { + self._log.verbose('Found an MRRT token.'); + returnVal = mrrtTokens[0]; + } else { + self._log.verbose('No MRRT tokens found.'); + } + + } else if (resourceTenantSpecificEntries.length === 1) { + self._log.verbose('Resource specific token found.'); + returnVal = resourceTenantSpecificEntries[0]; + isResourceTenantSpecific = true; + }else { + callback(self._log.createError('More than one token matches the criteria. The result is ambiguous.')); + return; + } + } + if (returnVal) { + self._log.verbose('Returning token from cache lookup'); + self._log.verbose('Returning token from cache lookup, ' + createTokenIdMessage(returnVal), true); + } + callback(null, returnVal, isResourceTenantSpecific); + }); +}; + +/** + * The response from a token refresh request never contains an id_token and therefore no + * userInfo can be created from the response. This function creates a new cache entry + * combining the id_token based info and cache metadata from the cache entry that was refreshed with the + * new tokens in the refresh response. + * @param {object} entry A cache entry corresponding to the resfreshResponse. + * @param {object} refreshResponse The response from a token refresh request for the entry parameter. + * @return {object} A new cache entry. + */ +CacheDriver.prototype._createEntryFromRefresh = function(entry, refreshResponse) { + var newEntry = _.clone(entry); + newEntry = _.extend(newEntry, refreshResponse); + + if (entry.isMRRT && this._authority !== entry[METADATA_AUTHORITY]) { + newEntry[METADATA_AUTHORITY] = this._authority; + } + + this._log.verbose('Created new cache entry from refresh response.'); + return newEntry; +}; + +CacheDriver.prototype._replaceEntry = function(entryToReplace, newEntry, callback) { + var self = this; + this.remove(entryToReplace, function(err) { + if (err) { + callback(err); + return; + } + self.add(newEntry, callback); + }); +}; + +/** + * Given an expired cache entry refreshes it and updates the cache. + * @param {object} entry A cache entry with an MRRT to refresh for another resource. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._refreshExpiredEntry = function(entry, callback) { + var self = this; + this._refreshFunction(entry, null, function(err, tokenResponse) { + if (err) { + callback(err); + return; + } + + var newEntry = self._createEntryFromRefresh(entry, tokenResponse); + self._replaceEntry(entry, newEntry, function(err) { + if (err) { + self._log.error('error refreshing expired token', err, true); + } else { + self._log.info('Returning token refreshed after expiry.'); + } + callback(err, newEntry); + }); + }); +}; + +/** + * Given a cache entry with an MRRT will acquire a new token for a new resource via the MRRT, and cache it. + * @param {object} entry A cache entry with an MRRT to refresh for another resource. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._acquireNewTokenFromMrrt = function(entry, callback) { + var self = this; + this._refreshFunction(entry, this._resource, function(err, tokenResponse) { + if (err) { + callback(err); + return; + } + + var newEntry = self._createEntryFromRefresh(entry, tokenResponse); + self.add(newEntry, function(err) { + if (err) { + self._log.error('error refreshing mrrt', err, true); + } else { + self._log.info('Returning token derived from mrrt refresh.'); + } + callback(err, newEntry); + }); + }); +}; + +/** + * Given a token this function will refresh it if it is either expired, or an MRRT. + * @param {object} entry A cache entry to refresh if necessary. + * @param {Boolean} isResourceSpecific Indicates whether this token is appropriate for the resource for which + * it was requested or whether it is possibly an MRRT token for which + * a resource specific access token should be acquired. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._refreshEntryIfNecessary = function(entry, isResourceSpecific, callback) { + var expiryDate = entry[TokenResponseFields.EXPIRES_ON]; + + // Add some buffer in to the time comparison to account for clock skew or latency. + var nowPlusBuffer = (new Date()).addMinutes(constants.Misc.CLOCK_BUFFER); + + if (isResourceSpecific && nowPlusBuffer.isAfter(expiryDate)) { + this._log.info('Cached token is expired. Refreshing: ' + expiryDate); + this._refreshExpiredEntry(entry, callback); + return; + } else if (!isResourceSpecific && entry.isMRRT) { + this._log.info('Acquiring new access token from MRRT token.'); + this._acquireNewTokenFromMrrt(entry, callback); + return; + } else { + callback(null, entry); + } +}; + +/** + * Finds a single entry in the cache that matches the query or fails if more than one match is found. + * @param {object} query A query object + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype.find = function(query, callback) { + var self = this; + query = query || {}; + this._log.verbose('finding using query'); + this._log.verbose('finding with query:' + JSON.stringify(query), true); + this._loadSingleEntryFromCache(query, function(err, entry, isResourceTenantSpecific) { + if (err) { + callback(err); + return; + } + + if (!entry) { + callback(); + return; + } + + self._refreshEntryIfNecessary(entry, isResourceTenantSpecific, function(err, newEntry) { + callback(err, newEntry); + return; + }); + }); +}; + +/** + * Removes a single entry from the cache. + * @param {object} entry The entry to remove. + * @param {Function} callback Called on completion. The first parameter may contain an error. + */ +CacheDriver.prototype.remove = function(entry, callback) { + this._log.verbose('Removing entry.'); + return this._cache.remove([entry], function(err) { + callback(err); + return; + }); +}; + +/** + * Removes a collection of entries from the cache in a single batch operation. + * @param {Array} entries An array of cache entries to remove. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +CacheDriver.prototype._removeMany = function(entries, callback) { + this._log.verbose('Remove many: ' + entries.length); + this._cache.remove(entries, function(err) { + callback(err); + return; + }); +}; + +/** + * Adds a collection of entries to the cache in a single batch operation. + * @param {Array} entries An array of entries to add to the cache. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +CacheDriver.prototype._addMany = function(entries, callback) { + this._log.verbose('Add many: ' + entries.length); + this._cache.add(entries, function(err) { + callback(err); + return; + }); +}; + +/* + * Tests whether the passed entry is a multi resource refresh token. + * Somewhat mysteriously the presense of a resource field in a returned + * token response indicates that the response is an MRRT. + * @param {object} entry + * @return {Boolean} true if the entry is an MRRT. + */ +function isMRRT(entry) { + return entry.resource ? true : false; +} + +/** + * Given an cache entry this function finds all of the MRRT tokens already in the cache + * and updates them with the refresh_token of the passed in entry. + * @param {object} entry The entry from which to get an updated refresh_token + * @param {Function} callback Called back on completion. The first parameter may contain an error. + */ +CacheDriver.prototype._updateRefreshTokens = function(entry, callback) { + var self = this; + if (isMRRT(entry)) { + this._findMRRTTokensForUser(entry.userId, function(err, mrrtTokens) { + if (err) { + callback(err); + return; + } + + if (!mrrtTokens || 0 === mrrtTokens.length) { + callback(); + return; + } + + self._log.verbose('Updating ' + mrrtTokens.length + ' cached refresh tokens.'); + self._removeMany(mrrtTokens, function(err) { + if (err) { + callback(err); + return; + } + + for (var i = 0; i < mrrtTokens.length; i++) { + mrrtTokens[i][TokenResponseFields.REFRESH_TOKEN] = entry[TokenResponseFields.REFRESH_TOKEN]; + } + + self._addMany(mrrtTokens, function(err) { + callback(err); + return; + }); + }); + }); + } else { + callback(); + return; + } +}; + +/** + * Checks to see if the entry has cache metadata already. If it does + * then it probably came from a refresh operation and the metadata + * was copied from the originating entry. + * @param {object} entry The entry to check + * @return {bool} Returns true if the entry has already been augmented + * with cache metadata. + */ +CacheDriver.prototype._entryHasMetadata = function(entry) { + return (_.has(entry, METADATA_CLIENTID) && _.has(entry, METADATA_AUTHORITY)); +}; + +CacheDriver.prototype._augmentEntryWithCacheMetadata = function(entry) { + if (this._entryHasMetadata(entry)) { + return; + } + + if (isMRRT(entry)) { + this._log.verbose('Added entry is MRRT'); + entry.isMRRT = true; + } else { + entry.resource = this._resource; + } + + entry[METADATA_CLIENTID] = this._clientId; + entry[METADATA_AUTHORITY] = this._authority; +}; + +/** + * Adds a single entry to the cache. + * @param {object} entry The entry to add. + * @param {string} clientId The id of this client app. + * @param {string} resource The id of the resource for which the cached token was obtained. + * @param {Function} callback Called back on completion. The first parameter may contain an error. + */ +CacheDriver.prototype.add = function(entry, callback) { + var self = this; + this._log.verbose('Adding entry'); + this._log.verbose('Adding entry, ' + createTokenIdMessage(entry)); + + this._augmentEntryWithCacheMetadata(entry); + + this._updateRefreshTokens(entry, function(err) { + if (err) { + callback(err); + return; + } + + self._cache.add([entry], function(err) { + callback(err); + return; + }); + }); +}; + +module.exports = CacheDriver; - _proto.minusDays = function minusDays(daysToSubtract) { - return this.plusDays(-1 * daysToSubtract); - }; +/***/ }), - _proto.multipliedBy = function multipliedBy(scalar) { - if (this === Period.ZERO || scalar === 1) { - return this; - } +/***/ 66576: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return Period.create(MathUtil.safeMultiply(this._years, scalar), MathUtil.safeMultiply(this._months, scalar), MathUtil.safeMultiply(this._days, scalar)); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var constants = __nccwpck_require__(10282); +var Logger = __nccwpck_require__(92288).Logger; +var Mex = __nccwpck_require__(27078); +var OAuth2Client = __nccwpck_require__(41602); + +var OAuth2Parameters = constants.OAuth2.Parameters; +var TokenResponseFields = constants.TokenResponseFields; +var OAuth2GrantType = constants.OAuth2.GrantType; +var OAuth2Scope = constants.OAuth2.Scope; + +/** + * Constructs a new CodeRequest object. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {AuthenticationContext} authenticationContext + * @param {string} resource + * @param {string} clientId + */ +// TODO: probably need to modify the parameter list. +function CodeRequest(callContext, authenticationContext, clientId, resource) { + this._log = new Logger('DeviceCodeRequest', callContext._logContext); + this._callContext = callContext; + this._authenticationContext = authenticationContext; + this._resource = resource; + this._clientId = clientId; + + // This should be set at the beginning of getToken + // functions that have a userId. + this._userId = null; +}; + +/** + * Get user code info. + * @private + * @param {object} oauthParameters containing all the parameters needed to get the user code info. + * @param {callback} callback + */ +CodeRequest.prototype._getUserCodeInfo = function (oauthParameters, callback) { + var oauth2Client = this._createOAuth2Client(); + oauth2Client.getUserCodeInfo(oauthParameters, callback); +}; + +CodeRequest.prototype._createOAuth2Client = function () { + return new OAuth2Client(this._callContext, this._authenticationContext._authority); +}; + +/** + * Creates a set of basic, common, OAuthParameters based on values that the CodeRequest was created with. + * @private + * @return {object} containing all the basic parameters. + */ +CodeRequest.prototype._createOAuthParameters = function () { + var oauthParameters = {}; + + oauthParameters[OAuth2Parameters.CLIENT_ID] = this._clientId; + oauthParameters[OAuth2Parameters.RESOURCE] = this._resource; + + return oauthParameters; +}; + +/** + * Get the user code information. + * @param {string} language optional parameter used to get the user code info. + * @param {callback} callback + */ +CodeRequest.prototype.getUserCodeInfo = function(language, callback) { + this._log.info('Getting user code info.'); + + var oauthParameters = this._createOAuthParameters(); + if (language){ + oauthParameters[OAuth2Parameters.LANGUAGE] = language; + } + + this._getUserCodeInfo(oauthParameters, callback); +}; +module.exports = CodeRequest; - _proto.negated = function negated() { - return this.multipliedBy(-1); - }; +/***/ }), - _proto.normalized = function normalized() { - var totalMonths = this.toTotalMonths(); - var splitYears = MathUtil.intDiv(totalMonths, 12); - var splitMonths = MathUtil.intMod(totalMonths, 12); +/***/ 10282: +/***/ ((module) => { - if (splitYears === this._years && splitMonths === this._months) { - return this; - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var Constants = { + OAuth2 : { + Parameters : { + GRANT_TYPE : 'grant_type', + CLIENT_ASSERTION : 'client_assertion', + CLIENT_ASSERTION_TYPE : 'client_assertion_type', + CLIENT_ID : 'client_id', + CLIENT_SECRET : 'client_secret', + REDIRECT_URI : 'redirect_uri', + RESOURCE : 'resource', + CODE : 'code', + SCOPE : 'scope', + ASSERTION : 'assertion', + AAD_API_VERSION : 'api-version', + USERNAME : 'username', + PASSWORD : 'password', + REFRESH_TOKEN : 'refresh_token', + LANGUAGE : 'mkt', + DEVICE_CODE : 'device_code', + }, + + GrantType : { + AUTHORIZATION_CODE : 'authorization_code', + REFRESH_TOKEN : 'refresh_token', + CLIENT_CREDENTIALS : 'client_credentials', + JWT_BEARER : 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', + PASSWORD : 'password', + SAML1 : 'urn:ietf:params:oauth:grant-type:saml1_1-bearer', + SAML2 : 'urn:ietf:params:oauth:grant-type:saml2-bearer', + DEVICE_CODE: 'device_code' + }, + + ResponseParameters : { + CODE : 'code', + TOKEN_TYPE : 'token_type', + ACCESS_TOKEN : 'access_token', + ID_TOKEN : 'id_token', + REFRESH_TOKEN : 'refresh_token', + CREATED_ON : 'created_on', + EXPIRES_ON : 'expires_on', + EXPIRES_IN : 'expires_in', + RESOURCE : 'resource', + ERROR : 'error', + ERROR_DESCRIPTION : 'error_description' + }, + + DeviceCodeResponseParameters : { + USER_CODE : 'user_code', + DEVICE_CODE : 'device_code', + VERIFICATION_URL : 'verification_url', + EXPIRES_IN : 'expires_in', + INTERVAL: 'interval', + MESSAGE: 'message', + ERROR: 'error', + ERROR_DESCRIPTION: 'error_description' + }, + + Scope : { + OPENID : 'openid' + }, + + IdTokenMap : { + 'tid' : 'tenantId', + 'given_name' : 'givenName', + 'family_name' : 'familyName', + 'idp' : 'identityProvider', + 'oid': 'oid' + } + }, + + TokenResponseFields : { + TOKEN_TYPE : 'tokenType', + ACCESS_TOKEN : 'accessToken', + REFRESH_TOKEN : 'refreshToken', + CREATED_ON : 'createdOn', + EXPIRES_ON : 'expiresOn', + EXPIRES_IN : 'expiresIn', + RESOURCE : 'resource', + USER_ID : 'userId', + ERROR : 'error', + ERROR_DESCRIPTION : 'errorDescription' + }, + + UserCodeResponseFields : { + USER_CODE : 'userCode', + DEVICE_CODE: 'deviceCode', + VERIFICATION_URL: 'verificationUrl', + EXPIRES_IN: 'expiresIn', + INTERVAL: 'interval', + MESSAGE: 'message', + ERROR: 'error', + ERROR_DESCRIPTION: 'errorDescription' + }, + + IdTokenFields : { + USER_ID : 'userId', + IS_USER_ID_DISPLAYABLE : 'isUserIdDisplayable', + TENANT_ID : 'tenantId', + GIVE_NAME : 'givenName', + FAMILY_NAME : 'familyName', + IDENTITY_PROVIDER : 'identityProvider' + }, + + Misc : { + MAX_DATE : 0xffffffff, + CLOCK_BUFFER : 5 // In minutes. + }, + + Jwt : { + SELF_SIGNED_JWT_LIFETIME : 10, // 10 mins in mins + AUDIENCE : 'aud', + ISSUER : 'iss', + SUBJECT : 'sub', + NOT_BEFORE : 'nbf', + EXPIRES_ON : 'exp', + JWT_ID : 'jti' + }, + + AADConstants : { + WORLD_WIDE_AUTHORITY : 'login.windows.net', + WELL_KNOWN_AUTHORITY_HOSTS : ['login.windows.net', 'login.microsoftonline.com', 'login.chinacloudapi.cn', 'login-us.microsoftonline.com', 'login.microsoftonline.de', 'login.microsoftonline.us'], + INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE : 'https://{authorize_host}/common/discovery/instance?authorization_endpoint={authorize_endpoint}&api-version=1.0', + AUTHORIZE_ENDPOINT_PATH : '/oauth2/authorize', + TOKEN_ENDPOINT_PATH : '/oauth2/token', + DEVICE_ENDPOINT_PATH : '/oauth2/devicecode' + }, + + UserRealm : { + FederationProtocolType : { + WSFederation : 'wstrust', + SAML2 : 'saml20', + Unknown : 'unknown' + }, + + AccountType : { + Federated : 'federated', + Managed : 'managed', + Unknown : 'unknown' + } + }, + + Saml : { + TokenTypeV1 : 'urn:oasis:names:tc:SAML:1.0:assertion', + TokenTypeV2 : 'urn:oasis:names:tc:SAML:2.0:assertion' + }, + + XmlNamespaces : { + wsdl : 'http://schemas.xmlsoap.org/wsdl/', + sp : 'http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702', + sp2005 : 'http://schemas.xmlsoap.org/ws/2005/07/securitypolicy', + wsu : 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd', + wsa10 : 'http://www.w3.org/2005/08/addressing', + http : 'http://schemas.microsoft.com/ws/06/2004/policy/http', + soap12 : 'http://schemas.xmlsoap.org/wsdl/soap12/', + wsp : 'http://schemas.xmlsoap.org/ws/2004/09/policy', + s : 'http://www.w3.org/2003/05/soap-envelope', + wsa : 'http://www.w3.org/2005/08/addressing', + wst : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512', + t : 'http://schemas.xmlsoap.org/ws/2005/02/trust' + }, + + Cache : { + HASH_ALGORITHM : 'sha256' + }, + + HttpError : { + UNAUTHORIZED : 401 + }, + + AdalIdParameters : { + SKU : 'x-client-SKU', + VERSION : 'x-client-Ver', + OS : 'x-client-OS', + CPU : 'x-client-CPU', + NODE_SKU : 'Node' + }, + + WSTrustVersion : { + UNDEFINED : 'undefined', + WSTRUST13 : 'wstrust13', + WSTRUST2005 : 'wstrust2005' + } + }; + +module.exports = Constants; - return Period.create(MathUtil.safeToInt(splitYears), splitMonths, this._days); - }; - _proto.toTotalMonths = function toTotalMonths() { - return this._years * 12 + this._months; - }; +/***/ }), - _proto.addTo = function addTo(temporal) { - requireNonNull(temporal, 'temporal'); +/***/ 92288: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this._years !== 0) { - if (this._months !== 0) { - temporal = temporal.plus(this.toTotalMonths(), ChronoUnit.MONTHS); - } else { - temporal = temporal.plus(this._years, ChronoUnit.YEARS); - } - } else if (this._months !== 0) { - temporal = temporal.plus(this._months, ChronoUnit.MONTHS); - } - - if (this._days !== 0) { - temporal = temporal.plus(this._days, ChronoUnit.DAYS); - } - - return temporal; - }; - - _proto.subtractFrom = function subtractFrom(temporal) { - requireNonNull(temporal, 'temporal'); - - if (this._years !== 0) { - if (this._months !== 0) { - temporal = temporal.minus(this.toTotalMonths(), ChronoUnit.MONTHS); - } else { - temporal = temporal.minus(this._years, ChronoUnit.YEARS); - } - } else if (this._months !== 0) { - temporal = temporal.minus(this._months, ChronoUnit.MONTHS); - } - - if (this._days !== 0) { - temporal = temporal.minus(this._days, ChronoUnit.DAYS); - } - - return temporal; - }; - - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } - - if (obj instanceof Period) { - var other = obj; - return this._years === other._years && this._months === other._months && this._days === other._days; - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._years, this._months, this._days); - }; - - _proto.toString = function toString() { - if (this === Period.ZERO) { - return 'P0D'; - } else { - var buf = 'P'; - - if (this._years !== 0) { - buf += '' + this._years + 'Y'; - } - - if (this._months !== 0) { - buf += '' + this._months + 'M'; - } - - if (this._days !== 0) { - buf += '' + this._days + 'D'; - } - - return buf; - } - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return Period; - }(TemporalAmount); - function _init$6() { - Period.ofDays(0); - } - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ParsePosition = function () { - function ParsePosition(index) { - this._index = index; - this._errorIndex = -1; - } - - var _proto = ParsePosition.prototype; - - _proto.getIndex = function getIndex() { - return this._index; - }; - - _proto.setIndex = function setIndex(index) { - this._index = index; - }; - - _proto.getErrorIndex = function getErrorIndex() { - return this._errorIndex; - }; - - _proto.setErrorIndex = function setErrorIndex(errorIndex) { - this._errorIndex = errorIndex; - }; - - return ParsePosition; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var EnumMap = function () { - function EnumMap() { - this._map = {}; - } - - var _proto = EnumMap.prototype; - - _proto.putAll = function putAll(otherMap) { - for (var key in otherMap._map) { - this._map[key] = otherMap._map[key]; - } - - return this; - }; - - _proto.containsKey = function containsKey(key) { - return this._map.hasOwnProperty(key.name()) && this.get(key) !== undefined; - }; - - _proto.get = function get(key) { - return this._map[key.name()]; - }; - - _proto.put = function put(key, val) { - return this.set(key, val); - }; - - _proto.set = function set(key, val) { - this._map[key.name()] = val; - return this; - }; - - _proto.retainAll = function retainAll(keyList) { - var map = {}; - - for (var i = 0; i < keyList.length; i++) { - var key = keyList[i].name(); - map[key] = this._map[key]; - } - - this._map = map; - return this; - }; - - _proto.remove = function remove(key) { - var keyName = key.name(); - var val = this._map[keyName]; - this._map[keyName] = undefined; - return val; - }; - - _proto.keySet = function keySet() { - return this._map; - }; - - _proto.clear = function clear() { - this._map = {}; - }; - - return EnumMap; - }(); - - var ResolverStyle = function (_Enum) { - _inheritsLoose(ResolverStyle, _Enum); - - function ResolverStyle() { - return _Enum.apply(this, arguments) || this; - } - - return ResolverStyle; - }(Enum); - ResolverStyle.STRICT = new ResolverStyle('STRICT'); - ResolverStyle.SMART = new ResolverStyle('SMART'); - ResolverStyle.LENIENT = new ResolverStyle('LENIENT'); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalAdjuster = function () { - function TemporalAdjuster() {} - - var _proto = TemporalAdjuster.prototype; - - _proto.adjustInto = function adjustInto(temporal) { - abstractMethodFail('adjustInto'); - }; - - return TemporalAdjuster; - }(); - - var Temporal = function (_TemporalAccessor) { - _inheritsLoose(Temporal, _TemporalAccessor); - - function Temporal() { - return _TemporalAccessor.apply(this, arguments) || this; - } - - var _proto = Temporal.prototype; - - _proto.isSupported = function isSupported(unit) { - abstractMethodFail('isSupported'); - }; - - _proto.minus = function minus(p1, p2) { - if (arguments.length < 2) { - return this.minusAmount(p1); - } else { - return this.minusAmountUnit(p1, p2); - } - }; - - _proto.minusAmount = function minusAmount(amount) { - abstractMethodFail('minusAmount'); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - abstractMethodFail('minusAmountUnit'); - }; - - _proto.plus = function plus(p1, p2) { - if (arguments.length < 2) { - return this.plusAmount(p1); - } else { - return this.plusAmountUnit(p1, p2); - } - }; - - _proto.plusAmount = function plusAmount(amount) { - abstractMethodFail('plusAmount'); - }; - - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - abstractMethodFail('plusAmountUnit'); - }; - - _proto.until = function until(endTemporal, unit) { - abstractMethodFail('until'); - }; - - _proto.with = function _with(p1, p2) { - if (arguments.length < 2) { - return this.withAdjuster(p1); - } else { - return this.withFieldValue(p1, p2); - } - }; - - _proto.withAdjuster = function withAdjuster(adjuster) { - abstractMethodFail('withAdjuster'); - }; - - _proto.withFieldValue = function withFieldValue(field, newValue) { - abstractMethodFail('withFieldValue'); - }; - - return Temporal; - }(TemporalAccessor); - - var DefaultInterfaceTemporal = function (_Temporal) { - _inheritsLoose(DefaultInterfaceTemporal, _Temporal); - - function DefaultInterfaceTemporal() { - return _Temporal.apply(this, arguments) || this; - } - - var _proto = DefaultInterfaceTemporal.prototype; - - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - requireInstance(adjuster, TemporalAdjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; - - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.addTo(this); - }; - - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.subtractFrom(this); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); - return amountToSubtract === MIN_SAFE_INTEGER ? this.plusAmountUnit(MAX_SAFE_INTEGER, unit).plusAmountUnit(1, unit) : this.plusAmount(-amountToSubtract, unit); - }; - - return DefaultInterfaceTemporal; - }(Temporal); - - var ChronoLocalDate = function (_DefaultInterfaceTemp) { - _inheritsLoose(ChronoLocalDate, _DefaultInterfaceTemp); - - function ChronoLocalDate() { - return _DefaultInterfaceTemp.apply(this, arguments) || this; - } - - var _proto = ChronoLocalDate.prototype; - - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isDateBased(); - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased(); - } - - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.chronology()) { - return this.chronology(); - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.DAYS; - } else if (_query === TemporalQueries.localDate()) { - return LocalDate.ofEpochDay(this.toEpochDay()); - } else if (_query === TemporalQueries.localTime() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } - - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; - - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.EPOCH_DAY, this.toEpochDay()); - }; - - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.format(this); - }; - - return ChronoLocalDate; - }(DefaultInterfaceTemporal); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var StringUtil = function () { - function StringUtil() {} - - StringUtil.startsWith = function startsWith(text, pattern) { - return text.indexOf(pattern) === 0; - }; - - StringUtil.hashCode = function hashCode(text) { - var len = text.length; - - if (len === 0) { - return 0; - } - - var hash = 0; - - for (var i = 0; i < len; i++) { - var chr = text.charCodeAt(i); - hash = (hash << 5) - hash + chr; - hash |= 0; - } - - return MathUtil.smi(hash); - }; - - return StringUtil; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneId = function () { - function ZoneId() {} - - ZoneId.systemDefault = function systemDefault() { - throw new DateTimeException('not supported operation'); - }; - - ZoneId.getAvailableZoneIds = function getAvailableZoneIds() { - throw new DateTimeException('not supported operation'); - }; - - ZoneId.of = function of(zoneId) { - throw new DateTimeException('not supported operation' + zoneId); - }; - - ZoneId.ofOffset = function ofOffset(prefix, offset) { - throw new DateTimeException('not supported operation' + prefix + offset); - }; - - ZoneId.from = function from(temporal) { - throw new DateTimeException('not supported operation' + temporal); - }; - - var _proto = ZoneId.prototype; - - _proto.id = function id() { - abstractMethodFail('ZoneId.id'); - }; - - _proto.rules = function rules() { - abstractMethodFail('ZoneId.rules'); - }; - - _proto.normalized = function normalized() { - var rules = this.rules(); - - if (rules.isFixedOffset()) { - return rules.offset(Instant.EPOCH); - } - - return this; - }; - - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - - if (other instanceof ZoneId) { - return this.id() === other.id(); - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return StringUtil.hashCode(this.id()); - }; - - _proto.toString = function toString() { - return this.id(); - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return ZoneId; - }(); - - var ZoneRules = function () { - function ZoneRules() {} - - ZoneRules.of = function of(offset) { - requireNonNull(offset, 'offset'); - return new Fixed(offset); - }; - - var _proto = ZoneRules.prototype; - - _proto.isFixedOffset = function isFixedOffset() { - abstractMethodFail('ZoneRules.isFixedOffset'); - }; - - _proto.offset = function offset(instantOrLocalDateTime) { - if (instantOrLocalDateTime instanceof Instant) { - return this.offsetOfInstant(instantOrLocalDateTime); - } else { - return this.offsetOfLocalDateTime(instantOrLocalDateTime); - } - }; - - _proto.offsetOfInstant = function offsetOfInstant(instant) { - abstractMethodFail('ZoneRules.offsetInstant'); - }; - - _proto.offsetOfEpochMilli = function offsetOfEpochMilli(epochMilli) { - abstractMethodFail('ZoneRules.offsetOfEpochMilli'); - }; - - _proto.offsetOfLocalDateTime = function offsetOfLocalDateTime(localDateTime) { - abstractMethodFail('ZoneRules.offsetLocalDateTime'); - }; - - _proto.validOffsets = function validOffsets(localDateTime) { - abstractMethodFail('ZoneRules.validOffsets'); - }; - - _proto.transition = function transition(localDateTime) { - abstractMethodFail('ZoneRules.transition'); - }; - - _proto.standardOffset = function standardOffset(instant) { - abstractMethodFail('ZoneRules.standardOffset'); - }; - - _proto.daylightSavings = function daylightSavings(instant) { - abstractMethodFail('ZoneRules.daylightSavings'); - }; - - _proto.isDaylightSavings = function isDaylightSavings(instant) { - abstractMethodFail('ZoneRules.isDaylightSavings'); - }; - - _proto.isValidOffset = function isValidOffset(localDateTime, offset) { - abstractMethodFail('ZoneRules.isValidOffset'); - }; - - _proto.nextTransition = function nextTransition(instant) { - abstractMethodFail('ZoneRules.nextTransition'); - }; - - _proto.previousTransition = function previousTransition(instant) { - abstractMethodFail('ZoneRules.previousTransition'); - }; - - _proto.transitions = function transitions() { - abstractMethodFail('ZoneRules.transitions'); - }; - - _proto.transitionRules = function transitionRules() { - abstractMethodFail('ZoneRules.transitionRules'); - }; - - _proto.toString = function toString() { - abstractMethodFail('ZoneRules.toString'); - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return ZoneRules; - }(); - - var Fixed = function (_ZoneRules) { - _inheritsLoose(Fixed, _ZoneRules); - - function Fixed(offset) { - var _this; - - _this = _ZoneRules.call(this) || this; - _this._offset = offset; - return _this; - } - - var _proto2 = Fixed.prototype; - - _proto2.isFixedOffset = function isFixedOffset() { - return true; - }; - - _proto2.offsetOfInstant = function offsetOfInstant() { - return this._offset; - }; - - _proto2.offsetOfEpochMilli = function offsetOfEpochMilli() { - return this._offset; - }; - - _proto2.offsetOfLocalDateTime = function offsetOfLocalDateTime() { - return this._offset; - }; - - _proto2.validOffsets = function validOffsets() { - return [this._offset]; - }; - - _proto2.transition = function transition() { - return null; - }; - - _proto2.standardOffset = function standardOffset() { - return this._offset; - }; - - _proto2.daylightSavings = function daylightSavings() { - return Duration.ZERO; - }; - - _proto2.isDaylightSavings = function isDaylightSavings() { - return false; - }; - - _proto2.isValidOffset = function isValidOffset(localDateTime, offset) { - return this._offset.equals(offset); - }; - - _proto2.nextTransition = function nextTransition() { - return null; - }; - - _proto2.previousTransition = function previousTransition() { - return null; - }; - - _proto2.transitions = function transitions() { - return []; - }; - - _proto2.transitionRules = function transitionRules() { - return []; - }; - - _proto2.equals = function equals(other) { - if (this === other) { - return true; - } - - if (other instanceof Fixed) { - return this._offset.equals(other._offset); - } - - return false; - }; - - _proto2.toString = function toString() { - return 'FixedRules:' + this._offset.toString(); - }; - - return Fixed; - }(ZoneRules); - - var SECONDS_CACHE = {}; - var ID_CACHE = {}; - var ZoneOffset = function (_ZoneId) { - _inheritsLoose(ZoneOffset, _ZoneId); - - function ZoneOffset(totalSeconds) { - var _this; - - _this = _ZoneId.call(this) || this; - - ZoneOffset._validateTotalSeconds(totalSeconds); - - _this._totalSeconds = MathUtil.safeToInt(totalSeconds); - _this._rules = ZoneRules.of(_assertThisInitialized(_this)); - _this._id = ZoneOffset._buildId(totalSeconds); - return _this; - } - - var _proto = ZoneOffset.prototype; - - _proto.totalSeconds = function totalSeconds() { - return this._totalSeconds; - }; - - _proto.id = function id() { - return this._id; - }; - - ZoneOffset._buildId = function _buildId(totalSeconds) { - if (totalSeconds === 0) { - return 'Z'; - } else { - var absTotalSeconds = Math.abs(totalSeconds); - var absHours = MathUtil.intDiv(absTotalSeconds, LocalTime.SECONDS_PER_HOUR); - var absMinutes = MathUtil.intMod(MathUtil.intDiv(absTotalSeconds, LocalTime.SECONDS_PER_MINUTE), LocalTime.MINUTES_PER_HOUR); - var buf = '' + (totalSeconds < 0 ? '-' : '+') + (absHours < 10 ? '0' : '') + absHours + (absMinutes < 10 ? ':0' : ':') + absMinutes; - var absSeconds = MathUtil.intMod(absTotalSeconds, LocalTime.SECONDS_PER_MINUTE); - - if (absSeconds !== 0) { - buf += (absSeconds < 10 ? ':0' : ':') + absSeconds; - } - - return buf; - } - }; - - ZoneOffset._validateTotalSeconds = function _validateTotalSeconds(totalSeconds) { - if (Math.abs(totalSeconds) > ZoneOffset.MAX_SECONDS) { - throw new DateTimeException('Zone offset not in valid range: -18:00 to +18:00'); - } - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var uuid = __nccwpck_require__(19744); // want to replace with this in the future: https://gist.github.com/jed/982883 + + + +var LEVEL_STRING_MAP = { + 0 : 'ERROR:', + 1 : 'WARNING:', + 2 : 'INFO:', + 3 : 'VERBOSE:' +}; + +/** + * Methods for controling global logging options for ADAL + * @namespace + */ +var Logging = { + + /** + * @callback LoggingCallback + * @memberOf Logging + * @param {Logging.LOGGING_LEVEL} level The level of this log entry. + * @param {string} message The text content of the log entry. + * @param {Error} [error] An Error object if this is an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. + */ + + /** + * @typedef LoggingOptions + * @memberOf Logging + * @property {LoggingCallback} [log] The function to call when ADAL generates a log entry. + * @property {Logging.LOGGING_LEVEL} [level] The maximum level of log entries to generate. + */ + + /** + * Describes the available logging levels. + * @enum + * @type {Number} + */ + LOGGING_LEVEL : { + ERROR : 0, + WARN : 1, + INFO : 2, + VERBOSE : 3 + }, + + /** + * Sets global logging options for ADAL. + * @param {LoggingOptions} options + */ + setLoggingOptions : function(options) { + if (!options) { + options = {}; + } + + if (options.log) { + if (!_.isFunction(options.log)) { + throw new Error('setLogOptions expects the log key in the options parameter to be a function'); + } + } else { + // if no log function was passed set it to a default no op function. + options.log = function() {}; + } + + if (options.level) { + var level = options.level; + if (level < 0 || level > 3) { + throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive'); + } + } else { + options.level = this.LOGGING_LEVEL.ERROR; + } + + if (options.loggingWithPII != true) { + options.loggingWithPII = false; + } + + this.LogOptions = options; + }, + + /** + * Get's the current global logging options. + * @return {LoggingOptions} + */ + getLoggingOptions : function() { + return this.LogOptions; + }, + + /** + * Stores the current global logging options. + * @private + * @type {LoggingOptions} + */ + LogOptions : { + log : function() {}, + level : 0, + loggingWithPII: false + } +}; + +/** + * An internal logging object. + * @class + * @private + * @param {string} componentName The name of the component that created this instance. This name will be + * prepended to the beginning of all log entries generated by this instance. + */ +function Logger(componentName, logContext) { + if (!logContext) { + throw new Error('Logger: logContext is a required parameter'); + } + this._componentName = componentName; + this._logContext = logContext; +} + +Object.defineProperty(Logger.prototype, 'context', { + get: function () { + return this._logContext; + } +}); + +/** + * Generates a log entry + * @param {Logging.LOGGING_LEVEL} level The level of this log entry + * @param {string|function} message A message string, or a function that returns a message string, to log. + * @param {Error} [error] If this is a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry then the caller + * should pass an error object in this parameter. + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.log = function (level, message, error, containsPII) { + if (containsPII == true && !Logging.LogOptions.loggingWithPII) { + return; + } + + if (level <= Logging.LogOptions.level) { + if (_.isFunction(message)) { + message = message(); + } + + var correlationId = this._logContext.correlationId || ''; + var timeStamp = new Date().toUTCString(); + + var formattedMessage = timeStamp + ':' + correlationId + ' - ' + this._componentName + ': ' + LEVEL_STRING_MAP[level] + ' ' + message; + if (error) { + formattedMessage += '\nStack:\n' + error.stack; + } + Logging.LogOptions.log(level, formattedMessage, error); + } +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. + * @param {string} message A message to log + * @param {Error} error The Error object associated with this log entry + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.error = function (message, error, containsPII) { + this.log(Logging.LOGGING_LEVEL.ERROR, message, error, containsPII); +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.WARN|WARN} level log entry. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.warn = function (message, containsPII) { + this.log(Logging.LOGGING_LEVEL.WARN, message, null, containsPII); +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.INFO|INFO} level log entry. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.info = function (message, containsPII) { + this.log(Logging.LOGGING_LEVEL.INFO, message, null, containsPII); +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.VERBOSE|VERBOSE} level log entry. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.verbose = function (message, containsPII) { + this.log(Logging.LOGGING_LEVEL.VERBOSE, message, null, containsPII); +}; + +/** + * Generate a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry, as well as an + * Error object to go with it. This is a convenience method for throwing logged errors. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.createError = function(message, containsPII) { + var err = new Error(message); + this.error(message, err, containsPII); + return err; +}; + +/** + * Creates a new log context based on the correlationId passed in. If no correlationId is passed in + * then one is generated, by the function uuid.v4() + * @private + */ +function createLogContext(correlationId) { + var id = correlationId || uuid.v4(); + return { correlationId : id }; +} + +var exports = { + Logging : Logging, + Logger : Logger, + createLogContext : createLogContext +}; + +module.exports = exports; - ZoneOffset._validate = function _validate(hours, minutes, seconds) { - if (hours < -18 || hours > 18) { - throw new DateTimeException('Zone offset hours not in valid range: value ' + hours + ' is not in the range -18 to 18'); - } +/***/ }), - if (hours > 0) { - if (minutes < 0 || seconds < 0) { - throw new DateTimeException('Zone offset minutes and seconds must be positive because hours is positive'); - } - } else if (hours < 0) { - if (minutes > 0 || seconds > 0) { - throw new DateTimeException('Zone offset minutes and seconds must be negative because hours is negative'); - } - } else if (minutes > 0 && seconds < 0 || minutes < 0 && seconds > 0) { - throw new DateTimeException('Zone offset minutes and seconds must have the same sign'); - } +/***/ 92474: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (Math.abs(minutes) > 59) { - throw new DateTimeException('Zone offset minutes not in valid range: abs(value) ' + Math.abs(minutes) + ' is not in the range 0 to 59'); - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + + +var _ = __nccwpck_require__(83571); + +/** + * Constructs a new in memory token cache. + * @constructor + */ +function MemoryCache() { + this._entries = []; +} + +/** + * Removes a collection of entries from the cache in a single batch operation. + * @param {Array} entries An array of cache entries to remove. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +MemoryCache.prototype.remove = function(entries, callback) { + var updatedEntries = _.filter(this._entries, function(element) { + if (_.findWhere(entries, element)) { + return false; + } + return true; + }); + + this._entries = updatedEntries; + callback(); +}; + +/** + * Adds a collection of entries to the cache in a single batch operation. + * @param {Array} entries An array of entries to add to the cache. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +MemoryCache.prototype.add = function(entries, callback) { + // Remove any entries that are duplicates of the existing + // cache elements. + _.each(this._entries, function(element) { + _.each(entries, function(addElement, index) { + if (_.isEqual(element, addElement)) { + entries[index] = null; + } + }); + }); + + // Add the new entries to the end of the cache. + entries = _.compact(entries); + for (var i = 0; i < entries.length; i++) { + this._entries.push(entries[i]); + } + + callback(null, true); +}; + +/** + * Finds all entries in the cache that match all of the passed in values. + * @param {object} query This object will be compared to each entry in the cache. Any entries that + * match all of the values in this object will be returned. All the values + * in the passed in object must match values in a potentialy returned object + * exactly. The returned object may have more values than the passed in query + * object. + * @param {TokenCacheFindCallback} callback + */ +MemoryCache.prototype.find = function(query, callback) { + var results = _.where(this._entries, query); + callback(null, results); +}; + +module.exports = MemoryCache; - if (Math.abs(seconds) > 59) { - throw new DateTimeException('Zone offset seconds not in valid range: abs(value) ' + Math.abs(seconds) + ' is not in the range 0 to 59'); - } +/***/ }), - if (Math.abs(hours) === 18 && (Math.abs(minutes) > 0 || Math.abs(seconds) > 0)) { - throw new DateTimeException('Zone offset not in valid range: -18:00 to +18:00'); - } - }; +/***/ 27078: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - ZoneOffset.of = function of(offsetId) { - requireNonNull(offsetId, 'offsetId'); - var offset = ID_CACHE[offsetId]; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + +var request = __nccwpck_require__(48699); +var url = __nccwpck_require__(78835); +var DOMParser = __nccwpck_require__(57286).DOMParser; +var _ = __nccwpck_require__(83571); +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +var xmlutil = __nccwpck_require__(27387); +var select = xmlutil.xpathSelect; + +var Namespaces = __nccwpck_require__(10282).XmlNamespaces; + +var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + +/** + * Create a new Mex object. + * @private + * @constructor + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} url The url of the mex endpoint. + */ +function Mex(callContext, url) { + this._log = new Logger('MEX', callContext._logContext); + this._callContext = callContext; + this._url = url; + this._dom = null; + this._mexDoc = null; + this._usernamePasswordPolicy = {}; + this._log.verbose('Mex created'); + this._log.verbose('Mex created with url: ' + url, true); +} + +/** +* Returns the policy containing IDP url and wstrust version from which a username passwowrd can be exchanged for a token. +* @instance +* @memberOf Mex +* @name usernamePasswordPolicy +*/ +Object.defineProperty(Mex.prototype, 'usernamePasswordPolicy', { + get: function() { + return this._usernamePasswordPolicy; + } +}); + +/** +* @callback DiscoverCallback +* @memberOf Mex +* @param {object} error +*/ + +/** +* Performs Mex discovery. This method will retrieve the mex document, parse it, and extract +* the username password ws-trust endpoint. +* @private +* @param {Mex.DiscoverCallback} callback Called when discover is complete. +*/ +Mex.prototype.discover = function (callback) { + this._log.verbose('Retrieving mex'); + this._log.verbose('Retrieving mex at: ' + this._url); + var self = this; + var options = util.createRequestOptions(self, { headers : { 'Content-Type' : 'application/soap+xml'} }); + request.get(this._url, options, util.createRequestHandler('Mex Get', this._log, callback, + function(response, body) { + try { + self._mexDoc = body; + var options = { + errorHandler : self._log.error + }; + self._dom = new DOMParser(options).parseFromString(self._mexDoc); + self._parse(callback); + return; + } catch (err) { + self._log.error('Failed to parse mex response in to DOM', err, true); + callback(err); + } + }) + ); +}; + +var TRANSPORT_BINDING_XPATH = 'wsp:ExactlyOne/wsp:All/sp:TransportBinding'; +var TRANSPORT_BINDING_2005_XPATH = 'wsp:ExactlyOne/wsp:All/sp2005:TransportBinding'; +/** +* Checks a DOM policy node that is a potentialy appplicable username password policy +* to ensure that it has the correct transport. +* @private +* @param {object} policyNode The policy node to check. +* @returns {string} If the policy matches the desired transport then the id of the policy is returned. +* If not then null is returned. +*/ +Mex.prototype._checkPolicy = function(policyNode) { + var policyId = null; + var id = policyNode.getAttributeNS(Namespaces.wsu, 'Id'); + var transportBindingNodes = select(policyNode, TRANSPORT_BINDING_XPATH); + if (0 === transportBindingNodes.length) { + transportBindingNodes = select(policyNode, TRANSPORT_BINDING_2005_XPATH); + } + if (0 !== transportBindingNodes.length) { + if (id) { + policyId = id; + } + } + if (policyId) { + this._log.verbose('found matching policy id'); + this._log.verbose('found matching policy id: ' + policyId, true); + } else { + if (!id) { + id = ''; + } + this._log.verbose('potential policy did not match required transport binding'); + this._log.verbose('potential policy did not match required transport binding: ' + id, true); + } + return policyId; +}; + +/** +* Finds all username password policies within the mex document. +* @private +* @param xpath The xpath expression for selecting username token nodes. +* @returns {object} A map object that contains objects containing the id of username password polices. +*/ +Mex.prototype._selectUsernamePasswordPolicies = function(xpath) { + var policies = {}; + var usernameTokenNodes = select(this._dom, xpath); + if (!usernameTokenNodes.length) { + this._log.warn('no username token policy nodes found'); + return; + } + for (var i=0; i < usernameTokenNodes.length; i++) { + var policyNode = usernameTokenNodes[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; + var id = this._checkPolicy(policyNode); + if (id) { + var idRef = '#' + id; + policies[idRef] = { id : idRef }; + } + } + return _.isEmpty(policies) ? null : policies; +}; + +var SOAP_ACTION_XPATH = 'wsdl:operation/soap12:operation/@soapAction'; +var RST_SOAP_ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; +var RST_SOAP_ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; +var SOAP_TRANSPORT_XPATH = 'soap12:binding/@transport'; +var SOAP_HTTP_TRANSPORT_VALUE = 'http://schemas.xmlsoap.org/soap/http'; +/** +* Given a DOM binding node determines whether it matches the correct soap action and transport. +* @private +* @param {object} bindingNode The DOM node to check. +* @returns {bool} +*/ +Mex.prototype._checkSoapActionAndTransport = function(bindingNode) { + var soapTransportAttributes; + var soapAction; + var soapTransport; + var bindingName = bindingNode.getAttribute('name'); + var soapActionAttributes = select(bindingNode, SOAP_ACTION_XPATH); + if (soapActionAttributes.length) { + soapAction = soapActionAttributes[0].value; + soapTransportAttributes = select(bindingNode, SOAP_TRANSPORT_XPATH); + } + if (soapTransportAttributes.length) { + soapTransport = soapTransportAttributes[0].value; + } + + if (soapTransport === SOAP_HTTP_TRANSPORT_VALUE) { + if (soapAction === RST_SOAP_ACTION_13) { + this._log.verbose('foud binding matching Action and Transport: ' + bindingName); + return WSTrustVersion.WSTRUST13; + } + else if (soapAction === RST_SOAP_ACTION_2005) { + this._log.verbose('found binding matching Action and Transport: ' + bindingName); + return WSTrustVersion.WSTRUST2005; + } + } + + this._log.verbose('binding node did not match soap Action or Transport: ' + bindingName); + return WSTrustVersion.UNDEFINED; +}; + +/** +* Given a map with policy id keys, finds the bindings in the mex document that are linked to thos policies. +* @private +* @param {object} policies A map with policy id keys. +* @returns {object} a map of bindings id's to policy id's. +*/ +Mex.prototype._getMatchingBindings = function(policies) { + var bindings = {}; + var bindingPolicyRefNodes = select(this._dom, '//wsdl:definitions/wsdl:binding/wsp:PolicyReference'); + for (var i=0; i < bindingPolicyRefNodes.length; i++) { + var node = bindingPolicyRefNodes[i]; + var uri = node.getAttribute('URI'); + var policy = policies[uri]; + if (policy) { + var bindingNode = node.parentNode; + var bindingName = bindingNode.getAttribute('name'); + var version = this._checkSoapActionAndTransport(bindingNode); + if (version !== WSTrustVersion.UNDEFINED) { + var bindingPolicy = {}; + bindingPolicy.url = uri; + bindingPolicy.version = version; + + bindings[bindingName] = bindingPolicy; + } + } + } + return _.isEmpty(bindings) ? null : bindings; +}; + +/** +* Ensures that a url points to an SSL endpoint. +* @private +* @param {string} endpointUrl The url to check. +* @returns {bool} +*/ +Mex.prototype._urlIsSecure = function(endpointUrl) { + var parsedUrl = url.parse(endpointUrl); + return parsedUrl.protocol === 'https:'; +}; + +var PORT_XPATH = '//wsdl:definitions/wsdl:service/wsdl:port'; +var ADDRESS_XPATH = 'wsa10:EndpointReference/wsa10:Address'; +/** +* Finds all of the wsdl ports in the mex document that are associated with username password policies. Augments +* the passed in bindings with the endpoint url of the correct port. +* @private +* @param {object} bindings A map of binding id's to policy id's. +*/ +Mex.prototype._getPortsForPolicyBindings = function(bindings, policies) { + var portNodes = select(this._dom, PORT_XPATH); + if (0 === portNodes.length) { + this._log.warning('no ports found'); + } + for (var i=0; i < portNodes.length; i++) { + var portNode = portNodes[i]; + var bindingId = portNode.getAttribute('binding'); + + // Clear any prefix + var bindingIdParts = bindingId.split(':'); + bindingId = bindingIdParts[bindingIdParts.length - 1]; + + var trustPolicy = bindings[bindingId]; + if (trustPolicy) { + var bindingPolicy = policies[trustPolicy.url]; + + if (bindingPolicy && !bindingPolicy.url) { + bindingPolicy.version = trustPolicy.version; + var addressNode = select(portNode, ADDRESS_XPATH); + if (0 === addressNode) { + throw this._log.createError('no address nodes on port.'); + } + var address = xmlutil.findElementText(addressNode[0]); + if (this._urlIsSecure(address)) { + bindingPolicy.url = address; + } else { + this._log.warn('skipping insecure endpoint: ' + address); + } + } + } + } +}; + +/** +* Given a list of username password policies chooses one of them at random as the policy chosen by this Mex instance. +* @private +* @param {object} policies A map of policy id's to an object containing username password ws-trust endpoint addresses. +*/ +Mex.prototype._selectSingleMatchingPolicy = function(policies) { + // if both wstrust13 and wstrust2005 policy exists, then choose wstrust13, otherwise choose whatever exists. + var matchingPolicies = _.filter(policies, function(policy) { return policy.url ? true : false; }); + if (!matchingPolicies) { + this._log.warn('no policies found with an url'); + return; + } + + var wstrust13Policy = null, wstrust2005Policy = null; + for(var i = 0; i < matchingPolicies.length; ++i) { + var matchingPolicy = matchingPolicies[i]; + if (WSTrustVersion.WSTRUST13 === matchingPolicy.version) { + wstrust13Policy = matchingPolicy; + } + else if (WSTrustVersion.WSTRUST2005 === matchingPolicy.version) { + wstrust2005Policy = matchingPolicy; + } + } + + if (!wstrust13Policy && !wstrust2005Policy) { + this._log.warn('no policies found with an url'); + this._usernamePasswordPolicy = null; + return; + } + + this._usernamePasswordPolicy = wstrust13Policy ? wstrust13Policy : wstrust2005Policy; +}; + +/** +* Parses the mex document previously retrieved. +* @private +* @param {Mex.DiscoverCallback} callback +*/ +Mex.prototype._parse = function(callback) { + var self = this; + var xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp:SignedEncryptedSupportingTokens/wsp:Policy/sp:UsernameToken/wsp:Policy/sp:WssUsernameToken10'; + var policies = self._selectUsernamePasswordPolicies(xpathExpression); + + xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10'; + + if (policies) { + _.extend(policies, self._selectUsernamePasswordPolicies(xpathExpression)); + } + else { + policies = self._selectUsernamePasswordPolicies(xpathExpression); + } + + if (!policies) { + callback(self._log.createError('No matching policies')); + return; + } + var bindings = self._getMatchingBindings(policies); + if (!bindings) { + callback(self._log.createError('No matching bindings')); + return; + } + self._getPortsForPolicyBindings(bindings, policies); + self._selectSingleMatchingPolicy(policies); + var err = this._url ? undefined : this._log.createError('No ws-trust endpoints match requirements.'); + callback(err); +}; + +module.exports = Mex; - if (offset != null) { - return offset; - } +/***/ }), - var hours, minutes, seconds; +/***/ 41602: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - switch (offsetId.length) { - case 2: - offsetId = offsetId[0] + '0' + offsetId[1]; - - case 3: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = 0; - seconds = 0; - break; - - case 5: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 3, false); - seconds = 0; - break; - - case 6: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 4, true); - seconds = 0; - break; - - case 7: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 3, false); - seconds = ZoneOffset._parseNumber(offsetId, 5, false); - break; - - case 9: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 4, true); - seconds = ZoneOffset._parseNumber(offsetId, 7, true); - break; - - default: - throw new DateTimeException('Invalid ID for ZoneOffset, invalid format: ' + offsetId); - } - - var first = offsetId[0]; - - if (first !== '+' && first !== '-') { - throw new DateTimeException('Invalid ID for ZoneOffset, plus/minus not found when expected: ' + offsetId); - } - - if (first === '-') { - return ZoneOffset.ofHoursMinutesSeconds(-hours, -minutes, -seconds); - } else { - return ZoneOffset.ofHoursMinutesSeconds(hours, minutes, seconds); - } - }; - - ZoneOffset._parseNumber = function _parseNumber(offsetId, pos, precededByColon) { - if (precededByColon && offsetId[pos - 1] !== ':') { - throw new DateTimeException('Invalid ID for ZoneOffset, colon not found when expected: ' + offsetId); - } - - var ch1 = offsetId[pos]; - var ch2 = offsetId[pos + 1]; - - if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') { - throw new DateTimeException('Invalid ID for ZoneOffset, non numeric characters found: ' + offsetId); - } - - return (ch1.charCodeAt(0) - 48) * 10 + (ch2.charCodeAt(0) - 48); - }; - - ZoneOffset.ofHours = function ofHours(hours) { - return ZoneOffset.ofHoursMinutesSeconds(hours, 0, 0); - }; - - ZoneOffset.ofHoursMinutes = function ofHoursMinutes(hours, minutes) { - return ZoneOffset.ofHoursMinutesSeconds(hours, minutes, 0); - }; - - ZoneOffset.ofHoursMinutesSeconds = function ofHoursMinutesSeconds(hours, minutes, seconds) { - ZoneOffset._validate(hours, minutes, seconds); - - var totalSeconds = hours * LocalTime.SECONDS_PER_HOUR + minutes * LocalTime.SECONDS_PER_MINUTE + seconds; - return ZoneOffset.ofTotalSeconds(totalSeconds); - }; - - ZoneOffset.ofTotalMinutes = function ofTotalMinutes(totalMinutes) { - var totalSeconds = totalMinutes * LocalTime.SECONDS_PER_MINUTE; - return ZoneOffset.ofTotalSeconds(totalSeconds); - }; - - ZoneOffset.ofTotalSeconds = function ofTotalSeconds(totalSeconds) { - if (totalSeconds % (15 * LocalTime.SECONDS_PER_MINUTE) === 0) { - var totalSecs = totalSeconds; - var result = SECONDS_CACHE[totalSecs]; - - if (result == null) { - result = new ZoneOffset(totalSeconds); - SECONDS_CACHE[totalSecs] = result; - ID_CACHE[result.id()] = result; - } - - return result; - } else { - return new ZoneOffset(totalSeconds); - } - }; - - _proto.rules = function rules() { - return this._rules; - }; - - _proto.get = function get(field) { - return this.getLong(field); - }; - - _proto.getLong = function getLong(field) { - if (field === ChronoField.OFFSET_SECONDS) { - return this._totalSeconds; - } else if (field instanceof ChronoField) { - throw new DateTimeException('Unsupported field: ' + field); - } - - return field.getFrom(this); - }; - - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - - if (_query === TemporalQueries.offset() || _query === TemporalQueries.zone()) { - return this; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.precision() || _query === TemporalQueries.chronology() || _query === TemporalQueries.zoneId()) { - return null; - } - - return _query.queryFrom(this); - }; - - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.OFFSET_SECONDS, this._totalSeconds); - }; - - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - return other._totalSeconds - this._totalSeconds; - }; - - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } - - if (obj instanceof ZoneOffset) { - return this._totalSeconds === obj._totalSeconds; - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return this._totalSeconds; - }; - - _proto.toString = function toString() { - return this._id; - }; - - return ZoneOffset; - }(ZoneId); - function _init$7() { - ZoneOffset.MAX_SECONDS = 18 * LocalTime.SECONDS_PER_HOUR; - ZoneOffset.UTC = ZoneOffset.ofTotalSeconds(0); - ZoneOffset.MIN = ZoneOffset.ofTotalSeconds(-ZoneOffset.MAX_SECONDS); - ZoneOffset.MAX = ZoneOffset.ofTotalSeconds(ZoneOffset.MAX_SECONDS); - } - - var DateTimeBuilder = function (_TemporalAccessor) { - _inheritsLoose(DateTimeBuilder, _TemporalAccessor); - - DateTimeBuilder.create = function create(field, value) { - var dtb = new DateTimeBuilder(); - - dtb._addFieldValue(field, value); - - return dtb; - }; - - function DateTimeBuilder() { - var _this; - - _this = _TemporalAccessor.call(this) || this; - _this.fieldValues = new EnumMap(); - _this.chrono = null; - _this.zone = null; - _this.date = null; - _this.time = null; - _this.leapSecond = false; - _this.excessDays = null; - return _this; - } - - var _proto = DateTimeBuilder.prototype; - - _proto.getFieldValue0 = function getFieldValue0(field) { - return this.fieldValues.get(field); - }; - - _proto._addFieldValue = function _addFieldValue(field, value) { - requireNonNull(field, 'field'); - var old = this.getFieldValue0(field); - - if (old != null && old !== value) { - throw new DateTimeException('Conflict found: ' + field + ' ' + old + ' differs from ' + field + ' ' + value + ': ' + this); - } - - return this._putFieldValue0(field, value); - }; - - _proto._putFieldValue0 = function _putFieldValue0(field, value) { - this.fieldValues.put(field, value); - return this; - }; - - _proto.resolve = function resolve(resolverStyle, resolverFields) { - if (resolverFields != null) { - this.fieldValues.retainAll(resolverFields); - } - - this._mergeDate(resolverStyle); - - this._mergeTime(resolverStyle); - - this._resolveTimeInferZeroes(resolverStyle); - - if (this.excessDays != null && this.excessDays.isZero() === false && this.date != null && this.time != null) { - this.date = this.date.plus(this.excessDays); - this.excessDays = Period.ZERO; - } - - this._resolveInstant(); - - return this; - }; - - _proto._mergeDate = function _mergeDate(resolverStyle) { - this._checkDate(IsoChronology.INSTANCE.resolveDate(this.fieldValues, resolverStyle)); - }; - - _proto._checkDate = function _checkDate(date) { - if (date != null) { - this._addObject(date); - - for (var fieldName in this.fieldValues.keySet()) { - var field = ChronoField.byName(fieldName); - - if (field) { - if (this.fieldValues.get(field) !== undefined) { - if (field.isDateBased()) { - var val1 = void 0; - - try { - val1 = date.getLong(field); - } catch (ex) { - if (ex instanceof DateTimeException) { - continue; - } else { - throw ex; - } - } - - var val2 = this.fieldValues.get(field); - - if (val1 !== val2) { - throw new DateTimeException('Conflict found: Field ' + field + ' ' + val1 + ' differs from ' + field + ' ' + val2 + ' derived from ' + date); - } - } - } - } - } - } - }; - - _proto._mergeTime = function _mergeTime(resolverStyle) { - if (this.fieldValues.containsKey(ChronoField.CLOCK_HOUR_OF_DAY)) { - var ch = this.fieldValues.remove(ChronoField.CLOCK_HOUR_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (resolverStyle === ResolverStyle.SMART && ch === 0) ; else { - ChronoField.CLOCK_HOUR_OF_DAY.checkValidValue(ch); - } - } - - this._addFieldValue(ChronoField.HOUR_OF_DAY, ch === 24 ? 0 : ch); - } - - if (this.fieldValues.containsKey(ChronoField.CLOCK_HOUR_OF_AMPM)) { - var _ch = this.fieldValues.remove(ChronoField.CLOCK_HOUR_OF_AMPM); - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (resolverStyle === ResolverStyle.SMART && _ch === 0) ; else { - ChronoField.CLOCK_HOUR_OF_AMPM.checkValidValue(_ch); - } - } - - this._addFieldValue(ChronoField.HOUR_OF_AMPM, _ch === 12 ? 0 : _ch); - } - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (this.fieldValues.containsKey(ChronoField.AMPM_OF_DAY)) { - ChronoField.AMPM_OF_DAY.checkValidValue(this.fieldValues.get(ChronoField.AMPM_OF_DAY)); - } - - if (this.fieldValues.containsKey(ChronoField.HOUR_OF_AMPM)) { - ChronoField.HOUR_OF_AMPM.checkValidValue(this.fieldValues.get(ChronoField.HOUR_OF_AMPM)); - } - } - - if (this.fieldValues.containsKey(ChronoField.AMPM_OF_DAY) && this.fieldValues.containsKey(ChronoField.HOUR_OF_AMPM)) { - var ap = this.fieldValues.remove(ChronoField.AMPM_OF_DAY); - var hap = this.fieldValues.remove(ChronoField.HOUR_OF_AMPM); - - this._addFieldValue(ChronoField.HOUR_OF_DAY, ap * 12 + hap); - } - - if (this.fieldValues.containsKey(ChronoField.NANO_OF_DAY)) { - var nod = this.fieldValues.remove(ChronoField.NANO_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.NANO_OF_DAY.checkValidValue(nod); - } - - this._addFieldValue(ChronoField.SECOND_OF_DAY, MathUtil.intDiv(nod, 1000000000)); - - this._addFieldValue(ChronoField.NANO_OF_SECOND, MathUtil.intMod(nod, 1000000000)); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_DAY)) { - var cod = this.fieldValues.remove(ChronoField.MICRO_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.MICRO_OF_DAY.checkValidValue(cod); - } - - this._addFieldValue(ChronoField.SECOND_OF_DAY, MathUtil.intDiv(cod, 1000000)); - - this._addFieldValue(ChronoField.MICRO_OF_SECOND, MathUtil.intMod(cod, 1000000)); - } - - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_DAY)) { - var lod = this.fieldValues.remove(ChronoField.MILLI_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.MILLI_OF_DAY.checkValidValue(lod); - } - - this._addFieldValue(ChronoField.SECOND_OF_DAY, MathUtil.intDiv(lod, 1000)); - - this._addFieldValue(ChronoField.MILLI_OF_SECOND, MathUtil.intMod(lod, 1000)); - } - - if (this.fieldValues.containsKey(ChronoField.SECOND_OF_DAY)) { - var sod = this.fieldValues.remove(ChronoField.SECOND_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.SECOND_OF_DAY.checkValidValue(sod); - } - - this._addFieldValue(ChronoField.HOUR_OF_DAY, MathUtil.intDiv(sod, 3600)); - - this._addFieldValue(ChronoField.MINUTE_OF_HOUR, MathUtil.intMod(MathUtil.intDiv(sod, 60), 60)); - - this._addFieldValue(ChronoField.SECOND_OF_MINUTE, MathUtil.intMod(sod, 60)); - } - - if (this.fieldValues.containsKey(ChronoField.MINUTE_OF_DAY)) { - var mod = this.fieldValues.remove(ChronoField.MINUTE_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.MINUTE_OF_DAY.checkValidValue(mod); - } - - this._addFieldValue(ChronoField.HOUR_OF_DAY, MathUtil.intDiv(mod, 60)); - - this._addFieldValue(ChronoField.MINUTE_OF_HOUR, MathUtil.intMod(mod, 60)); - } - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND)) { - ChronoField.MILLI_OF_SECOND.checkValidValue(this.fieldValues.get(ChronoField.MILLI_OF_SECOND)); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND)) { - ChronoField.MICRO_OF_SECOND.checkValidValue(this.fieldValues.get(ChronoField.MICRO_OF_SECOND)); - } - } - - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND) && this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND)) { - var los = this.fieldValues.remove(ChronoField.MILLI_OF_SECOND); - var cos = this.fieldValues.get(ChronoField.MICRO_OF_SECOND); - - this._putFieldValue0(ChronoField.MICRO_OF_SECOND, los * 1000 + MathUtil.intMod(cos, 1000)); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND) && this.fieldValues.containsKey(ChronoField.NANO_OF_SECOND)) { - var nos = this.fieldValues.get(ChronoField.NANO_OF_SECOND); - - this._putFieldValue0(ChronoField.MICRO_OF_SECOND, MathUtil.intDiv(nos, 1000)); - - this.fieldValues.remove(ChronoField.MICRO_OF_SECOND); - } - - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND) && this.fieldValues.containsKey(ChronoField.NANO_OF_SECOND)) { - var _nos = this.fieldValues.get(ChronoField.NANO_OF_SECOND); - - this._putFieldValue0(ChronoField.MILLI_OF_SECOND, MathUtil.intDiv(_nos, 1000000)); - - this.fieldValues.remove(ChronoField.MILLI_OF_SECOND); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND)) { - var _cos = this.fieldValues.remove(ChronoField.MICRO_OF_SECOND); - - this._putFieldValue0(ChronoField.NANO_OF_SECOND, _cos * 1000); - } else if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND)) { - var _los = this.fieldValues.remove(ChronoField.MILLI_OF_SECOND); - - this._putFieldValue0(ChronoField.NANO_OF_SECOND, _los * 1000000); - } - }; - - _proto._resolveTimeInferZeroes = function _resolveTimeInferZeroes(resolverStyle) { - var hod = this.fieldValues.get(ChronoField.HOUR_OF_DAY); - var moh = this.fieldValues.get(ChronoField.MINUTE_OF_HOUR); - var som = this.fieldValues.get(ChronoField.SECOND_OF_MINUTE); - var nos = this.fieldValues.get(ChronoField.NANO_OF_SECOND); - - if (hod == null) { - return; - } - - if (moh == null && (som != null || nos != null)) { - return; - } - - if (moh != null && som == null && nos != null) { - return; - } - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (hod != null) { - if (resolverStyle === ResolverStyle.SMART && hod === 24 && (moh == null || moh === 0) && (som == null || som === 0) && (nos == null || nos === 0)) { - hod = 0; - this.excessDays = Period.ofDays(1); - } - - var hodVal = ChronoField.HOUR_OF_DAY.checkValidIntValue(hod); - - if (moh != null) { - var mohVal = ChronoField.MINUTE_OF_HOUR.checkValidIntValue(moh); - - if (som != null) { - var somVal = ChronoField.SECOND_OF_MINUTE.checkValidIntValue(som); - - if (nos != null) { - var nosVal = ChronoField.NANO_OF_SECOND.checkValidIntValue(nos); - - this._addObject(LocalTime.of(hodVal, mohVal, somVal, nosVal)); - } else { - this._addObject(LocalTime.of(hodVal, mohVal, somVal)); - } - } else { - if (nos == null) { - this._addObject(LocalTime.of(hodVal, mohVal)); - } - } - } else { - if (som == null && nos == null) { - this._addObject(LocalTime.of(hodVal, 0)); - } - } - } - } else { - if (hod != null) { - var _hodVal = hod; - - if (moh != null) { - if (som != null) { - if (nos == null) { - nos = 0; - } - - var totalNanos = MathUtil.safeMultiply(_hodVal, 3600000000000); - totalNanos = MathUtil.safeAdd(totalNanos, MathUtil.safeMultiply(moh, 60000000000)); - totalNanos = MathUtil.safeAdd(totalNanos, MathUtil.safeMultiply(som, 1000000000)); - totalNanos = MathUtil.safeAdd(totalNanos, nos); - var excessDays = MathUtil.floorDiv(totalNanos, 86400000000000); - var nod = MathUtil.floorMod(totalNanos, 86400000000000); - - this._addObject(LocalTime.ofNanoOfDay(nod)); - - this.excessDays = Period.ofDays(excessDays); - } else { - var totalSecs = MathUtil.safeMultiply(_hodVal, 3600); - totalSecs = MathUtil.safeAdd(totalSecs, MathUtil.safeMultiply(moh, 60)); - - var _excessDays = MathUtil.floorDiv(totalSecs, 86400); - - var sod = MathUtil.floorMod(totalSecs, 86400); - - this._addObject(LocalTime.ofSecondOfDay(sod)); - - this.excessDays = Period.ofDays(_excessDays); - } - } else { - var _excessDays2 = MathUtil.safeToInt(MathUtil.floorDiv(_hodVal, 24)); - - _hodVal = MathUtil.floorMod(_hodVal, 24); - - this._addObject(LocalTime.of(_hodVal, 0)); - - this.excessDays = Period.ofDays(_excessDays2); - } - } - } - - this.fieldValues.remove(ChronoField.HOUR_OF_DAY); - this.fieldValues.remove(ChronoField.MINUTE_OF_HOUR); - this.fieldValues.remove(ChronoField.SECOND_OF_MINUTE); - this.fieldValues.remove(ChronoField.NANO_OF_SECOND); - }; - - _proto._addObject = function _addObject(dateOrTime) { - if (dateOrTime instanceof ChronoLocalDate) { - this.date = dateOrTime; - } else if (dateOrTime instanceof LocalTime) { - this.time = dateOrTime; - } - }; - - _proto._resolveInstant = function _resolveInstant() { - if (this.date != null && this.time != null) { - var offsetSecs = this.fieldValues.get(ChronoField.OFFSET_SECONDS); - - if (offsetSecs != null) { - var offset = ZoneOffset.ofTotalSeconds(offsetSecs); - var instant = this.date.atTime(this.time).atZone(offset).getLong(ChronoField.INSTANT_SECONDS); - this.fieldValues.put(ChronoField.INSTANT_SECONDS, instant); - } else if (this.zone != null) { - var _instant = this.date.atTime(this.time).atZone(this.zone).getLong(ChronoField.INSTANT_SECONDS); - - this.fieldValues.put(ChronoField.INSTANT_SECONDS, _instant); - } - } - }; - - _proto.build = function build(type) { - return type.queryFrom(this); - }; - - _proto.isSupported = function isSupported(field) { - if (field == null) { - return false; - } - - return this.fieldValues.containsKey(field) && this.fieldValues.get(field) !== undefined || this.date != null && this.date.isSupported(field) || this.time != null && this.time.isSupported(field); - }; - - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); - var value = this.getFieldValue0(field); - - if (value == null) { - if (this.date != null && this.date.isSupported(field)) { - return this.date.getLong(field); - } - - if (this.time != null && this.time.isSupported(field)) { - return this.time.getLong(field); - } - - throw new DateTimeException('Field not found: ' + field); - } - - return value; - }; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.zoneId()) { - return this.zone; - } else if (_query === TemporalQueries.chronology()) { - return this.chrono; - } else if (_query === TemporalQueries.localDate()) { - return this.date != null ? LocalDate.from(this.date) : null; - } else if (_query === TemporalQueries.localTime()) { - return this.time; - } else if (_query === TemporalQueries.zone() || _query === TemporalQueries.offset()) { - return _query.queryFrom(this); - } else if (_query === TemporalQueries.precision()) { - return null; - } - - return _query.queryFrom(this); - }; - - return DateTimeBuilder; - }(TemporalAccessor); - - var DateTimeParseContext = function () { - function DateTimeParseContext() { - if (arguments.length === 1) { - if (arguments[0] instanceof DateTimeParseContext) { - this._constructorSelf.apply(this, arguments); - - return; - } else { - this._constructorFormatter.apply(this, arguments); - } - } else { - this._constructorParam.apply(this, arguments); - } - - this._caseSensitive = true; - this._strict = true; - this._parsed = [new Parsed(this)]; - } - - var _proto = DateTimeParseContext.prototype; - - _proto._constructorParam = function _constructorParam(locale, symbols, chronology) { - this._locale = locale; - this._symbols = symbols; - this._overrideChronology = chronology; - }; - - _proto._constructorFormatter = function _constructorFormatter(formatter) { - this._locale = formatter.locale(); - this._symbols = formatter.decimalStyle(); - this._overrideChronology = formatter.chronology(); - }; - - _proto._constructorSelf = function _constructorSelf(other) { - this._locale = other._locale; - this._symbols = other._symbols; - this._overrideChronology = other._overrideChronology; - this._overrideZone = other._overrideZone; - this._caseSensitive = other._caseSensitive; - this._strict = other._strict; - this._parsed = [new Parsed(this)]; - }; - - _proto.copy = function copy() { - return new DateTimeParseContext(this); - }; - - _proto.symbols = function symbols() { - return this._symbols; - }; - - _proto.isStrict = function isStrict() { - return this._strict; - }; - - _proto.setStrict = function setStrict(strict) { - this._strict = strict; - }; - - _proto.locale = function locale() { - return this._locale; - }; - - _proto.setLocale = function setLocale(locale) { - this._locale = locale; - }; - - _proto.startOptional = function startOptional() { - this._parsed.push(this.currentParsed().copy()); - }; - - _proto.endOptional = function endOptional(successful) { - if (successful) { - this._parsed.splice(this._parsed.length - 2, 1); - } else { - this._parsed.splice(this._parsed.length - 1, 1); - } - }; - - _proto.isCaseSensitive = function isCaseSensitive() { - return this._caseSensitive; - }; - - _proto.setCaseSensitive = function setCaseSensitive(caseSensitive) { - this._caseSensitive = caseSensitive; - }; - - _proto.subSequenceEquals = function subSequenceEquals(cs1, offset1, cs2, offset2, length) { - if (offset1 + length > cs1.length || offset2 + length > cs2.length) { - return false; - } - - if (!this.isCaseSensitive()) { - cs1 = cs1.toLowerCase(); - cs2 = cs2.toLowerCase(); - } - - for (var i = 0; i < length; i++) { - var ch1 = cs1[offset1 + i]; - var ch2 = cs2[offset2 + i]; - - if (ch1 !== ch2) { - return false; - } - } - - return true; - }; - - _proto.charEquals = function charEquals(ch1, ch2) { - if (this.isCaseSensitive()) { - return ch1 === ch2; - } - - return this.charEqualsIgnoreCase(ch1, ch2); - }; - - _proto.charEqualsIgnoreCase = function charEqualsIgnoreCase(c1, c2) { - return c1 === c2 || c1.toLowerCase() === c2.toLowerCase(); - }; - - _proto.setParsedField = function setParsedField(field, value, errorPos, successPos) { - var currentParsedFieldValues = this.currentParsed().fieldValues; - var old = currentParsedFieldValues.get(field); - currentParsedFieldValues.set(field, value); - return old != null && old !== value ? ~errorPos : successPos; - }; - - _proto.setParsedZone = function setParsedZone(zone) { - requireNonNull(zone, 'zone'); - this.currentParsed().zone = zone; - }; - - _proto.getParsed = function getParsed(field) { - return this.currentParsed().fieldValues.get(field); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. +var querystring = __nccwpck_require__(71191); +var uuid = __nccwpck_require__(19744); +var request = __nccwpck_require__(48699); +var url = __nccwpck_require__(78835); +var async = __nccwpck_require__(57888); + +var constants = __nccwpck_require__(10282); +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +var OAuth2Parameters = constants.OAuth2.Parameters; +var OAuth2ResponseParameters = constants.OAuth2.ResponseParameters; +var DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters; +var IdTokenMap = constants.OAuth2.IdTokenMap; +var TokenResponseFields = constants.TokenResponseFields; +var UserCodeResponseFields = constants.UserCodeResponseFields; +var IdTokenFields = constants.IdTokenFields; + +var TOKEN_RESPONSE_MAP = {}; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION; + + +var DEVICE_CODE_RESPONSE_MAP = {}; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION; + +/** + * Constructs an instances of OAuth2Client + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string|url} authority An url that points to an authority. + */ +function OAuth2Client(callContext, authority) { + this._tokenEndpoint = authority.tokenEndpoint; + this._deviceCodeEndpoint = authority.deviceCodeEndpoint; + + this._log = new Logger('OAuth2Client', callContext._logContext); + this._callContext = callContext; + this._cancelPollingRequest = false; +} + +/** + * Constructs an OAuth 2.0 token request url. + * @private + * @return {URL} + */ +OAuth2Client.prototype._createTokenUrl = function () { + var tokenUrl = url.parse(this._tokenEndpoint); + + var parameters = {}; + parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0'; + + tokenUrl.search = querystring.stringify(parameters); + return tokenUrl; +}; + +/** + * Constructs the user code info request url. + * @private + * @return {URL} + */ +OAuth2Client.prototype._createDeviceCodeUrl = function () { + var deviceCodeUrl = url.parse(this._deviceCodeEndpoint); + + var parameters = {}; + parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0'; + + deviceCodeUrl.search = querystring.stringify(parameters); + + return deviceCodeUrl; +}; + +/** + * @private + * @param {object} obj An object in which integer values may reside. + * @param {array} keys An array of strings that specify keys in which integers may need parsing. + */ +OAuth2Client.prototype._parseOptionalInts = function (obj, keys) { + var self = this; + keys.forEach(function(element) { + if (_.has(obj, element)) { + obj[element] = parseInt(obj[element], 10); + if (isNaN(obj[element])) { + throw self._log.createError(element + ' could not be parsed as an int.'); + } + } + }); +}; + +/** + * Parses a JWS encoded JWT into it's three parts. + * @param {string} jwtToken The token to parse. + * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined. + */ +OAuth2Client.prototype._crackJwt = function(jwtToken) { + var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; + + var matches = idTokenPartsRegex.exec(jwtToken); + if (!matches || matches.length < 4) { + this._log.warn('The returned id_token is not parseable.'); + return; + } + + var crackedToken = { + header : matches[1], + JWSPayload : matches[2], + JWSSig : matches[3] + }; + + return crackedToken; +}; + +/** + * Finds the value that should be used as the userId value. + * @param {object} idToken The id token that parsed. + * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field. + */ +OAuth2Client.prototype._getUserId = function(idToken) { + var userId; + var isDisplayable; + + if (idToken.upn) { + userId = idToken.upn; + isDisplayable = true; + } else if (idToken.email) { + userId = idToken.email; + isDisplayable = true; + } else if (idToken.sub) { + userId = idToken.sub; + } + + if (!userId) { + // generate a random GUID. + userId = uuid.v4(); + } + + var userIdVals = {}; + userIdVals[IdTokenFields.USER_ID] = userId; + if (isDisplayable) { + userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true; + } + + return userIdVals; +}; + +function mapFields(inObj, outObj, map) { + for (var key in inObj) { + if (map[key]) { + var mappedKey = map[key]; + outObj[mappedKey] = inObj[key]; + } + } +} + +/** + * Given a decoded id token off the wire, this function extracts the values that + * ADAL commonly returns to callers and translates the names to more user + * friendly names. + * @param {Object} idToken A decoded id token. + * @return {Object} The set of extracted values with their new names. + */ +OAuth2Client.prototype._extractIdTokenValues = function(idToken) { + var extractedValues = {}; + _.extend(extractedValues, this._getUserId(idToken)); + + mapFields(idToken, extractedValues, IdTokenMap); + + return extractedValues; +}; + +/** + * Parses the value of the id_token OAuth 2 Reponse. + * @param {string} encodedIdToken An unencrypted JWT token. + * @return {object} returns the decoded id_token or undefined. + */ +OAuth2Client.prototype._parseIdToken = function(encodedIdToken) { + var crackedToken = this._crackJwt(encodedIdToken); + if (!crackedToken) { + return; + } + + var idToken; + try { + var base64IdToken = crackedToken.JWSPayload; + var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken); + if (!base64Decoded) { + this._log.warn('The returned id_token could not be base64 url safe decoded.'); + return; + } + + idToken = JSON.parse(base64Decoded); + } catch (err) { + this._log.warn('the returned id_token could not be decoded'); + this._log.warn('The returned id_token could not be decoded: ' + err.stack, true); + return; + } + + return this._extractIdTokenValues(idToken); +}; + +/** + * Validates the response returned from an OAuth 2.0 token request. + * @private + * @param {string} body The response as a string encoded JSON object. + * @return {object} The parsed response. + */ +OAuth2Client.prototype._validateTokenResponse = function(body) { + var wireResponse; + var tokenResponse = {}; + + try { + wireResponse = JSON.parse(body); + } catch(e) { + throw new Error('The token response returned from the server is unparseable as JSON'); + } + + var intKeys = [ + OAuth2ResponseParameters.EXPIRES_ON, + OAuth2ResponseParameters.EXPIRES_IN, + OAuth2ResponseParameters.CREATED_ON + ]; + + this._parseOptionalInts(wireResponse, intKeys); + + if (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) { + var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN]; + var now = new Date(); + wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn }); + } + + if (wireResponse[OAuth2ResponseParameters.CREATED_ON]) { + var tempDate = new Date(); + var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON]; + tempDate.setTime(createdOn); + wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate; + } + + if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) { + throw this._log.createError('wireResponse is missing token_type'); + } + if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) { + throw this._log.createError('wireResponse missing access_token'); + } + + mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); + + if (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) { + var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]); + if (idToken) { + _.extend(tokenResponse, idToken); + } + } + + return tokenResponse; +}; + +/** + * Validates the response returned from an OAuth 2.0 device code request. + * @private + * @param {string} body The response as a string encoded JSON object. + * @return {object} The parsed response. + */ +OAuth2Client.prototype._validateDeviceCodeResponse = function(body) { + var wireResponse; + var deviceCodeResponse = {}; + + try { + wireResponse = JSON.parse(body); + } catch(e) { + throw new Error('The device code response returned from the server is unparseable as JSON.'); + } + + var intKeys = [ + DeviceCodeResponseParameters.EXPIRES_IN, + DeviceCodeResponseParameters.INTERVAL + ]; + + this._parseOptionalInts(wireResponse, intKeys); + + if (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){ + throw this._log.createError('wireResponse is missing expires_in'); + } + + if (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) { + throw this._log.createError('wireResponse is missing device code'); + } + + if (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) { + throw this._log.createError('wireResponse is missing user code'); + } + + mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP); + + return deviceCodeResponse; +}; + +/** + * @private + * @param {string} body The body of a http token response. + */ +OAuth2Client.prototype._handlePollingResponse = function(body) { + //handle token error response + var tokenResponse = this._handlePollingRequestErrorResponse(body); + if (_.isEmpty(tokenResponse)){ + tokenResponse = this._validateTokenResponse(body); + } + + return tokenResponse; +}; + +/** + * @private + * @param {string} body The body of a http token response. + */ +OAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) { + var wireResponse; + var tokenResponse = {}; + + try { + wireResponse = JSON.parse(body); + } catch (e) { + throw new Error ('The token response returned from the server is unparsable as JSON'); + } + + if (wireResponse[OAuth2ResponseParameters.ERROR]) { + mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); + } + + return tokenResponse; +}; + +/** + * @private + * @param {object} response An http response object. + * @param {string} body The body of a http token response. + * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed + * into this function. + */ +OAuth2Client.prototype._handleGetTokenResponse = function(response, body, callback) { + var tokenResponse; + try { + tokenResponse = this._validateTokenResponse(body); + } catch (e) { + this._log.error('Error validating get token response', e, true); + callback(e); + return; + } + callback(null, tokenResponse); +}; + +OAuth2Client.prototype._handleGetDeviceCodeResponse = function(response, body, callback) { + var deviceCodeResponse; + try { + deviceCodeResponse = this._validateDeviceCodeResponse(body); + } catch (e) { + this._log.error('Error validating get user code response', e, true); + callback(e); + return; + } + + callback(null, deviceCodeResponse); +}; + +OAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) { + var self = this; + if (self._cancelPollingRequest === true) { + callback(null, new Error('Polling_Request_Cancelled')); + return; + } + + request.post(postOptions, util.createRequestHandler('Get Token', this._log, function(response, body) { + //error response callback, for error response, it's already parsed as Json. + if (body && body.hasOwnProperty(TokenResponseFields.ERROR) && body[TokenResponseFields.ERROR] === 'authorization_pending') { + callback(new Error(body[TokenResponseFields.ERROR]), body); + } + else { + callback(null, body); + } + }, + // success response callback + function (response, body) { + var tokenResponse; + try { + tokenResponse = self._handlePollingResponse(body); + } catch (e) { + self._log.error('Error validating get token response', e, true); + callback(null, e); + return; + } + + callback(null, tokenResponse); + }) + ); +}; + +OAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) { + var postOptions = util.createRequestOptions( + this, + { + 'url' : url.format(postUrl), + body : urlEncodedRequestForm, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + followRedirect : false, + encoding : 'utf8' + } + ); + + return postOptions; +}; + +/** + * @callback GetTokenCallback + * @memberOf OAuth2Client + * @param {Error} [error] In case of an error this will hold the associated Error object. + * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request. + */ + +/** +* @param {object} oauthParameters An object whose keys come from +* Constants.OAuth2.Parameters +* @param {OAuth2Client.GetTokenCallback} callback The callback function. +*/ +OAuth2Client.prototype.getToken = function(oauthParameters, callback) { + var self = this; + var tokenUrl = self._createTokenUrl(); + + var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); + + var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); + + request.post(postOptions, util.createRequestHandler('Get Token', this._log, callback, + function (response, body) { + self._handleGetTokenResponse(response, body, callback); + }) + ); +}; + +/** + * @param {object} oauthParameters An object whose keys come from + * Constants.OAuth2.Parameters + * @param {integer} refresh_interval The interval for polling request. + * @param {integer} exipres_in The timeout for polling request. + * @param {OAuth2Client.GetTokenCallback} callback The callback function. + */ +OAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){ + var self = this; + var maxTimesForRetry = Math.floor(expires_in / refresh_interval); + + var tokenUrl = self._createTokenUrl(); + var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); + var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); + + var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000}; + + async.retry(optionsForRetry, function(retryCallback, response) { + self._getTokenWithPolling(postOptions, retryCallback); + }, function(err, response) { + if (response && response instanceof Error) { + callback(response); + return; + } + else if (response && response.hasOwnProperty(DeviceCodeResponseParameters.ERROR)) { + callback(response); + return; + } + callback(err, response); + }); +}; + +OAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) { + // for now make it as a post request + var self = this; + var deviceCodeUrl = self._createDeviceCodeUrl(); + + var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters); + + var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm); + + request.post(postOptions, util.createRequestHandler('Get Device Code ', this._log, callback, + function (response, body) { + self._handleGetDeviceCodeResponse(response, body, callback); + }) + ); +}; + +/** + * Cancel the polling request made for acquiring token by device code. + */ +OAuth2Client.prototype.cancelPollingRequest = function() { + this._cancelPollingRequest = true; +}; + +module.exports = OAuth2Client; - _proto.toParsed = function toParsed() { - return this.currentParsed(); - }; - _proto.currentParsed = function currentParsed() { - return this._parsed[this._parsed.length - 1]; - }; +/***/ }), - _proto.setParsedLeapSecond = function setParsedLeapSecond() { - this.currentParsed().leapSecond = true; - }; +/***/ 60772: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.getEffectiveChronology = function getEffectiveChronology() { - var chrono = this.currentParsed().chrono; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var jwtConstants = __nccwpck_require__(10282).Jwt; +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +__nccwpck_require__(1693); +var jws = __nccwpck_require__(4636); +var uuid = __nccwpck_require__(19744); + +/** + * JavaScript dates are in milliseconds, but JWT dates are in seconds. + * This function does the conversion. + * @param {Date} date + * @return {string} + */ +function dateGetTimeInSeconds(date) { + return Math.floor(date.getTime()/1000); +} + +/** + * Constructs a new SelfSignedJwt object. + * @param {object} callContext Context specific to this token request. + * @param {Authority} authority The authority to be used as the JWT audience. + * @param {string} clientId The client id of the calling app. + */ +function SelfSignedJwt(callContext, authority, clientId) { + this._log = new Logger('SelfSignedJwt', callContext._logContext); + this._callContext = callContext; + + this._authority = authority; + this._tokenEndpoint = authority.tokenEndpoint; + this._clientId = clientId; +} + +/** + * This wraps date creation in order to make unit testing easier. + * @return {Date} + */ +SelfSignedJwt.prototype._getDateNow = function() { + return new Date(); +}; + +SelfSignedJwt.prototype._getNewJwtId = function() { + return uuid.v4(); +}; + +/** + * A regular certificate thumbprint is a hex encode string of the binary certificate + * hash. For some reason teh x5t value in a JWT is a url save base64 encoded string + * instead. This function does the conversion. + * @param {string} thumbprint A hex encoded certificate thumbprint. + * @return {string} A url safe base64 encoded certificate thumbprint. + */ +SelfSignedJwt.prototype._createx5tValue = function(thumbprint) { + var hexString = thumbprint.replace(/:/g, '').replace(/ /g, ''); + var base64 = (new Buffer(hexString, 'hex')).toString('base64'); + return util.convertRegularToUrlSafeBase64EncodedString(base64); +}; + +/** + * Creates the JWT header. + * @param {string} thumbprint A hex encoded certificate thumbprint. + * @return {object} + */ +SelfSignedJwt.prototype._createHeader = function(thumbprint) { + var x5t = this._createx5tValue(thumbprint); + var header = { typ: 'JWT', alg: 'RS256', x5t : x5t }; + + this._log.verbose('Creating self signed JWT header'); + this._log.verbose('Creating self signed JWT header. x5t: ' + x5t, true); + + return header; +}; + +/** + * Creates the JWT payload. + * @return {object} + */ +SelfSignedJwt.prototype._createPayload = function() { + var now = this._getDateNow(); + var expires = (new Date(now.getTime())).addMinutes(jwtConstants.SELF_SIGNED_JWT_LIFETIME); + + this._log.verbose('Creating self signed JWT payload. Expires: ' + expires + ' NotBefore: ' + now); + + var jwtPayload = {}; + jwtPayload[jwtConstants.AUDIENCE] = this._tokenEndpoint; + jwtPayload[jwtConstants.ISSUER] = this._clientId; + jwtPayload[jwtConstants.SUBJECT] = this._clientId; + jwtPayload[jwtConstants.NOT_BEFORE] = dateGetTimeInSeconds(now); + jwtPayload[jwtConstants.EXPIRES_ON] = dateGetTimeInSeconds(expires); + jwtPayload[jwtConstants.JWT_ID] = this._getNewJwtId(); + + return jwtPayload; +}; + +SelfSignedJwt.prototype._throwOnInvalidJwtSignature = function(jwt) { + var jwtSegments = jwt.split('.'); + + if (3 > jwtSegments.length || !jwtSegments[2]) { + throw this._log.createError('Failed to sign JWT. This is most likely due to an invalid certificate.'); + } + + return; +}; + +SelfSignedJwt.prototype._signJwt = function(header, payload, certificate) { + var jwt; + try { + jwt = jws.sign({ header : header, payload : payload, secret : certificate }); + } + catch (err) { + this._log.error(err, true); + throw this._log.createError('Failed to sign JWT.This is most likely due to an invalid certificate.'); + } + + this._throwOnInvalidJwtSignature(jwt); + return jwt; +}; + +SelfSignedJwt.prototype._reduceThumbprint = function(thumbprint) { + var canonical = thumbprint.toLowerCase().replace(/ /g, '').replace(/:/g, ''); + this._throwOnInvalidThumbprint(canonical); + return canonical; +}; + +var numCharIn128BitHexString = 128/8*2; +var numCharIn160BitHexString = 160/8*2; +var thumbprintSizes = {}; +thumbprintSizes[numCharIn128BitHexString] = true; +thumbprintSizes[numCharIn160BitHexString] = true; +var thumbprintRegExp = /^[a-f\d]*$/; + +SelfSignedJwt.prototype._throwOnInvalidThumbprint = function(thumbprint) { + if (!thumbprintSizes[thumbprint.length] || !thumbprintRegExp.test(thumbprint)) { + throw this._log.createError('The thumbprint does not match a known format'); + } +}; + +/** + * Creates a self signed JWT that can be used as a client_assertion. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. + * @return {string} A self signed JWT token. + */ +SelfSignedJwt.prototype.create = function(certificate, thumbprint) { + thumbprint = this._reduceThumbprint(thumbprint); + var header = this._createHeader(thumbprint); + + var payload = this._createPayload(); + + var jwt = this._signJwt(header, payload, certificate); + return jwt; +}; + +module.exports = SelfSignedJwt; - if (chrono == null) { - chrono = this._overrideChronology; +/***/ }), - if (chrono == null) { - chrono = IsoChronology.INSTANCE; - } - } +/***/ 21178: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return chrono; - }; - - return DateTimeParseContext; - }(); - - var Parsed = function (_Temporal) { - _inheritsLoose(Parsed, _Temporal); - - function Parsed(dateTimeParseContext) { - var _this; - - _this = _Temporal.call(this) || this; - _this.chrono = null; - _this.zone = null; - _this.fieldValues = new EnumMap(); - _this.leapSecond = false; - _this.dateTimeParseContext = dateTimeParseContext; - return _this; - } - - var _proto2 = Parsed.prototype; - - _proto2.copy = function copy() { - var cloned = new Parsed(); - cloned.chrono = this.chrono; - cloned.zone = this.zone; - cloned.fieldValues.putAll(this.fieldValues); - cloned.leapSecond = this.leapSecond; - cloned.dateTimeParseContext = this.dateTimeParseContext; - return cloned; - }; - - _proto2.toString = function toString() { - return this.fieldValues + ", " + this.chrono + ", " + this.zone; - }; - - _proto2.isSupported = function isSupported(field) { - return this.fieldValues.containsKey(field); - }; - - _proto2.get = function get(field) { - var val = this.fieldValues.get(field); - assert(val != null); - return val; - }; - - _proto2.query = function query(_query) { - if (_query === TemporalQueries.chronology()) { - return this.chrono; - } - - if (_query === TemporalQueries.zoneId() || _query === TemporalQueries.zone()) { - return this.zone; - } - - return _Temporal.prototype.query.call(this, _query); - }; - - _proto2.toBuilder = function toBuilder() { - var builder = new DateTimeBuilder(); - builder.fieldValues.putAll(this.fieldValues); - builder.chrono = this.dateTimeParseContext.getEffectiveChronology(); - - if (this.zone != null) { - builder.zone = this.zone; - } else { - builder.zone = this.overrideZone; - } - - builder.leapSecond = this.leapSecond; - builder.excessDays = this.excessDays; - return builder; - }; - - return Parsed; - }(Temporal); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var DateTimePrintContext = function () { - function DateTimePrintContext(temporal, localeOrFormatter, symbols) { - if (arguments.length === 2 && arguments[1] instanceof DateTimeFormatter) { - this._temporal = DateTimePrintContext.adjust(temporal, localeOrFormatter); - this._locale = localeOrFormatter.locale(); - this._symbols = localeOrFormatter.decimalStyle(); - } else { - this._temporal = temporal; - this._locale = localeOrFormatter; - this._symbols = symbols; - } - - this._optional = 0; - } - - DateTimePrintContext.adjust = function adjust(temporal, formatter) { - return temporal; - }; - - var _proto = DateTimePrintContext.prototype; - - _proto.symbols = function symbols() { - return this._symbols; - }; - - _proto.startOptional = function startOptional() { - this._optional++; - }; - - _proto.endOptional = function endOptional() { - this._optional--; - }; - - _proto.getValueQuery = function getValueQuery(query) { - var result = this._temporal.query(query); - - if (result == null && this._optional === 0) { - throw new DateTimeException('Unable to extract value: ' + this._temporal); - } - - return result; - }; - - _proto.getValue = function getValue(field) { - try { - return this._temporal.getLong(field); - } catch (ex) { - if (ex instanceof DateTimeException && this._optional > 0) { - return null; - } - - throw ex; - } - }; - - _proto.temporal = function temporal() { - return this._temporal; - }; - - _proto.locale = function locale() { - return this._locale; - }; - - _proto.setDateTime = function setDateTime(temporal) { - this._temporal = temporal; - }; - - _proto.setLocale = function setLocale(locale) { - this._locale = locale; - }; - - return DateTimePrintContext; - }(); - - var IsoFields = {}; - var QUARTER_DAYS = [0, 90, 181, 273, 0, 91, 182, 274]; - - var Field = function (_TemporalField) { - _inheritsLoose(Field, _TemporalField); - - function Field() { - return _TemporalField.apply(this, arguments) || this; - } - - var _proto = Field.prototype; - - _proto.isDateBased = function isDateBased() { - return true; - }; - - _proto.isTimeBased = function isTimeBased() { - return false; - }; - - _proto._isIso = function _isIso() { - return true; - }; - - Field._getWeekRangeByLocalDate = function _getWeekRangeByLocalDate(date) { - var wby = Field._getWeekBasedYear(date); - - return ValueRange.of(1, Field._getWeekRangeByYear(wby)); - }; - - Field._getWeekRangeByYear = function _getWeekRangeByYear(wby) { - var date = LocalDate.of(wby, 1, 1); - - if (date.dayOfWeek() === DayOfWeek.THURSDAY || date.dayOfWeek() === DayOfWeek.WEDNESDAY && date.isLeapYear()) { - return 53; - } - - return 52; - }; - - Field._getWeek = function _getWeek(date) { - var dow0 = date.dayOfWeek().ordinal(); - var doy0 = date.dayOfYear() - 1; - var doyThu0 = doy0 + (3 - dow0); - var alignedWeek = MathUtil.intDiv(doyThu0, 7); - var firstThuDoy0 = doyThu0 - alignedWeek * 7; - var firstMonDoy0 = firstThuDoy0 - 3; - - if (firstMonDoy0 < -3) { - firstMonDoy0 += 7; - } - - if (doy0 < firstMonDoy0) { - return Field._getWeekRangeByLocalDate(date.withDayOfYear(180).minusYears(1)).maximum(); - } - - var week = MathUtil.intDiv(doy0 - firstMonDoy0, 7) + 1; - - if (week === 53) { - if ((firstMonDoy0 === -3 || firstMonDoy0 === -2 && date.isLeapYear()) === false) { - week = 1; - } - } - - return week; - }; - - Field._getWeekBasedYear = function _getWeekBasedYear(date) { - var year = date.year(); - var doy = date.dayOfYear(); - - if (doy <= 3) { - var dow = date.dayOfWeek().ordinal(); - - if (doy - dow < -2) { - year--; - } - } else if (doy >= 363) { - var _dow = date.dayOfWeek().ordinal(); - - doy = doy - 363 - (date.isLeapYear() ? 1 : 0); - - if (doy - _dow >= 0) { - year++; - } - } - - return year; - }; - - _proto.displayName = function displayName() { - return this.toString(); - }; - - _proto.resolve = function resolve() { - return null; - }; - - _proto.name = function name() { - return this.toString(); - }; - - return Field; - }(TemporalField); - - var DAY_OF_QUARTER_FIELD = function (_Field) { - _inheritsLoose(DAY_OF_QUARTER_FIELD, _Field); - - function DAY_OF_QUARTER_FIELD() { - return _Field.apply(this, arguments) || this; - } - - var _proto2 = DAY_OF_QUARTER_FIELD.prototype; - - _proto2.toString = function toString() { - return 'DayOfQuarter'; - }; - - _proto2.baseUnit = function baseUnit() { - return ChronoUnit.DAYS; - }; - - _proto2.rangeUnit = function rangeUnit() { - return QUARTER_YEARS; - }; - - _proto2.range = function range() { - return ValueRange.of(1, 90, 92); - }; - - _proto2.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.DAY_OF_YEAR) && temporal.isSupported(ChronoField.MONTH_OF_YEAR) && temporal.isSupported(ChronoField.YEAR) && this._isIso(temporal); - }; - - _proto2.rangeRefinedBy = function rangeRefinedBy(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: DayOfQuarter'); - } - - var qoy = temporal.getLong(QUARTER_OF_YEAR); - - if (qoy === 1) { - var year = temporal.getLong(ChronoField.YEAR); - return IsoChronology.isLeapYear(year) ? ValueRange.of(1, 91) : ValueRange.of(1, 90); - } else if (qoy === 2) { - return ValueRange.of(1, 91); - } else if (qoy === 3 || qoy === 4) { - return ValueRange.of(1, 92); - } - - return this.range(); - }; - - _proto2.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: DayOfQuarter'); - } - - var doy = temporal.get(ChronoField.DAY_OF_YEAR); - var moy = temporal.get(ChronoField.MONTH_OF_YEAR); - var year = temporal.getLong(ChronoField.YEAR); - return doy - QUARTER_DAYS[MathUtil.intDiv(moy - 1, 3) + (IsoChronology.isLeapYear(year) ? 4 : 0)]; - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var constants = __nccwpck_require__(10282); +var CacheDriver = __nccwpck_require__(38289); +var Logger = __nccwpck_require__(92288).Logger; +var Mex = __nccwpck_require__(27078); +var OAuth2Client = __nccwpck_require__(41602); +var SelfSignedJwt = __nccwpck_require__(60772); +var UserRealm = __nccwpck_require__(58663); +var WSTrustRequest = __nccwpck_require__(39035); + +var OAuth2Parameters = constants.OAuth2.Parameters; +var TokenResponseFields = constants.TokenResponseFields; +var OAuth2GrantType = constants.OAuth2.GrantType; +var OAuth2Scope = constants.OAuth2.Scope; +var Saml = constants.Saml; +var AccountType = constants.UserRealm.AccountType; +var WSTrustVersion = constants.WSTrustVersion; +var DeviceCodeResponseParameters = constants.UserCodeResponseFields; + +/** + * Constructs a new TokenRequest object. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {AuthenticationContext} authenticationContext + * @param {string} resource + * @param {string} clientId + * @param {string} redirectUri + */ +function TokenRequest(callContext, authenticationContext, clientId, resource, redirectUri) { + this._log = new Logger('TokenRequest', callContext._logContext); + this._callContext = callContext; + this._authenticationContext = authenticationContext; + this._resource = resource; + this._clientId = clientId; + this._redirectUri = redirectUri; + + // This should be set at the beginning of getToken + // functions that have a userId. + this._userId = null; + + this._userRealm = null; + this._pollingClient = {}; +} + +TokenRequest.prototype._createUserRealmRequest = function(username) { + return new UserRealm(this._callContext, username, this._authenticationContext.authority); +}; + +TokenRequest.prototype._createMex = function(mexEndpoint) { + return new Mex(this._callContext, mexEndpoint); +}; + +TokenRequest.prototype._createWSTrustRequest = function(wstrustEndpoint, appliesTo, wstrustEndpointVersion) { + return new WSTrustRequest(this._callContext, wstrustEndpoint, appliesTo, wstrustEndpointVersion); +}; + +TokenRequest.prototype._createOAuth2Client = function() { + return new OAuth2Client(this._callContext, this._authenticationContext._authority); +}; + +TokenRequest.prototype._createSelfSignedJwt = function() { + return new SelfSignedJwt(this._callContext, this._authenticationContext._authority, this._clientId); +}; + +TokenRequest.prototype._oauthGetToken = function(oauthParameters, callback) { + var client = this._createOAuth2Client(); + client.getToken(oauthParameters, callback); +}; + +TokenRequest.prototype._oauthGetTokenByPolling = function(oauthParameters, refresh_interval, expires_in, callback){ + var client = this._createOAuth2Client(); + client.getTokenWithPolling(oauthParameters, refresh_interval, expires_in, callback); + this._pollingClient = client; +} + +TokenRequest.prototype._createCacheDriver = function() { + return new CacheDriver( + this._callContext, + this._authenticationContext.authority, + this._resource, + this._clientId, + this._authenticationContext.cache, + this._getTokenWithTokenResponse.bind(this) + ); +}; + +/** + * Used by the cache driver to refresh tokens. + * @param {TokenResponse} entry A token response to refresh. + * @param {string} resource The resource for which to get the token. + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype._getTokenWithTokenResponse = function(entry, resource, callback) { + this._log.verbose('Called to refresh a token from the cache.'); + var refreshToken = entry[TokenResponseFields.REFRESH_TOKEN]; + this._getTokenWithRefreshToken(refreshToken, resource, null, callback); +}; + +TokenRequest.prototype._createCacheQuery = function() { + var query = { + clientId : this._clientId + }; + + if (this._userId) { + query.userId = this._userId; + } else { + this._log.verbose('No userId passed for cache query.'); + } + + return query; +}; + + +TokenRequest.prototype._getTokenWithCacheWrapper = function(callback, getTokenFunc) { + var self = this; + this._cacheDriver = this._createCacheDriver(); + var cacheQuery = this._createCacheQuery(); + this._cacheDriver.find(cacheQuery, function(err, token) { + if (err) { + self._log.warn('Attempt to look for token in cahce resulted in Error'); + self._log.warn('Attempt to look for token in cache resulted in Error: ' + err.stack, true); + } + + if (!token) { + self._log.verbose('No appropriate cached token found.'); + getTokenFunc.call(self, function(err, tokenResponse) { + if (err) { + self._log.verbose('getTokenFunc returned with err'); + callback(err, tokenResponse); + return; + } + + self._log.verbose('Successfully retrieved token from authority'); + self._cacheDriver.add(tokenResponse, function() { + callback(null, tokenResponse); + }); + }); + } else { + self._log.info('Returning cached token.'); + callback(err, token); + } + }); +}; + +/** + * Store token into cache. + * @param {object} tokenResponse Token response to be added into the cache. + */ +TokenRequest.prototype._addTokenIntoCache = function(tokenResponse, callback) { + this._cacheDriver = this._createCacheDriver(); + this._log.verbose('Storing retrieved token into cache'); + this._cacheDriver.add(tokenResponse, function(err) { + callback(err, tokenResponse); + }); +}; + +/** + * Adds an OAuth parameter to the paramters object if the parameter is + * not null or undefined. + * @private + * @param {object} parameters OAuth parameters object. + * @param {string} key A member of the OAuth2Parameters constants. + * @param {object} value + */ +function _addParameterIfAvailable(parameters, key, value) { + if (value) { + parameters[key] = value; + } +} + +/** + * Creates a set of basic, common, OAuthParameters based on values that the TokenRequest + * was created with. + * @private + * @param {string} grantType A member of the OAuth2GrantType constants. + * @return {object} + */ +TokenRequest.prototype._createOAuthParameters = function(grantType) { + var oauthParameters = {}; + oauthParameters[OAuth2Parameters.GRANT_TYPE] = grantType; + + if (OAuth2GrantType.AUTHORIZATION_CODE !== grantType && + OAuth2GrantType.CLIENT_CREDENTIALS !== grantType && + OAuth2GrantType.DEVICE_CODE != grantType) { + oauthParameters[OAuth2Parameters.SCOPE] = OAuth2Scope.OPENID; + } + + _addParameterIfAvailable(oauthParameters, OAuth2Parameters.CLIENT_ID, this._clientId); + _addParameterIfAvailable(oauthParameters, OAuth2Parameters.RESOURCE, this._resource); + _addParameterIfAvailable(oauthParameters, OAuth2Parameters.REDIRECT_URI, this._redirectUri); + + return oauthParameters; +}; + +/** + * Get's a token from AAD using a username and password + * @private + * @param {string} username + * @param {string} password + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype._getTokenUsernamePasswordManaged = function(username, password, callback) { + this._log.verbose('Acquiring token with username password for managed user'); + + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.PASSWORD); + + oauthParameters[OAuth2Parameters.PASSWORD] = password; + oauthParameters[OAuth2Parameters.USERNAME] = username; + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Determines the OAuth SAML grant type to use based on the passed in TokenType + * that was returned from a RSTR. + * @param {string} wstrustResponse RSTR token type. + * @return {string} An OAuth grant type. + */ +TokenRequest.prototype._getSamlGrantType = function(wstrustResponse) { + var tokenType = wstrustResponse.tokenType; + switch (tokenType) { + case Saml.TokenTypeV1: + return OAuth2GrantType.SAML1; + case Saml.TokenTypeV2: + return OAuth2GrantType.SAML2; + default: + throw this._log.createError('RSTR returned unknown token type: ' + tokenType); + } +}; + +/** + * Performs an OAuth SAML Assertion grant type exchange. Uses a SAML token as the credential for getting + * an OAuth access token. + * @param {WSTrustResponse} wstrustResponse A response from a WSTrustRequest + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._performWSTrustAssertionOAuthExchange = function(wstrustResponse, callback) { + this._log.verbose('Performing OAuth assertion grant type exchange.'); + + var oauthParameters; + try { + var grantType = this._getSamlGrantType(wstrustResponse); + var assertion = new Buffer(wstrustResponse.token).toString('base64'); + oauthParameters = this._createOAuthParameters(grantType); + oauthParameters[OAuth2Parameters.ASSERTION] = assertion; + } catch (err) { + callback(err); + return; + } + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Exchange a username and password for a SAML token from an ADFS instance via WSTrust. + * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. + * @param {string} wstrustEndpointVersion The version of the wstrust endpoint. + * @param {string} username username + * @param {string} password password + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._performWSTrustExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { + var self = this; + var wstrust = this._createWSTrustRequest(wstrustEndpoint, 'urn:federation:MicrosoftOnline', wstrustEndpointVersion); + wstrust.acquireToken(username, password, function(rstErr, response) { + if (rstErr) { + callback(rstErr); + return; + } + + if (!response.token) { + var rstrErr = self._log.createError('Unsucessful RSTR.\n\terror code: ' + response.errorCode + '\n\tfaultMessage: ' + response.faultMessage, true); + callback(rstrErr); + return; + } + + callback(null, response); + }); +}; + +/** + * Given a username and password this method invokes a WSTrust and OAuth exchange to get an access token. + * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. + * @param {string} username username + * @param {string} password password + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._performUsernamePasswordForAccessTokenExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { + var self = this; + this._performWSTrustExchange(wstrustEndpoint, wstrustEndpointVersion, username, password, function(err, wstrustResponse) { + if (err) { + callback(err); + return; + } + + self._performWSTrustAssertionOAuthExchange(wstrustResponse, callback); + }); +}; + +/** + * Returns an Error object indicating that AAD did not return a WSTrust endpoint. + * @return {Error} + */ +TokenRequest.prototype._createADWSTrustEndpointError = function() { + return this._log.createError('AAD did not return a WSTrust endpoint. Unable to proceed.'); +}; + +/** + * Gets an OAuth access token using a username and password via a federated ADFS instance. + * @param {string} username username + * @param {string} password password + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._getTokenUsernamePasswordFederated = function(username, password, callback) { + this._log.verbose('Acquiring token with username password for federated user'); + + var self = this; + if (!this._userRealm.federationMetadataUrl) { + this._log.warn('Unable to retrieve federationMetadataUrl from AAD. Attempting fallback to AAD supplied endpoint.'); + + if (!this._userRealm.federationActiveAuthUrl) { + callback(this._createADWSTrustEndpointError()); + return; + } + + var wstrustVersion = this._parseWStrustVersionFromFederationActiveAuthUrl(this._userRealm.federationActiveAuthUrl); + this._log.verbose('Wstrust endpoint version is: ' + wstrustVersion); + this._performUsernamePasswordForAccessTokenExchange(this._userRealm.federationActiveAuthUrl, wstrustVersion, username, password, callback); + return; + } else { + var mexEndpoint = this._userRealm.federationMetadataUrl; + this._log.verbose('Attempting mex'); + this._log.verbose('Attempting mex at: ' + mexEndpoint, true); + var mex = this._createMex(mexEndpoint); + mex.discover(function(mexErr) { + var wstrustEndpoint; + wstrustVersion = WSTrustVersion.UNDEFINED; + if (mexErr) { + self._log.warn('MEX exchange failed. Attempting fallback to AAD supplied endpoint.'); + + wstrustEndpoint = self._userRealm.federationActiveAuthUrl; + wstrustVersion = self._parseWStrustVersionFromFederationActiveAuthUrl(self._userRealm.federationActiveAuthUrl); + if (!wstrustEndpoint) { + callback(self._createADWSTrustEndpointError()); + return; + } + } else { + wstrustEndpoint = mex.usernamePasswordPolicy.url; + wstrustVersion = mex.usernamePasswordPolicy.version; + } + + self._performUsernamePasswordForAccessTokenExchange(wstrustEndpoint, wstrustVersion, username, password, callback); + return; + }); + } +}; + +/** + * Gets wstrust endpoint version from the federation active auth url. + * @private + * @param {string} federationActiveAuthUrl federationActiveAuthUrl + * @return {object} The wstrust endpoint version. + */ +TokenRequest.prototype._parseWStrustVersionFromFederationActiveAuthUrl = function(federationActiveAuthUrl) { + var wstrust2005Regex = /[/trust]?[2005][/usernamemixed]?/; + var wstrust13Regex = /[/trust]?[13][/usernamemixed]?/; + + if (wstrust2005Regex.exec(federationActiveAuthUrl)) { + return WSTrustVersion.WSTRUST2005; + } + else if (wstrust13Regex.exec(federationActiveAuthUrl)) { + return WSTrustVersion.WSTRUST13; + } + + return WSTrustVersion.UNDEFINED; +}; + +/** + * Decides whether the username represents a managed or a federated user and then + * obtains a token using the appropriate protocol flow. + * @private + * @param {string} username + * @param {string} password + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithUsernamePassword = function(username, password, callback) { + this._log.info('Acquiring token with username password'); + this._userId = username; + + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + var self = this; + + if(this._authenticationContext._authority._isAdfsAuthority) { + this._log.info('Skipping user realm discovery for ADFS authority'); + + self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); + return; + } + + this._userRealm = this._createUserRealmRequest(username); + this._userRealm.discover(function(err) { + if (err) { + getTokenCompleteCallback(err); + return; + } + + switch(self._userRealm.accountType) { + case AccountType.Managed: + self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); + return; + case AccountType.Federated: + self._getTokenUsernamePasswordFederated(username, password, getTokenCompleteCallback); + return; + default: + getTokenCompleteCallback(self._log.createError('Server returned an unknown AccountType: ' + self._userRealm.AccountType)); + } + }); + }); +}; + +/** + * Obtains a token using client credentials + * @private + * @param {string} clientSecret + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithClientCredentials = function(clientSecret, callback) { + this._log.info('Getting token with client credentials.'); + + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); + + oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; + + this._oauthGetToken(oauthParameters, getTokenCompleteCallback); + }); +}; + +/** + * Obtains a token using an authorization code. + * @private + * @param {string} authorizationCode + * @param {string} clientSecret + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithAuthorizationCode = function(authorizationCode, clientSecret, callback) { + this._log.info('Getting token with auth code.'); + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.AUTHORIZATION_CODE); + + oauthParameters[OAuth2Parameters.CODE] = authorizationCode; + oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Obtains a token using a refresh token. + * @param {string} refreshToken + * @param {string} resource + * @param {string} [clientSecret] + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype._getTokenWithRefreshToken = function(refreshToken, resource, clientSecret, callback) { + this._log.info('Getting a new token from a refresh token.'); + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.REFRESH_TOKEN); + + if (resource) { + oauthParameters[OAuth2Parameters.RESOURCE] = resource; + } + + if (clientSecret) { + oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; + } + + oauthParameters[OAuth2Parameters.REFRESH_TOKEN] = refreshToken; + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Obtains a token using a refresh token. + * @param {string} refreshToken + * @param {string} [clientSecret] + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithRefreshToken = function(refreshToken, clientSecret, callback) { + this._getTokenWithRefreshToken(refreshToken, null, clientSecret, callback); +}; + +/** + * Obtains a token from the cache, refreshing it or using a MRRT if necessary. + * @param {string} [userId] The user associated with the cached token. + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenFromCacheWithRefresh = function(userId, callback) { + var self = this; + this._log.info('Getting token from cache with refresh if necessary.'); + + this._userId = userId; + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + // If this method was called then no cached entry was found. Since + // this particular version of acquireToken can only retrieve tokens + // from the cache, return an error. + getTokenCompleteCallback(self._log.createError('Entry not found in cache.')); + }); +}; + +/** + * Creates a self signed jwt. + * @param {string} authorityUrl + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint + * @return {string} A self signed JWT + */ +TokenRequest.prototype._createJwt = function(authorityUrl, certificate, thumbprint) { + var jwt; + var ssj = this._createSelfSignedJwt(); + jwt = ssj.create(certificate, thumbprint); + if (!jwt) { + throw this._log.createError('Failed to create JWT'); + } + + return jwt; +}; + +/** + * Obtains a token via a certificate. The certificate is used to generate a self signed + * JWT token that is passed as a client_assertion. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithCertificate = function(certificate, thumbprint, callback) { + + this._log.info('Getting a token via certificate.'); + + var authorityUrl = this._authenticationContext._authority; + + var jwt; + try { + jwt = this._createJwt(authorityUrl, certificate, thumbprint); + } catch (err) { + callback(err); + return; + } + + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); + oauthParameters[OAuth2Parameters.CLIENT_ASSERTION_TYPE] = OAuth2GrantType.JWT_BEARER; + oauthParameters[OAuth2Parameters.CLIENT_ASSERTION] = jwt; + + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + this._oauthGetToken(oauthParameters, getTokenCompleteCallback); + }); +}; + +TokenRequest.prototype.getTokenWithDeviceCode = function(userCodeInfo, callback) { + this._log.info('Getting a token via device code'); + var self = this; + + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.DEVICE_CODE); + oauthParameters[OAuth2Parameters.CODE] = userCodeInfo[DeviceCodeResponseParameters.DEVICE_CODE]; + + var interval = userCodeInfo[DeviceCodeResponseParameters.INTERVAL]; + var expires_in = userCodeInfo[DeviceCodeResponseParameters.EXPIRES_IN]; + + if (interval <= 0) { + callback(new Error('invalid refresh interval')); + } + + this._oauthGetTokenByPolling(oauthParameters, interval, expires_in, function(err, tokenResponse) { + if (err) { + self._log.verbose('Token polling request returend with err.'); + callback(err, tokenResponse); + } + else { + self._addTokenIntoCache(tokenResponse, callback); + } + }); +}; + +TokenRequest.prototype.cancelTokenRequestWithDeviceCode = function() { + this._pollingClient.cancelPollingRequest(); +}; + +module.exports = TokenRequest; - _proto2.adjustInto = function adjustInto(temporal, newValue) { - var curValue = this.getFrom(temporal); - this.range().checkValidValue(newValue, this); - return temporal.with(ChronoField.DAY_OF_YEAR, temporal.getLong(ChronoField.DAY_OF_YEAR) + (newValue - curValue)); - }; - _proto2.resolve = function resolve(fieldValues, partialTemporal, resolverStyle) { - var yearLong = fieldValues.get(ChronoField.YEAR); - var qoyLong = fieldValues.get(QUARTER_OF_YEAR); +/***/ }), - if (yearLong == null || qoyLong == null) { - return null; - } +/***/ 58663: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var y = ChronoField.YEAR.checkValidIntValue(yearLong); - var doq = fieldValues.get(DAY_OF_QUARTER); - var date; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var querystring = __nccwpck_require__(71191); +var request = __nccwpck_require__(48699); +var _ = __nccwpck_require__(83571); +var url = __nccwpck_require__(78835); + +var constants = __nccwpck_require__(10282); +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +var AccountType = constants.UserRealm.AccountType; +var FederationProtocolType = constants.UserRealm.FederationProtocolType; + +var USER_REALM_PATH_TEMPLATE = 'common/UserRealm/'; + +/** + * Create a new UserRealm object + * @private + * @constructor + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} userPrinciple The username for which a realm needs to be discovered. + * @param {string} authority The string url of the authority that owns the userPrinciple. + */ +function UserRealm(callContext, userPrinciple, authority) { + this._log = new Logger('UserRealm', callContext._logContext); + this._callContext = callContext; + this._apiVersion = '1.0'; + this._federationProtocol = null; + this._accountType = null; + this._federationMetadataUrl = null; + this._federationActiveAuthUrl = null; + this._userPrinciple = userPrinciple; + this._authority = authority; +} + +/** +* The API version requested by UserRealm. +* @type {string} +* @instance +* @memberOf UserRealm +* @name apiVersion +*/ +Object.defineProperty(UserRealm.prototype, 'apiVersion', { + get : function() { + return this._apiVersion; + } +}); + +/** +* The federation protocol used by the users realm. +* @type {string} +* @instance +* @memberOf UserRealm +* @name federationProtocol +*/ +Object.defineProperty(UserRealm.prototype, 'federationProtocol', { + get : function() { + return this._federationProtocol; + } +}); + +/** +* The Type of account. Either managed or federated. +* @type {string} +* @instance +* @memberOf UserRealm +* @name accountType +*/ +Object.defineProperty(UserRealm.prototype, 'accountType', { + get : function() { + return this._accountType; + } +}); + +/** +* If this is a federated account then this property will contain the mex url. +* @type {string} +* @instance +* @memberOf UserRealm +* @name federationsMetadataUrl +*/ +Object.defineProperty(UserRealm.prototype, 'federationMetadataUrl', { + get : function() { + return this._federationMetadataUrl; + } +}); + +/** +* If the account is federated this will contain the authentication endpoint. +* @type {string} +* @instance +* @memberOf UserRealm +* @name federationActiveAuthUrl +*/ +Object.defineProperty(UserRealm.prototype, 'federationActiveAuthUrl', { + get : function() { + return this._federationActiveAuthUrl; + } +}); + +/** +* Given the authority url this method constructs a full user realm discovery url. +* @private +* @returns A full user realm discovery url including path and query string. +*/ +UserRealm.prototype._getUserRealmUrl = function() { + var userRealmUrl = util.copyUrl(this._authority); + var urlEncodedUser = encodeURIComponent(this._userPrinciple); + userRealmUrl.pathname = USER_REALM_PATH_TEMPLATE.replace('', urlEncodedUser); + + var userRealmQuery = { + 'api-version' : this._apiVersion + }; + + userRealmUrl.search = querystring.stringify(userRealmQuery); + + userRealmUrl = util.copyUrl(userRealmUrl); + + return userRealmUrl; +}; + +/** +* Given a constants object and a value, validates that the value is a key in the constants object. +* @private +* @param {object} constants An object containing constant key value pairs. +* @param {string} value A value to check against the constants +* @param {bool} caseSensitive set to true if comparisons should be made as case sensitive. Defaults to false. +* @returns {bool|string} If value passed in matches one of the constants then the return value is the matched constant. +* If a non case sensitive match was done, then the value returned may be different than the value +* passed in. If there is no match then the method returns false. +*/ +UserRealm.prototype._validateConstantValue = function(constants, value, caseSensitive) { + if (!value) { + return false; + } + if (!caseSensitive) { + value = value.toLowerCase(); + } + return _.contains(_.values(constants), value) ? value : false; +}; + +/** +* Checks whether an account type string is valid. +* @private +* @param {string} type An account type string. +* @returns {bool} +*/ +UserRealm.prototype._validateAccountType = function(type) { + return this._validateConstantValue(AccountType, type); +}; + +/** +* Checks whether a federation protocol string is valid. +* @private +* @param {string} protocol A federation protocol string. +* @returns {bool} +*/ +UserRealm.prototype._validateFederationProtocol = function(protocol) { + return this._validateConstantValue(FederationProtocolType, protocol); +}; + +/** +* Logs the values parsed as part of user realm discovery. +* @private +*/ +UserRealm.prototype._logParsedResponse = function() { + this._log.verbose('UserRealm response:'); + this._log.verbose(' AccountType: ' + this.accountType); + this._log.verbose(' FederationProtocol: ' + this.federationProtocol); + this._log.verbose(' FederationMetatdataUrl: ' + this.federationMetadataUrl, true); + this._log.verbose(' FederationActiveAuthUrl: ' + this.federationActiveAuthUrl, true); +}; + +/** +* Parses the response from a user realm discovery request. +* @private +* @param {string} body The body returned as part of the http user realm discovery request. +* @param {UserRealm.DiscoverCallback} callback Called when parsing is complete. +*/ +UserRealm.prototype._parseDiscoveryResponse = function(body, callback) { + this._log.verbose('Discovery response:\n' + body, true); + + var response; + try { + response = JSON.parse(body); + } catch (err) { + callback(this._log.createError('Parsing realm discovery respone JSON failed: ' + body, true)); + return; + } + + var accountType = this._validateAccountType(response['account_type']); + if (!accountType) { + callback(this._log.createError('Cannot parse account_type: ' + accountType)); + return; + } + + this._accountType = accountType; + + if (this._accountType === AccountType.Federated) { + var protocol = this._validateFederationProtocol(response['federation_protocol']); + + if (!protocol) { + callback(this._log.createError('Cannot parse federation protocol: ' + protocol)); + return; + } + + this._federationProtocol = protocol; + this._federationMetadataUrl = response['federation_metadata_url']; + this._federationActiveAuthUrl = response['federation_active_auth_url']; + } + + this._logParsedResponse(); + callback(); +}; + +/** +* @callback DiscoverCallback +* @memberOf UserRealm +* @param {Error} error If an error occurs during discovery then this parameter will be used to return the error. +*/ + +/** +* Performs user realm discovery and fills in the properties on this object. +* @private +* @param {UserRealm.DiscoverCallback} callback Called when discovery is complete. +*/ +UserRealm.prototype.discover = function(callback) { + var self = this; + var options = util.createRequestOptions( + this, + { + headers : { + Accept : 'application/json' + } + } + ); + + var userRealmUrl = this._getUserRealmUrl(); + this._log.verbose('Performing user realm discovery at: ' + url.format(userRealmUrl), true); + request.get(userRealmUrl, options, util.createRequestHandler('User Realm Discovery', this._log, callback, + function(response, body) { + self._parseDiscoveryResponse(body, callback); + }) + ); +}; + +module.exports = UserRealm; - if (resolverStyle === ResolverStyle.LENIENT) { - var qoy = qoyLong; - date = LocalDate.of(y, 1, 1); - date = date.plusMonths(MathUtil.safeMultiply(MathUtil.safeSubtract(qoy, 1), 3)); - date = date.plusDays(MathUtil.safeSubtract(doq, 1)); - } else { - var _qoy = QUARTER_OF_YEAR.range().checkValidIntValue(qoyLong, QUARTER_OF_YEAR); +/***/ }), - if (resolverStyle === ResolverStyle.STRICT) { - var max = 92; +/***/ 5336: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (_qoy === 1) { - max = IsoChronology.isLeapYear(y) ? 91 : 90; - } else if (_qoy === 2) { - max = 91; - } - - ValueRange.of(1, max).checkValidValue(doq, this); - } else { - this.range().checkValidValue(doq, this); - } - - date = LocalDate.of(y, (_qoy - 1) * 3 + 1, 1).plusDays(doq - 1); - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var adalIdConstants = __nccwpck_require__(10282).AdalIdParameters; +var os = __nccwpck_require__(12087); +var url = __nccwpck_require__(78835); + +var ADAL_VERSION; + +/** + * @namespace Util + * @private + */ + +function loadAdalVersion() { + ADAL_VERSION = __nccwpck_require__(93700)/* .version */ .i8; +} + +function adalInit() { + loadAdalVersion(); +} + +/** + * @static + * @memberOf Util + * @param {string|int} statusCode An HTTP status code. + */ +function isHttpSuccess(statusCode) { + return statusCode >= 200 && statusCode < 300; +} + +function addDefaultRequestHeaders (self, options) { + if (!options.headers) { + options.headers = {}; + } + var headers = options.headers; + if (!headers['Accept-Charset']) { + headers['Accept-Charset'] = 'utf-8'; + } + headers['client-request-id'] = self._callContext._logContext.correlationId; + headers['return-client-request-id'] = 'true'; + + // ADAL Id headers + headers[adalIdConstants.SKU] = adalIdConstants.NODE_SKU; + headers[adalIdConstants.VERSION] = ADAL_VERSION; + headers[adalIdConstants.OS] = os.platform(); + headers[adalIdConstants.CPU] = os.arch(); +} + +/** +* Central place for housing default request options. This is a place holder +* for when SSL validation is implemented an all requests are subject to that +* policy. +* @static +* @memberOf Util +* @param {object} options A set of options that will be merged with teh default options +* These will override any default options. +* @returns {object} Returns the merged options. +*/ +function createRequestOptions(self, options) { + var defaultOptions = {}; //{ strictSSL : true }; + var mergedOptions = defaultOptions; + if (options) { + _.extend(mergedOptions, options); + } + if (self._callContext.options && self._callContext.options.http) { + _.extend(mergedOptions, self._callContext.options.http); + } + + addDefaultRequestHeaders(self, mergedOptions); + return mergedOptions; +} + +function logReturnCorrelationId(log, operationMessage, response) { + if (response && response.headers && response.headers['client-request-id']) { + log.info(operationMessage + 'Server returned this correlationId: ' + response.headers['client-request-id'], true); + } +} + +/** +* Creates a function that can be used as the callback for http request operations. This is meant +* to centralize error handling in one place. +* @static +* @memberOf Util +* @param {string} operationMessage A message to be prepended to logged error strings. This should be something like 'Mex Request' +* and summarize the purpose of the http request. +* @param {object} log A Logger object being used by the calling component. +* @param {Util.CreateRequestHandlerErrorCallback} errorCallback Called in the event of an error. +* @param {Util.CreateRequestHandlerSuccessCallabck} successCallback Called on successfull completion of the request. +*/ +function createRequestHandler(operationMessage, log, errorCallback, successCallback) { + return function(err, response, body) { + logReturnCorrelationId(log, operationMessage, response); + if (err) { + log.error(operationMessage + ' request failed with', err, true); + errorCallback(err); + return; + } + if (!isHttpSuccess(response.statusCode)) { + var returnErrorString = operationMessage + ' request returned http error: ' + response.statusCode; + var errorResponse; + if (body) { + returnErrorString += ' and server response: ' + body; + try { + errorResponse = JSON.parse(body); + } catch (e) { + // No problem if it doesn't parse. + } + } + errorCallback(log.createError(returnErrorString, true), errorResponse); + return; + } + + successCallback(response, body); + }; +} + +/** +* @callback CreateRequestHandlerErrorCallback +* @memberOf Util +* @param {Error} error An error object. +*/ + +/** +* @callback CreateRequestHandlerSuccessCallabck +* @memberOf Util +* @param {object} response The response object returned from request. +* @param {string} body The body of the http response. +*/ + +/** +* Deep copies a url object. +* @static +* @memberOf Util +* @param {URL} urlSource The source url object to copy. +* @returns {URL} A deep copy of sourceUrl. +*/ +function copyUrl(urlSource) { + return url.parse(url.format(urlSource)); +} + +function convertUrlSafeToRegularBase64EncodedString(str) { + return str.replace(/-/g, '+').replace(/_/g, '/'); +} + +function convertRegularToUrlSafeBase64EncodedString(str) { + return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +} + +function base64DecodeStringUrlSafe(str) { + var base64 = convertUrlSafeToRegularBase64EncodedString(str); + return (new Buffer(base64, 'base64')).toString('utf8'); +} + +function base64EncodeStringUrlSafe(str) { + var base64 = (new Buffer(str, 'utf8').toString('base64')); + var converted = convertRegularToUrlSafeBase64EncodedString(base64); + return converted; +} + +module.exports.adalInit = adalInit; +module.exports.isHttpSuccess = isHttpSuccess; +module.exports.createRequestHandler = createRequestHandler; +module.exports.createRequestOptions = createRequestOptions; +module.exports.copyUrl = copyUrl; +module.exports.base64DecodeStringUrlSafe = base64DecodeStringUrlSafe; +module.exports.base64EncodeStringUrlSafe = base64EncodeStringUrlSafe; +module.exports.convertRegularToUrlSafeBase64EncodedString = convertRegularToUrlSafeBase64EncodedString; - fieldValues.remove(this); - fieldValues.remove(ChronoField.YEAR); - fieldValues.remove(QUARTER_OF_YEAR); - return date; - }; +/***/ }), - return DAY_OF_QUARTER_FIELD; - }(Field); +/***/ 39035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var QUARTER_OF_YEAR_FIELD = function (_Field2) { - _inheritsLoose(QUARTER_OF_YEAR_FIELD, _Field2); +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var request = __nccwpck_require__(48699); +var uuid = __nccwpck_require__(19744); + +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); +var WSTrustResponse = __nccwpck_require__(55927); +var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + +var USERNAME_PLACEHOLDER = '{UsernamePlaceHolder}'; +var PASSWORD_PLACEHOLDER = '{PasswordPlaceHolder}'; + +/** + * Creates a new instance of WSTrustRequest + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} wstrustEndpointUrl An STS WS-Trust soap endpoint. + * @param {string} appliesTo A URI that identifies a service for which the a token is to be obtained. + */ +function WSTrustRequest(callContext, wstrustEndpointUrl, appliesTo, wstrustEndpointVersion) { + this._log = new Logger('WSTrustRequest', callContext._logContext); + this._callContext = callContext; + this._wstrustEndpointUrl = wstrustEndpointUrl; + this._appliesTo = appliesTo; + this._wstrustEndpointVersion = wstrustEndpointVersion; +} + +/** +* Given a Date object adds the minutes parameter and returns a new Date object. +* @private +* @static +* @memberOf WSTrustRequest +* @param {Date} date A Date object. +* @param {Number} minutes The number of minutes to add to the date parameter. +* @returns {Date} Returns a Date object. +*/ +function _datePlusMinutes(date, minutes) { + var minutesInMilliSeconds = minutes * 60 * 1000; + var epochTime = date.getTime() + minutesInMilliSeconds; + return new Date(epochTime); +} + +/** + * Builds the soap security header for the RST message. + * @private + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @returns {string} A string that contains the soap security header. + */ +WSTrustRequest.prototype._buildSecurityHeader = function() { + var timeNow = new Date(); + var expireTime = _datePlusMinutes(timeNow, 10); + var timeNowString = timeNow.toISOString(); + var expireTimeString = expireTime.toISOString(); + + var securityHeaderXml = + '\ + \ + ' + timeNowString + '\ + ' + expireTimeString + '\ + \ + \ + ' + USERNAME_PLACEHOLDER + '\ + ' + PASSWORD_PLACEHOLDER + '\ + \ + '; + + return securityHeaderXml; +}; + +/** + * Replaces the placeholders in the RST template with the actual username and password values. + * @private + * @param {string} RSTTemplate An RST with placeholders for username and password. + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @returns {string} A string containing a complete RST soap message. + */ + +WSTrustRequest.prototype._populateRSTUsernamePassword = function(RSTTemplate, username, password) { + var RST = RSTTemplate.replace(USERNAME_PLACEHOLDER, username).replace(PASSWORD_PLACEHOLDER, this._populatedEscapedPassword(password)); + return RST; +}; + +/** + * Escape xml characters in password. + * @private + * @param {string} password The password to be excaped with xml charaters. + */ +WSTrustRequest.prototype._populatedEscapedPassword = function (password) { + var escapedPassword = password; + return escapedPassword.replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(//g, '>'); +} + +/** + * Builds a WS-Trust RequestSecurityToken (RST) message using username password authentication. + * @private + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @returns {string} A string containing a complete RST soap message. + */ +WSTrustRequest.prototype._buildRST = function(username, password) { + var messageID = uuid.v4(); + + // Create a template RST with placeholders for the username and password so the + // the RST can be logged without the sensitive information. + var schemaLocation = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'; + var soapAction = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; + var rstTrustNamespace = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'; + var keyType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer'; + var requestType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue'; + + if (this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005) { + soapAction = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; + rstTrustNamespace = 'http://schemas.xmlsoap.org/ws/2005/02/trust'; + keyType = 'http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey'; + requestType = 'http://schemas.xmlsoap.org/ws/2005/02/trust/Issue'; + } + + var RSTTemplate = + '\ + \ + ' + soapAction + '\ + urn:uuid:' + messageID + '\ + \ + http://www.w3.org/2005/08/addressing/anonymous\ + \ + ' + this._wstrustEndpointUrl + '\ + ' + this._buildSecurityHeader() + '\ + \ + \ + \ + \ + \ + ' + this._appliesTo + '\ + \ + \ + ' + keyType + '\ + ' + requestType + '\ + \ + \ + '; + + this._log.verbose('Created RST: \n' + RSTTemplate, true); + + var RST = this._populateRSTUsernamePassword(RSTTemplate, username, password); + return RST; +}; + +/** + * Handles the processing of a RSTR + * @private + * @param {string} body + * @param {WSTrustRequest.AcquireTokenCallback} callback + */ +WSTrustRequest.prototype._handleRSTR = function(body, callback) { + var err; + + var wstrustResponse = new WSTrustResponse(this._callContext, body, this._wstrustEndpointVersion); + try { + wstrustResponse.parse(); + } catch (error) { + err = error; + } + + callback(err, wstrustResponse); +}; + +/** + * Performs a WS-Trust RequestSecurityToken request to obtain a federated token in exchange for a username password. + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @param {WSTrustRequest.AcquireTokenCallback} callback Called once the federated token has been retrieved or on error. +*/ +WSTrustRequest.prototype.acquireToken = function(username, password, callback) { + if (this._wstrustEndpointVersion === WSTrustVersion.UNDEFINED) { + var err = this._log.createError('Unsupported wstrust endpoint version. Current support version is wstrust2005 or wstrust13.'); + callback(err); + return; + } + + var self = this; + var RST = this._buildRST(username, password); + + var soapAction = this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005 ? 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; + + var options = util.createRequestOptions( + this, + { + headers : { + 'Content-Type' : 'application/soap+xml; charset=utf-8', + 'SOAPAction' : soapAction + }, + body : RST + } + ); + + this._log.verbose('Sending RST to: ' + this._wstrustEndpointUrl, true); + + request.post(this._wstrustEndpointUrl, options, util.createRequestHandler('WS-Trust RST', this._log, callback, + function(response, body) { + self._handleRSTR(body, callback); + } + )); +}; + +/** +* @callback AcquireTokenCallback +* @memberOf WSTrustRequest +* @param {Error} err Contains an error object if acquireToken fails. +* @param {WSTrustResponse} A successful response to the RST. +*/ + +module.exports = WSTrustRequest; - function QUARTER_OF_YEAR_FIELD() { - return _Field2.apply(this, arguments) || this; - } - var _proto3 = QUARTER_OF_YEAR_FIELD.prototype; +/***/ }), - _proto3.toString = function toString() { - return 'QuarterOfYear'; - }; +/***/ 55927: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto3.baseUnit = function baseUnit() { - return QUARTER_YEARS; - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var xmldom = __nccwpck_require__(57286); + +var xmlutil = __nccwpck_require__(27387); + +var Logger = __nccwpck_require__(92288).Logger; + +var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + +var select = xmlutil.xpathSelect; +var DOMParser = xmldom.DOMParser; + +// A regular expression for finding the SAML Assertion in an RSTR. Used to remove the SAML +// assertion when logging the RSTR. +var assertionRegEx = /RequestedSecurityToken.*?((<.*?:Assertion.*?>).*<\/.*?Assertion>).*?/; + +/** + * Creates a log message that contains the RSTR scrubbed of the actual SAML assertion. + * @private + * @return {string} A log message. + */ +function scrubRSTRLogMessage(RSTR) { + var scrubbedRSTR = null; + + var singleLineRSTR = RSTR.replace(/(\r\n|\n|\r)/gm,''); + + var matchResult = assertionRegEx.exec(singleLineRSTR); + if (null === matchResult) { + // No Assertion was matched so just return the RSTR as is. + scrubbedRSTR = singleLineRSTR; + } else { + var samlAssertion = matchResult[1]; + var samlAssertionStartTag = matchResult[2]; + + scrubbedRSTR = singleLineRSTR.replace(samlAssertion, samlAssertionStartTag + 'ASSERTION CONTENTS REDACTED'); + } + + return 'RSTR Response: ' + scrubbedRSTR; +} + +/** + * Creates a new WSTrustResponse instance. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} response A soap response from a WS-Trust request. + * @param {sting} wstrustVersion The version for the WS-Trust request. + */ +function WSTrustResponse(callContext, response, wstrustVersion) { + this._log = new Logger('WSTrustResponse', callContext._logContext); + this._callContext = callContext; + this._response = response; + this._dom = null; + this._errorCode = null; + this._faultMessage = null; + this._tokenType = null; + this._token = null; + this._wstrustVersion = wstrustVersion; + + this._log.verbose(function(){return scrubRSTRLogMessage(response);}); +} + +/** + * If the soap response contained a soap fault then this property will contain the fault + * error code. Otherwise it will return null + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name errorCode + */ +Object.defineProperty(WSTrustResponse.prototype, 'errorCode', { + get: function() { + return this._errorCode; + } +}); + +/** + * @property {string} FaultMessage If the soap resopnse contained a soap fault with a fault message then it will + * be returned by this property. + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name faultMessage + */ +Object.defineProperty(WSTrustResponse.prototype, 'faultMessage', { + get: function() { + return this._faultMessage; + } +}); + +/** + * @property {string} TokenType If the soap resonse contained a token then this property will contain + * the token type uri + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name tokenType + */ +Object.defineProperty(WSTrustResponse.prototype, 'tokenType', { + get: function() { + return this._tokenType; + } +}); + +/** + * @property {string} Token If the soap response contained a token then this property will hold that token. + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name token + */ +Object.defineProperty(WSTrustResponse.prototype, 'token', { + get: function() { + return this._token; + } +}); + + // Sample error message + // + // + // http://www.w3.org/2005/08/addressing/soap/fault + // - + // + // 2013-07-30T00:32:21.989Z + // 2013-07-30T00:37:21.989Z + // + // + // + // + // + // + // s:Sender + // + // a:RequestFailed + // + // + // + // MSIS3127: The specified request failed. + // + // + // + // + +/** + * Attempts to parse an error from the soap response. If there is one then it + * will fill in the error related properties. Otherwsie it will do nothing. + * @private + * @returns {bool} true if an error was found and parsed in the response. + */ +WSTrustResponse.prototype._parseError = function() { + var errorFound = false; + + var faultNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Reason'); + if (faultNode.length) { + this._faultMessage = xmlutil.serializeNodeChildren(faultNode[0]); + + if (this._faultMessage) { + errorFound = true; + } + } + + // Subcode has minoccurs=0 and maxoccurs=1(default) according to the http://www.w3.org/2003/05/soap-envelope + // Subcode may have another subcode as well. This is only targetting at top level subcode. + // Subcode value may have different messages not always uses http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd. + // text inside the value is not possible to select without prefix, so substring is necessary + var subcodeNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value'); + if (1 < subcodeNode.length) { + throw this._log.createError('Found too many fault code values:' + subcodeNode.length); + } + + if (subcodeNode.length) { + var errorCode = subcodeNode[0].firstChild.data; + this._errorCode = (errorCode.split(':'))[1]; + errorFound = true; + } + + return errorFound; +}; + +/** + * Attempts to parse a token from the soap response. If there is one then it will fill in the + * token related properties. Otherwise it does nothing. + * @private + * @throws {Error} If the response is not parseable, or too many tokens are found. + */ +WSTrustResponse.prototype._parseToken = function() { + var xPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? '//s:Envelope/s:Body/t:RequestSecurityTokenResponse/t:TokenType' : '//s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/wst:RequestSecurityTokenResponse/wst:TokenType'; + + var tokenTypeNodes = select(this._dom, xPath); + if (!tokenTypeNodes.length) { + this._log.warn('No TokenType elements found in RSTR'); + } + + for (var i = 0, length = tokenTypeNodes.length; i < length; i++) { + if (this._token) { + this._log.warn('Found more than one returned token. Using the first.'); + break; + } + + var tokenTypeNode = tokenTypeNodes[i]; + var tokenType = xmlutil.findElementText(tokenTypeNode); + if (!tokenType) { + this._log.warn('Could not find token type in RSTR token'); + } + + var securityTokenPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? 't:RequestedSecurityToken' : 'wst:RequestedSecurityToken'; + var requestedTokenNode = select(tokenTypeNode.parentNode, securityTokenPath); + if (1 < requestedTokenNode) { + throw this._log.createError('Found too many RequestedSecurityToken nodes for token type: ' + tokenType); + } + if (!requestedTokenNode.length) { + this._log.warn('Unable to find RequestsSecurityToken element associated with TokenType element: ' + tokenType); + continue; + } + + var token = xmlutil.serializeNodeChildren(requestedTokenNode[0]); + if (!token) { + this._log.warn('Unable to find token associated with TokenType element: ' + tokenType); + continue; + } + + this._token = token; + this._tokenType = tokenType; + + this._log.info('Found token of type: ' + this._tokenType); + } + + if (!this._token) { + throw this._log.createError('Unable to find any tokens in RSTR.'); + } +}; + +/** + * This method parses the soap response that was passed in at construction. + * @throws {Error} If the server returned an error, or there was any failure to parse the response. + */ +WSTrustResponse.prototype.parse = function() { + if (!this._response) { + throw this._log.createError('Received empty RSTR response body.'); + } + + try { + try { + var options = { + errorHandler : this._log.error + }; + this._dom = new DOMParser(options).parseFromString(this._response); + } catch (err) { + throw this._log.createError('Failed to parse RSTR in to DOM', err, true); + } + + var errorFound = this._parseError(); + + if (errorFound) { + var stringErrorCode = this.ErrorCode || 'NONE'; + var stringFaultMessage = this.FaultMessage || 'NONE'; + throw this._log.createError('Server returned error in RSTR - ErrorCode: ' + stringErrorCode + ' : FaultMessage: ' + stringFaultMessage, true); + } + + this._parseToken(); + } catch (err) { + delete this._dom; + throw err; + } +}; + +module.exports = WSTrustResponse; - _proto3.rangeUnit = function rangeUnit() { - return ChronoUnit.YEARS; - }; +/***/ }), - _proto3.range = function range() { - return ValueRange.of(1, 4); - }; +/***/ 27387: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto3.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.MONTH_OF_YEAR) && this._isIso(temporal); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var select = __nccwpck_require__(74277); +var XMLSerializer = __nccwpck_require__(57286).XMLSerializer; + +var constants = __nccwpck_require__(10282); + +/** + * @namespace XmlUtil + * @private + */ + +var XPATH_PATH_TEMPLATE = '*[local-name() = \'LOCAL_NAME\' and namespace-uri() = \'NAMESPACE\']'; +/** +* The xpath implementation being used does not have a way of matching expanded namespace. +* This method takes an xpath query and expands all of the namespaces involved. It then +* re-writes the query in to a longer form that directory matches the correct namespaces. +* @private +* @static +* @memberOf XmlUtil +* @param {string} xpath The expath query string to expand. +* @returns {string} An expanded xpath query. +*/ +function expandQNames(xpath) { + var namespaces = constants.XmlNamespaces; + var pathParts = xpath.split('/'); + for (var i=0; i < pathParts.length; i++) { + if (pathParts[i].indexOf(':') !== -1) { + var QNameParts = pathParts[i].split(':'); + if (QNameParts.length !== 2) { + throw new Error('Unable to parse XPath string : ' + xpath + ' : with QName : ' + pathParts[i]); + } + var expandedPath = XPATH_PATH_TEMPLATE.replace('LOCAL_NAME', QNameParts[1]); + expandedPath = expandedPath.replace('NAMESPACE', namespaces[QNameParts[0]]); + pathParts[i] = expandedPath; + } + } + return pathParts.join('/'); +} + +var exports = { + + /** + * Performs an xpath select that does appropriate namespace matching since the imported + * xpath module does not properly handle namespaces. + * @static + * @memberOf XmlUtil + * @param {object} dom A dom object created by the xmldom module + * @param {string} xpath An xpath expression + * @return {array} An array of matching dom nodes. + */ + xpathSelect : function (dom, xpath) { + return select(dom, expandQNames(xpath)); + }, + + /** + * Given a dom node serializes all immediate children that are xml elements. + * @static + * @memberOf XmlUtil + * @param {object} node An xml dom node. + * @return {string} Serialized xml. + */ + serializeNodeChildren : function(node) { + var doc = ''; + var sibling = node.firstChild; + var serializer = new XMLSerializer(); + + while (sibling) { + if (this.isElementNode(sibling)) { + doc += serializer.serializeToString(sibling); + } + sibling = sibling.nextSibling; + } + + return doc !== '' ? doc : null; + }, + + /** + * Detects whether the passed in dom node represents an xml element. + * @static + * @memberOf XmlUtil + * @param {object} node An xml dom node. + * @return {Boolean} true if the node represents an element. + */ + isElementNode : function(node) { + return _.has(node, 'tagName'); + }, + + /** + * Given an xmldom node this function returns any text data contained within. + * @static + * @memberOf XmlUtil + * @param {object} node An xmldom node from which the data should be extracted. + * @return {string} Any data found within the element or null if none is found. + */ + findElementText : function(node) { + var sibling = node.firstChild; + while (sibling && !sibling.data) { + sibling = sibling.nextSibling; + } + + return sibling.data ? sibling.data : null; + } +}; + +module.exports = exports; - _proto3.rangeRefinedBy = function rangeRefinedBy(temporal) { - return this.range(); - }; +/***/ }), - _proto3.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: QuarterOfYear'); - } +/***/ 19744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var moy = temporal.getLong(ChronoField.MONTH_OF_YEAR); - return MathUtil.intDiv(moy + 2, 3); - }; +var v1 = __nccwpck_require__(64425); +var v4 = __nccwpck_require__(85258); - _proto3.adjustInto = function adjustInto(temporal, newValue) { - var curValue = this.getFrom(temporal); - this.range().checkValidValue(newValue, this); - return temporal.with(ChronoField.MONTH_OF_YEAR, temporal.getLong(ChronoField.MONTH_OF_YEAR) + (newValue - curValue) * 3); - }; +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; - return QUARTER_OF_YEAR_FIELD; - }(Field); +module.exports = uuid; - var WEEK_OF_WEEK_BASED_YEAR_FIELD = function (_Field3) { - _inheritsLoose(WEEK_OF_WEEK_BASED_YEAR_FIELD, _Field3); - function WEEK_OF_WEEK_BASED_YEAR_FIELD() { - return _Field3.apply(this, arguments) || this; - } +/***/ }), - var _proto4 = WEEK_OF_WEEK_BASED_YEAR_FIELD.prototype; +/***/ 54121: +/***/ ((module) => { - _proto4.toString = function toString() { - return 'WeekOfWeekBasedYear'; - }; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 0x100).toString(16).substr(1); +} - _proto4.baseUnit = function baseUnit() { - return ChronoUnit.WEEKS; - }; +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 + return ([ + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]] + ]).join(''); +} - _proto4.rangeUnit = function rangeUnit() { - return WEEK_BASED_YEARS; - }; +module.exports = bytesToUuid; - _proto4.range = function range() { - return ValueRange.of(1, 52, 53); - }; - _proto4.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.EPOCH_DAY) && this._isIso(temporal); - }; +/***/ }), - _proto4.rangeRefinedBy = function rangeRefinedBy(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekOfWeekBasedYear'); - } +/***/ 57455: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return Field._getWeekRangeByLocalDate(LocalDate.from(temporal)); - }; +// Unique ID creation requires a high quality random # generator. In node.js +// this is pretty straight-forward - we use the crypto API. - _proto4.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekOfWeekBasedYear'); - } +var crypto = __nccwpck_require__(76417); - return Field._getWeek(LocalDate.from(temporal)); - }; +module.exports = function nodeRNG() { + return crypto.randomBytes(16); +}; - _proto4.adjustInto = function adjustInto(temporal, newValue) { - this.range().checkValidValue(newValue, this); - return temporal.plus(MathUtil.safeSubtract(newValue, this.getFrom(temporal)), ChronoUnit.WEEKS); - }; - _proto4.resolve = function resolve(fieldValues, partialTemporal, resolverStyle) { - var wbyLong = fieldValues.get(WEEK_BASED_YEAR); - var dowLong = fieldValues.get(ChronoField.DAY_OF_WEEK); +/***/ }), - if (wbyLong == null || dowLong == null) { - return null; - } +/***/ 64425: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var wby = WEEK_BASED_YEAR.range().checkValidIntValue(wbyLong, WEEK_BASED_YEAR); - var wowby = fieldValues.get(WEEK_OF_WEEK_BASED_YEAR); - var date; +var rng = __nccwpck_require__(57455); +var bytesToUuid = __nccwpck_require__(54121); - if (resolverStyle === ResolverStyle.LENIENT) { - var dow = dowLong; - var weeks = 0; +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html - if (dow > 7) { - weeks = MathUtil.intDiv(dow - 1, 7); - dow = MathUtil.intMod(dow - 1, 7) + 1; - } else if (dow < 1) { - weeks = MathUtil.intDiv(dow, 7) - 1; - dow = MathUtil.intMod(dow, 7) + 7; - } +var _nodeId; +var _clockseq; - date = LocalDate.of(wby, 1, 4).plusWeeks(wowby - 1).plusWeeks(weeks).with(ChronoField.DAY_OF_WEEK, dow); - } else { - var _dow2 = ChronoField.DAY_OF_WEEK.checkValidIntValue(dowLong); +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; - if (resolverStyle === ResolverStyle.STRICT) { - var temp = LocalDate.of(wby, 1, 4); +// See https://github.com/uuidjs/uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; - var range = Field._getWeekRangeByLocalDate(temp); + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - range.checkValidValue(wowby, this); - } else { - this.range().checkValidValue(wowby, this); - } + // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = rng(); + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [ + seedBytes[0] | 0x01, + seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] + ]; + } + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } - date = LocalDate.of(wby, 1, 4).plusWeeks(wowby - 1).with(ChronoField.DAY_OF_WEEK, _dow2); - } + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - fieldValues.remove(this); - fieldValues.remove(WEEK_BASED_YEAR); - fieldValues.remove(ChronoField.DAY_OF_WEEK); - return date; - }; + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - _proto4.displayName = function displayName() { - return 'Week'; - }; + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; - return WEEK_OF_WEEK_BASED_YEAR_FIELD; - }(Field); + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } - var WEEK_BASED_YEAR_FIELD = function (_Field4) { - _inheritsLoose(WEEK_BASED_YEAR_FIELD, _Field4); + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } - function WEEK_BASED_YEAR_FIELD() { - return _Field4.apply(this, arguments) || this; - } + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } - var _proto5 = WEEK_BASED_YEAR_FIELD.prototype; + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; - _proto5.toString = function toString() { - return 'WeekBasedYear'; - }; + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; - _proto5.baseUnit = function baseUnit() { - return WEEK_BASED_YEARS; - }; + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; - _proto5.rangeUnit = function rangeUnit() { - return ChronoUnit.FOREVER; - }; + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; - _proto5.range = function range() { - return ChronoField.YEAR.range(); - }; + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; - _proto5.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.EPOCH_DAY) && this._isIso(temporal); - }; + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; - _proto5.rangeRefinedBy = function rangeRefinedBy(temporal) { - return ChronoField.YEAR.range(); - }; + // `clock_seq_low` + b[i++] = clockseq & 0xff; - _proto5.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekBasedYear'); - } - - return Field._getWeekBasedYear(LocalDate.from(temporal)); - }; + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } - _proto5.adjustInto = function adjustInto(temporal, newValue) { - if (this.isSupportedBy(temporal) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekBasedYear'); - } + return buf ? buf : bytesToUuid(b); +} - var newWby = this.range().checkValidIntValue(newValue, WEEK_BASED_YEAR); - var date = LocalDate.from(temporal); - var dow = date.get(ChronoField.DAY_OF_WEEK); +module.exports = v1; - var week = Field._getWeek(date); - if (week === 53 && Field._getWeekRangeByYear(newWby) === 52) { - week = 52; - } +/***/ }), - var resolved = LocalDate.of(newWby, 1, 4); - var days = dow - resolved.get(ChronoField.DAY_OF_WEEK) + (week - 1) * 7; - resolved = resolved.plusDays(days); - return temporal.with(resolved); - }; +/***/ 85258: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return WEEK_BASED_YEAR_FIELD; - }(Field); +var rng = __nccwpck_require__(57455); +var bytesToUuid = __nccwpck_require__(54121); - var Unit = function (_TemporalUnit) { - _inheritsLoose(Unit, _TemporalUnit); +function v4(options, buf, offset) { + var i = buf && offset || 0; - function Unit(name, estimatedDuration) { - var _this; + if (typeof(options) == 'string') { + buf = options === 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; - _this = _TemporalUnit.call(this) || this; - _this._name = name; - _this._duration = estimatedDuration; - return _this; - } + var rnds = options.random || (options.rng || rng)(); - var _proto6 = Unit.prototype; + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; - _proto6.duration = function duration() { - return this._duration; - }; + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } - _proto6.isDurationEstimated = function isDurationEstimated() { - return true; - }; + return buf || bytesToUuid(rnds); +} - _proto6.isDateBased = function isDateBased() { - return true; - }; +module.exports = v4; - _proto6.isTimeBased = function isTimeBased() { - return false; - }; - _proto6.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.EPOCH_DAY); - }; +/***/ }), - _proto6.addTo = function addTo(temporal, periodToAdd) { - switch (this) { - case WEEK_BASED_YEARS: - { - var added = MathUtil.safeAdd(temporal.get(WEEK_BASED_YEAR), periodToAdd); - return temporal.with(WEEK_BASED_YEAR, added); - } +/***/ 64941: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case QUARTER_YEARS: - return temporal.plus(MathUtil.intDiv(periodToAdd, 256), ChronoUnit.YEARS).plus(MathUtil.intMod(periodToAdd, 256) * 3, ChronoUnit.MONTHS); +"use strict"; - default: - throw new IllegalStateException('Unreachable'); - } - }; - _proto6.between = function between(temporal1, temporal2) { - switch (this) { - case WEEK_BASED_YEARS: - return MathUtil.safeSubtract(temporal2.getLong(WEEK_BASED_YEAR), temporal1.getLong(WEEK_BASED_YEAR)); +var compileSchema = __nccwpck_require__(875) + , resolve = __nccwpck_require__(63896) + , Cache = __nccwpck_require__(93679) + , SchemaObject = __nccwpck_require__(37605) + , stableStringify = __nccwpck_require__(30969) + , formats = __nccwpck_require__(66627) + , rules = __nccwpck_require__(68561) + , $dataMetaSchema = __nccwpck_require__(21412) + , util = __nccwpck_require__(76578); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = __nccwpck_require__(80890); +var customKeyword = __nccwpck_require__(53297); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = __nccwpck_require__(25726); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; - case QUARTER_YEARS: - return MathUtil.intDiv(temporal1.until(temporal2, ChronoUnit.MONTHS), 3); +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); - default: - throw new IllegalStateException('Unreachable'); - } - }; + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); - _proto6.toString = function toString() { - return name; - }; + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); - return Unit; - }(TemporalUnit); - - var DAY_OF_QUARTER = null; - var QUARTER_OF_YEAR = null; - var WEEK_OF_WEEK_BASED_YEAR = null; - var WEEK_BASED_YEAR = null; - var WEEK_BASED_YEARS = null; - var QUARTER_YEARS = null; - function _init$8() { - DAY_OF_QUARTER = new DAY_OF_QUARTER_FIELD(); - QUARTER_OF_YEAR = new QUARTER_OF_YEAR_FIELD(); - WEEK_OF_WEEK_BASED_YEAR = new WEEK_OF_WEEK_BASED_YEAR_FIELD(); - WEEK_BASED_YEAR = new WEEK_BASED_YEAR_FIELD(); - WEEK_BASED_YEARS = new Unit('WeekBasedYears', Duration.ofSeconds(31556952)); - QUARTER_YEARS = new Unit('QuarterYears', Duration.ofSeconds(31556952 / 4)); - IsoFields.DAY_OF_QUARTER = DAY_OF_QUARTER; - IsoFields.QUARTER_OF_YEAR = QUARTER_OF_YEAR; - IsoFields.WEEK_OF_WEEK_BASED_YEAR = WEEK_OF_WEEK_BASED_YEAR; - IsoFields.WEEK_BASED_YEAR = WEEK_BASED_YEAR; - IsoFields.WEEK_BASED_YEARS = WEEK_BASED_YEARS; - IsoFields.QUARTER_YEARS = QUARTER_YEARS; - - LocalDate.prototype.isoWeekOfWeekyear = function () { - return this.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); - }; + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} - LocalDate.prototype.isoWeekyear = function () { - return this.get(IsoFields.WEEK_BASED_YEAR); - }; - } - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var DecimalStyle = function () { - function DecimalStyle(zeroChar, positiveSignChar, negativeSignChar, decimalPointChar) { - this._zeroDigit = zeroChar; - this._zeroDigitCharCode = zeroChar.charCodeAt(0); - this._positiveSign = positiveSignChar; - this._negativeSign = negativeSignChar; - this._decimalSeparator = decimalPointChar; - } - var _proto = DecimalStyle.prototype; +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } - _proto.positiveSign = function positiveSign() { - return this._positiveSign; - }; + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} - _proto.withPositiveSign = function withPositiveSign(positiveSign) { - if (positiveSign === this._positiveSign) { - return this; - } - return new DecimalStyle(this._zeroDigit, positiveSign, this._negativeSign, this._decimalSeparator); - }; +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} - _proto.negativeSign = function negativeSign() { - return this._negativeSign; - }; - _proto.withNegativeSign = function withNegativeSign(negativeSign) { - if (negativeSign === this._negativeSign) { - return this; - } +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} 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`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i= 0 && val <= 9 ? val : -1; - }; - _proto.convertNumberToI18N = function convertNumberToI18N(numericText) { - if (this._zeroDigit === '0') { - return numericText; - } +function _getSchemaObj(self, keyRef) { + keyRef = resolve.normalizeId(keyRef); + return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; +} - var diff = this._zeroDigitCharCode - '0'.charCodeAt(0); - var convertedText = ''; - for (var i = 0; i < numericText.length; i++) { - convertedText += String.fromCharCode(numericText.charCodeAt(i) + diff); - } +/** + * 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. + * @this Ajv + * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object + * @return {Ajv} this for method chaining + */ +function removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + _removeAllSchemas(this, this._schemas, schemaKeyRef); + _removeAllSchemas(this, this._refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case 'undefined': + _removeAllSchemas(this, this._schemas); + _removeAllSchemas(this, this._refs); + this._cache.clear(); + return this; + case 'string': + var schemaObj = _getSchemaObj(this, schemaKeyRef); + if (schemaObj) this._cache.del(schemaObj.cacheKey); + delete this._schemas[schemaKeyRef]; + delete this._refs[schemaKeyRef]; + return this; + case 'object': + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; + this._cache.del(cacheKey); + var id = this._getId(schemaKeyRef); + if (id) { + id = resolve.normalizeId(id); + delete this._schemas[id]; + delete this._refs[id]; + } + } + return this; +} - return convertedText; - }; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } +function _removeAllSchemas(self, schemas, regex) { + for (var keyRef in schemas) { + var schemaObj = schemas[keyRef]; + if (!schemaObj.meta && (!regex || regex.test(keyRef))) { + self._cache.del(schemaObj.cacheKey); + delete schemas[keyRef]; + } + } +} - if (other instanceof DecimalStyle) { - return this._zeroDigit === other._zeroDigit && this._positiveSign === other._positiveSign && this._negativeSign === other._negativeSign && this._decimalSeparator === other._decimalSeparator; - } - return false; - }; +/* @this Ajv */ +function _addSchema(schema, skipValidation, meta, shouldAddSchema) { + if (typeof schema != 'object' && typeof schema != 'boolean') + throw new Error('schema should be object or boolean'); + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schema) : schema; + var cached = this._cache.get(cacheKey); + if (cached) return cached; - _proto.hashCode = function hashCode() { - return this._zeroDigit + this._positiveSign + this._negativeSign + this._decimalSeparator; - }; + shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; - _proto.toString = function toString() { - return 'DecimalStyle[' + this._zeroDigit + this._positiveSign + this._negativeSign + this._decimalSeparator + ']'; - }; + var id = resolve.normalizeId(this._getId(schema)); + if (id && shouldAddSchema) checkUnique(this, id); - DecimalStyle.of = function of() { - throw new Error('not yet supported'); - }; + var willValidate = this._opts.validateSchema !== false && !skipValidation; + var recursiveMeta; + if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) + this.validateSchema(schema, true); - DecimalStyle.availableLocales = function availableLocales() { - throw new Error('not yet supported'); - }; + var localRefs = resolve.ids.call(this, schema); - return DecimalStyle; - }(); - DecimalStyle.STANDARD = new DecimalStyle('0', '+', '-', '.'); + var schemaObj = new SchemaObject({ + id: id, + schema: schema, + localRefs: localRefs, + cacheKey: cacheKey, + meta: meta + }); - var SignStyle = function (_Enum) { - _inheritsLoose(SignStyle, _Enum); + if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; + this._cache.put(cacheKey, schemaObj); - function SignStyle() { - return _Enum.apply(this, arguments) || this; - } + if (willValidate && recursiveMeta) this.validateSchema(schema, true); - var _proto = SignStyle.prototype; + return schemaObj; +} - _proto.parse = function parse(positive, strict, fixedWidth) { - switch (this) { - case SignStyle.NORMAL: - return !positive || !strict; - case SignStyle.ALWAYS: - case SignStyle.EXCEEDS_PAD: - return true; +/* @this Ajv */ +function _compile(schemaObj, root) { + if (schemaObj.compiling) { + schemaObj.validate = callValidate; + callValidate.schema = schemaObj.schema; + callValidate.errors = null; + callValidate.root = root ? root : callValidate; + if (schemaObj.schema.$async === true) + callValidate.$async = true; + return callValidate; + } + schemaObj.compiling = true; - default: - return !strict && !fixedWidth; - } - }; + var currentOpts; + if (schemaObj.meta) { + currentOpts = this._opts; + this._opts = this._metaOpts; + } - return SignStyle; - }(Enum); - SignStyle.NORMAL = new SignStyle('NORMAL'); - SignStyle.NEVER = new SignStyle('NEVER'); - SignStyle.ALWAYS = new SignStyle('ALWAYS'); - SignStyle.EXCEEDS_PAD = new SignStyle('EXCEEDS_PAD'); - SignStyle.NOT_NEGATIVE = new SignStyle('NOT_NEGATIVE'); + var v; + try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } + catch(e) { + delete schemaObj.validate; + throw e; + } + finally { + schemaObj.compiling = false; + if (schemaObj.meta) this._opts = currentOpts; + } - var TextStyle = function (_Enum) { - _inheritsLoose(TextStyle, _Enum); + schemaObj.validate = v; + schemaObj.refs = v.refs; + schemaObj.refVal = v.refVal; + schemaObj.root = v.root; + return v; - function TextStyle() { - return _Enum.apply(this, arguments) || this; - } - var _proto = TextStyle.prototype; + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var _validate = schemaObj.validate; + var result = _validate.apply(this, arguments); + callValidate.errors = _validate.errors; + return result; + } +} - _proto.isStandalone = function isStandalone() { - switch (this) { - case TextStyle.FULL_STANDALONE: - case TextStyle.SHORT_STANDALONE: - case TextStyle.NARROW_STANDALONE: - return true; - default: - return false; - } - }; +function chooseGetId(opts) { + switch (opts.schemaId) { + case 'auto': return _get$IdOrId; + case 'id': return _getId; + default: return _get$Id; + } +} - _proto.asStandalone = function asStandalone() { - switch (this) { - case TextStyle.FULL: - return TextStyle.FULL_STANDALONE; +/* @this Ajv */ +function _getId(schema) { + if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); + return schema.id; +} - case TextStyle.SHORT: - return TextStyle.SHORT_STANDALONE; +/* @this Ajv */ +function _get$Id(schema) { + if (schema.id) this.logger.warn('schema id ignored', schema.id); + return schema.$id; +} - case TextStyle.NARROW: - return TextStyle.NARROW_STANDALONE; - default: - return this; - } - }; +function _get$IdOrId(schema) { + if (schema.$id && schema.id && schema.$id != schema.id) + throw new Error('schema $id is different from id'); + return schema.$id || schema.id; +} - _proto.asNormal = function asNormal() { - switch (this) { - case TextStyle.FULL_STANDALONE: - return TextStyle.FULL; - case TextStyle.SHORT_STANDALONE: - return TextStyle.SHORT; +/** + * Convert array of error message objects to string + * @this Ajv + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; - case TextStyle.NARROW_STANDALONE: - return TextStyle.NARROW; + var text = ''; + for (var i=0; i 1) { - throw new IllegalArgumentException('invalid literal, too long: "' + literal + '"'); - } - this._literal = literal; - } +function addDefaultMetaSchema(self) { + var $dataSchema; + if (self._opts.$data) { + $dataSchema = __nccwpck_require__(66835); + self.addMetaSchema($dataSchema, $dataSchema.$id, true); + } + if (self._opts.meta === false) return; + var metaSchema = __nccwpck_require__(40038); + if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); + self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); + self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; +} - var _proto = CharLiteralPrinterParser.prototype; - _proto.print = function print(context, buf) { - buf.append(this._literal); - return true; - }; +function addInitialSchemas(self) { + var optsSchemas = self._opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas); + else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key); +} - _proto.parse = function parse(context, text, position) { - var length = text.length; - if (position === length) { - return ~position; - } +function addInitialFormats(self) { + for (var name in self._opts.formats) { + var format = self._opts.formats[name]; + self.addFormat(name, format); + } +} - var ch = text.charAt(position); - if (context.charEquals(this._literal, ch) === false) { - return ~position; - } +function addInitialKeywords(self) { + for (var name in self._opts.keywords) { + var keyword = self._opts.keywords[name]; + self.addKeyword(name, keyword); + } +} - return position + this._literal.length; - }; - _proto.toString = function toString() { - if (this._literal === '\'') { - return "''"; - } +function checkUnique(self, id) { + if (self._schemas[id] || self._refs[id]) + throw new Error('schema with key or id "' + id + '" already exists'); +} - return "'" + this._literal + "'"; - }; - return CharLiteralPrinterParser; - }(); +function getMetaSchemaOptions(self) { + var metaOpts = util.copy(self._opts); + for (var i=0; i { - if (pp.print(context, buf) === false) { - buf.setLength(length); - return true; - } - } - } finally { - if (this._optional) { - context.endOptional(); - } - } +"use strict"; - return true; - }; - _proto.parse = function parse(context, text, position) { - if (this._optional) { - context.startOptional(); - var pos = position; - for (var i = 0; i < this._printerParsers.length; i++) { - var pp = this._printerParsers[i]; - pos = pp.parse(context, text, pos); +var Cache = module.exports = function Cache() { + this._cache = {}; +}; - if (pos < 0) { - context.endOptional(false); - return position; - } - } - context.endOptional(true); - return pos; - } else { - for (var _i = 0; _i < this._printerParsers.length; _i++) { - var _pp = this._printerParsers[_i]; - position = _pp.parse(context, text, position); +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; - if (position < 0) { - break; - } - } - return position; - } - }; +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; +}; - _proto.toString = function toString() { - var buf = ''; - if (this._printerParsers != null) { - buf += this._optional ? '[' : '('; +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; - for (var i = 0; i < this._printerParsers.length; i++) { - var pp = this._printerParsers[i]; - buf += pp.toString(); - } - buf += this._optional ? ']' : ')'; - } +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; +}; - return buf; - }; - return CompositePrinterParser; - }(); +/***/ }), - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var FractionPrinterParser = function () { - function FractionPrinterParser(field, minWidth, maxWidth, decimalPoint) { - requireNonNull(field, 'field'); +/***/ 80890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (field.range().isFixed() === false) { - throw new IllegalArgumentException('Field must have a fixed set of values: ' + field); - } +"use strict"; - if (minWidth < 0 || minWidth > 9) { - throw new IllegalArgumentException('Minimum width must be from 0 to 9 inclusive but was ' + minWidth); - } - if (maxWidth < 1 || maxWidth > 9) { - throw new IllegalArgumentException('Maximum width must be from 1 to 9 inclusive but was ' + maxWidth); - } +var MissingRefError = __nccwpck_require__(25726).MissingRef; - if (maxWidth < minWidth) { - throw new IllegalArgumentException('Maximum width must exceed or equal the minimum width but ' + maxWidth + ' < ' + minWidth); - } +module.exports = compileAsync; - this.field = field; - this.minWidth = minWidth; - this.maxWidth = maxWidth; - this.decimalPoint = decimalPoint; - } - var _proto = FractionPrinterParser.prototype; +/** + * 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. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. + * @return {Promise} promise that resolves with a validating function. + */ +function compileAsync(schema, meta, callback) { + /* eslint no-shadow: 0 */ + /* global Promise */ + /* jshint validthis: true */ + var self = this; + if (typeof this._opts.loadSchema != 'function') + throw new Error('options.loadSchema should be a function'); - _proto.print = function print(context, buf) { - var value = context.getValue(this.field); + if (typeof meta == 'function') { + callback = meta; + meta = undefined; + } - if (value === null) { - return false; - } + var p = loadMetaSchemaOf(schema).then(function () { + var schemaObj = self._addSchema(schema, undefined, meta); + return schemaObj.validate || _compileAsync(schemaObj); + }); - var symbols = context.symbols(); + if (callback) { + p.then( + function(v) { callback(null, v); }, + callback + ); + } - if (value === 0) { - if (this.minWidth > 0) { - if (this.decimalPoint) { - buf.append(symbols.decimalSeparator()); - } + return p; - for (var i = 0; i < this.minWidth; i++) { - buf.append(symbols.zeroDigit()); - } - } - } else { - var fraction = this.convertToFraction(value, symbols.zeroDigit()); - var outputScale = Math.min(Math.max(fraction.length, this.minWidth), this.maxWidth); - fraction = fraction.substr(0, outputScale); - if (fraction * 1 > 0) { - while (fraction.length > this.minWidth && fraction[fraction.length - 1] === '0') { - fraction = fraction.substr(0, fraction.length - 1); - } - } + function loadMetaSchemaOf(sch) { + var $schema = sch.$schema; + return $schema && !self.getSchema($schema) + ? compileAsync.call(self, { $ref: $schema }, true) + : Promise.resolve(); + } - var str = fraction; - str = symbols.convertNumberToI18N(str); - if (this.decimalPoint) { - buf.append(symbols.decimalSeparator()); - } + function _compileAsync(schemaObj) { + try { return self._compile(schemaObj); } + catch(e) { + if (e instanceof MissingRefError) return loadMissingSchema(e); + throw e; + } - buf.append(str); - } - return true; - }; + function loadMissingSchema(e) { + var ref = e.missingSchema; + if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); - _proto.parse = function parse(context, text, position) { - var effectiveMin = context.isStrict() ? this.minWidth : 0; - var effectiveMax = context.isStrict() ? this.maxWidth : 9; - var length = text.length; + var schemaPromise = self._loadingSchemas[ref]; + if (!schemaPromise) { + schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); + schemaPromise.then(removePromise, removePromise); + } - if (position === length) { - return effectiveMin > 0 ? ~position : position; + return schemaPromise.then(function (sch) { + if (!added(ref)) { + return loadMetaSchemaOf(sch).then(function () { + if (!added(ref)) self.addSchema(sch, ref, undefined, meta); + }); } + }).then(function() { + return _compileAsync(schemaObj); + }); - if (this.decimalPoint) { - if (text[position] !== context.symbols().decimalSeparator()) { - return effectiveMin > 0 ? ~position : position; - } - - position++; - } + function removePromise() { + delete self._loadingSchemas[ref]; + } - var minEndPos = position + effectiveMin; + function added(ref) { + return self._refs[ref] || self._schemas[ref]; + } + } + } +} - if (minEndPos > length) { - return ~position; - } - var maxEndPos = Math.min(position + effectiveMax, length); - var total = 0; - var pos = position; +/***/ }), - while (pos < maxEndPos) { - var ch = text.charAt(pos++); - var digit = context.symbols().convertToDigit(ch); +/***/ 25726: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (digit < 0) { - if (pos < minEndPos) { - return ~position; - } +"use strict"; - pos--; - break; - } - total = total * 10 + digit; - } +var resolve = __nccwpck_require__(63896); - var moveLeft = pos - position; - var scale = Math.pow(10, moveLeft); - var value = this.convertFromFraction(total, scale); - return context.setParsedField(this.field, value, position, pos); - }; +module.exports = { + Validation: errorSubclass(ValidationError), + MissingRef: errorSubclass(MissingRefError) +}; - _proto.convertToFraction = function convertToFraction(value, zeroDigit) { - var range = this.field.range(); - range.checkValidValue(value, this.field); - var _min = range.minimum(); +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; +} - var _range = range.maximum() - _min + 1; - var _value = value - _min; +MissingRefError.message = function (baseId, ref) { + return 'can\'t resolve reference ' + ref + ' from id ' + baseId; +}; - var _scaled = MathUtil.intDiv(_value * 1000000000, _range); - var fraction = '' + _scaled; +function MissingRefError(baseId, ref, message) { + this.message = message || MissingRefError.message(baseId, ref); + this.missingRef = resolve.url(baseId, ref); + this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); +} - while (fraction.length < 9) { - fraction = zeroDigit + fraction; - } - return fraction; - }; +function errorSubclass(Subclass) { + Subclass.prototype = Object.create(Error.prototype); + Subclass.prototype.constructor = Subclass; + return Subclass; +} - _proto.convertFromFraction = function convertFromFraction(total, scale) { - var range = this.field.range(); - var _min = range.minimum(); +/***/ }), - var _range = range.maximum() - _min + 1; +/***/ 66627: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var _value = MathUtil.intDiv(total * _range, scale); +"use strict"; - return _value; - }; - _proto.toString = function toString() { - var decimal = this.decimalPoint ? ',DecimalPoint' : ''; - return 'Fraction(' + this.field + ',' + this.minWidth + ',' + this.maxWidth + decimal + ')'; - }; +var util = __nccwpck_require__(76578); + +var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +var 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; +var 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; +var URIREF = /^(?:[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 +var URITEMPLATE = /^(?:(?:[^\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 +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + - return FractionPrinterParser; - }(); +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\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, + // 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, + 'uri-template': URITEMPLATE, + url: URL, + // 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 'willful 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, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; - var MAX_WIDTH = 15; - var EXCEED_POINTS = [0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; - var NumberPrinterParser = function () { - function NumberPrinterParser(field, minWidth, maxWidth, signStyle, subsequentWidth) { - if (subsequentWidth === void 0) { - subsequentWidth = 0; - } - this._field = field; - this._minWidth = minWidth; - this._maxWidth = maxWidth; - this._signStyle = signStyle; - this._subsequentWidth = subsequentWidth; - } +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + 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: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; - var _proto = NumberPrinterParser.prototype; - _proto.field = function field() { - return this._field; - }; +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} - _proto.minWidth = function minWidth() { - return this._minWidth; - }; - _proto.maxWidth = function maxWidth() { - return this._maxWidth; - }; +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; - _proto.signStyle = function signStyle() { - return this._signStyle; - }; + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; - _proto.withFixedWidth = function withFixedWidth() { - if (this._subsequentWidth === -1) { - return this; - } + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} - return new NumberPrinterParser(this._field, this._minWidth, this._maxWidth, this._signStyle, -1); - }; - _proto.withSubsequentWidth = function withSubsequentWidth(subsequentWidth) { - return new NumberPrinterParser(this._field, this._minWidth, this._maxWidth, this._signStyle, this._subsequentWidth + subsequentWidth); - }; +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} - _proto._isFixedWidth = function _isFixedWidth() { - return this._subsequentWidth === -1 || this._subsequentWidth > 0 && this._minWidth === this._maxWidth && this._signStyle === SignStyle.NOT_NEGATIVE; - }; - _proto.print = function print(context, buf) { - var contextValue = context.getValue(this._field); +var NOT_URI_FRAGMENT = /\/|:/; +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); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} - if (contextValue == null) { - return false; - } - var value = this._getValue(context, contextValue); +/***/ }), - var symbols = context.symbols(); - var str = '' + Math.abs(value); +/***/ 875: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (str.length > this._maxWidth) { - throw new DateTimeException('Field ' + this._field + ' cannot be printed as the value ' + value + ' exceeds the maximum print width of ' + this._maxWidth); - } +"use strict"; - str = symbols.convertNumberToI18N(str); - if (value >= 0) { - switch (this._signStyle) { - case SignStyle.EXCEEDS_PAD: - if (this._minWidth < MAX_WIDTH && value >= EXCEED_POINTS[this._minWidth]) { - buf.append(symbols.positiveSign()); - } +var resolve = __nccwpck_require__(63896) + , util = __nccwpck_require__(76578) + , errorClasses = __nccwpck_require__(25726) + , stableStringify = __nccwpck_require__(30969); - break; +var validateGenerator = __nccwpck_require__(49585); - case SignStyle.ALWAYS: - buf.append(symbols.positiveSign()); - break; - } - } else { - switch (this._signStyle) { - case SignStyle.NORMAL: - case SignStyle.EXCEEDS_PAD: - case SignStyle.ALWAYS: - buf.append(symbols.negativeSign()); - break; +/** + * Functions below are used inside compiled validations function + */ - case SignStyle.NOT_NEGATIVE: - throw new DateTimeException('Field ' + this._field + ' cannot be printed as the value ' + value + ' cannot be negative according to the SignStyle'); - } - } +var ucs2length = util.ucs2length; +var equal = __nccwpck_require__(28206); - for (var i = 0; i < this._minWidth - str.length; i++) { - buf.append(symbols.zeroDigit()); - } +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; - buf.append(str); - return true; - }; +module.exports = compile; - _proto.parse = function parse(context, text, position) { - var length = text.length; - if (position === length) { - return ~position; - } +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; - assert(position >= 0 && position < length); - var sign = text.charAt(position); - var negative = false; - var positive = false; + root = root || { schema: schema, refVal: refVal, refs: refs }; - if (sign === context.symbols().positiveSign()) { - if (this._signStyle.parse(true, context.isStrict(), this._minWidth === this._maxWidth) === false) { - return ~position; - } + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); - positive = true; - position++; - } else if (sign === context.symbols().negativeSign()) { - if (this._signStyle.parse(false, context.isStrict(), this._minWidth === this._maxWidth) === false) { - return ~position; - } + var formats = this._formats; + var RULES = this.RULES; - negative = true; - position++; - } else { - if (this._signStyle === SignStyle.ALWAYS && context.isStrict()) { - return ~position; - } - } + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } - var effMinWidth = context.isStrict() || this._isFixedWidth() ? this._minWidth : 1; - var minEndPos = position + effMinWidth; + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } - if (minEndPos > length) { - return ~position; - } + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); - var effMaxWidth = (context.isStrict() || this._isFixedWidth() ? this._maxWidth : 9) + Math.max(this._subsequentWidth, 0); - var total = 0; - var pos = position; + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; - for (var pass = 0; pass < 2; pass++) { - var maxEndPos = Math.min(pos + effMaxWidth, length); + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + sourceCode + ); - while (pos < maxEndPos) { - var ch = text.charAt(pos++); - var digit = context.symbols().convertToDigit(ch); + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError + ); - if (digit < 0) { - pos--; + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } - if (pos < minEndPos) { - return ~position; - } + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } - break; - } + return validate; + } - if (pos - position > MAX_WIDTH) { - throw new ArithmeticException('number text exceeds length'); - } else { - total = total * 10 + digit; - } - } + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } - if (this._subsequentWidth > 0 && pass === 0) { - var parseLen = pos - position; - effMaxWidth = Math.max(effMinWidth, parseLen - this._subsequentWidth); - pos = position; - total = 0; - } else { - break; - } - } + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } - if (negative) { - if (total === 0 && context.isStrict()) { - return ~(position - 1); - } + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } - if (total !== 0) { - total = -total; - } - } else if (this._signStyle === SignStyle.EXCEEDS_PAD && context.isStrict()) { - var _parseLen = pos - position; + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } - if (positive) { - if (_parseLen <= this._minWidth) { - return ~(position - 1); - } - } else { - if (_parseLen > this._minWidth) { - return ~position; - } - } - } + function removeLocalRef(ref) { + delete refs[ref]; + } - return this._setValue(context, total, position, pos); - }; + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } - _proto._getValue = function _getValue(context, value) { - return value; - }; + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } - _proto._setValue = function _setValue(context, value, errorPos, successPos) { - return context.setParsedField(this._field, value, errorPos, successPos); - }; + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } - _proto.toString = function toString() { - if (this._minWidth === 1 && this._maxWidth === MAX_WIDTH && this._signStyle === SignStyle.NORMAL) { - return 'Value(' + this._field + ')'; + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); - if (this._minWidth === this._maxWidth && this._signStyle === SignStyle.NOT_NEGATIVE) { - return 'Value(' + this._field + ',' + this._minWidth + ')'; + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); } + } + } - return 'Value(' + this._field + ',' + this._minWidth + ',' + this._maxWidth + ',' + this._signStyle + ')'; - }; + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; - return NumberPrinterParser; - }(); - var ReducedPrinterParser = function (_NumberPrinterParser) { - _inheritsLoose(ReducedPrinterParser, _NumberPrinterParser); + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } - function ReducedPrinterParser(field, width, maxWidth, baseValue, baseDate) { - var _this; + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); - _this = _NumberPrinterParser.call(this, field, width, maxWidth, SignStyle.NOT_NEGATIVE) || this; + var index = customRules.length; + customRules[index] = validate; - if (width < 1 || width > 10) { - throw new IllegalArgumentException('The width must be from 1 to 10 inclusive but was ' + width); - } + return { + code: 'customRule' + index, + validate: validate + }; + } +} - if (maxWidth < 1 || maxWidth > 10) { - throw new IllegalArgumentException('The maxWidth must be from 1 to 10 inclusive but was ' + maxWidth); - } - if (maxWidth < width) { - throw new IllegalArgumentException('The maxWidth must be greater than the width'); - } +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} - if (baseDate === null) { - if (field.range().isValidValue(baseValue) === false) { - throw new IllegalArgumentException('The base value must be within the range of the field'); - } - if (baseValue + EXCEED_POINTS[width] > MathUtil.MAX_SAFE_INTEGER) { - throw new DateTimeException('Unable to add printer-parser as the range exceeds the capacity of an int'); - } - } +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} - _this._baseValue = baseValue; - _this._baseDate = baseDate; - return _this; - } - var _proto2 = ReducedPrinterParser.prototype; +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= baseValue && value < baseValue + EXCEED_POINTS[this._minWidth]) { - return absValue % EXCEED_POINTS[this._minWidth]; - } - return absValue % EXCEED_POINTS[this._maxWidth]; - }; +function defaultCode(i) { + return 'var default' + i + ' = defaults[' + i + '];'; +} - _proto2._setValue = function _setValue(context, value, errorPos, successPos) { - var baseValue = this._baseValue; - if (this._baseDate != null) { - var chrono = context.getEffectiveChronology(); - baseValue = chrono.date(this._baseDate).get(this._field); - } +function refValCode(i, refVal) { + return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];'; +} - var parseLen = successPos - errorPos; - if (parseLen === this._minWidth && value >= 0) { - var range = EXCEED_POINTS[this._minWidth]; - var lastPart = baseValue % range; - var basePart = baseValue - lastPart; +function customRuleCode(i) { + return 'var customRule' + i + ' = customRules[' + i + '];'; +} - if (baseValue > 0) { - value = basePart + value; - } else { - value = basePart - value; - } - if (value < baseValue) { - value += range; - } - } +function vars(arr, statement) { + if (!arr.length) return ''; + var code = ''; + for (var i=0; i { - _proto2.withSubsequentWidth = function withSubsequentWidth(subsequentWidth) { - return new ReducedPrinterParser(this._field, this._minWidth, this._maxWidth, this._baseValue, this._baseDate, this._subsequentWidth + subsequentWidth); - }; +"use strict"; - _proto2.isFixedWidth = function isFixedWidth(context) { - if (context.isStrict() === false) { - return false; - } - return _NumberPrinterParser.prototype.isFixedWidth.call(this, context); - }; +var URI = __nccwpck_require__(70020) + , equal = __nccwpck_require__(28206) + , util = __nccwpck_require__(76578) + , SchemaObject = __nccwpck_require__(37605) + , traverse = __nccwpck_require__(52533); - _proto2.toString = function toString() { - return 'ReducedValue(' + this._field + ',' + this._minWidth + ',' + this._maxWidth + ',' + (this._baseDate != null ? this._baseDate : this._baseValue) + ')'; - }; +module.exports = resolve; - return ReducedPrinterParser; - }(NumberPrinterParser); +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var PATTERNS = ['+HH', '+HHmm', '+HH:mm', '+HHMM', '+HH:MM', '+HHMMss', '+HH:MM:ss', '+HHMMSS', '+HH:MM:SS']; - var OffsetIdPrinterParser = function () { - function OffsetIdPrinterParser(noOffsetText, pattern) { - requireNonNull(noOffsetText, 'noOffsetText'); - requireNonNull(pattern, 'pattern'); - this.noOffsetText = noOffsetText; - this.type = this._checkPattern(pattern); - } +/** + * [resolve and compile the references ($ref)] + * @this Ajv + * @param {Function} compile reference to schema compilation funciton (localCompile) + * @param {Object} root object with information about the root schema for the current schema + * @param {String} ref reference to resolve + * @return {Object|Function} schema object (if the schema can be inlined) or validation function + */ +function resolve(compile, root, ref) { + /* jshint validthis: true */ + var refVal = this._refs[ref]; + if (typeof refVal == 'string') { + if (this._refs[refVal]) refVal = this._refs[refVal]; + else return resolve.call(this, compile, root, refVal); + } - var _proto = OffsetIdPrinterParser.prototype; + refVal = refVal || this._schemas[ref]; + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) + ? refVal.schema + : refVal.validate || this._compile(refVal); + } - _proto._checkPattern = function _checkPattern(pattern) { - for (var i = 0; i < PATTERNS.length; i++) { - if (PATTERNS[i] === pattern) { - return i; - } - } + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } - throw new IllegalArgumentException('Invalid zone offset pattern: ' + pattern); - }; + if (schema instanceof SchemaObject) { + v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); + } else if (schema !== undefined) { + v = inlineRef(schema, this._opts.inlineRefs) + ? schema + : compile.call(this, schema, root, undefined, baseId); + } - _proto.print = function print(context, buf) { - var offsetSecs = context.getValue(ChronoField.OFFSET_SECONDS); + return v; +} - if (offsetSecs == null) { - return false; - } - var totalSecs = MathUtil.safeToInt(offsetSecs); +/** + * Resolve schema, its root and baseId + * @this Ajv + * @param {Object} root root object with properties schema, refVal, refs + * @param {String} ref reference to resolve + * @return {Object} object with properties schema, root, baseId + */ +function resolveSchema(root, ref) { + /* jshint validthis: true */ + var p = URI.parse(ref) + , refPath = _getFullPath(p) + , baseId = getFullPath(this._getId(root.schema)); + if (Object.keys(root.schema).length === 0 || refPath !== baseId) { + var id = normalizeId(refPath); + var refVal = this._refs[id]; + if (typeof refVal == 'string') { + return resolveRecursive.call(this, root, refVal, p); + } else if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + root = refVal; + } else { + refVal = this._schemas[id]; + if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + if (id == normalizeId(ref)) + return { schema: refVal, root: root, baseId: baseId }; + root = refVal; + } else { + return; + } + } + if (!root.schema) return; + baseId = getFullPath(this._getId(root.schema)); + } + return getJsonPointer.call(this, p, baseId, root.schema, root); +} - if (totalSecs === 0) { - buf.append(this.noOffsetText); - } else { - var absHours = Math.abs(MathUtil.intMod(MathUtil.intDiv(totalSecs, 3600), 100)); - var absMinutes = Math.abs(MathUtil.intMod(MathUtil.intDiv(totalSecs, 60), 60)); - var absSeconds = Math.abs(MathUtil.intMod(totalSecs, 60)); - var bufPos = buf.length(); - var output = absHours; - buf.append(totalSecs < 0 ? '-' : '+').appendChar(MathUtil.intDiv(absHours, 10) + '0').appendChar(MathUtil.intMod(absHours, 10) + '0'); - if (this.type >= 3 || this.type >= 1 && absMinutes > 0) { - buf.append(this.type % 2 === 0 ? ':' : '').appendChar(MathUtil.intDiv(absMinutes, 10) + '0').appendChar(absMinutes % 10 + '0'); - output += absMinutes; +/* @this Ajv */ +function resolveRecursive(root, ref, parsedRef) { + /* jshint validthis: true */ + var res = resolveSchema.call(this, root, ref); + if (res) { + var schema = res.schema; + var baseId = res.baseId; + root = res.root; + var id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + return getJsonPointer.call(this, parsedRef, baseId, schema, root); + } +} - if (this.type >= 7 || this.type >= 5 && absSeconds > 0) { - buf.append(this.type % 2 === 0 ? ':' : '').appendChar(MathUtil.intDiv(absSeconds, 10) + '0').appendChar(absSeconds % 10 + '0'); - output += absSeconds; - } - } - if (output === 0) { - buf.setLength(bufPos); - buf.append(this.noOffsetText); +var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); +/* @this Ajv */ +function getJsonPointer(parsedRef, baseId, schema, root) { + /* jshint validthis: true */ + parsedRef.fragment = parsedRef.fragment || ''; + if (parsedRef.fragment.slice(0,1) != '/') return; + var parts = parsedRef.fragment.split('/'); + + for (var i = 1; i < parts.length; i++) { + var part = parts[i]; + if (part) { + part = util.unescapeFragment(part); + schema = schema[part]; + if (schema === undefined) break; + var id; + if (!PREVENT_SCOPE_CHANGE[part]) { + id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + if (schema.$ref) { + var $ref = resolveUrl(baseId, schema.$ref); + var res = resolveSchema.call(this, root, $ref); + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; } } + } + } + } + if (schema !== undefined && schema !== root.schema) + return { schema: schema, root: root, baseId: baseId }; +} - return true; - }; - - _proto.parse = function parse(context, text, position) { - var length = text.length; - var noOffsetLen = this.noOffsetText.length; - if (noOffsetLen === 0) { - if (position === length) { - return context.setParsedField(ChronoField.OFFSET_SECONDS, 0, position, position); - } - } else { - if (position === length) { - return ~position; - } +var SIMPLE_INLINED = util.toHash([ + 'type', 'format', 'pattern', + 'maxLength', 'minLength', + 'maxProperties', 'minProperties', + 'maxItems', 'minItems', + 'maximum', 'minimum', + 'uniqueItems', 'multipleOf', + 'required', 'enum' +]); +function inlineRef(schema, limit) { + if (limit === false) return false; + if (limit === undefined || limit === true) return checkNoRef(schema); + else if (limit) return countKeys(schema) <= limit; +} - if (context.subSequenceEquals(text, position, this.noOffsetText, 0, noOffsetLen)) { - return context.setParsedField(ChronoField.OFFSET_SECONDS, 0, position, position + noOffsetLen); - } - } - var sign = text[position]; +function checkNoRef(schema) { + var item; + if (Array.isArray(schema)) { + for (var i=0; i= 3) || this._parseNumber(array, 3, text, false)) === false) { - var offsetSecs = MathUtil.safeZero(negative * (array[1] * 3600 + array[2] * 60 + array[3])); - return context.setParsedField(ChronoField.OFFSET_SECONDS, offsetSecs, position, array[0]); - } - } +function countKeys(schema) { + var count = 0, item; + if (Array.isArray(schema)) { + for (var i=0; i 1) { - if (pos + 1 > parseText.length || parseText[pos] !== ':') { - return required; - } - pos++; - } +var TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; +} - if (pos + 2 > parseText.length) { - return required; - } - var ch1 = parseText[pos++]; - var ch2 = parseText[pos++]; +function resolveUrl(baseId, id) { + id = normalizeId(id); + return URI.resolve(baseId, id); +} - if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') { - return required; - } - var value = (ch1.charCodeAt(0) - 48) * 10 + (ch2.charCodeAt(0) - 48); +/* @this Ajv */ +function resolveIds(schema) { + var schemaId = normalizeId(this._getId(schema)); + var baseIds = {'': schemaId}; + var fullPaths = {'': getFullPath(schemaId, false)}; + var localRefs = {}; + var self = this; - if (value < 0 || value > 59) { - return required; + traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (jsonPtr === '') return; + var id = self._getId(sch); + var baseId = baseIds[parentJsonPtr]; + var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword; + if (keyIndex !== undefined) + fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex)); + + if (typeof id == 'string') { + id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); + + var refVal = self._refs[id]; + if (typeof refVal == 'string') refVal = self._refs[refVal]; + if (refVal && refVal.schema) { + if (!equal(sch, refVal.schema)) + throw new Error('id "' + id + '" resolves to more than one schema'); + } else if (id != normalizeId(fullPath)) { + if (id[0] == '#') { + if (localRefs[id] && !equal(sch, localRefs[id])) + throw new Error('id "' + id + '" resolves to more than one schema'); + localRefs[id] = sch; + } else { + self._refs[id] = fullPath; } + } + } + baseIds[jsonPtr] = baseId; + fullPaths[jsonPtr] = fullPath; + }); - array[arrayIndex] = value; - array[0] = pos; - return false; - }; + return localRefs; +} - _proto.toString = function toString() { - var converted = this.noOffsetText.replace('\'', '\'\''); - return 'Offset(' + PATTERNS[this.type] + ',\'' + converted + '\')'; - }; - return OffsetIdPrinterParser; - }(); - OffsetIdPrinterParser.INSTANCE_ID = new OffsetIdPrinterParser('Z', '+HH:MM:ss'); - OffsetIdPrinterParser.PATTERNS = PATTERNS; +/***/ }), - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var PadPrinterParserDecorator = function () { - function PadPrinterParserDecorator(printerParser, padWidth, padChar) { - this._printerParser = printerParser; - this._padWidth = padWidth; - this._padChar = padChar; - } +/***/ 68561: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var _proto = PadPrinterParserDecorator.prototype; +"use strict"; - _proto.print = function print(context, buf) { - var preLen = buf.length(); - if (this._printerParser.print(context, buf) === false) { - return false; - } +var ruleModules = __nccwpck_require__(85810) + , toHash = __nccwpck_require__(76578).toHash; + +module.exports = function rules() { + var RULES = [ + { type: 'number', + rules: [ { 'maximum': ['exclusiveMaximum'] }, + { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, + { type: 'string', + rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, + { type: 'array', + rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, + { type: 'object', + rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', + { 'properties': ['additionalProperties', 'patternProperties'] } ] }, + { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } + ]; - var len = buf.length() - preLen; + var ALL = [ 'type', '$comment' ]; + var KEYWORDS = [ + '$schema', '$id', 'id', '$data', '$async', 'title', + 'description', 'default', 'definitions', + 'examples', 'readOnly', 'writeOnly', + 'contentMediaType', 'contentEncoding', + 'additionalItems', 'then', 'else' + ]; + var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; + RULES.all = toHash(ALL); + RULES.types = toHash(TYPES); + + RULES.forEach(function (group) { + group.rules = group.rules.map(function (keyword) { + var implKeywords; + if (typeof keyword == 'object') { + var key = Object.keys(keyword)[0]; + implKeywords = keyword[key]; + keyword = key; + implKeywords.forEach(function (k) { + ALL.push(k); + RULES.all[k] = true; + }); + } + ALL.push(keyword); + var rule = RULES.all[keyword] = { + keyword: keyword, + code: ruleModules[keyword], + implements: implKeywords + }; + return rule; + }); - if (len > this._padWidth) { - throw new DateTimeException("Cannot print as output of " + len + " characters exceeds pad width of " + this._padWidth); - } + RULES.all.$comment = { + keyword: '$comment', + code: ruleModules.$comment + }; - for (var i = 0; i < this._padWidth - len; i++) { - buf.insert(preLen, this._padChar); - } + if (group.type) RULES.types[group.type] = group; + }); - return true; - }; + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.custom = {}; - _proto.parse = function parse(context, text, position) { - var strict = context.isStrict(); - var caseSensitive = context.isCaseSensitive(); - assert(!(position > text.length)); - assert(position >= 0); + return RULES; +}; - if (position === text.length) { - return ~position; - } - var endPos = position + this._padWidth; +/***/ }), - if (endPos > text.length) { - if (strict) { - return ~position; - } +/***/ 37605: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - endPos = text.length; - } +"use strict"; - var pos = position; - while (pos < endPos && (caseSensitive ? text[pos] === this._padChar : context.charEquals(text[pos], this._padChar))) { - pos++; - } +var util = __nccwpck_require__(76578); - text = text.substring(0, endPos); +module.exports = SchemaObject; - var resultPos = this._printerParser.parse(context, text, pos); +function SchemaObject(obj) { + util.copy(obj, this); +} - if (resultPos !== endPos && strict) { - return ~(position + pos); - } - return resultPos; - }; +/***/ }), - _proto.toString = function toString() { - return "Pad(" + this._printerParser + "," + this._padWidth + (this._padChar === ' ' ? ')' : ',\'' + this._padChar + '\')'); - }; +/***/ 64580: +/***/ ((module) => { - return PadPrinterParserDecorator; - }(); +"use strict"; - var SettingsParser = function (_Enum) { - _inheritsLoose(SettingsParser, _Enum); - function SettingsParser() { - return _Enum.apply(this, arguments) || this; - } +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +module.exports = function ucs2length(str) { + var length = 0 + , len = str.length + , pos = 0 + , 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; +}; - var _proto = SettingsParser.prototype; - _proto.print = function print() { - return true; - }; +/***/ }), - _proto.parse = function parse(context, text, position) { - switch (this) { - case SettingsParser.SENSITIVE: - context.setCaseSensitive(true); - break; +/***/ 76578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case SettingsParser.INSENSITIVE: - context.setCaseSensitive(false); - break; +"use strict"; - case SettingsParser.STRICT: - context.setStrict(true); - break; - case SettingsParser.LENIENT: - context.setStrict(false); - break; - } - return position; - }; +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: __nccwpck_require__(28206), + ucs2length: __nccwpck_require__(64580), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} - _proto.toString = function toString() { - switch (this) { - case SettingsParser.SENSITIVE: - return 'ParseCaseSensitive(true)'; - case SettingsParser.INSENSITIVE: - return 'ParseCaseSensitive(false)'; +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} - case SettingsParser.STRICT: - return 'ParseStrict(true)'; - case SettingsParser.LENIENT: - return 'ParseStrict(false)'; - } - }; +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); - return SettingsParser; - }(Enum); - SettingsParser.SENSITIVE = new SettingsParser('SENSITIVE'); - SettingsParser.INSENSITIVE = new SettingsParser('INSENSITIVE'); - SettingsParser.STRICT = new SettingsParser('STRICT'); - SettingsParser.LENIENT = new SettingsParser('LENIENT'); + return code; + } +} - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var StringLiteralPrinterParser = function () { - function StringLiteralPrinterParser(literal) { - this._literal = literal; - } - var _proto = StringLiteralPrinterParser.prototype; +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i length || position < 0)); +function toHash(arr) { + var hash = {}; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } - _proto.parse = function parse(context, text, position) { - var length = text.length; + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } - if (position > length) { - return ~position; - } + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i= position + 2) { - var nextNextChar = text.charAt(position + 1); - if (context.charEquals(nextChar, 'U') && context.charEquals(nextNextChar, 'T')) { - if (length >= position + 3 && context.charEquals(text.charAt(position + 2), 'C')) { - return this._parsePrefixedOffset(context, text, position, position + 3); - } +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); +} - return this._parsePrefixedOffset(context, text, position, position + 2); - } else if (context.charEquals(nextChar, 'G') && length >= position + 3 && context.charEquals(nextNextChar, 'M') && context.charEquals(text.charAt(position + 2), 'T')) { - return this._parsePrefixedOffset(context, text, position, position + 3); - } - } - if (text.substr(position, 6) === 'SYSTEM') { - context.setParsedZone(ZoneId.systemDefault()); - return position + 6; - } +function escapeJsonPointer(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); +} - if (context.charEquals(nextChar, 'Z')) { - context.setParsedZone(ZoneOffset.UTC); - return position + 1; - } - var availableZoneIds = ZoneRulesProvider.getAvailableZoneIds(); +function unescapeJsonPointer(str) { + return str.replace(/~1/g, '/').replace(/~0/g, '~'); +} - if (zoneIdTree.size !== availableZoneIds.length) { - zoneIdTree = ZoneIdTree.createTreeMap(availableZoneIds); - } - var maxParseLength = length - position; - var treeMap = zoneIdTree.treeMap; - var parsedZoneId = null; - var parseLength = 0; +/***/ }), - while (treeMap != null) { - var parsedSubZoneId = text.substr(position, Math.min(treeMap.length, maxParseLength)); - treeMap = treeMap.get(parsedSubZoneId); +/***/ 21412: +/***/ ((module) => { - if (treeMap != null && treeMap.isLeaf) { - parsedZoneId = parsedSubZoneId; - parseLength = treeMap.length; - } - } +"use strict"; - if (parsedZoneId != null) { - context.setParsedZone(ZoneRegion.ofId(parsedZoneId)); - return position + parseLength; - } - return ~position; - }; +var KEYWORDS = [ + 'multipleOf', + 'maximum', + 'exclusiveMaximum', + 'minimum', + 'exclusiveMinimum', + 'maxLength', + 'minLength', + 'pattern', + 'additionalItems', + 'maxItems', + 'minItems', + 'uniqueItems', + 'maxProperties', + 'minProperties', + 'required', + 'additionalProperties', + 'enum', + 'format', + 'const' +]; - _proto._parsePrefixedOffset = function _parsePrefixedOffset(context, text, prefixPos, position) { - var prefix = text.substring(prefixPos, position).toUpperCase(); - var newContext = context.copy(); +module.exports = function (metaSchema, keywordsJsonPointers) { + for (var i=0; i { - _proto.toString = function toString() { - return this.description; - }; +"use strict"; - return ZoneIdPrinterParser; - }(); - var ZoneIdTree = function () { - ZoneIdTree.createTreeMap = function createTreeMap(availableZoneIds) { - var sortedZoneIds = availableZoneIds.sort(function (a, b) { - return a.length - b.length; - }); - var treeMap = new ZoneIdTreeMap(sortedZoneIds[0].length, false); +var metaSchema = __nccwpck_require__(40038); - for (var i = 0; i < sortedZoneIds.length; i++) { - treeMap.add(sortedZoneIds[i]); - } +module.exports = { + $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', + definitions: { + simpleTypes: metaSchema.definitions.simpleTypes + }, + type: 'object', + dependencies: { + schema: ['validate'], + $data: ['validate'], + statements: ['inline'], + valid: {not: {required: ['macro']}} + }, + properties: { + type: metaSchema.properties.type, + schema: {type: 'boolean'}, + statements: {type: 'boolean'}, + dependencies: { + type: 'array', + items: {type: 'string'} + }, + metaSchema: {type: 'object'}, + modifying: {type: 'boolean'}, + valid: {type: 'boolean'}, + $data: {type: 'boolean'}, + async: {type: 'boolean'}, + errors: { + anyOf: [ + {type: 'boolean'}, + {const: 'full'} + ] + } + } +}; - return new ZoneIdTree(sortedZoneIds.length, treeMap); - }; - function ZoneIdTree(size, treeMap) { - this.size = size; - this.treeMap = treeMap; - } +/***/ }), - return ZoneIdTree; - }(); +/***/ 7404: +/***/ ((module) => { - var ZoneIdTreeMap = function () { - function ZoneIdTreeMap(length, isLeaf) { - if (length === void 0) { - length = 0; - } +"use strict"; - if (isLeaf === void 0) { - isLeaf = false; +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; } - - this.length = length; - this.isLeaf = isLeaf; - this._treeMap = {}; } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - var _proto2 = ZoneIdTreeMap.prototype; - - _proto2.add = function add(zoneId) { - var idLength = zoneId.length; - - if (idLength === this.length) { - this._treeMap[zoneId] = new ZoneIdTreeMap(idLength, true); - } else if (idLength > this.length) { - var subZoneId = zoneId.substr(0, this.length); - var subTreeMap = this._treeMap[subZoneId]; - - if (subTreeMap == null) { - subTreeMap = new ZoneIdTreeMap(idLength, false); - this._treeMap[subZoneId] = subTreeMap; - } - - subTreeMap.add(zoneId); - } - }; - _proto2.get = function get(zoneId) { - return this._treeMap[zoneId]; - }; +/***/ }), - return ZoneIdTreeMap; - }(); +/***/ 64683: +/***/ ((module) => { - var zoneIdTree = new ZoneIdTree([]); +"use strict"; - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var MAX_WIDTH$1 = 15; - var DateTimeFormatterBuilder = function () { - function DateTimeFormatterBuilder() { - this._active = this; - this._parent = null; - this._printerParsers = []; - this._optional = false; - this._padNextWidth = 0; - this._padNextChar = null; - this._valueParserIndex = -1; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - DateTimeFormatterBuilder._of = function _of(parent, optional) { - requireNonNull(parent, 'parent'); - requireNonNull(optional, 'optional'); - var dtFormatterBuilder = new DateTimeFormatterBuilder(); - dtFormatterBuilder._parent = parent; - dtFormatterBuilder._optional = optional; - return dtFormatterBuilder; - }; - var _proto = DateTimeFormatterBuilder.prototype; +/***/ }), - _proto.parseCaseSensitive = function parseCaseSensitive() { - this._appendInternalPrinterParser(SettingsParser.SENSITIVE); +/***/ 52114: +/***/ ((module) => { - return this; - }; +"use strict"; - _proto.parseCaseInsensitive = function parseCaseInsensitive() { - this._appendInternalPrinterParser(SettingsParser.INSENSITIVE); +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - return this; - }; - _proto.parseStrict = function parseStrict() { - this._appendInternalPrinterParser(SettingsParser.STRICT); +/***/ }), - return this; - }; +/***/ 71142: +/***/ ((module) => { - _proto.parseLenient = function parseLenient() { - this._appendInternalPrinterParser(SettingsParser.LENIENT); +"use strict"; - return this; - }; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - _proto.appendValue = function appendValue() { - if (arguments.length === 1) { - return this._appendValue1.apply(this, arguments); - } else if (arguments.length === 2) { - return this._appendValue2.apply(this, arguments); - } else { - return this._appendValue4.apply(this, arguments); - } - }; - _proto._appendValue1 = function _appendValue1(field) { - requireNonNull(field); +/***/ }), - this._appendValuePrinterParser(new NumberPrinterParser(field, 1, MAX_WIDTH$1, SignStyle.NORMAL)); +/***/ 89443: +/***/ ((module) => { - return this; - }; +"use strict"; + +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + return out; +} - _proto._appendValue2 = function _appendValue2(field, width) { - requireNonNull(field); - if (width < 1 || width > MAX_WIDTH$1) { - throw new IllegalArgumentException("The width must be from 1 to " + MAX_WIDTH$1 + " inclusive but was " + width); - } +/***/ }), - var pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE); +/***/ 63093: +/***/ ((module) => { - this._appendValuePrinterParser(pp); +"use strict"; - return this; - }; +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} - _proto._appendValue4 = function _appendValue4(field, minWidth, maxWidth, signStyle) { - requireNonNull(field); - requireNonNull(signStyle); - if (minWidth === maxWidth && signStyle === SignStyle.NOT_NEGATIVE) { - return this._appendValue2(field, maxWidth); - } +/***/ }), - if (minWidth < 1 || minWidth > MAX_WIDTH$1) { - throw new IllegalArgumentException("The minimum width must be from 1 to " + MAX_WIDTH$1 + " inclusive but was " + minWidth); - } +/***/ 30134: +/***/ ((module) => { - if (maxWidth < 1 || maxWidth > MAX_WIDTH$1) { - throw new IllegalArgumentException("The minimum width must be from 1 to " + MAX_WIDTH$1 + " inclusive but was " + maxWidth); - } +"use strict"; - if (maxWidth < minWidth) { - throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " + maxWidth + " < " + minWidth); - } +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} - var pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle); - this._appendValuePrinterParser(pp); +/***/ }), - return this; - }; +/***/ 1661: +/***/ ((module) => { - _proto.appendValueReduced = function appendValueReduced() { - if (arguments.length === 4 && arguments[3] instanceof ChronoLocalDate) { - return this._appendValueReducedFieldWidthMaxWidthBaseDate.apply(this, arguments); - } else { - return this._appendValueReducedFieldWidthMaxWidthBaseValue.apply(this, arguments); - } - }; +"use strict"; - _proto._appendValueReducedFieldWidthMaxWidthBaseValue = function _appendValueReducedFieldWidthMaxWidthBaseValue(field, width, maxWidth, baseValue) { - requireNonNull(field, 'field'); - var pp = new ReducedPrinterParser(field, width, maxWidth, baseValue, null); +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - this._appendValuePrinterParser(pp); - return this; - }; +/***/ }), - _proto._appendValueReducedFieldWidthMaxWidthBaseDate = function _appendValueReducedFieldWidthMaxWidthBaseDate(field, width, maxWidth, baseDate) { - requireNonNull(field, 'field'); - requireNonNull(baseDate, 'baseDate'); - requireInstance(baseDate, ChronoLocalDate, 'baseDate'); - var pp = new ReducedPrinterParser(field, width, maxWidth, 0, baseDate); +/***/ 55964: +/***/ ((module) => { - this._appendValuePrinterParser(pp); +"use strict"; - return this; - }; +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} - _proto._appendValuePrinterParser = function _appendValuePrinterParser(pp) { - assert(pp != null); - if (this._active._valueParserIndex >= 0 && this._active._printerParsers[this._active._valueParserIndex] instanceof NumberPrinterParser) { - var activeValueParser = this._active._valueParserIndex; - var basePP = this._active._printerParsers[activeValueParser]; +/***/ }), - if (pp.minWidth() === pp.maxWidth() && pp.signStyle() === SignStyle.NOT_NEGATIVE) { - basePP = basePP.withSubsequentWidth(pp.maxWidth()); +/***/ 5912: +/***/ ((module) => { - this._appendInternal(pp.withFixedWidth()); +"use strict"; - this._active._valueParserIndex = activeValueParser; - } else { - basePP = basePP.withFixedWidth(); - this._active._valueParserIndex = this._appendInternal(pp); +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' { - _proto.appendInstant = function appendInstant(fractionalDigits) { - if (fractionalDigits === void 0) { - fractionalDigits = -2; - } +"use strict"; - if (fractionalDigits < -2 || fractionalDigits > 9) { - throw new IllegalArgumentException('Invalid fractional digits: ' + fractionalDigits); +module.exports = function generate_dependencies(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $schemaDeps = {}, + $propertyDeps = {}, + $ownProperties = it.opts.ownProperties; + for ($property in $schema) { + if ($property == '__proto__') continue; + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } + out += 'var ' + ($errs) + ' = errors;'; + var $currentErrorPath = it.errorPath; + out += 'var missing' + ($lvl) + ';'; + for (var $property in $propertyDeps) { + $deps = $propertyDeps[$property]; + if ($deps.length) { + out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + if ($breakOnError) { + out += ' && ( '; + var arr1 = $deps; + if (arr1) { + var $propertyKey, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $propertyKey = arr1[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } } + out += ')) { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); + } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + out += ' ) { '; + var arr2 = $deps; + if (arr2) { + var $propertyKey, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $propertyKey = arr2[i2 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); + } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; + for (var $property in $schemaDeps) { + var $sch = $schemaDeps[$property]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} - this._appendInternal(new InstantPrinterParser(fractionalDigits)); - - return this; - }; - - _proto.appendOffsetId = function appendOffsetId() { - this._appendInternal(OffsetIdPrinterParser.INSTANCE_ID); - return this; - }; +/***/ }), - _proto.appendOffset = function appendOffset(pattern, noOffsetText) { - this._appendInternalPrinterParser(new OffsetIdPrinterParser(noOffsetText, pattern)); +/***/ 10163: +/***/ ((module) => { - return this; - }; +"use strict"; - _proto.appendZoneId = function appendZoneId() { - this._appendInternal(new ZoneIdPrinterParser(TemporalQueries.zoneId(), 'ZoneId()')); +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - return this; - }; - _proto.appendPattern = function appendPattern(pattern) { - requireNonNull(pattern, 'pattern'); +/***/ }), - this._parsePattern(pattern); +/***/ 63847: +/***/ ((module) => { - return this; - }; +"use strict"; - _proto.appendZoneText = function appendZoneText() { - throw new IllegalArgumentException('Pattern using (localized) text not implemented, use js-joda-locale plugin!'); - }; - - _proto.appendText = function appendText() { - throw new IllegalArgumentException('Pattern using (localized) text not implemented, use js-joda-locale plugin!'); - }; - - _proto.appendLocalizedOffset = function appendLocalizedOffset() { - throw new IllegalArgumentException('Pattern using (localized) text not implemented, use js-joda-locale plugin!'); - }; - - _proto.appendWeekField = function appendWeekField() { - throw new IllegalArgumentException('Pattern using (localized) text not implemented, use js-joda-locale plugin!'); - }; - - _proto._parsePattern = function _parsePattern(pattern) { - var FIELD_MAP = { - 'G': ChronoField.ERA, - 'y': ChronoField.YEAR_OF_ERA, - 'u': ChronoField.YEAR, - 'Q': IsoFields.QUARTER_OF_YEAR, - 'q': IsoFields.QUARTER_OF_YEAR, - 'M': ChronoField.MONTH_OF_YEAR, - 'L': ChronoField.MONTH_OF_YEAR, - 'D': ChronoField.DAY_OF_YEAR, - 'd': ChronoField.DAY_OF_MONTH, - 'F': ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, - 'E': ChronoField.DAY_OF_WEEK, - 'c': ChronoField.DAY_OF_WEEK, - 'e': ChronoField.DAY_OF_WEEK, - 'a': ChronoField.AMPM_OF_DAY, - 'H': ChronoField.HOUR_OF_DAY, - 'k': ChronoField.CLOCK_HOUR_OF_DAY, - 'K': ChronoField.HOUR_OF_AMPM, - 'h': ChronoField.CLOCK_HOUR_OF_AMPM, - 'm': ChronoField.MINUTE_OF_HOUR, - 's': ChronoField.SECOND_OF_MINUTE, - 'S': ChronoField.NANO_OF_SECOND, - 'A': ChronoField.MILLI_OF_DAY, - 'n': ChronoField.NANO_OF_SECOND, - 'N': ChronoField.NANO_OF_DAY - }; - - for (var pos = 0; pos < pattern.length; pos++) { - var cur = pattern.charAt(pos); - - if (cur >= 'A' && cur <= 'Z' || cur >= 'a' && cur <= 'z') { - var start = pos++; - - for (; pos < pattern.length && pattern.charAt(pos) === cur; pos++) { - } - - var count = pos - start; - - if (cur === 'p') { - var pad = 0; - - if (pos < pattern.length) { - cur = pattern.charAt(pos); - - if (cur >= 'A' && cur <= 'Z' || cur >= 'a' && cur <= 'z') { - pad = count; - start = pos++; - - for (; pos < pattern.length && pattern.charAt(pos) === cur; pos++) { - } - - count = pos - start; - } - } - - if (pad === 0) { - throw new IllegalArgumentException('Pad letter \'p\' must be followed by valid pad pattern: ' + pattern); - } - - this.padNext(pad); - } +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - var field = FIELD_MAP[cur]; - if (field != null) { - this._parseField(cur, count, field); - } else if (cur === 'z') { - if (count > 4) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } else if (count === 4) { - this.appendZoneText(TextStyle.FULL); - } else { - this.appendZoneText(TextStyle.SHORT); - } - } else if (cur === 'V') { - if (count !== 2) { - throw new IllegalArgumentException('Pattern letter count must be 2: ' + cur); - } +/***/ }), - this.appendZoneId(); - } else if (cur === 'Z') { - if (count < 4) { - this.appendOffset('+HHMM', '+0000'); - } else if (count === 4) { - this.appendLocalizedOffset(TextStyle.FULL); - } else if (count === 5) { - this.appendOffset('+HH:MM:ss', 'Z'); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } - } else if (cur === 'O') { - if (count === 1) { - this.appendLocalizedOffset(TextStyle.SHORT); - } else if (count === 4) { - this.appendLocalizedOffset(TextStyle.FULL); - } else { - throw new IllegalArgumentException('Pattern letter count must be 1 or 4: ' + cur); - } - } else if (cur === 'X') { - if (count > 5) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +/***/ 80862: +/***/ ((module) => { - this.appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count === 1 ? 0 : 1)], 'Z'); - } else if (cur === 'x') { - if (count > 5) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +"use strict"; - var zero = count === 1 ? '+00' : count % 2 === 0 ? '+0000' : '+00:00'; - this.appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count === 1 ? 0 : 1)], zero); - } else if (cur === 'W') { - if (count > 1) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} - this.appendWeekField('W', count); - } else if (cur === 'w') { - if (count > 2) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } - this.appendWeekField('w', count); - } else if (cur === 'Y') { - this.appendWeekField('Y', count); - } else { - throw new IllegalArgumentException('Unknown pattern letter: ' + cur); - } +/***/ }), - pos--; - } else if (cur === '\'') { - var _start = pos++; +/***/ 85810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (; pos < pattern.length; pos++) { - if (pattern.charAt(pos) === '\'') { - if (pos + 1 < pattern.length && pattern.charAt(pos + 1) === '\'') { - pos++; - } else { - break; - } - } - } +"use strict"; - if (pos >= pattern.length) { - throw new IllegalArgumentException('Pattern ends with an incomplete string literal: ' + pattern); - } - var str = pattern.substring(_start + 1, pos); +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': __nccwpck_require__(42393), + allOf: __nccwpck_require__(89443), + anyOf: __nccwpck_require__(63093), + '$comment': __nccwpck_require__(30134), + const: __nccwpck_require__(1661), + contains: __nccwpck_require__(55964), + dependencies: __nccwpck_require__(2591), + 'enum': __nccwpck_require__(10163), + format: __nccwpck_require__(63847), + 'if': __nccwpck_require__(80862), + items: __nccwpck_require__(54408), + maximum: __nccwpck_require__(7404), + minimum: __nccwpck_require__(7404), + maxItems: __nccwpck_require__(64683), + minItems: __nccwpck_require__(64683), + maxLength: __nccwpck_require__(52114), + minLength: __nccwpck_require__(52114), + maxProperties: __nccwpck_require__(71142), + minProperties: __nccwpck_require__(71142), + multipleOf: __nccwpck_require__(39772), + not: __nccwpck_require__(60750), + oneOf: __nccwpck_require__(6106), + pattern: __nccwpck_require__(13912), + properties: __nccwpck_require__(52924), + propertyNames: __nccwpck_require__(19195), + required: __nccwpck_require__(8420), + uniqueItems: __nccwpck_require__(24995), + validate: __nccwpck_require__(49585) +}; + + +/***/ }), + +/***/ 54408: +/***/ ((module) => { - if (str.length === 0) { - this.appendLiteral('\''); - } else { - this.appendLiteral(str.replace('\'\'', '\'')); - } - } else if (cur === '[') { - this.optionalStart(); - } else if (cur === ']') { - if (this._active._parent === null) { - throw new IllegalArgumentException('Pattern invalid as it contains ] without previous ['); - } +"use strict"; - this.optionalEnd(); - } else if (cur === '{' || cur === '}' || cur === '#') { - throw new IllegalArgumentException('Pattern includes reserved character: \'' + cur + '\''); +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { - this.appendLiteral(cur); + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; } } - }; - - _proto._parseField = function _parseField(cur, count, field) { - switch (cur) { - case 'u': - case 'y': - if (count === 2) { - this.appendValueReduced(field, 2, 2, ReducedPrinterParser.BASE_DATE); - } else if (count < 4) { - this.appendValue(field, count, MAX_WIDTH$1, SignStyle.NORMAL); - } else { - this.appendValue(field, count, MAX_WIDTH$1, SignStyle.EXCEEDS_PAD); - } - - break; - - case 'M': - case 'Q': - switch (count) { - case 1: - this.appendValue(field); - break; - - case 2: - this.appendValue(field, 2); - break; - - case 3: - this.appendText(field, TextStyle.SHORT); - break; - - case 4: - this.appendText(field, TextStyle.FULL); - break; - - case 5: - this.appendText(field, TextStyle.NARROW); - break; - - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } - - break; - - case 'L': - case 'q': - switch (count) { - case 1: - this.appendValue(field); - break; - - case 2: - this.appendValue(field, 2); - break; - - case 3: - this.appendText(field, TextStyle.SHORT_STANDALONE); - break; - - case 4: - this.appendText(field, TextStyle.FULL_STANDALONE); - break; + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} - case 5: - this.appendText(field, TextStyle.NARROW_STANDALONE); - break; - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +/***/ }), - break; +/***/ 39772: +/***/ ((module) => { - case 'e': - switch (count) { - case 1: - case 2: - this.appendWeekField('e', count); - break; +"use strict"; - case 3: - this.appendText(field, TextStyle.SHORT); - break; +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - case 4: - this.appendText(field, TextStyle.FULL); - break; - case 5: - this.appendText(field, TextStyle.NARROW); - break; +/***/ }), - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +/***/ 60750: +/***/ ((module) => { - break; +"use strict"; - case 'c': - switch (count) { - case 1: - this.appendWeekField('c', count); - break; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} - case 2: - throw new IllegalArgumentException('Invalid number of pattern letters: ' + cur); - case 3: - this.appendText(field, TextStyle.SHORT_STANDALONE); - break; +/***/ }), - case 4: - this.appendText(field, TextStyle.FULL_STANDALONE); - break; +/***/ 6106: +/***/ ((module) => { - case 5: - this.appendText(field, TextStyle.NARROW_STANDALONE); - break; +"use strict"; - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} - break; - case 'a': - if (count === 1) { - this.appendText(field, TextStyle.SHORT); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +/***/ }), - break; +/***/ 13912: +/***/ ((module) => { - case 'E': - case 'G': - switch (count) { - case 1: - case 2: - case 3: - this.appendText(field, TextStyle.SHORT); - break; +"use strict"; - case 4: - this.appendText(field, TextStyle.FULL); - break; +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - case 5: - this.appendText(field, TextStyle.NARROW); - break; - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +/***/ }), - break; +/***/ 52924: +/***/ ((module) => { - case 'S': - this.appendFraction(ChronoField.NANO_OF_SECOND, count, count, false); - break; +"use strict"; - case 'F': - if (count === 1) { - this.appendValue(field); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { + return p !== '__proto__'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; } - - break; - - case 'd': - case 'h': - case 'H': - case 'k': - case 'K': - case 'm': - case 's': - if (count === 1) { - this.appendValue(field); - } else if (count === 2) { - this.appendValue(field, count); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; } - - break; - - case 'D': - if (count === 1) { - this.appendValue(field); - } else if (count <= 3) { - this.appendValue(field, count); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - - break; - - default: - if (count === 1) { - this.appendValue(field); + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - this.appendValue(field, count); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - - break; + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } } - }; - - _proto.padNext = function padNext() { - if (arguments.length === 1) { - return this._padNext1.apply(this, arguments); + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; } else { - return this._padNext2.apply(this, arguments); - } - }; - - _proto._padNext1 = function _padNext1(padWidth) { - return this._padNext2(padWidth, ' '); - }; - - _proto._padNext2 = function _padNext2(padWidth, padChar) { - if (padWidth < 1) { - throw new IllegalArgumentException('The pad width must be at least one but was ' + padWidth); + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } } - - this._active._padNextWidth = padWidth; - this._active._padNextChar = padChar; - this._active._valueParserIndex = -1; - return this; - }; - - _proto.optionalStart = function optionalStart() { - this._active._valueParserIndex = -1; - this._active = DateTimeFormatterBuilder._of(this._active, true); - return this; - }; - - _proto.optionalEnd = function optionalEnd() { - if (this._active._parent == null) { - throw new IllegalStateException('Cannot call optionalEnd() as there was no previous call to optionalStart()'); + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } } - - if (this._active._printerParsers.length > 0) { - var cpp = new CompositePrinterParser(this._active._printerParsers, this._active._optional); - this._active = this._active._parent; - - this._appendInternal(cpp); - } else { - this._active = this._active._parent; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; } - - return this; - }; - - _proto._appendInternal = function _appendInternal(pp) { - assert(pp != null); - - if (this._active._padNextWidth > 0) { - if (pp != null) { - pp = new PadPrinterParserDecorator(pp, this._active._padNextWidth, this._active._padNextChar); + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } - - this._active._padNextWidth = 0; - this._active._padNextChar = 0; - } - - this._active._printerParsers.push(pp); - - this._active._valueParserIndex = -1; - return this._active._printerParsers.length - 1; - }; - - _proto.appendLiteral = function appendLiteral(literal) { - assert(literal != null); - - if (literal.length > 0) { - if (literal.length === 1) { - this._appendInternalPrinterParser(new CharLiteralPrinterParser(literal.charAt(0))); + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { - this._appendInternalPrinterParser(new StringLiteralPrinterParser(literal)); + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } - } - - return this; - }; - - _proto._appendInternalPrinterParser = function _appendInternalPrinterParser(pp) { - assert(pp != null); - - if (this._active._padNextWidth > 0) { - if (pp != null) { - pp = new PadPrinterParserDecorator(pp, this._active._padNextWidth, this._active._padNextChar); + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; } - - this._active._padNextWidth = 0; - this._active._padNextChar = 0; } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} - this._active._printerParsers.push(pp); - - this._active._valueParserIndex = -1; - return this._active._printerParsers.length - 1; - }; - - _proto.append = function append(formatter) { - requireNonNull(formatter, 'formatter'); - - this._appendInternal(formatter._toPrinterParser(false)); - - return this; - }; - - _proto.toFormatter = function toFormatter(resolverStyle) { - if (resolverStyle === void 0) { - resolverStyle = ResolverStyle.SMART; - } - while (this._active._parent != null) { - this.optionalEnd(); - } +/***/ }), - var pp = new CompositePrinterParser(this._printerParsers, false); - return new DateTimeFormatter(pp, null, DecimalStyle.STANDARD, resolverStyle, null, null, null); - }; +/***/ 19195: +/***/ ((module) => { - return DateTimeFormatterBuilder; - }(); - var SECONDS_PER_10000_YEARS = 146097 * 25 * 86400; - var SECONDS_0000_TO_1970 = (146097 * 5 - (30 * 365 + 7)) * 86400; +"use strict"; - var InstantPrinterParser = function () { - function InstantPrinterParser(fractionalDigits) { - this.fractionalDigits = fractionalDigits; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' { - if (inSec >= -SECONDS_0000_TO_1970) { - var zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970; - var hi = MathUtil.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1; - var lo = MathUtil.floorMod(zeroSecs, SECONDS_PER_10000_YEARS); - var ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC); +"use strict"; - if (hi > 0) { - buf.append('+').append(hi); +module.exports = function generate_ref(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + } else { + var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); + if ($refVal === undefined) { + var $message = it.MissingRefError.message(it.baseId, $schema); + if (it.opts.missingRefs == 'fail') { + it.logger.error($message); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; } - - buf.append(ldt); - - if (ldt.second() === 0) { - buf.append(':00'); + if (it.opts.verbose) { + out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { - var _zeroSecs = inSec + SECONDS_0000_TO_1970; + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + if ($breakOnError) { + out += ' if (false) { '; + } + } else if (it.opts.missingRefs == 'ignore') { + it.logger.warn($message); + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + throw new it.MissingRefError(it.baseId, $schema, $message); + } + } else if ($refVal.inline) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); + out += ' ' + ($code) + ' '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + } + } else { + $async = $refVal.$async === true || (it.async && $refVal.$async !== false); + $refCode = $refVal.code; + } + } + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + if (it.opts.passContext) { + out += ' ' + ($refCode) + '.call(this, '; + } else { + out += ' ' + ($refCode) + '( '; + } + out += ' ' + ($data) + ', (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; + var __callValidate = out; + out = $$outStack.pop(); + if ($async) { + if (!it.async) throw new Error('async schema referenced by sync schema'); + if ($breakOnError) { + out += ' var ' + ($valid) + '; '; + } + out += ' try { await ' + (__callValidate) + '; '; + if ($breakOnError) { + out += ' ' + ($valid) + ' = true; '; + } + out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; + if ($breakOnError) { + out += ' ' + ($valid) + ' = false; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + } + } else { + out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' else { '; + } + } + } + return out; +} - var _hi = MathUtil.intDiv(_zeroSecs, SECONDS_PER_10000_YEARS); - var _lo = MathUtil.intMod(_zeroSecs, SECONDS_PER_10000_YEARS); +/***/ }), - var _ldt = LocalDateTime.ofEpochSecond(_lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC); +/***/ 8420: +/***/ ((module) => { - var pos = buf.length(); - buf.append(_ldt); +"use strict"; - if (_ldt.second() === 0) { - buf.append(':00'); +module.exports = function generate_required(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $vSchema = 'schema' + $lvl; + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; + if (arr1) { + var $property, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; + if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; } - - if (_hi < 0) { - if (_ldt.year() === -10000) { - buf.replace(pos, pos + 2, '' + (_hi - 1)); - } else if (_lo === 0) { - buf.insert(pos, _hi); + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; } else { - buf.insert(pos + 1, Math.abs(_hi)); + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - - if (this.fractionalDigits === -2) { - if (inNano !== 0) { - buf.append('.'); - - if (MathUtil.intMod(inNano, 1000000) === 0) { - buf.append(('' + (MathUtil.intDiv(inNano, 1000000) + 1000)).substring(1)); - } else if (MathUtil.intMod(inNano, 1000) === 0) { - buf.append(('' + (MathUtil.intDiv(inNano, 1000) + 1000000)).substring(1)); + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; } else { - buf.append(('' + (inNano + 1000000000)).substring(1)); + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } + out += '\' '; } - } else if (this.fractionalDigits > 0 || this.fractionalDigits === -1 && inNano > 0) { - buf.append('.'); - var div = 100000000; - - for (var i = 0; this.fractionalDigits === -1 && inNano > 0 || i < this.fractionalDigits; i++) { - var digit = MathUtil.intDiv(inNano, div); - buf.append(digit); - inNano = inNano - digit * div; - div = MathUtil.intDiv(div, 10); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - - buf.append('Z'); - return true; - }; - - _proto2.parse = function parse(context, text, position) { - var newContext = context.copy(); - var minDigits = this.fractionalDigits < 0 ? 0 : this.fractionalDigits; - var maxDigits = this.fractionalDigits < 0 ? 9 : this.fractionalDigits; - - var parser = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':').appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(ChronoField.SECOND_OF_MINUTE, 2).appendFraction(ChronoField.NANO_OF_SECOND, minDigits, maxDigits, true).appendLiteral('Z').toFormatter()._toPrinterParser(false); - - var pos = parser.parse(newContext, text, position); - - if (pos < 0) { - return pos; + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; } - - var yearParsed = newContext.getParsed(ChronoField.YEAR); - var month = newContext.getParsed(ChronoField.MONTH_OF_YEAR); - var day = newContext.getParsed(ChronoField.DAY_OF_MONTH); - var hour = newContext.getParsed(ChronoField.HOUR_OF_DAY); - var min = newContext.getParsed(ChronoField.MINUTE_OF_HOUR); - var secVal = newContext.getParsed(ChronoField.SECOND_OF_MINUTE); - var nanoVal = newContext.getParsed(ChronoField.NANO_OF_SECOND); - var sec = secVal != null ? secVal : 0; - var nano = nanoVal != null ? nanoVal : 0; - var year = MathUtil.intMod(yearParsed, 10000); - var days = 0; - - if (hour === 24 && min === 0 && sec === 0 && nano === 0) { - hour = 0; - days = 1; - } else if (hour === 23 && min === 59 && sec === 60) { - context.setParsedLeapSecond(); - sec = 59; + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; } - - var instantSecs; - - try { - var ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0).plusDays(days); - instantSecs = ldt.toEpochSecond(ZoneOffset.UTC); - instantSecs += MathUtil.safeMultiply(MathUtil.intDiv(yearParsed, 10000), SECONDS_PER_10000_YEARS); - } catch (ex) { - return ~position; + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } } - - var successPos = pos; - successPos = context.setParsedField(ChronoField.INSTANT_SECONDS, instantSecs, position, successPos); - return context.setParsedField(ChronoField.NANO_OF_SECOND, nano, position, successPos); - }; - - _proto2.toString = function toString() { - return 'Instant()'; - }; - - return InstantPrinterParser; - }(); - - function _init$9() { - ReducedPrinterParser.BASE_DATE = LocalDate.of(2000, 1, 1); - DateTimeFormatterBuilder.CompositePrinterParser = CompositePrinterParser; - DateTimeFormatterBuilder.PadPrinterParserDecorator = PadPrinterParserDecorator; - DateTimeFormatterBuilder.SettingsParser = SettingsParser; - DateTimeFormatterBuilder.CharLiteralPrinterParser = StringLiteralPrinterParser; - DateTimeFormatterBuilder.StringLiteralPrinterParser = StringLiteralPrinterParser; - DateTimeFormatterBuilder.CharLiteralPrinterParser = CharLiteralPrinterParser; - DateTimeFormatterBuilder.NumberPrinterParser = NumberPrinterParser; - DateTimeFormatterBuilder.ReducedPrinterParser = ReducedPrinterParser; - DateTimeFormatterBuilder.FractionPrinterParser = FractionPrinterParser; - DateTimeFormatterBuilder.OffsetIdPrinterParser = OffsetIdPrinterParser; - DateTimeFormatterBuilder.ZoneIdPrinterParser = ZoneIdPrinterParser; - } - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var StringBuilder = function () { - function StringBuilder() { - this._str = ''; } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} - var _proto = StringBuilder.prototype; - - _proto.append = function append(str) { - this._str += str; - return this; - }; - - _proto.appendChar = function appendChar(str) { - this._str += str[0]; - return this; - }; - - _proto.insert = function insert(offset, str) { - this._str = this._str.slice(0, offset) + str + this._str.slice(offset); - return this; - }; - - _proto.replace = function replace(start, end, str) { - this._str = this._str.slice(0, start) + str + this._str.slice(end); - return this; - }; - - _proto.length = function length() { - return this._str.length; - }; - - _proto.setLength = function setLength(length) { - this._str = this._str.slice(0, length); - return this; - }; - - _proto.toString = function toString() { - return this._str; - }; - - return StringBuilder; - }(); - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var DateTimeFormatter = function () { - DateTimeFormatter.parsedExcessDays = function parsedExcessDays() { - return DateTimeFormatter.PARSED_EXCESS_DAYS; - }; +/***/ }), - DateTimeFormatter.parsedLeapSecond = function parsedLeapSecond() { - return DateTimeFormatter.PARSED_LEAP_SECOND; - }; +/***/ 24995: +/***/ ((module) => { - DateTimeFormatter.ofPattern = function ofPattern(pattern) { - return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); - }; +"use strict"; - function DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone) { - if (chrono === void 0) { - chrono = IsoChronology.INSTANCE; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); } - - assert(printerParser != null); - assert(decimalStyle != null); - assert(resolverStyle != null); - this._printerParser = printerParser; - this._locale = locale; - this._decimalStyle = decimalStyle; - this._resolverStyle = resolverStyle; - this._resolverFields = resolverFields; - this._chrono = chrono; - this._zone = zone; + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} - var _proto = DateTimeFormatter.prototype; - _proto.locale = function locale() { - return this._locale; - }; +/***/ }), - _proto.decimalStyle = function decimalStyle() { - return this._decimalStyle; - }; +/***/ 49585: +/***/ ((module) => { - _proto.chronology = function chronology() { - return this._chrono; - }; +"use strict"; - _proto.withChronology = function withChronology(chrono) { - if (this._chrono != null && this._chrono.equals(chrono)) { - return this; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; } - - return new DateTimeFormatter(this._printerParser, this._locale, this._decimalStyle, this._resolverStyle, this._resolverFields, chrono, this._zone); - }; - - _proto.withLocale = function withLocale() { - return this; - }; - - _proto.withResolverStyle = function withResolverStyle(resolverStyle) { - requireNonNull(resolverStyle, 'resolverStyle'); - - if (resolverStyle.equals(this._resolverStyle)) { - return this; + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - - return new DateTimeFormatter(this._printerParser, this._locale, this._decimalStyle, resolverStyle, this._resolverFields, this._chrono, this._zone); - }; - - _proto.format = function format(temporal) { - var buf = new StringBuilder(32); - - this._formatTo(temporal, buf); - - return buf.toString(); - }; - - _proto._formatTo = function _formatTo(temporal, appendable) { - requireNonNull(temporal, 'temporal'); - requireNonNull(appendable, 'appendable'); - var context = new DateTimePrintContext(temporal, this); - - this._printerParser.print(context, appendable); - }; - - _proto.parse = function parse(text, type) { - if (arguments.length === 1) { - return this.parse1(text); + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - return this.parse2(text, type); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - }; - - _proto.parse1 = function parse1(text) { - requireNonNull(text, 'text'); - - try { - return this._parseToBuilder(text, null).resolve(this._resolverStyle, this._resolverFields); - } catch (ex) { - if (ex instanceof DateTimeParseException) { - throw ex; - } else { - throw this._createError(text, ex); - } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; } - }; - - _proto.parse2 = function parse2(text, type) { - requireNonNull(text, 'text'); - requireNonNull(type, 'type'); - - try { - var builder = this._parseToBuilder(text, null).resolve(this._resolverStyle, this._resolverFields); - - return builder.build(type); - } catch (ex) { - if (ex instanceof DateTimeParseException) { - throw ex; - } else { - throw this._createError(text, ex); + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; + } + out += ' if (' + ($coerced) + ' !== undefined) ; '; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($type == 'string') { + out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } } } - }; - - _proto._createError = function _createError(text, ex) { - var abbr = ''; - - if (text.length > 64) { - abbr = text.substring(0, 64) + '...'; - } else { - abbr = text; - } - - return new DateTimeParseException('Text \'' + abbr + '\' could not be parsed: ' + ex.message, text, 0, ex); - }; - - _proto._parseToBuilder = function _parseToBuilder(text, position) { - var pos = position != null ? position : new ParsePosition(0); - - var result = this._parseUnresolved0(text, pos); - - if (result == null || pos.getErrorIndex() >= 0 || position == null && pos.getIndex() < text.length) { - var abbr = ''; - - if (text.length > 64) { - abbr = text.substr(0, 64).toString() + '...'; + out += ' else { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); } else { - abbr = text; + out += '' + ($typeSchema); } - - if (pos.getErrorIndex() >= 0) { - throw new DateTimeParseException('Text \'' + abbr + '\' could not be parsed at index ' + pos.getErrorIndex(), text, pos.getErrorIndex()); + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - throw new DateTimeParseException('Text \'' + abbr + '\' could not be parsed, unparsed text found at index ' + pos.getIndex(), text, pos.getIndex()); + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - - return result.toBuilder(); - }; - - _proto.parseUnresolved = function parseUnresolved(text, position) { - return this._parseUnresolved0(text, position); - }; - - _proto._parseUnresolved0 = function _parseUnresolved0(text, position) { - assert(text != null, 'text', NullPointerException); - assert(position != null, 'position', NullPointerException); - var context = new DateTimeParseContext(this); - var pos = position.getIndex(); - pos = this._printerParser.parse(context, text, pos); - - if (pos < 0) { - position.setErrorIndex(~pos); - return null; + out += ' } if (' + ($coerced) + ' !== undefined) { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; } - - position.setIndex(pos); - return context.toParsed(); - }; - - _proto._toPrinterParser = function _toPrinterParser(optional) { - return this._printerParser.withOptional(optional); - }; - - _proto.toString = function toString() { - var pattern = this._printerParser.toString(); - - return pattern.indexOf('[') === 0 ? pattern : pattern.substring(1, pattern.length - 1); - }; - - return DateTimeFormatter; - }(); - function _init$a() { - DateTimeFormatter.ISO_LOCAL_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-').appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-').appendValue(ChronoField.DAY_OF_MONTH, 2).toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_LOCAL_TIME = new DateTimeFormatterBuilder().appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':').appendValue(ChronoField.MINUTE_OF_HOUR, 2).optionalStart().appendLiteral(':').appendValue(ChronoField.SECOND_OF_MINUTE, 2).optionalStart().appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true).toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_INSTANT = new DateTimeFormatterBuilder().parseCaseInsensitive().appendInstant().toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE_TIME).appendOffsetId().toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_OFFSET_DATE_TIME).optionalStart().appendLiteral('[').parseCaseSensitive().appendZoneId().appendLiteral(']').toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.BASIC_ISO_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendValue(ChronoField.MONTH_OF_YEAR, 2).appendValue(ChronoField.DAY_OF_MONTH, 2).toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_OFFSET_DATE = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendOffsetId().toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_OFFSET_TIME = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_TIME).appendOffsetId().toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_ORDINAL_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-').appendValue(ChronoField.DAY_OF_YEAR).toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.ISO_WEEK_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-W').appendValue(ChronoField.ALIGNED_WEEK_OF_YEAR).appendLiteral('-').appendValue(ChronoField.DAY_OF_WEEK).toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.PARSED_EXCESS_DAYS = createTemporalQuery('PARSED_EXCESS_DAYS', function (temporal) { - if (temporal instanceof DateTimeBuilder) { - return temporal.excessDays; + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; } else { - return Period.ZERO; - } - }); - DateTimeFormatter.PARSED_LEAP_SECOND = createTemporalQuery('PARSED_LEAP_SECOND', function (temporal) { - if (temporal instanceof DateTimeBuilder) { - return temporal.leapSecond; + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } } else { - return false; + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - }); + } + out += ' } '; } - - var MonthDay = function (_TemporalAccessor) { - _inheritsLoose(MonthDay, _TemporalAccessor); - - MonthDay.now = function now(zoneIdOrClock) { - if (arguments.length === 0) { - return MonthDay.now0(); - } else if (arguments.length === 1 && zoneIdOrClock instanceof ZoneId) { - return MonthDay.nowZoneId(zoneIdOrClock); - } else { - return MonthDay.nowClock(zoneIdOrClock); + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } } - }; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } - MonthDay.now0 = function now0() { - return this.nowClock(Clock.systemDefaultZone()); - }; + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } - MonthDay.nowZoneId = function nowZoneId(zone) { - requireNonNull(zone, 'zone'); - return this.nowClock(Clock.system(zone)); - }; + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } - MonthDay.nowClock = function nowClock(clock) { - requireNonNull(clock, 'clock'); - var now = LocalDate.now(clock); - return MonthDay.of(now.month(), now.dayOfMonth()); - }; + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} - MonthDay.of = function of(monthOrNumber, number) { - if (arguments.length === 2 && monthOrNumber instanceof Month) { - return MonthDay.ofMonthNumber(monthOrNumber, number); - } else { - return MonthDay.ofNumberNumber(monthOrNumber, number); - } - }; - MonthDay.ofMonthNumber = function ofMonthNumber(month, dayOfMonth) { - requireNonNull(month, 'month'); - ChronoField.DAY_OF_MONTH.checkValidValue(dayOfMonth); +/***/ }), - if (dayOfMonth > month.maxLength()) { - throw new DateTimeException('Illegal value for DayOfMonth field, value ' + dayOfMonth + ' is not valid for month ' + month.toString()); - } +/***/ 53297: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return new MonthDay(month.value(), dayOfMonth); - }; +"use strict"; - MonthDay.ofNumberNumber = function ofNumberNumber(month, dayOfMonth) { - requireNonNull(month, 'month'); - requireNonNull(dayOfMonth, 'dayOfMonth'); - return MonthDay.of(Month.of(month), dayOfMonth); - }; - MonthDay.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - requireInstance(temporal, TemporalAccessor, 'temporal'); +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = __nccwpck_require__(5912); +var definitionSchema = __nccwpck_require__(10458); - if (temporal instanceof MonthDay) { - return temporal; - } +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; - try { - return MonthDay.of(temporal.get(ChronoField.MONTH_OF_YEAR), temporal.get(ChronoField.DAY_OF_MONTH)); - } catch (ex) { - throw new DateTimeException('Unable to obtain MonthDay from TemporalAccessor: ' + temporal + ', type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : '')); - } - }; - MonthDay.parse = function parse(text, formatter) { - if (arguments.length === 1) { - return MonthDay.parseString(text); - } else { - return MonthDay.parseStringFormatter(text, formatter); - } - }; +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + this.validateKeyword(definition, true); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i { - _proto.isValidYear = function isValidYear(year) { - return (this._day === 29 && this._month === 2 && Year.isLeap(year) === false) === false; - }; +"use strict"; +/* module decorator */ module = __nccwpck_require__.nmd(module); - _proto.withMonth = function withMonth(month) { - return this.with(Month.of(month)); - }; - _proto.with = function _with(month) { - requireNonNull(month, 'month'); +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; - if (month.value() === this._month) { - return this; - } +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; - var day = Math.min(this._day, month.maxLength()); - return new MonthDay(month.value(), day); - }; +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - if (dayOfMonth === this._day) { - return this; - } +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; - return MonthDay.of(this._month, dayOfMonth); - }; +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - requireInstance(_query, TemporalQuery, 'query'); + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } + return value; + }, + enumerable: true, + configurable: true + }); +}; - return _TemporalAccessor.prototype.query.call(this, _query); - }; +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = __nccwpck_require__(86931); + } - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - temporal = temporal.with(ChronoField.MONTH_OF_YEAR, this._month); - return temporal.with(ChronoField.DAY_OF_MONTH, Math.min(temporal.range(ChronoField.DAY_OF_MONTH).maximum(), this._day)); - }; + const offset = isBackground ? 10 : 0; + const styles = {}; - _proto.atYear = function atYear(year) { - return LocalDate.of(year, this._month, this.isValidYear(year) ? this._day : 28); - }; + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, MonthDay, 'other'); - var cmp = this._month - other.monthValue(); + return styles; +}; - if (cmp === 0) { - cmp = this._day - other.dayOfMonth(); - } +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], - return cmp; - }; + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - requireInstance(other, MonthDay, 'other'); - return this.compareTo(other) > 0; - }; + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - requireInstance(other, MonthDay, 'other'); - return this.compareTo(other) < 0; - }; + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; - if (obj instanceof MonthDay) { - var other = obj; - return this.monthValue() === other.monthValue() && this.dayOfMonth() === other.dayOfMonth(); - } + group[styleName] = styles[styleName]; - return false; - }; + codes.set(style[0], style[1]); + } - _proto.toString = function toString() { - return '--' + (this._month < 10 ? '0' : '') + this._month + (this._day < 10 ? '-0' : '-') + this._day; - }; + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } - _proto.toJSON = function toJSON() { - return this.toString(); - }; + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.format(this); - }; + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; - return MonthDay; - }(TemporalAccessor); - var PARSER; - function _init$b() { - PARSER = new DateTimeFormatterBuilder().appendLiteral('--').appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-').appendValue(ChronoField.DAY_OF_MONTH, 2).toFormatter(); - MonthDay.FROM = createTemporalQuery('MonthDay.FROM', function (temporal) { - return MonthDay.from(temporal); - }); - } + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - var YearMonth = function (_Temporal) { - _inheritsLoose(YearMonth, _Temporal); + return styles; +} - YearMonth.now = function now(zoneIdOrClock) { - if (arguments.length === 0) { - return YearMonth.now0(); - } else if (arguments.length === 1 && zoneIdOrClock instanceof ZoneId) { - return YearMonth.nowZoneId(zoneIdOrClock); - } else { - return YearMonth.nowClock(zoneIdOrClock); - } - }; +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); - YearMonth.now0 = function now0() { - return YearMonth.nowClock(Clock.systemDefaultZone()); - }; - YearMonth.nowZoneId = function nowZoneId(zone) { - return YearMonth.nowClock(Clock.system(zone)); - }; +/***/ }), - YearMonth.nowClock = function nowClock(clock) { - var now = LocalDate.now(clock); - return YearMonth.of(now.year(), now.month()); - }; +/***/ 64808: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - YearMonth.of = function of(year, monthOrNumber) { - if (arguments.length === 2 && monthOrNumber instanceof Month) { - return YearMonth.ofNumberMonth(year, monthOrNumber); - } else { - return YearMonth.ofNumberNumber(year, monthOrNumber); - } - }; +"use strict"; - YearMonth.ofNumberMonth = function ofNumberMonth(year, month) { - requireNonNull(month, 'month'); - requireInstance(month, Month, 'month'); - return YearMonth.ofNumberNumber(year, month.value()); - }; - YearMonth.ofNumberNumber = function ofNumberNumber(year, month) { - requireNonNull(year, 'year'); - requireNonNull(month, 'month'); - ChronoField.YEAR.checkValidValue(year); - ChronoField.MONTH_OF_YEAR.checkValidValue(month); - return new YearMonth(year, month); - }; +var lib = __nccwpck_require__(98035); +module.exports = lib(__dirname); - YearMonth.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); +/***/ }), - if (temporal instanceof YearMonth) { - return temporal; - } +/***/ 98035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - return YearMonth.of(temporal.get(ChronoField.YEAR), temporal.get(ChronoField.MONTH_OF_YEAR)); - } catch (ex) { - throw new DateTimeException('Unable to obtain YearMonth from TemporalAccessor: ' + temporal + ', type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : '')); - } - }; +"use strict"; - YearMonth.parse = function parse(text, formatter) { - if (arguments.length === 1) { - return YearMonth.parseString(text); - } else { - return YearMonth.parseStringFormatter(text, formatter); - } - }; - YearMonth.parseString = function parseString(text) { - return YearMonth.parseStringFormatter(text, PARSER$1); - }; +module.exports = function(dirname) { + var path = __nccwpck_require__(85622); + var resolve = __nccwpck_require__(15619); + var appRootPath = resolve(dirname); - YearMonth.parseStringFormatter = function parseStringFormatter(text, formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, YearMonth.FROM); - }; + var publicInterface = { + resolve: function(pathToModule) { + return path.join(appRootPath, pathToModule); + }, - function YearMonth(year, month) { - var _this; + require: function(pathToModule) { + return require(publicInterface.resolve(pathToModule)); + }, - _this = _Temporal.call(this) || this; - _this._year = MathUtil.safeToInt(year); - _this._month = MathUtil.safeToInt(month); - return _this; - } + toString: function() { + return appRootPath; + }, - var _proto = YearMonth.prototype; + setPath: function(explicitlySetPath) { + appRootPath = path.resolve(explicitlySetPath); + publicInterface.path = appRootPath; + }, - _proto.isSupported = function isSupported(fieldOrUnit) { - if (arguments.length === 1 && fieldOrUnit instanceof TemporalField) { - return this.isSupportedField(fieldOrUnit); - } else { - return this.isSupportedUnit(fieldOrUnit); - } - }; + path: appRootPath + }; - _proto.isSupportedField = function isSupportedField(field) { - if (field instanceof ChronoField) { - return field === ChronoField.YEAR || field === ChronoField.MONTH_OF_YEAR || field === ChronoField.PROLEPTIC_MONTH || field === ChronoField.YEAR_OF_ERA || field === ChronoField.ERA; - } + return publicInterface; +}; - return field != null && field.isSupportedBy(this); - }; +/***/ }), - _proto.isSupportedUnit = function isSupportedUnit(unit) { - if (unit instanceof ChronoUnit) { - return unit === ChronoUnit.MONTHS || unit === ChronoUnit.YEARS || unit === ChronoUnit.DECADES || unit === ChronoUnit.CENTURIES || unit === ChronoUnit.MILLENNIA || unit === ChronoUnit.ERAS; - } +/***/ 15619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return unit != null && unit.isSupportedBy(this); - }; +"use strict"; - _proto.range = function range(field) { - if (field === ChronoField.YEAR_OF_ERA) { - return this.year() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE); - } - return _Temporal.prototype.range.call(this, field); - }; +// Dependencies +var path = __nccwpck_require__(85622); - _proto.get = function get(field) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; +// Load global paths +var globalPaths = __nccwpck_require__(32282).globalPaths; - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); +// Guess at NPM's global install dir +var npmGlobalPrefix; +if ('win32' === process.platform) { + npmGlobalPrefix = path.dirname(process.execPath); +} else { + npmGlobalPrefix = path.dirname(path.dirname(process.execPath)); +} +var npmGlobalModuleDir = path.resolve(npmGlobalPrefix, 'lib', 'node_modules'); - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.MONTH_OF_YEAR: - return this._month; +// Save OS-specific path separator +var sep = path.sep; - case ChronoField.PROLEPTIC_MONTH: - return this._getProlepticMonth(); - - case ChronoField.YEAR_OF_ERA: - return this._year < 1 ? 1 - this._year : this._year; +// If we're in webpack, force it to use the original require() method +var requireFunction = ( true) + ? eval("require") + : 0; - case ChronoField.YEAR: - return this._year; +const isInstalledWithPNPM = function(resolved) { + const pnpmDir = sep + '.pnpm'; - case ChronoField.ERA: - return this._year < 1 ? 0 : 1; - } + for (const globalPath of globalPaths) { + if (-1 !== globalPath.indexOf(pnpmDir) && -1 !== resolved.indexOf(pnpmDir)) { + return true; + } + } + return false; +} - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +const getFirstPartFromNodeModules = function(resolved) { + const nodeModulesDir = sep + 'node_modules'; - return field.getFrom(this); - }; + if (-1 !== resolved.indexOf(nodeModulesDir)) { + const parts = resolved.split(nodeModulesDir); + if (parts.length) { + return parts[0]; + } + } - _proto._getProlepticMonth = function _getProlepticMonth() { - return MathUtil.safeAdd(MathUtil.safeMultiply(this._year, 12), this._month - 1); - }; + return null; +} - _proto.year = function year() { - return this._year; - }; +// Resolver +module.exports = function resolve(dirname) { + // Check for environmental variable + if (process.env.APP_ROOT_PATH) { + return path.resolve(process.env.APP_ROOT_PATH); + } - _proto.monthValue = function monthValue() { - return this._month; - }; + // Defer to Yarn Plug'n'Play if enabled + if (process.versions.pnp) { + try { + var pnp = requireFunction('pnpapi'); + return pnp.getPackageInformation(pnp.topLevel).packageLocation; + } catch (e) {} + } - _proto.month = function month() { - return Month.of(this._month); - }; + // Defer to main process in electron renderer + if ('undefined' !== typeof window && window.process && 'renderer' === window.process.type) { + try { + var remote = requireFunction('electron').remote; + return remote.require('app-root-path').path; + } catch (e) {} + } - _proto.isLeapYear = function isLeapYear() { - return IsoChronology.isLeapYear(this._year); - }; + // Defer to AWS Lambda when executing there + if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) { + return process.env.LAMBDA_TASK_ROOT; + } - _proto.isValidDay = function isValidDay(dayOfMonth) { - return dayOfMonth >= 1 && dayOfMonth <= this.lengthOfMonth(); - }; + var resolved = path.resolve(dirname); + var alternateMethod = false; + var appRootPath = null; - _proto.lengthOfMonth = function lengthOfMonth() { - return this.month().length(this.isLeapYear()); - }; + // Check if the globalPaths contain some folders with '.pnpm' in the path + // If yes this means it is most likely installed with pnpm + if (isInstalledWithPNPM(resolved)) { + appRootPath = getFirstPartFromNodeModules(resolved); - _proto.lengthOfYear = function lengthOfYear() { - return this.isLeapYear() ? 366 : 365; - }; + if (appRootPath) { + return appRootPath; + } + } - _proto.with = function _with(adjusterOrField, value) { - if (arguments.length === 1) { - return this.withAdjuster(adjusterOrField); - } else { - return this.withFieldValue(adjusterOrField, value); - } - }; + // Make sure that we're not loaded from a global include path + // Eg. $HOME/.node_modules + // $HOME/.node_libraries + // $PREFIX/lib/node + globalPaths.forEach(function(globalPath) { + if (!alternateMethod && 0 === resolved.indexOf(globalPath)) { + alternateMethod = true; + } + }); - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; + // If the app-root-path library isn't loaded globally, + // and node_modules exists in the path, just split __dirname + if (!alternateMethod) { + appRootPath = getFirstPartFromNodeModules(resolved); + } - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); + // If the above didn't work, or this module is loaded globally, then + // resort to require.main.filename (See http://nodejs.org/api/modules.html) + if (alternateMethod || null == appRootPath) { + appRootPath = path.dirname(requireFunction.main.filename); + } - if (field instanceof ChronoField) { - var f = field; - f.checkValidValue(newValue); + // Handle global bin/ directory edge-case + if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) { + appRootPath = appRootPath.slice(0, -4); + } - switch (f) { - case ChronoField.MONTH_OF_YEAR: - return this.withMonth(newValue); + // Return + return appRootPath; +}; - case ChronoField.PROLEPTIC_MONTH: - return this.plusMonths(newValue - this.getLong(ChronoField.PROLEPTIC_MONTH)); - case ChronoField.YEAR_OF_ERA: - return this.withYear(this._year < 1 ? 1 - newValue : newValue); +/***/ }), - case ChronoField.YEAR: - return this.withYear(newValue); +/***/ 83278: +/***/ ((module) => { - case ChronoField.ERA: - return this.getLong(ChronoField.ERA) === newValue ? this : this.withYear(1 - this._year); - } +"use strict"; - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - return field.adjustInto(this, newValue); - }; +function isArguments (thingy) { + return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') +} - _proto.withYear = function withYear(year) { - ChronoField.YEAR.checkValidValue(year); - return new YearMonth(year, this._month); - }; +var types = { + '*': {label: 'any', check: function () { return true }}, + A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }}, + S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }}, + N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }}, + F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }}, + O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }}, + B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }}, + E: {label: 'error', check: function (thingy) { return thingy instanceof Error }}, + Z: {label: 'null', check: function (thingy) { return thingy == null }} +} - _proto.withMonth = function withMonth(month) { - ChronoField.MONTH_OF_YEAR.checkValidValue(month); - return new YearMonth(this._year, month); - }; +function addSchema (schema, arity) { + var group = arity[schema.length] = arity[schema.length] || [] + if (group.indexOf(schema) === -1) group.push(schema) +} - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.addTo(this); - }; +var validate = module.exports = function (rawSchemas, args) { + if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) + if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') + if (!args) throw missingRequiredArg(1, 'args') + if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) + if (!types.A.check(args)) throw invalidType(1, ['array'], args) + var schemas = rawSchemas.split('|') + var arity = {} - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); + schemas.forEach(function (schema) { + for (var ii = 0; ii < schema.length; ++ii) { + var type = schema[ii] + if (!types[type]) throw unknownType(ii, type) + } + if (/E.*E/.test(schema)) throw moreThanOneError(schema) + addSchema(schema, arity) + if (/E/.test(schema)) { + addSchema(schema.replace(/E.*$/, 'E'), arity) + addSchema(schema.replace(/E/, 'Z'), arity) + if (schema.length === 1) addSchema('', arity) + } + }) + var matching = arity[args.length] + if (!matching) { + throw wrongNumberOfArgs(Object.keys(arity), args.length) + } + for (var ii = 0; ii < args.length; ++ii) { + var newMatching = matching.filter(function (schema) { + var type = schema[ii] + var typeCheck = types[type].check + return typeCheck(args[ii]) + }) + if (!newMatching.length) { + var labels = matching.map(function (schema) { + return types[schema[ii]].label + }).filter(function (schema) { return schema != null }) + throw invalidType(ii, labels, args[ii]) + } + matching = newMatching + } +} - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.MONTHS: - return this.plusMonths(amountToAdd); +function missingRequiredArg (num) { + return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) +} - case ChronoUnit.YEARS: - return this.plusYears(amountToAdd); +function unknownType (num, type) { + return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) +} - case ChronoUnit.DECADES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 10)); +function invalidType (num, expectedTypes, value) { + var valueType + Object.keys(types).forEach(function (typeCode) { + if (types[typeCode].check(value)) valueType = types[typeCode].label + }) + return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + + englishList(expectedTypes) + ' but got ' + valueType) +} - case ChronoUnit.CENTURIES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 100)); +function englishList (list) { + return list.join(', ').replace(/, ([^,]+)$/, ' or $1') +} - case ChronoUnit.MILLENNIA: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 1000)); +function wrongNumberOfArgs (expected, got) { + var english = englishList(expected) + var args = expected.every(function (ex) { return ex.length === 1 }) + ? 'argument' + : 'arguments' + return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) +} - case ChronoUnit.ERAS: - return this.with(ChronoField.ERA, MathUtil.safeAdd(this.getLong(ChronoField.ERA), amountToAdd)); - } +function moreThanOneError (schema) { + return newException('ETOOMANYERRORTYPES', + 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') +} - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +function newException (code, msg) { + var e = new Error(msg) + e.code = code + if (Error.captureStackTrace) Error.captureStackTrace(e, validate) + return e +} - return unit.addTo(this, amountToAdd); - }; - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } +/***/ }), - var newYear = ChronoField.YEAR.checkValidIntValue(this._year + yearsToAdd); - return this.withYear(newYear); - }; +/***/ 11083: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _proto.plusMonths = function plusMonths(monthsToAdd) { - if (monthsToAdd === 0) { - return this; - } +"use strict"; - var monthCount = this._year * 12 + (this._month - 1); - var calcMonths = monthCount + monthsToAdd; - var newYear = ChronoField.YEAR.checkValidIntValue(MathUtil.floorDiv(calcMonths, 12)); - var newMonth = MathUtil.floorMod(calcMonths, 12) + 1; - return new YearMonth(newYear, newMonth); - }; +exports.TrackerGroup = __nccwpck_require__(60660) +exports.Tracker = __nccwpck_require__(8074) +exports.TrackerStream = __nccwpck_require__(31375) - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return amountToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusAmountUnit(MathUtil.MAX_SAFE_INTEGER, unit).plusAmountUnit(1, unit) : this.plusAmountUnit(-amountToSubtract, unit); - }; +/***/ }), - _proto.minusYears = function minusYears(yearsToSubtract) { - return yearsToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusYears(MathUtil.MIN_SAFE_INTEGER).plusYears(1) : this.plusYears(-yearsToSubtract); - }; +/***/ 10165: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.minusMonths = function minusMonths(monthsToSubtract) { - return monthsToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusMonths(Math.MAX_SAFE_INTEGER).plusMonths(1) : this.plusMonths(-monthsToSubtract); - }; +"use strict"; - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - requireInstance(_query, TemporalQuery, 'query'); +var EventEmitter = __nccwpck_require__(28614).EventEmitter +var util = __nccwpck_require__(31669) - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.MONTHS; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } +var trackerId = 0 +var TrackerBase = module.exports = function (name) { + EventEmitter.call(this) + this.id = ++trackerId + this.name = name +} +util.inherits(TrackerBase, EventEmitter) - return _Temporal.prototype.query.call(this, _query); - }; - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - requireInstance(temporal, Temporal, 'temporal'); - return temporal.with(ChronoField.PROLEPTIC_MONTH, this._getProlepticMonth()); - }; +/***/ }), - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - requireInstance(endExclusive, Temporal, 'endExclusive'); - requireInstance(unit, TemporalUnit, 'unit'); - var end = YearMonth.from(endExclusive); +/***/ 60660: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (unit instanceof ChronoUnit) { - var monthsUntil = end._getProlepticMonth() - this._getProlepticMonth(); +"use strict"; - switch (unit) { - case ChronoUnit.MONTHS: - return monthsUntil; +var util = __nccwpck_require__(31669) +var TrackerBase = __nccwpck_require__(10165) +var Tracker = __nccwpck_require__(8074) +var TrackerStream = __nccwpck_require__(31375) - case ChronoUnit.YEARS: - return monthsUntil / 12; +var TrackerGroup = module.exports = function (name) { + TrackerBase.call(this, name) + this.parentGroup = null + this.trackers = [] + this.completion = {} + this.weight = {} + this.totalWeight = 0 + this.finished = false + this.bubbleChange = bubbleChange(this) +} +util.inherits(TrackerGroup, TrackerBase) - case ChronoUnit.DECADES: - return monthsUntil / 120; +function bubbleChange (trackerGroup) { + return function (name, completed, tracker) { + trackerGroup.completion[tracker.id] = completed + if (trackerGroup.finished) return + trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup) + } +} - case ChronoUnit.CENTURIES: - return monthsUntil / 1200; +TrackerGroup.prototype.nameInTree = function () { + var names = [] + var from = this + while (from) { + names.unshift(from.name) + from = from.parentGroup + } + return names.join('/') +} - case ChronoUnit.MILLENNIA: - return monthsUntil / 12000; +TrackerGroup.prototype.addUnit = function (unit, weight) { + if (unit.addUnit) { + var toTest = this + while (toTest) { + if (unit === toTest) { + throw new Error( + 'Attempted to add tracker group ' + + unit.name + ' to tree that already includes it ' + + this.nameInTree(this)) + } + toTest = toTest.parentGroup + } + unit.parentGroup = this + } + this.weight[unit.id] = weight || 1 + this.totalWeight += this.weight[unit.id] + this.trackers.push(unit) + this.completion[unit.id] = unit.completed() + unit.on('change', this.bubbleChange) + if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit) + return unit +} - case ChronoUnit.ERAS: - return end.getLong(ChronoField.ERA) - this.getLong(ChronoField.ERA); - } +TrackerGroup.prototype.completed = function () { + if (this.trackers.length === 0) return 0 + var valPerWeight = 1 / this.totalWeight + var completed = 0 + for (var ii = 0; ii < this.trackers.length; ii++) { + var trackerId = this.trackers[ii].id + completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId] + } + return completed +} - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +TrackerGroup.prototype.newGroup = function (name, weight) { + return this.addUnit(new TrackerGroup(name), weight) +} - return unit.between(this, end); - }; +TrackerGroup.prototype.newItem = function (name, todo, weight) { + return this.addUnit(new Tracker(name, todo), weight) +} - _proto.atDay = function atDay(dayOfMonth) { - return LocalDate.of(this._year, this._month, dayOfMonth); - }; +TrackerGroup.prototype.newStream = function (name, todo, weight) { + return this.addUnit(new TrackerStream(name, todo), weight) +} - _proto.atEndOfMonth = function atEndOfMonth() { - return LocalDate.of(this._year, this._month, this.lengthOfMonth()); - }; +TrackerGroup.prototype.finish = function () { + this.finished = true + if (!this.trackers.length) this.addUnit(new Tracker(), 1, true) + for (var ii = 0; ii < this.trackers.length; ii++) { + var tracker = this.trackers[ii] + tracker.finish() + tracker.removeListener('change', this.bubbleChange) + } + this.emit('change', this.name, 1, this) +} - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, YearMonth, 'other'); - var cmp = this._year - other.year(); +var buffer = ' ' +TrackerGroup.prototype.debug = function (depth) { + depth = depth || 0 + var indent = depth ? buffer.substr(0, depth) : '' + var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n' + this.trackers.forEach(function (tracker) { + if (tracker instanceof TrackerGroup) { + output += tracker.debug(depth + 1) + } else { + output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n' + } + }) + return output +} - if (cmp === 0) { - cmp = this._month - other.monthValue(); - } - return cmp; - }; +/***/ }), - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; +/***/ 31375: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; +"use strict"; - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } +var util = __nccwpck_require__(31669) +var stream = __nccwpck_require__(51642) +var delegate = __nccwpck_require__(61318) +var Tracker = __nccwpck_require__(8074) - if (obj instanceof YearMonth) { - var other = obj; - return this.year() === other.year() && this.monthValue() === other.monthValue(); - } +var TrackerStream = module.exports = function (name, size, options) { + stream.Transform.call(this, options) + this.tracker = new Tracker(name, size) + this.name = name + this.id = this.tracker.id + this.tracker.on('change', delegateChange(this)) +} +util.inherits(TrackerStream, stream.Transform) - return false; - }; +function delegateChange (trackerStream) { + return function (name, completion, tracker) { + trackerStream.emit('change', name, completion, trackerStream) + } +} - _proto.toString = function toString() { - return PARSER$1.format(this); - }; +TrackerStream.prototype._transform = function (data, encoding, cb) { + this.tracker.completeWork(data.length ? data.length : 1) + this.push(data) + cb() +} - _proto.toJSON = function toJSON() { - return this.toString(); - }; +TrackerStream.prototype._flush = function (cb) { + this.tracker.finish() + cb() +} - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; +delegate(TrackerStream.prototype, 'tracker') + .method('completed') + .method('addWork') + .method('finish') - return YearMonth; - }(Temporal); - var PARSER$1; - function _init$c() { - PARSER$1 = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-').appendValue(ChronoField.MONTH_OF_YEAR, 2).toFormatter(); - YearMonth.FROM = createTemporalQuery('YearMonth.FROM', function (temporal) { - return YearMonth.from(temporal); - }); - } - var Year = function (_Temporal) { - _inheritsLoose(Year, _Temporal); +/***/ }), - function Year(value) { - var _this; +/***/ 8074: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _this = _Temporal.call(this) || this; - _this._year = MathUtil.safeToInt(value); - return _this; - } +"use strict"; - var _proto = Year.prototype; +var util = __nccwpck_require__(31669) +var TrackerBase = __nccwpck_require__(10165) - _proto.value = function value() { - return this._year; - }; +var Tracker = module.exports = function (name, todo) { + TrackerBase.call(this, name) + this.workDone = 0 + this.workTodo = todo || 0 +} +util.inherits(Tracker, TrackerBase) - Year.now = function now(zoneIdOrClock) { - if (zoneIdOrClock === void 0) { - zoneIdOrClock = undefined; - } +Tracker.prototype.completed = function () { + return this.workTodo === 0 ? 0 : this.workDone / this.workTodo +} - if (zoneIdOrClock === undefined) { - return Year.now0(); - } else if (zoneIdOrClock instanceof ZoneId) { - return Year.nowZoneId(zoneIdOrClock); - } else { - return Year.nowClock(zoneIdOrClock); - } - }; +Tracker.prototype.addWork = function (work) { + this.workTodo += work + this.emit('change', this.name, this.completed(), this) +} - Year.now0 = function now0() { - return Year.nowClock(Clock.systemDefaultZone()); - }; +Tracker.prototype.completeWork = function (work) { + this.workDone += work + if (this.workDone > this.workTodo) this.workDone = this.workTodo + this.emit('change', this.name, this.completed(), this) +} - Year.nowZoneId = function nowZoneId(zone) { - requireNonNull(zone, 'zone'); - requireInstance(zone, ZoneId, 'zone'); - return Year.nowClock(Clock.system(zone)); - }; +Tracker.prototype.finish = function () { + this.workTodo = this.workDone = 1 + this.emit('change', this.name, 1, this) +} - Year.nowClock = function nowClock(clock) { - requireNonNull(clock, 'clock'); - requireInstance(clock, Clock, 'clock'); - var now = LocalDate.now(clock); - return Year.of(now.year()); - }; - Year.of = function of(isoYear) { - requireNonNull(isoYear, 'isoYear'); - ChronoField.YEAR.checkValidValue(isoYear); - return new Year(isoYear); - }; +/***/ }), - Year.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - requireInstance(temporal, TemporalAccessor, 'temporal'); +/***/ 99348: +/***/ ((module) => { - if (temporal instanceof Year) { - return temporal; - } +// Copyright 2011 Mark Cavage All rights reserved. - try { - return Year.of(temporal.get(ChronoField.YEAR)); - } catch (ex) { - throw new DateTimeException('Unable to obtain Year from TemporalAccessor: ' + temporal + ', type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : '')); - } - }; - Year.parse = function parse(text, formatter) { - if (arguments.length <= 1) { - return Year.parseText(text); - } else { - return Year.parseTextFormatter(text, formatter); - } - }; +module.exports = { - Year.parseText = function parseText(text) { - requireNonNull(text, 'text'); - return Year.parse(text, PARSER$2); - }; + newInvalidAsn1Error: function (msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } - Year.parseTextFormatter = function parseTextFormatter(text, formatter) { - if (formatter === void 0) { - formatter = PARSER$2; - } +}; - requireNonNull(text, 'text'); - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.parse(text, Year.FROM); - }; - Year.isLeap = function isLeap(year) { - return MathUtil.intMod(year, 4) === 0 && (MathUtil.intMod(year, 100) !== 0 || MathUtil.intMod(year, 400) === 0); - }; +/***/ }), - _proto.isSupported = function isSupported(fieldOrUnit) { - if (arguments.length === 1 && fieldOrUnit instanceof TemporalField) { - return this.isSupportedField(fieldOrUnit); - } else { - return this.isSupportedUnit(fieldOrUnit); - } - }; +/***/ 194: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.isSupportedField = function isSupportedField(field) { - if (field instanceof ChronoField) { - return field === ChronoField.YEAR || field === ChronoField.YEAR_OF_ERA || field === ChronoField.ERA; - } +// Copyright 2011 Mark Cavage All rights reserved. - return field != null && field.isSupportedBy(this); - }; +var errors = __nccwpck_require__(99348); +var types = __nccwpck_require__(42473); - _proto.isSupportedUnit = function isSupportedUnit(unit) { - if (unit instanceof ChronoUnit) { - return unit === ChronoUnit.YEARS || unit === ChronoUnit.DECADES || unit === ChronoUnit.CENTURIES || unit === ChronoUnit.MILLENNIA || unit === ChronoUnit.ERAS; - } +var Reader = __nccwpck_require__(20290); +var Writer = __nccwpck_require__(43200); - return unit != null && unit.isSupportedBy(this); - }; - _proto.range = function range(field) { - if (this.isSupported(field)) { - return field.range(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +// --- Exports - return _Temporal.prototype.range.call(this, field); - }; +module.exports = { - _proto.get = function get(field) { - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; + Reader: Reader, - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); + Writer: Writer - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.YEAR_OF_ERA: - return this._year < 1 ? 1 - this._year : this._year; +}; - case ChronoField.YEAR: - return this._year; +for (var t in types) { + if (types.hasOwnProperty(t)) + module.exports[t] = types[t]; +} +for (var e in errors) { + if (errors.hasOwnProperty(e)) + module.exports[e] = errors[e]; +} - case ChronoField.ERA: - return this._year < 1 ? 0 : 1; - } - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +/***/ }), - return field.getFrom(this); - }; +/***/ 20290: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.isLeap = function isLeap() { - return Year.isLeap(this._year); - }; +// Copyright 2011 Mark Cavage All rights reserved. - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; +var assert = __nccwpck_require__(42357); +var Buffer = __nccwpck_require__(15118).Buffer; - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); - if (field instanceof ChronoField) { - field.checkValidValue(newValue); - switch (field) { - case ChronoField.YEAR_OF_ERA: - return Year.of(this._year < 1 ? 1 - newValue : newValue); +// --- Globals - case ChronoField.YEAR: - return Year.of(newValue); +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - case ChronoField.ERA: - return this.getLong(ChronoField.ERA) === newValue ? this : Year.of(1 - this._year); - } - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - return field.adjustInto(this, newValue); - }; +// --- API - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.addTo(this); - }; +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); + this._buf = data; + this._size = data.length; - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.YEARS: - return this.plusYears(amountToAdd); + // These hold the "current" state + this._len = 0; + this._offset = 0; +} - case ChronoUnit.DECADES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 10)); +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); - case ChronoUnit.CENTURIES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 100)); +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); - case ChronoUnit.MILLENNIA: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 1000)); +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); - case ChronoUnit.ERAS: - return this.with(ChronoField.ERA, MathUtil.safeAdd(this.getLong(ChronoField.ERA), amountToAdd)); - } +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } - return unit.addTo(this, amountToAdd); - }; +/** + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. + */ +Reader.prototype.readByte = function (peek) { + if (this._size - this._offset < 1) + return null; - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } + var b = this._buf[this._offset] & 0xff; - return Year.of(ChronoField.YEAR.checkValidIntValue(MathUtil.safeAdd(this._year, yearsToAdd))); - }; + if (!peek) + this._offset += 1; - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.subtractFrom(this); - }; + return b; +}; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); - return amountToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plus(MathUtil.MAX_SAFE_INTEGER, unit).plus(1, unit) : this.plus(-amountToSubtract, unit); - }; - _proto.minusYears = function minusYears(yearsToSubtract) { - return yearsToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusYears(MathUtil.MAX_SAFE_INTEGER).plusYears(1) : this.plusYears(-yearsToSubtract); - }; +Reader.prototype.peek = function () { + return this.readByte(true); +}; - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - return temporal.with(ChronoField.YEAR, this._year); - }; - _proto.isValidMonthDay = function isValidMonthDay(monthDay) { - return monthDay != null && monthDay.isValidYear(this._year); - }; +/** + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 + */ +Reader.prototype.readLength = function (offset) { + if (offset === undefined) + offset = this._offset; - _proto.length = function length() { - return this.isLeap() ? 366 : 365; - }; + if (offset >= this._size) + return null; - _proto.atDay = function atDay(dayOfYear) { - return LocalDate.ofYearDay(this._year, dayOfYear); - }; + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; - _proto.atMonth = function atMonth(monthOrNumber) { - if (arguments.length === 1 && monthOrNumber instanceof Month) { - return this.atMonthMonth(monthOrNumber); - } else { - return this.atMonthNumber(monthOrNumber); - } - }; + if ((lenB & 0x80) === 0x80) { + lenB &= 0x7f; - _proto.atMonthMonth = function atMonthMonth(month) { - requireNonNull(month, 'month'); - requireInstance(month, Month, 'month'); - return YearMonth.of(this._year, month); - }; + if (lenB === 0) + throw newInvalidAsn1Error('Indefinite length not supported'); - _proto.atMonthNumber = function atMonthNumber(month) { - requireNonNull(month, 'month'); - return YearMonth.of(this._year, month); - }; + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); - _proto.atMonthDay = function atMonthDay(monthDay) { - requireNonNull(monthDay, 'monthDay'); - requireInstance(monthDay, MonthDay, 'monthDay'); - return monthDay.atYear(this._year); - }; + if (this._size - offset < lenB) + return null; - _proto.query = function query(_query) { - requireNonNull(_query, 'query()'); - requireInstance(_query, TemporalQuery, 'query()'); + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.YEARS; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } + } else { + // Wasn't a variable length + this._len = lenB; + } - return _Temporal.prototype.query.call(this, _query); - }; + return offset; +}; - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, Year, 'other'); - return this._year - other._year; - }; - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - requireInstance(other, Year, 'other'); - return this._year > other._year; - }; +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ +Reader.prototype.readSequence = function (tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== undefined && tag !== seq) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + seq.toString(16)); - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - requireInstance(other, Year, 'other'); - return this._year < other._year; - }; + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.format(this); - }; + this._offset = o; + return seq; +}; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - if (other instanceof Year) { - return this.value() === other.value(); - } +Reader.prototype.readInt = function () { + return this._readTag(ASN1.Integer); +}; - return false; - }; - _proto.toString = function toString() { - return '' + this._year; - }; +Reader.prototype.readBoolean = function () { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; - _proto.toJSON = function toJSON() { - return this.toString(); - }; - _proto.until = function until(endExclusive, unit) { - var end = Year.from(endExclusive); +Reader.prototype.readEnumeration = function () { + return this._readTag(ASN1.Enumeration); +}; - if (unit instanceof ChronoUnit) { - var yearsUntil = end.value() - this.value(); - switch (unit) { - case ChronoUnit.YEARS: - return yearsUntil; +Reader.prototype.readString = function (tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; - case ChronoUnit.DECADES: - return MathUtil.intDiv(yearsUntil, 10); + var b = this.peek(); + if (b === null) + return null; - case ChronoUnit.CENTURIES: - return MathUtil.intDiv(yearsUntil, 100); + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - case ChronoUnit.MILLENNIA: - return MathUtil.intDiv(yearsUntil, 1000); + var o = this.readLength(this._offset + 1); // stored in `length` - case ChronoUnit.ERAS: - return end.getLong(ChronoField.ERA) - this.getLong(ChronoField.ERA); - } + if (o === null) + return null; - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } + if (this.length > this._size - o) + return null; - return unit.between(this, end); - }; + this._offset = o; - return Year; - }(Temporal); - var PARSER$2; - function _init$d() { - Year.MIN_VALUE = YearConstants.MIN_VALUE; - Year.MAX_VALUE = YearConstants.MAX_VALUE; - PARSER$2 = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).toFormatter(); - Year.FROM = createTemporalQuery('Year.FROM', function (temporal) { - return Year.from(temporal); - }); - } + if (this.length === 0) + return retbuf ? Buffer.alloc(0) : ''; - var TemporalAdjusters = function () { - function TemporalAdjusters() {} + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; - TemporalAdjusters.firstDayOfMonth = function firstDayOfMonth() { - return Impl.FIRST_DAY_OF_MONTH; - }; + return retbuf ? str : str.toString('utf8'); +}; - TemporalAdjusters.lastDayOfMonth = function lastDayOfMonth() { - return Impl.LAST_DAY_OF_MONTH; - }; +Reader.prototype.readOID = function (tag) { + if (!tag) + tag = ASN1.OID; - TemporalAdjusters.firstDayOfNextMonth = function firstDayOfNextMonth() { - return Impl.FIRST_DAY_OF_NEXT_MONTH; - }; + var b = this.readString(tag, true); + if (b === null) + return null; - TemporalAdjusters.firstDayOfYear = function firstDayOfYear() { - return Impl.FIRST_DAY_OF_YEAR; - }; + var values = []; + var value = 0; - TemporalAdjusters.lastDayOfYear = function lastDayOfYear() { - return Impl.LAST_DAY_OF_YEAR; - }; + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; - TemporalAdjusters.firstDayOfNextYear = function firstDayOfNextYear() { - return Impl.FIRST_DAY_OF_NEXT_YEAR; - }; + value <<= 7; + value += byte & 0x7f; + if ((byte & 0x80) === 0) { + values.push(value); + value = 0; + } + } - TemporalAdjusters.firstInMonth = function firstInMonth(dayOfWeek) { - requireNonNull(dayOfWeek, 'dayOfWeek'); - return new DayOfWeekInMonth(1, dayOfWeek); - }; + value = values.shift(); + values.unshift(value % 40); + values.unshift((value / 40) >> 0); - TemporalAdjusters.lastInMonth = function lastInMonth(dayOfWeek) { - requireNonNull(dayOfWeek, 'dayOfWeek'); - return new DayOfWeekInMonth(-1, dayOfWeek); - }; + return values.join('.'); +}; - TemporalAdjusters.dayOfWeekInMonth = function dayOfWeekInMonth(ordinal, dayOfWeek) { - requireNonNull(dayOfWeek, 'dayOfWeek'); - return new DayOfWeekInMonth(ordinal, dayOfWeek); - }; - TemporalAdjusters.next = function next(dayOfWeek) { - return new RelativeDayOfWeek(2, dayOfWeek); - }; +Reader.prototype._readTag = function (tag) { + assert.ok(tag !== undefined); - TemporalAdjusters.nextOrSame = function nextOrSame(dayOfWeek) { - return new RelativeDayOfWeek(0, dayOfWeek); - }; + var b = this.peek(); - TemporalAdjusters.previous = function previous(dayOfWeek) { - return new RelativeDayOfWeek(3, dayOfWeek); - }; + if (b === null) + return null; - TemporalAdjusters.previousOrSame = function previousOrSame(dayOfWeek) { - return new RelativeDayOfWeek(1, dayOfWeek); - }; + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - return TemporalAdjusters; - }(); + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - var Impl = function (_TemporalAdjuster) { - _inheritsLoose(Impl, _TemporalAdjuster); + if (this.length > 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); - function Impl(ordinal) { - var _this; + if (this.length > this._size - o) + return null; + this._offset = o; - _this = _TemporalAdjuster.call(this) || this; - _this._ordinal = ordinal; - return _this; - } + var fb = this._buf[this._offset]; + var value = 0; - var _proto = Impl.prototype; + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); + } - _proto.adjustInto = function adjustInto(temporal) { - switch (this._ordinal) { - case 0: - return temporal.with(ChronoField.DAY_OF_MONTH, 1); + if ((fb & 0x80) === 0x80 && i !== 4) + value -= (1 << (i * 8)); - case 1: - return temporal.with(ChronoField.DAY_OF_MONTH, temporal.range(ChronoField.DAY_OF_MONTH).maximum()); + return value >> 0; +}; - case 2: - return temporal.with(ChronoField.DAY_OF_MONTH, 1).plus(1, ChronoUnit.MONTHS); - case 3: - return temporal.with(ChronoField.DAY_OF_YEAR, 1); - case 4: - return temporal.with(ChronoField.DAY_OF_YEAR, temporal.range(ChronoField.DAY_OF_YEAR).maximum()); +// --- Exported API - case 5: - return temporal.with(ChronoField.DAY_OF_YEAR, 1).plus(1, ChronoUnit.YEARS); - } +module.exports = Reader; - throw new IllegalStateException('Unreachable'); - }; - return Impl; - }(TemporalAdjuster); +/***/ }), - Impl.FIRST_DAY_OF_MONTH = new Impl(0); - Impl.LAST_DAY_OF_MONTH = new Impl(1); - Impl.FIRST_DAY_OF_NEXT_MONTH = new Impl(2); - Impl.FIRST_DAY_OF_YEAR = new Impl(3); - Impl.LAST_DAY_OF_YEAR = new Impl(4); - Impl.FIRST_DAY_OF_NEXT_YEAR = new Impl(5); +/***/ 42473: +/***/ ((module) => { - var DayOfWeekInMonth = function (_TemporalAdjuster2) { - _inheritsLoose(DayOfWeekInMonth, _TemporalAdjuster2); +// Copyright 2011 Mark Cavage All rights reserved. - function DayOfWeekInMonth(ordinal, dow) { - var _this2; - _this2 = _TemporalAdjuster2.call(this) || this; - _this2._ordinal = ordinal; - _this2._dowValue = dow.value(); - return _this2; - } +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; + + +/***/ }), + +/***/ 43200: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var _proto2 = DayOfWeekInMonth.prototype; +// Copyright 2011 Mark Cavage All rights reserved. - _proto2.adjustInto = function adjustInto(temporal) { - if (this._ordinal >= 0) { - var temp = temporal.with(ChronoField.DAY_OF_MONTH, 1); - var curDow = temp.get(ChronoField.DAY_OF_WEEK); - var dowDiff = MathUtil.intMod(this._dowValue - curDow + 7, 7); - dowDiff += (this._ordinal - 1) * 7; - return temp.plus(dowDiff, ChronoUnit.DAYS); - } else { - var _temp = temporal.with(ChronoField.DAY_OF_MONTH, temporal.range(ChronoField.DAY_OF_MONTH).maximum()); +var assert = __nccwpck_require__(42357); +var Buffer = __nccwpck_require__(15118).Buffer; +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); - var _curDow = _temp.get(ChronoField.DAY_OF_WEEK); - var daysDiff = this._dowValue - _curDow; - daysDiff = daysDiff === 0 ? 0 : daysDiff > 0 ? daysDiff - 7 : daysDiff; - daysDiff -= (-this._ordinal - 1) * 7; - return _temp.plus(daysDiff, ChronoUnit.DAYS); - } - }; +// --- Globals - return DayOfWeekInMonth; - }(TemporalAdjuster); +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - var RelativeDayOfWeek = function (_TemporalAdjuster3) { - _inheritsLoose(RelativeDayOfWeek, _TemporalAdjuster3); +var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; - function RelativeDayOfWeek(relative, dayOfWeek) { - var _this3; - _this3 = _TemporalAdjuster3.call(this) || this; - requireNonNull(dayOfWeek, 'dayOfWeek'); - _this3._relative = relative; - _this3._dowValue = dayOfWeek.value(); - return _this3; - } +// --- Helpers - var _proto3 = RelativeDayOfWeek.prototype; +function merge(from, to) { + assert.ok(from); + assert.equal(typeof (from), 'object'); + assert.ok(to); + assert.equal(typeof (to), 'object'); - _proto3.adjustInto = function adjustInto(temporal) { - var calDow = temporal.get(ChronoField.DAY_OF_WEEK); + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function (key) { + if (to[key]) + return; - if (this._relative < 2 && calDow === this._dowValue) { - return temporal; - } + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); + }); - if ((this._relative & 1) === 0) { - var daysDiff = calDow - this._dowValue; - return temporal.plus(daysDiff >= 0 ? 7 - daysDiff : -daysDiff, ChronoUnit.DAYS); - } else { - var _daysDiff = this._dowValue - calDow; + return to; +} - return temporal.minus(_daysDiff >= 0 ? 7 - _daysDiff : -_daysDiff, ChronoUnit.DAYS); - } - }; - return RelativeDayOfWeek; - }(TemporalAdjuster); - var IsoChronology = function (_Enum) { - _inheritsLoose(IsoChronology, _Enum); +// --- API - function IsoChronology() { - return _Enum.apply(this, arguments) || this; - } +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); - IsoChronology.isLeapYear = function isLeapYear(prolepticYear) { - return (prolepticYear & 3) === 0 && (prolepticYear % 100 !== 0 || prolepticYear % 400 === 0); - }; + this._buf = Buffer.alloc(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; - var _proto = IsoChronology.prototype; + // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. + this._seq = []; +} - _proto._updateResolveMap = function _updateResolveMap(fieldValues, field, value) { - requireNonNull(fieldValues, 'fieldValues'); - requireNonNull(field, 'field'); - var current = fieldValues.get(field); +Object.defineProperty(Writer.prototype, 'buffer', { + get: function () { + if (this._seq.length) + throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); - if (current != null && current !== value) { - throw new DateTimeException('Invalid state, field: ' + field + ' ' + current + ' conflicts with ' + field + ' ' + value); - } + return (this._buf.slice(0, this._offset)); + } +}); - fieldValues.put(field, value); - }; +Writer.prototype.writeByte = function (b) { + if (typeof (b) !== 'number') + throw new TypeError('argument must be a Number'); - _proto.resolveDate = function resolveDate(fieldValues, resolverStyle) { - if (fieldValues.containsKey(ChronoField.EPOCH_DAY)) { - return LocalDate.ofEpochDay(fieldValues.remove(ChronoField.EPOCH_DAY)); - } + this._ensure(1); + this._buf[this._offset++] = b; +}; - var prolepticMonth = fieldValues.remove(ChronoField.PROLEPTIC_MONTH); - if (prolepticMonth != null) { - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.PROLEPTIC_MONTH.checkValidValue(prolepticMonth); - } +Writer.prototype.writeInt = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Integer; - this._updateResolveMap(fieldValues, ChronoField.MONTH_OF_YEAR, MathUtil.floorMod(prolepticMonth, 12) + 1); + var sz = 4; - this._updateResolveMap(fieldValues, ChronoField.YEAR, MathUtil.floorDiv(prolepticMonth, 12)); - } + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; + } - var yoeLong = fieldValues.remove(ChronoField.YEAR_OF_ERA); + if (sz > 4) + throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - if (yoeLong != null) { - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.YEAR_OF_ERA.checkValidValue(yoeLong); - } + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; - var era = fieldValues.remove(ChronoField.ERA); + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; + } - if (era == null) { - var year = fieldValues.get(ChronoField.YEAR); +}; - if (resolverStyle === ResolverStyle.STRICT) { - if (year != null) { - this._updateResolveMap(fieldValues, ChronoField.YEAR, year > 0 ? yoeLong : MathUtil.safeSubtract(1, yoeLong)); - } else { - fieldValues.put(ChronoField.YEAR_OF_ERA, yoeLong); - } - } else { - this._updateResolveMap(fieldValues, ChronoField.YEAR, year == null || year > 0 ? yoeLong : MathUtil.safeSubtract(1, yoeLong)); - } - } else if (era === 1) { - this._updateResolveMap(fieldValues, ChronoField.YEAR, yoeLong); - } else if (era === 0) { - this._updateResolveMap(fieldValues, ChronoField.YEAR, MathUtil.safeSubtract(1, yoeLong)); - } else { - throw new DateTimeException('Invalid value for era: ' + era); - } - } else if (fieldValues.containsKey(ChronoField.ERA)) { - ChronoField.ERA.checkValidValue(fieldValues.get(ChronoField.ERA)); - } - if (fieldValues.containsKey(ChronoField.YEAR)) { - if (fieldValues.containsKey(ChronoField.MONTH_OF_YEAR)) { - if (fieldValues.containsKey(ChronoField.DAY_OF_MONTH)) { - var y = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); - var moy = fieldValues.remove(ChronoField.MONTH_OF_YEAR); - var dom = fieldValues.remove(ChronoField.DAY_OF_MONTH); +Writer.prototype.writeNull = function () { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; - if (resolverStyle === ResolverStyle.LENIENT) { - var months = moy - 1; - var days = dom - 1; - return LocalDate.of(y, 1, 1).plusMonths(months).plusDays(days); - } else if (resolverStyle === ResolverStyle.SMART) { - ChronoField.DAY_OF_MONTH.checkValidValue(dom); - if (moy === 4 || moy === 6 || moy === 9 || moy === 11) { - dom = Math.min(dom, 30); - } else if (moy === 2) { - dom = Math.min(dom, Month.FEBRUARY.length(Year.isLeap(y))); - } +Writer.prototype.writeEnumeration = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Enumeration; - return LocalDate.of(y, moy, dom); - } else { - return LocalDate.of(y, moy, dom); - } - } - } + return this.writeInt(i, tag); +}; - if (fieldValues.containsKey(ChronoField.DAY_OF_YEAR)) { - var _y = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); - if (resolverStyle === ResolverStyle.LENIENT) { - var _days = MathUtil.safeSubtract(fieldValues.remove(ChronoField.DAY_OF_YEAR), 1); +Writer.prototype.writeBoolean = function (b, tag) { + if (typeof (b) !== 'boolean') + throw new TypeError('argument must be a Boolean'); + if (typeof (tag) !== 'number') + tag = ASN1.Boolean; - return LocalDate.ofYearDay(_y, 1).plusDays(_days); - } + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; - var doy = ChronoField.DAY_OF_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.DAY_OF_YEAR)); - return LocalDate.ofYearDay(_y, doy); - } - if (fieldValues.containsKey(ChronoField.ALIGNED_WEEK_OF_YEAR)) { - if (fieldValues.containsKey(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)) { - var _y2 = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); +Writer.prototype.writeString = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); + if (typeof (tag) !== 'number') + tag = ASN1.OctetString; - if (resolverStyle === ResolverStyle.LENIENT) { - var weeks = MathUtil.safeSubtract(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR), 1); + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; + } +}; - var _days2 = MathUtil.safeSubtract(fieldValues.remove(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), 1); - return LocalDate.of(_y2, 1, 1).plusWeeks(weeks).plusDays(_days2); - } +Writer.prototype.writeBuffer = function (buf, tag) { + if (typeof (tag) !== 'number') + throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) + throw new TypeError('argument must be a buffer'); - var aw = ChronoField.ALIGNED_WEEK_OF_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR)); - var ad = ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); - var date = LocalDate.of(_y2, 1, 1).plusDays((aw - 1) * 7 + (ad - 1)); + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; - if (resolverStyle === ResolverStyle.STRICT && date.get(ChronoField.YEAR) !== _y2) { - throw new DateTimeException('Strict mode rejected date parsed to a different year'); - } - return date; - } +Writer.prototype.writeStringArray = function (strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); - if (fieldValues.containsKey(ChronoField.DAY_OF_WEEK)) { - var _y3 = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); + var self = this; + strings.forEach(function (s) { + self.writeString(s); + }); +}; - if (resolverStyle === ResolverStyle.LENIENT) { - var _weeks = MathUtil.safeSubtract(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR), 1); +// This is really to solve DER cases, but whatever for now +Writer.prototype.writeOID = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string'); + if (typeof (tag) !== 'number') + tag = ASN1.OID; + + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); + + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push((octet >>> 7) | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push((octet >>> 14) | 0x80); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push((octet >>> 21) | 0x80); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push(((octet >>> 28) | 0x80) & 0xFF); + bytes.push(((octet >>> 21) | 0x80) & 0xFF); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } + } - var _days3 = MathUtil.safeSubtract(fieldValues.remove(ChronoField.DAY_OF_WEEK), 1); + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function (b) { + encodeOctet(bytes, parseInt(b, 10)); + }); - return LocalDate.of(_y3, 1, 1).plusWeeks(_weeks).plusDays(_days3); - } + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function (b) { + self.writeByte(b); + }); +}; - var _aw = ChronoField.ALIGNED_WEEK_OF_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR)); - var dow = ChronoField.DAY_OF_WEEK.checkValidIntValue(fieldValues.remove(ChronoField.DAY_OF_WEEK)); +Writer.prototype.writeLength = function (len) { + if (typeof (len) !== 'number') + throw new TypeError('argument must be a Number'); - var _date = LocalDate.of(_y3, 1, 1).plusWeeks(_aw - 1).with(TemporalAdjusters.nextOrSame(DayOfWeek.of(dow))); + this._ensure(4); - if (resolverStyle === ResolverStyle.STRICT && _date.get(ChronoField.YEAR) !== _y3) { - throw new DateTimeException('Strict mode rejected date parsed to a different month'); - } + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw newInvalidAsn1Error('Length too long (> 4 bytes)'); + } +}; + +Writer.prototype.startSequence = function (tag) { + if (typeof (tag) !== 'number') + tag = ASN1.Sequence | ASN1.Constructor; + + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; +}; + + +Writer.prototype.endSequence = function () { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; + + if (len <= 0x7f) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw newInvalidAsn1Error('Sequence too long'); + } +}; - return _date; - } - } - } - return null; - }; +Writer.prototype._shift = function (start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); - _proto.date = function date(temporal) { - return LocalDate.from(temporal); - }; + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; - return IsoChronology; - }(Enum); - function _init$e() { - IsoChronology.INSTANCE = new IsoChronology('IsoChronology'); - } +Writer.prototype._ensure = function (len) { + assert.ok(len); - var OffsetTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(OffsetTime, _DefaultInterfaceTemp); + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; - OffsetTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); + var buf = Buffer.alloc(sz); - if (temporal instanceof OffsetTime) { - return temporal; - } else if (temporal instanceof OffsetDateTime) { - return temporal.toOffsetTime(); - } + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; + } +}; - try { - var time = LocalTime.from(temporal); - var offset = ZoneOffset.from(temporal); - return new OffsetTime(time, offset); - } catch (ex) { - throw new DateTimeException("Unable to obtain OffsetTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } - }; - OffsetTime.now = function now(clockOrZone) { - if (arguments.length === 0) { - return OffsetTime._now(Clock.systemDefaultZone()); - } else if (clockOrZone instanceof Clock) { - return OffsetTime._now(clockOrZone); - } else { - return OffsetTime._now(Clock.system(clockOrZone)); - } - }; - OffsetTime._now = function _now(clock) { - requireNonNull(clock, 'clock'); - var now = clock.instant(); - return OffsetTime.ofInstant(now, clock.zone().rules().offset(now)); - }; +// --- Exported API - OffsetTime.of = function of() { - if (arguments.length <= 2) { - return OffsetTime.ofTimeAndOffset.apply(this, arguments); - } else { - return OffsetTime.ofNumbers.apply(this, arguments); - } - }; +module.exports = Writer; - OffsetTime.ofNumbers = function ofNumbers(hour, minute, second, nanoOfSecond, offset) { - var time = LocalTime.of(hour, minute, second, nanoOfSecond); - return new OffsetTime(time, offset); - }; - OffsetTime.ofTimeAndOffset = function ofTimeAndOffset(time, offset) { - return new OffsetTime(time, offset); - }; +/***/ }), - OffsetTime.ofInstant = function ofInstant(instant, zone) { - requireNonNull(instant, 'instant'); - requireInstance(instant, Instant, 'instant'); - requireNonNull(zone, 'zone'); - requireInstance(zone, ZoneId, 'zone'); - var rules = zone.rules(); - var offset = rules.offset(instant); - var secsOfDay = instant.epochSecond() % LocalTime.SECONDS_PER_DAY; - secsOfDay = (secsOfDay + offset.totalSeconds()) % LocalTime.SECONDS_PER_DAY; +/***/ 80970: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (secsOfDay < 0) { - secsOfDay += LocalTime.SECONDS_PER_DAY; - } +// Copyright 2011 Mark Cavage All rights reserved. - var time = LocalTime.ofSecondOfDay(secsOfDay, instant.nano()); - return new OffsetTime(time, offset); - }; +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc - OffsetTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_OFFSET_TIME; - } +var Ber = __nccwpck_require__(194); - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, OffsetTime.FROM); - }; - function OffsetTime(time, offset) { - var _this; - _this = _DefaultInterfaceTemp.call(this) || this; - requireNonNull(time, 'time'); - requireInstance(time, LocalTime, 'time'); - requireNonNull(offset, 'offset'); - requireInstance(offset, ZoneOffset, 'offset'); - _this._time = time; - _this._offset = offset; - return _this; - } +// --- Exported API - var _proto = OffsetTime.prototype; +module.exports = { - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.NANO_OF_DAY, this._time.toNanoOfDay()).with(ChronoField.OFFSET_SECONDS, this.offset().totalSeconds()); - }; + Ber: Ber, - _proto.atDate = function atDate(date) { - return OffsetDateTime.of(date, this._time, this._offset); - }; + BerReader: Ber.Reader, - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this, OffsetTime.FROM); - }; + BerWriter: Ber.Writer - _proto.get = function get(field) { - return _DefaultInterfaceTemp.prototype.get.call(this, field); - }; +}; - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.OFFSET_SECONDS) { - return this._offset.totalSeconds(); - } - return this._time.getLong(field); - } +/***/ }), - return field.getFrom(this); - }; +/***/ 66631: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.hour = function hour() { - return this._time.hour(); - }; +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. - _proto.minute = function minute() { - return this._time.minute(); - }; +var assert = __nccwpck_require__(42357); +var Stream = __nccwpck_require__(92413).Stream; +var util = __nccwpck_require__(31669); - _proto.second = function second() { - return this._time.second(); - }; - _proto.nano = function nano() { - return this._time.nano(); - }; +///--- Globals - _proto.offset = function offset() { - return this._offset; - }; +/* JSSTYLED */ +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - return this._toEpochNano() > other._toEpochNano(); - }; - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - return this._toEpochNano() < other._toEpochNano(); - }; +///--- Internal - _proto.isEqual = function isEqual(other) { - requireNonNull(other, 'other'); - return this._toEpochNano() === other._toEpochNano(); - }; +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); +} - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isTimeBased() || fieldOrUnit === ChronoField.OFFSET_SECONDS; - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isTimeBased(); - } +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: (actual === undefined) ? typeof (arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); +} - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); +} - _proto.minusHours = function minusHours(hours) { - return this._withLocalTimeOffset(this._time.minusHours(hours), this._offset); - }; +function noop() { + // Why even bother with asserts? +} - _proto.minusMinutes = function minusMinutes(minutes) { - return this._withLocalTimeOffset(this._time.minusMinutes(minutes), this._offset); - }; - _proto.minusSeconds = function minusSeconds(seconds) { - return this._withLocalTimeOffset(this._time.minusSeconds(seconds), this._offset); - }; +///--- Exports - _proto.minusNanos = function minusNanos(nanos) { - return this._withLocalTimeOffset(this._time.minusNanos(nanos), this._offset); - }; +var types = { + bool: { + check: function (arg) { return typeof (arg) === 'boolean'; } + }, + func: { + check: function (arg) { return typeof (arg) === 'function'; } + }, + string: { + check: function (arg) { return typeof (arg) === 'string'; } + }, + object: { + check: function (arg) { + return typeof (arg) === 'object' && arg !== null; + } + }, + number: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg); + } + }, + finite: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function (arg) { return Buffer.isBuffer(arg); }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function (arg) { return Array.isArray(arg); }, + operator: 'Array.isArray' + }, + stream: { + check: function (arg) { return arg instanceof Stream; }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function (arg) { return arg instanceof Date; }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function (arg) { return arg instanceof RegExp; }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function (arg) { + return typeof (arg) === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' + } +}; - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount); - return amount.subtractFrom(this); - }; +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plus(-1 * amountToSubtract, unit); - }; + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount); - return amount.addTo(this); - }; + /* standard checks */ + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; + } + var type = types[k]; + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - if (unit instanceof ChronoUnit) { - return this._withLocalTimeOffset(this._time.plus(amountToAdd, unit), this._offset); + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); - return unit.addTo(this, amountToAdd); - }; + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); - _proto.plusHours = function plusHours(hours) { - return this._withLocalTimeOffset(this._time.plusHours(hours), this._offset); - }; + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); - _proto.plusMinutes = function plusMinutes(minutes) { - return this._withLocalTimeOffset(this._time.plusMinutes(minutes), this._offset); - }; + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); - _proto.plusSeconds = function plusSeconds(seconds) { - return this._withLocalTimeOffset(this._time.plusSeconds(seconds), this._offset); - }; + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; - _proto.plusNanos = function plusNanos(nanos) { - return this._withLocalTimeOffset(this._time.plusNanos(nanos), this._offset); - }; + return out; +} - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); +module.exports = _setExports(process.env.NODE_NDEBUG); - if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.offset() || _query === TemporalQueries.zone()) { - return this.offset(); - } else if (_query === TemporalQueries.localTime()) { - return this._time; - } else if (_query === TemporalQueries.chronology() || _query === TemporalQueries.localDate() || _query === TemporalQueries.zoneId()) { - return null; - } - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; +/***/ }), - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.OFFSET_SECONDS) { - return field.range(); - } +/***/ 57888: +/***/ (function(__unused_webpack_module, exports) { - return this._time.range(field); - } +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; - return field.rangeRefinedBy(this); - }; + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } - _proto.toLocalTime = function toLocalTime() { - return this._time; - }; + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } - _proto.truncatedTo = function truncatedTo(unit) { - return this._withLocalTimeOffset(this._time.truncatedTo(unit), this._offset); - }; + /* istanbul ignore file */ - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = OffsetTime.from(endExclusive); + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - if (unit instanceof ChronoUnit) { - var nanosUntil = end._toEpochNano() - this._toEpochNano(); + function fallback(fn) { + setTimeout(fn, 0); + } - switch (unit) { - case ChronoUnit.NANOS: - return nanosUntil; + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } - case ChronoUnit.MICROS: - return Math.floor(nanosUntil / 1000); + var _defer; - case ChronoUnit.MILLIS: - return Math.floor(nanosUntil / 1000000); + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback; + } - case ChronoUnit.SECONDS: - return Math.floor(nanosUntil / LocalTime.NANOS_PER_SECOND); + var setImmediate$1 = wrap(_defer); - case ChronoUnit.MINUTES: - return Math.floor(nanosUntil / LocalTime.NANOS_PER_MINUTE); + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } - case ChronoUnit.HOURS: - return Math.floor(nanosUntil / LocalTime.NANOS_PER_HOUR); + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); + } - case ChronoUnit.HALF_DAYS: - return Math.floor(nanosUntil / (12 * LocalTime.NANOS_PER_HOUR)); - } + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); + } - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); } + } - return unit.between(this, end); - }; - - _proto.withHour = function withHour(hour) { - return this._withLocalTimeOffset(this._time.withHour(hour), this._offset); - }; + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } - _proto.withMinute = function withMinute(minute) { - return this._withLocalTimeOffset(this._time.withMinute(minute), this._offset); - }; + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } - _proto.withSecond = function withSecond(second) { - return this._withLocalTimeOffset(this._time.withSecond(second), this._offset); - }; + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } - _proto.withNano = function withNano(nano) { - return this._withLocalTimeOffset(this._time.withNano(nano), this._offset); - }; + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } - _proto.withOffsetSameInstant = function withOffsetSameInstant(offset) { - requireNonNull(offset, 'offset'); + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity = asyncFn.length) { + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } - if (offset.equals(this._offset)) { - return this; + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) } - var difference = offset.totalSeconds() - this._offset.totalSeconds(); - - var adjusted = this._time.plusSeconds(difference); + return awaitable + } - return new OffsetTime(adjusted, offset); - }; + function applyEach (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } - _proto.withOffsetSameLocal = function withOffsetSameLocal(offset) { - return offset != null && offset.equals(this._offset) ? this : new OffsetTime(this._time, offset); - }; + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); - _proto._toEpochNano = function _toEpochNano() { - var nod = this._time.toNanoOfDay(); + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } - var offsetNanos = this._offset.totalSeconds() * LocalTime.NANOS_PER_SECOND; - return nod - offsetNanos; - }; + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; - if (adjuster instanceof LocalTime) { - return this._withLocalTimeOffset(adjuster, this._offset); - } else if (adjuster instanceof ZoneOffset) { - return this._withLocalTimeOffset(this._time, adjuster); - } else if (adjuster instanceof OffsetTime) { - return adjuster; + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); } + Object.assign(wrapper, fn); + return wrapper + } - return adjuster.adjustInto(this); - }; - - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } - if (field instanceof ChronoField) { - if (field === ChronoField.OFFSET_SECONDS) { - return this._withLocalTimeOffset(this._time, ZoneOffset.ofTotalSeconds(field.checkValidIntValue(newValue))); - } + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } - return this._withLocalTimeOffset(this._time.with(field, newValue), this._offset); + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; } + } - return field.adjustInto(this, newValue); - }; + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? {value: obj[key], key} : null; + }; + } - _proto._withLocalTimeOffset = function _withLocalTimeOffset(time, offset) { - if (this._time === time && this._offset.equals(offset)) { - return this; + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); } - return new OffsetTime(time, offset); - }; + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, OffsetTime, 'other'); + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } - if (this._offset.equals(other._offset)) { - return this._time.compareTo(other._time); + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); } - var compare = MathUtil.compareNumbers(this._toEpochNano(), other._toEpochNano()); - - if (compare === 0) { - return this._time.compareTo(other._time); - } + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) - return compare; - }; + if (err === false) { + done = true; + canceled = true; + return + } - _proto.equals = function equals(other) { - if (this === other) { - return true; + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); } - if (other instanceof OffsetTime) { - return this._time.equals(other._time) && this._offset.equals(other._offset); + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); } - return false; - }; - - _proto.hashCode = function hashCode() { - return this._time.hashCode() ^ this._offset.hashCode(); - }; - - _proto.toString = function toString() { - return this._time.toString() + this._offset.toString(); - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return OffsetTime; - }(DefaultInterfaceTemporal); - function _init$f() { - OffsetTime.MIN = OffsetTime.ofNumbers(0, 0, 0, 0, ZoneOffset.MAX); - OffsetTime.MAX = OffsetTime.ofNumbers(23, 59, 59, 999999999, ZoneOffset.MIN); - OffsetTime.FROM = createTemporalQuery('OffsetTime.FROM', function (temporal) { - return OffsetTime.from(temporal); - }); + replenish(); } - var ChronoZonedDateTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(ChronoZonedDateTime, _DefaultInterfaceTemp); + var eachOfLimit = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } - function ChronoZonedDateTime() { - return _DefaultInterfaceTemp.apply(this, arguments) || this; - } + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } - var _proto = ChronoZonedDateTime.prototype; + replenish(); + }; + }; - _proto.query = function query(_query) { - if (_query === TemporalQueries.zoneId() || _query === TemporalQueries.zone()) { - return this.zone(); - } else if (_query === TemporalQueries.chronology()) { - return this.toLocalDate().chronology(); - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.offset()) { - return this.offset(); - } else if (_query === TemporalQueries.localDate()) { - return LocalDate.ofEpochDay(this.toLocalDate().toEpochDay()); - } else if (_query === TemporalQueries.localTime()) { - return this.toLocalTime(); + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); + } + + var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); } - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } - _proto.toInstant = function toInstant() { - return Instant.ofEpochSecond(this.toEpochSecond(), this.toLocalTime().nano()); - }; + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$2(coll, Infinity, iteratee, callback); + } - _proto.toEpochSecond = function toEpochSecond() { - var epochDay = this.toLocalDate().toEpochDay(); - var secs = epochDay * 86400 + this.toLocalTime().toSecondOfDay(); - secs -= this.offset().totalSeconds(); - return secs; - }; + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - var cmp = MathUtil.compareNumbers(this.toEpochSecond(), other.toEpochSecond()); + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach$1 = applyEach(map$1); - if (cmp === 0) { - cmp = this.toLocalTime().nano() - other.toLocalTime().nano(); + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$2(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); + + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach(mapSeries$1); - if (cmp === 0) { - cmp = this.toLocalDateTime().compareTo(other.toLocalDateTime()); + const PROMISE_SYMBOL = Symbol('promiseCallback'); - if (cmp === 0) { - cmp = strcmp(this.zone().id(), other.zone().id()); - } - } + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); } - return cmp; - }; - - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec > otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() > other.toLocalTime().nano(); - }; - - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec < otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() < other.toLocalTime().nano(); - }; + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); - _proto.isEqual = function isEqual(other) { - requireNonNull(other, 'other'); - return this.toEpochSecond() === other.toEpochSecond() && this.toLocalTime().nano() === other.toLocalTime().nano(); - }; + return callback + } - _proto.equals = function equals(other) { - if (this === other) { - return true; + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); } - - if (other instanceof ChronoZonedDateTime) { - return this.compareTo(other) === 0; + if (!concurrency) { + concurrency = numTasks; } - return false; - }; + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; - return ChronoZonedDateTime; - }(DefaultInterfaceTemporal); + var listeners = Object.create(null); - function strcmp(a, b) { - if (a < b) { - return -1; - } + var readyTasks = []; - if (a > b) { - return 1; - } + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; - return 0; - } + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } - var ZonedDateTime = function (_ChronoZonedDateTime) { - _inheritsLoose(ZonedDateTime, _ChronoZonedDateTime); + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); - ZonedDateTime.now = function now(clockOrZone) { - var clock; + checkForDeadlocks(); + processQueue(); - if (clockOrZone instanceof ZoneId) { - clock = Clock.system(clockOrZone); - } else { - clock = clockOrZone == null ? Clock.systemDefaultZone() : clockOrZone; + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); } - return ZonedDateTime.ofInstant(clock.instant(), clock.zone()); - }; + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } - ZonedDateTime.of = function of() { - if (arguments.length <= 2) { - return ZonedDateTime.of2.apply(this, arguments); - } else if (arguments.length === 3 && arguments[0] instanceof LocalDate) { - return ZonedDateTime.of3.apply(this, arguments); - } else { - return ZonedDateTime.of8.apply(this, arguments); } - }; - ZonedDateTime.of3 = function of3(date, time, zone) { - return ZonedDateTime.of2(LocalDateTime.of(date, time), zone); - }; + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } - ZonedDateTime.of2 = function of2(localDateTime, zone) { - return ZonedDateTime.ofLocal(localDateTime, zone, null); - }; + taskListeners.push(fn); + } - ZonedDateTime.of8 = function of8(year, month, dayOfMonth, hour, minute, second, nanoOfSecond, zone) { - var dt = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond); - return ZonedDateTime.ofLocal(dt, zone, null); - }; - - ZonedDateTime.ofLocal = function ofLocal(localDateTime, zone, preferredOffset) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(zone, 'zone'); - - if (zone instanceof ZoneOffset) { - return new ZonedDateTime(localDateTime, zone, zone); + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); } - var offset = null; - var rules = zone.rules(); - var validOffsets = rules.validOffsets(localDateTime); - if (validOffsets.length === 1) { - offset = validOffsets[0]; - } else if (validOffsets.length === 0) { - var trans = rules.transition(localDateTime); - localDateTime = localDateTime.plusSeconds(trans.duration().seconds()); - offset = trans.offsetAfter(); - } else { - if (preferredOffset != null && validOffsets.some(function (validOffset) { - return validOffset.equals(preferredOffset); - })) { - offset = preferredOffset; - } else { - offset = requireNonNull(validOffsets[0], 'offset'); - } - } + function runTask(key, task) { + if (hasError) return; - return new ZonedDateTime(localDateTime, offset, zone); - }; + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); - ZonedDateTime.ofInstant = function ofInstant() { - if (arguments.length === 2) { - return ZonedDateTime.ofInstant2.apply(this, arguments); - } else { - return ZonedDateTime.ofInstant3.apply(this, arguments); + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } } - }; - - ZonedDateTime.ofInstant2 = function ofInstant2(instant, zone) { - requireNonNull(instant, 'instant'); - requireNonNull(zone, 'zone'); - return ZonedDateTime._create(instant.epochSecond(), instant.nano(), zone); - }; - - ZonedDateTime.ofInstant3 = function ofInstant3(localDateTime, offset, zone) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); - return ZonedDateTime._create(localDateTime.toEpochSecond(offset), localDateTime.nano(), zone); - }; - - ZonedDateTime._create = function _create(epochSecond, nanoOfSecond, zone) { - var rules = zone.rules(); - var instant = Instant.ofEpochSecond(epochSecond, nanoOfSecond); - var offset = rules.offset(instant); - var ldt = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset); - return new ZonedDateTime(ldt, offset, zone); - }; - - ZonedDateTime.ofStrict = function ofStrict(localDateTime, offset, zone) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); - var rules = zone.rules(); - if (rules.isValidOffset(localDateTime, offset) === false) { - var trans = rules.transition(localDateTime); + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } - if (trans != null && trans.isGap()) { - throw new DateTimeException('LocalDateTime ' + localDateTime + ' does not exist in zone ' + zone + ' due to a gap in the local time-line, typically caused by daylight savings'); - } + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } - throw new DateTimeException('ZoneOffset "' + offset + '" is not valid for LocalDateTime "' + localDateTime + '" in zone "' + zone + '"'); + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; } - return new ZonedDateTime(localDateTime, offset, zone); - }; + return callback[PROMISE_SYMBOL] + } - ZonedDateTime.ofLenient = function ofLenient(localDateTime, offset, zone) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - if (zone instanceof ZoneOffset && offset.equals(zone) === false) { - throw new IllegalArgumentException('ZoneId must match ZoneOffset'); + function parseParams(func) { + const src = func.toString().replace(STRIP_COMMENTS, ''); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } - return new ZonedDateTime(localDateTime, offset, zone); - }; + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } - ZonedDateTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); + // remove callback param + if (!fnIsAsync) params.pop(); - if (temporal instanceof ZonedDateTime) { - return temporal; - } + newTasks[key] = params.concat(newTask); + } - var zone = ZoneId.from(temporal); + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); - if (temporal.isSupported(ChronoField.INSTANT_SECONDS)) { - var zdt = ZonedDateTime._from(temporal, zone); + return auto(newTasks, callback); + } - if (zdt != null) return zdt; + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; } - var ldt = LocalDateTime.from(temporal); - return ZonedDateTime.of2(ldt, zone); - }; + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; - ZonedDateTime._from = function _from(temporal, zone) { - try { - return ZonedDateTime.__from(temporal, zone); - } catch (ex) { - if (!(ex instanceof DateTimeException)) throw ex; + node.prev = node.next = null; + this.length -= 1; + return node; } - }; - - ZonedDateTime.__from = function __from(temporal, zone) { - var epochSecond = temporal.getLong(ChronoField.INSTANT_SECONDS); - var nanoOfSecond = temporal.get(ChronoField.NANO_OF_SECOND); - return ZonedDateTime._create(epochSecond, nanoOfSecond, zone); - }; - ZonedDateTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; + empty () { + while(this.head) this.shift(); + return this; } - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, ZonedDateTime.FROM); - }; - - function ZonedDateTime(dateTime, offset, zone) { - var _this; + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } - requireNonNull(dateTime, 'dateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); - _this = _ChronoZonedDateTime.call(this) || this; - _this._dateTime = dateTime; - _this._offset = offset; - _this._zone = zone; - return _this; - } + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } - var _proto = ZonedDateTime.prototype; + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } - _proto._resolveLocal = function _resolveLocal(newDateTime) { - requireNonNull(newDateTime, 'newDateTime'); - return ZonedDateTime.ofLocal(newDateTime, this._zone, this._offset); - }; + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } - _proto._resolveInstant = function _resolveInstant(newDateTime) { - return ZonedDateTime.ofInstant3(newDateTime, this._offset, this._zone); - }; + shift() { + return this.head && this.removeLink(this.head); + } - _proto._resolveOffset = function _resolveOffset(offset) { - if (offset.equals(this._offset) === false && this._zone.rules().isValidOffset(this._dateTime, offset)) { - return new ZonedDateTime(this._dateTime, offset, this._zone); + pop() { + return this.tail && this.removeLink(this.tail); } - return this; - }; + toArray() { + return [...this] + } - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return true; - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } } - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.INSTANT_SECONDS || field === ChronoField.OFFSET_SECONDS) { - return field.range(); - } + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } - return this._dateTime.range(field); + function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); } - return field.rangeRefinedBy(this); - }; + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; - _proto.get = function get(field) { - return this.getLong(field); - }; + function on (event, handler) { + events[event].push(handler); + } - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - return this.toEpochSecond(); + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } - case ChronoField.OFFSET_SECONDS: - return this._offset.totalSeconds(); - } + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } - return this._dateTime.getLong(field); + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); } - requireNonNull(field, 'field'); - return field.getFrom(this); - }; + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } - _proto.offset = function offset() { - return this._offset; - }; + var item = { + data, + callback: rejectOnError ? + promiseCallback : + (callback || promiseCallback) + }; - _proto.withEarlierOffsetAtOverlap = function withEarlierOffsetAtOverlap() { - var trans = this._zone.rules().transition(this._dateTime); + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } - if (trans != null && trans.isOverlap()) { - var earlierOffset = trans.offsetBefore(); + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } - if (earlierOffset.equals(this._offset) === false) { - return new ZonedDateTime(this._dateTime, earlierOffset, this._zone); - } + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } } - return this; - }; - - _proto.withLaterOffsetAtOverlap = function withLaterOffsetAtOverlap() { - var trans = this._zone.rules().transition(this.toLocalDateTime()); - - if (trans != null) { - var laterOffset = trans.offsetAfter(); + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; - if (laterOffset.equals(this._offset) === false) { - return new ZonedDateTime(this._dateTime, laterOffset, this._zone); - } - } + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; - return this; - }; + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } - _proto.zone = function zone() { - return this._zone; - }; + task.callback(err, ...args); - _proto.withZoneSameLocal = function withZoneSameLocal(zone) { - requireNonNull(zone, 'zone'); - return this._zone.equals(zone) ? this : ZonedDateTime.ofLocal(this._dateTime, zone, this._offset); - }; + if (err != null) { + trigger('error', err, task.data); + } + } - _proto.withZoneSameInstant = function withZoneSameInstant(zone) { - requireNonNull(zone, 'zone'); - return this._zone.equals(zone) ? this : ZonedDateTime._create(this._dateTime.toEpochSecond(this._offset), this._dateTime.nano(), zone); - }; + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } - _proto.withFixedOffsetZone = function withFixedOffsetZone() { - return this._zone.equals(this._offset) ? this : new ZonedDateTime(this._dateTime, this._offset, this._offset); - }; + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } - _proto.year = function year() { - return this._dateTime.year(); - }; + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } - _proto.monthValue = function monthValue() { - return this._dateTime.monthValue(); - }; + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); - _proto.month = function month() { - return this._dateTime.month(); - }; + }; - _proto.dayOfMonth = function dayOfMonth() { - return this._dateTime.dayOfMonth(); - }; + var isProcessing = false; + var q = { + _tasks: new DLL(), + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } - _proto.dayOfYear = function dayOfYear() { - return this._dateTime.dayOfYear(); - }; + numRunning += 1; - _proto.dayOfWeek = function dayOfWeek() { - return this._dateTime.dayOfWeek(); - }; + if (q._tasks.length === 0) { + trigger('empty'); + } - _proto.hour = function hour() { - return this._dateTime.hour(); - }; + if (numRunning === q.concurrency) { + trigger('saturated'); + } - _proto.minute = function minute() { - return this._dateTime.minute(); - }; + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } - _proto.second = function second() { - return this._dateTime.second(); - }; + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); - _proto.nano = function nano() { - return this._dateTime.nano(); - }; + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; - _proto.withAdjuster = function withAdjuster(adjuster) { - if (adjuster instanceof LocalDate) { - return this._resolveLocal(LocalDateTime.of(adjuster, this._dateTime.toLocalTime())); - } else if (adjuster instanceof LocalTime) { - return this._resolveLocal(LocalDateTime.of(this._dateTime.toLocalDate(), adjuster)); - } else if (adjuster instanceof LocalDateTime) { - return this._resolveLocal(adjuster); - } else if (adjuster instanceof Instant) { - var instant = adjuster; - return ZonedDateTime._create(instant.epochSecond(), instant.nano(), this._zone); - } else if (adjuster instanceof ZoneOffset) { - return this._resolveOffset(adjuster); - } - - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } - _proto.withFieldValue = function withFieldValue(field, newValue) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - return ZonedDateTime._create(newValue, this.nano(), this._zone); + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); - case ChronoField.OFFSET_SECONDS: - { - var offset = ZoneOffset.ofTotalSeconds(field.checkValidIntValue(newValue)); - return this._resolveOffset(offset); - } - } + return cb[PROMISE_SYMBOL] + }; + } - return this._resolveLocal(this._dateTime.with(field, newValue)); - } + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); + } - return field.adjustInto(this, newValue); - }; + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } - _proto.withYear = function withYear(year) { - return this._resolveLocal(this._dateTime.withYear(year)); - }; + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); - _proto.withMonth = function withMonth(month) { - return this._resolveLocal(this._dateTime.withMonth(month)); - }; + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { + * // files is now a list of filenames that exist in the 3 directories + * }); + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - return this._resolveLocal(this._dateTime.withDayOfMonth(dayOfMonth)); - }; + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); + + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - return this._resolveLocal(this._dateTime.withDayOfYear(dayOfYear)); - }; + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); - _proto.withHour = function withHour(hour) { - return this._resolveLocal(this._dateTime.withHour(hour)); - }; + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } - _proto.withMinute = function withMinute(minute) { - return this._resolveLocal(this._dateTime.withMinute(minute)); - }; + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. - _proto.withSecond = function withSecond(second) { - return this._resolveLocal(this._dateTime.withSecond(second)); - }; + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); - _proto.withNano = function withNano(nanoOfSecond) { - return this._resolveLocal(this._dateTime.withNano(nanoOfSecond)); - }; + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + resultArgs.forEach(x => console[name](x)); + } + } + }) + } - _proto.truncatedTo = function truncatedTo(unit) { - return this._resolveLocal(this._dateTime.truncatedTo(unit)); - }; + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount); - return amount.addTo(this); - }; + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - if (unit instanceof ChronoUnit) { - if (unit.isDateBased()) { - return this._resolveLocal(this._dateTime.plus(amountToAdd, unit)); - } else { - return this._resolveInstant(this._dateTime.plus(amountToAdd, unit)); - } + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); } - requireNonNull(unit, 'unit'); - return unit.addTo(this, amountToAdd); - }; + return check(null, true); + } - _proto.plusYears = function plusYears(years) { - return this._resolveLocal(this._dateTime.plusYears(years)); - }; + var doWhilst$1 = awaitify(doWhilst, 3); - _proto.plusMonths = function plusMonths(months) { - return this._resolveLocal(this._dateTime.plusMonths(months)); - }; + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } + + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ + function eachLimit(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + + var each = awaitify(eachLimit, 3); + + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$2 = awaitify(eachLimit$1, 4); + + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$2(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); + + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } - _proto.plusWeeks = function plusWeeks(weeks) { - return this._resolveLocal(this._dateTime.plusWeeks(weeks)); - }; + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) + } + var every$1 = awaitify(every, 3); - _proto.plusDays = function plusDays(days) { - return this._resolveLocal(this._dateTime.plusDays(days)); - }; + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) + } + var everyLimit$1 = awaitify(everyLimit, 4); + + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } - _proto.plusHours = function plusHours(hours) { - return this._resolveInstant(this._dateTime.plusHours(hours)); - }; + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } - _proto.plusMinutes = function plusMinutes(minutes) { - return this._resolveInstant(this._dateTime.plusMinutes(minutes)); - }; + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } - _proto.plusSeconds = function plusSeconds(seconds) { - return this._resolveInstant(this._dateTime.plusSeconds(seconds)); - }; + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); - _proto.plusNanos = function plusNanos(nanos) { - return this._resolveInstant(this._dateTime.plusNanos(nanos)); - }; + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } - _proto.minusYears = function minusYears(years) { - return this.plusYears(-1 * years); - }; + return callback(err, result); + }); + } - _proto.minusMonths = function minusMonths(months) { - return this.plusMonths(-1 * months); - }; + var groupByLimit$1 = awaitify(groupByLimit, 4); - _proto.minusWeeks = function minusWeeks(weeks) { - return this.plusWeeks(-1 * weeks); - }; + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } - _proto.minusDays = function minusDays(days) { - return this.plusDays(-1 * days); - }; + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } + + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); - _proto.minusHours = function minusHours(hours) { - return this.plusHours(-1 * hours); - }; + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } - _proto.minusMinutes = function minusMinutes(minutes) { - return this.plusMinutes(-1 * minutes); - }; + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); - _proto.minusSeconds = function minusSeconds(seconds) { - return this.plusSeconds(-1 * seconds); - }; + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } + + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } - _proto.minusNanos = function minusNanos(nanos) { - return this.plusNanos(-1 * nanos); - }; + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer$1; - _proto.query = function query(_query) { - if (_query === TemporalQueries.localDate()) { - return this.toLocalDate(); - } + if (hasNextTick) { + _defer$1 = process.nextTick; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else { + _defer$1 = fallback; + } - requireNonNull(_query, 'query'); - return _ChronoZonedDateTime.prototype.query.call(this, _query); - }; + var nextTick = wrap(_defer$1); - _proto.until = function until(endExclusive, unit) { - var end = ZonedDateTime.from(endExclusive); + var parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; - if (unit instanceof ChronoUnit) { - end = end.withZoneSameInstant(this._zone); + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); - if (unit.isDateBased()) { - return this._dateTime.until(end._dateTime, unit); - } else { - var difference = this._offset.totalSeconds() - end._offset.totalSeconds(); + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ + function parallel$1(tasks, callback) { + return parallel(eachOf$1, tasks, callback); + } + + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return parallel(eachOfLimit(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = aync.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ - var adjustedEnd = end._dateTime.plusSeconds(difference); + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue$1 (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } - return this._dateTime.until(adjustedEnd, unit); - } + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; } - return unit.between(this, end); - }; - - _proto.toLocalDateTime = function toLocalDateTime() { - return this._dateTime; - }; - - _proto.toLocalDate = function toLocalDate() { - return this._dateTime.toLocalDate(); - }; - - _proto.toLocalTime = function toLocalTime() { - return this._dateTime.toLocalTime(); - }; - - _proto.toOffsetDateTime = function toOffsetDateTime() { - return OffsetDateTime.of(this._dateTime, this._offset); - }; - - _proto.equals = function equals(other) { - if (this === other) { - return true; + get length() { + return this.heap.length; } - if (other instanceof ZonedDateTime) { - return this._dateTime.equals(other._dateTime) && this._offset.equals(other._offset) && this._zone.equals(other._zone); + empty () { + this.heap = []; + return this; } - return false; - }; - - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._dateTime.hashCode(), this._offset.hashCode(), this._zone.hashCode()); - }; + percUp(index) { + let p; - _proto.toString = function toString() { - var str = this._dateTime.toString() + this._offset.toString(); + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; - if (this._offset !== this._zone) { - str += '[' + this._zone.toString() + ']'; + index = p; + } } - return str; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - _proto.format = function format(formatter) { - return _ChronoZonedDateTime.prototype.format.call(this, formatter); - }; - - return ZonedDateTime; - }(ChronoZonedDateTime); - function _init$g() { - ZonedDateTime.FROM = createTemporalQuery('ZonedDateTime.FROM', function (temporal) { - return ZonedDateTime.from(temporal); - }); - } + percDown(index) { + let l; - var OffsetDateTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(OffsetDateTime, _DefaultInterfaceTemp); - - OffsetDateTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } - if (temporal instanceof OffsetDateTime) { - return temporal; - } + if (smaller(this.heap[index], this.heap[l])) { + break; + } - try { - var offset = ZoneOffset.from(temporal); + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; - try { - var ldt = LocalDateTime.from(temporal); - return OffsetDateTime.of(ldt, offset); - } catch (_) { - var instant = Instant.from(temporal); - return OffsetDateTime.ofInstant(instant, offset); - } - } catch (ex) { - throw new DateTimeException("Unable to obtain OffsetDateTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); + index = l; + } } - }; - - OffsetDateTime.now = function now(clockOrZone) { - if (arguments.length === 0) { - return OffsetDateTime.now(Clock.systemDefaultZone()); - } else { - requireNonNull(clockOrZone, 'clockOrZone'); - if (clockOrZone instanceof ZoneId) { - return OffsetDateTime.now(Clock.system(clockOrZone)); - } else if (clockOrZone instanceof Clock) { - var now = clockOrZone.instant(); - return OffsetDateTime.ofInstant(now, clockOrZone.zone().rules().offset(now)); - } else { - throw new IllegalArgumentException('clockOrZone must be an instance of ZoneId or Clock'); - } + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); } - }; - OffsetDateTime.of = function of() { - if (arguments.length <= 2) { - return OffsetDateTime.ofDateTime.apply(this, arguments); - } else if (arguments.length === 3) { - return OffsetDateTime.ofDateAndTime.apply(this, arguments); - } else { - return OffsetDateTime.ofNumbers.apply(this, arguments); + unshift(node) { + return this.heap.push(node); } - }; - OffsetDateTime.ofDateTime = function ofDateTime(dateTime, offset) { - return new OffsetDateTime(dateTime, offset); - }; + shift() { + let [top] = this.heap; - OffsetDateTime.ofDateAndTime = function ofDateAndTime(date, time, offset) { - var dt = LocalDateTime.of(date, time); - return new OffsetDateTime(dt, offset); - }; + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); - OffsetDateTime.ofNumbers = function ofNumbers(year, month, dayOfMonth, hour, minute, second, nanoOfSecond, offset) { - if (hour === void 0) { - hour = 0; + return top; } - if (minute === void 0) { - minute = 0; + toArray() { + return [...this]; } - if (second === void 0) { - second = 0; + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } } - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } - var dt = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond); - return new OffsetDateTime(dt, offset); - }; + this.heap.splice(j); - OffsetDateTime.ofInstant = function ofInstant(instant, zone) { - requireNonNull(instant, 'instant'); - requireNonNull(zone, 'zone'); - var rules = zone.rules(); - var offset = rules.offset(instant); - var ldt = LocalDateTime.ofEpochSecond(instant.epochSecond(), instant.nano(), offset); - return new OffsetDateTime(ldt, offset); - }; + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } - OffsetDateTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + return this; } + } - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, OffsetDateTime.FROM); - }; + function leftChi(i) { + return (i<<1)+1; + } - function OffsetDateTime(dateTime, offset) { - var _this; + function parent(i) { + return ((i+1)>>1)-1; + } - _this = _DefaultInterfaceTemp.call(this) || this; - requireNonNull(dateTime, 'dateTime'); - requireInstance(dateTime, LocalDateTime, 'dateTime'); - requireNonNull(offset, 'offset'); - requireInstance(offset, ZoneOffset, 'offset'); - _this._dateTime = dateTime; - _this._offset = offset; - return _this; - } + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } + } - var _proto = OffsetDateTime.prototype; + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + + q._tasks = new Heap(); + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback = () => {}) { + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!Array.isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(() => q.drain()); + } - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.EPOCH_DAY, this.toLocalDate().toEpochDay()).with(ChronoField.NANO_OF_DAY, this.toLocalTime().toNanoOfDay()).with(ChronoField.OFFSET_SECONDS, this.offset().totalSeconds()); - }; + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority, + callback + }; - _proto.until = function until(endExclusive, unit) { - var end = OffsetDateTime.from(endExclusive); + q._tasks.push(item); + } - if (unit instanceof ChronoUnit) { - end = end.withOffsetSameInstant(this._offset); - return this._dateTime.until(end._dateTime, unit); - } + setImmediate$1(q.process); + }; - return unit.between(this, end); - }; + // Remove unshift function + delete q.unshift; - _proto.atZoneSameInstant = function atZoneSameInstant(zone) { - return ZonedDateTime.ofInstant(this._dateTime, this._offset, zone); - }; + return q; + } - _proto.atZoneSimilarLocal = function atZoneSimilarLocal(zone) { - return ZonedDateTime.ofLocal(this._dateTime, zone, this._offset); - }; + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + var race$1 = awaitify(race, 2); + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } + + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.offset() || _query === TemporalQueries.zone()) { - return this.offset(); - } else if (_query === TemporalQueries.localDate()) { - return this.toLocalDate(); - } else if (_query === TemporalQueries.localTime()) { - return this.toLocalTime(); - } else if (_query === TemporalQueries.zoneId()) { - return null; - } + return _fn.apply(this, args); + }); + } - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } - _proto.get = function get(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - throw new DateTimeException('Field too large for an int: ' + field); + function reject(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } - case ChronoField.OFFSET_SECONDS: - return this.offset().totalSeconds(); - } + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ + function reject$1 (coll, iteratee, callback) { + return reject(eachOf$1, coll, iteratee, callback) + } + var reject$2 = awaitify(reject$1, 3); - return this._dateTime.get(field); + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject(eachOfLimit(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant$1(value) { + return function () { + return value; } + } - return _DefaultInterfaceTemp.prototype.get.call(this, field); - }; - - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - return this.toEpochSecond(); + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; - case ChronoField.OFFSET_SECONDS: - return this.offset().totalSeconds(); - } + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; - return this._dateTime.getLong(field); + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); } - return field.getFrom(this); - }; - - _proto.offset = function offset() { - return this._offset; - }; + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } - _proto.year = function year() { - return this._dateTime.year(); - }; + var _task = wrapAsync(task); - _proto.monthValue = function monthValue() { - return this._dateTime.monthValue(); - }; + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } - _proto.month = function month() { - return this._dateTime.month(); - }; + retryAttempt(); + return callback[PROMISE_SYMBOL] + } - _proto.dayOfMonth = function dayOfMonth() { - return this._dateTime.dayOfMonth(); - }; + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; - _proto.dayOfYear = function dayOfYear() { - return this._dateTime.dayOfYear(); - }; + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); - _proto.dayOfWeek = function dayOfWeek() { - return this._dateTime.dayOfWeek(); - }; + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } - _proto.hour = function hour() { - return this._dateTime.hour(); - }; + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } - _proto.minute = function minute() { - return this._dateTime.minute(); - }; + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); - _proto.second = function second() { - return this._dateTime.second(); - }; + return callback[PROMISE_SYMBOL] + }); + } - _proto.nano = function nano() { - return this._dateTime.nano(); - }; + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ + function series(tasks, callback) { + return parallel(eachOfSeries$1, tasks, callback); + } + + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + } + var some$1 = awaitify(some, 3); - _proto.toLocalDateTime = function toLocalDateTime() { - return this._dateTime; - }; + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); + + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); + + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); - _proto.toLocalDate = function toLocalDate() { - return this._dateTime.toLocalDate(); - }; + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + } + var sortBy$1 = awaitify(sortBy, 3); - _proto.toLocalTime = function toLocalTime() { - return this._dateTime.toLocalTime(); - }; + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); - _proto.toOffsetTime = function toOffsetTime() { - return OffsetTime.of(this._dateTime.toLocalTime(), this._offset); - }; + return initialParams((args, callback) => { + var timedOut = false; + var timer; - _proto.toZonedDateTime = function toZonedDateTime() { - return ZonedDateTime.of(this._dateTime, this._offset); - }; + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } - _proto.toInstant = function toInstant() { - return this._dateTime.toInstant(this._offset); - }; + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); - _proto.toEpochSecond = function toEpochSecond() { - return this._dateTime.toEpochSecond(this._offset); - }; + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; } + return result; + } - if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); - } + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); + } + + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) + } - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } + + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc[index] = item * 2 + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.INSTANT_SECONDS || field === ChronoField.OFFSET_SECONDS) { - return field.range(); - } + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } - return this._dateTime.range(field); - } + var tryEach$1 = awaitify(tryEach); - return field.rangeRefinedBy(this); - }; + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster); + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; - if (adjuster instanceof LocalDate || adjuster instanceof LocalTime || adjuster instanceof LocalDateTime) { - return this._withDateTimeOffset(this._dateTime.with(adjuster), this._offset); - } else if (adjuster instanceof Instant) { - return OffsetDateTime.ofInstant(adjuster, this._offset); - } else if (adjuster instanceof ZoneOffset) { - return this._withDateTimeOffset(this._dateTime, adjuster); - } else if (adjuster instanceof OffsetDateTime) { - return adjuster; + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); } - return adjuster.adjustInto(this); - }; - - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field); - - if (field instanceof ChronoField) { - var f = field; - - switch (f) { - case ChronoField.INSTANT_SECONDS: - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(newValue, this.nano()), this._offset); - - case ChronoField.OFFSET_SECONDS: - { - return this._withDateTimeOffset(this._dateTime, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue))); - } - } - - return this._withDateTimeOffset(this._dateTime.with(field, newValue), this._offset); + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); } - return field.adjustInto(this, newValue); - }; + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); - _proto._withDateTimeOffset = function _withDateTimeOffset(dateTime, offset) { - if (this._dateTime === dateTime && this._offset.equals(offset)) { - return this; + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(page, cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } + + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); } - return new OffsetDateTime(dateTime, offset); - }; + nextTask([]); + } - _proto.withYear = function withYear(year) { - return this._withDateTimeOffset(this._dateTime.withYear(year), this._offset); - }; + var waterfall$1 = awaitify(waterfall); - _proto.withMonth = function withMonth(month) { - return this._withDateTimeOffset(this._dateTime.withMonth(month), this._offset); - }; + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + var index = { + apply, + applyEach: applyEach$1, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo, + cargoQueue: cargo$1, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$2, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$2, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel: parallel$1, + parallelLimit, + priorityQueue, + queue: queue$1, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$2, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$2, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$2, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + + exports.default = index; + exports.apply = apply; + exports.applyEach = applyEach$1; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo; + exports.cargoQueue = cargo$1; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.each = each; + exports.eachLimit = eachLimit$2; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$2; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel$1; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue$1; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$2; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.forEach = each; + exports.forEachSeries = eachSeries$1; + exports.forEachLimit = eachLimit$2; + exports.forEachOf = eachOf$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachOfLimit = eachOfLimit$2; + exports.inject = reduce$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.wrapSync = asyncify; + exports.during = whilst$1; + exports.doDuring = doWhilst$1; - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - return this._withDateTimeOffset(this._dateTime.withDayOfMonth(dayOfMonth), this._offset); - }; + Object.defineProperty(exports, '__esModule', { value: true }); - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - return this._withDateTimeOffset(this._dateTime.withDayOfYear(dayOfYear), this._offset); - }; +}))); - _proto.withHour = function withHour(hour) { - return this._withDateTimeOffset(this._dateTime.withHour(hour), this._offset); - }; - _proto.withMinute = function withMinute(minute) { - return this._withDateTimeOffset(this._dateTime.withMinute(minute), this._offset); - }; +/***/ }), - _proto.withSecond = function withSecond(second) { - return this._withDateTimeOffset(this._dateTime.withSecond(second), this._offset); - }; +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.withNano = function withNano(nanoOfSecond) { - return this._withDateTimeOffset(this._dateTime.withNano(nanoOfSecond), this._offset); - }; +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) +}; - _proto.withOffsetSameLocal = function withOffsetSameLocal(offset) { - requireNonNull(offset, 'offset'); - return this._withDateTimeOffset(this._dateTime, offset); - }; - _proto.withOffsetSameInstant = function withOffsetSameInstant(offset) { - requireNonNull(offset, 'offset'); +/***/ }), - if (offset.equals(this._offset)) { - return this; - } +/***/ 1700: +/***/ ((module) => { - var difference = offset.totalSeconds() - this._offset.totalSeconds(); +// API +module.exports = abort; - var adjusted = this._dateTime.plusSeconds(difference); +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); - return new OffsetDateTime(adjusted, offset); - }; + // reset leftover jobs + state.jobs = {}; +} - _proto.truncatedTo = function truncatedTo(unit) { - return this._withDateTimeOffset(this._dateTime.truncatedTo(unit), this._offset); - }; +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - if (unit instanceof ChronoUnit) { - return this._withDateTimeOffset(this._dateTime.plus(amountToAdd, unit), this._offset); - } +/***/ }), - return unit.addTo(this, amountToAdd); - }; +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.plusYears = function plusYears(years) { - return this._withDateTimeOffset(this._dateTime.plusYears(years), this._offset); - }; +var defer = __nccwpck_require__(15295); - _proto.plusMonths = function plusMonths(months) { - return this._withDateTimeOffset(this._dateTime.plusMonths(months), this._offset); - }; +// API +module.exports = async; - _proto.plusWeeks = function plusWeeks(weeks) { - return this._withDateTimeOffset(this._dateTime.plusWeeks(weeks), this._offset); - }; +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; - _proto.plusDays = function plusDays(days) { - return this._withDateTimeOffset(this._dateTime.plusDays(days), this._offset); - }; + // check if async happened + defer(function() { isAsync = true; }); - _proto.plusHours = function plusHours(hours) { - return this._withDateTimeOffset(this._dateTime.plusHours(hours), this._offset); - }; + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} - _proto.plusMinutes = function plusMinutes(minutes) { - return this._withDateTimeOffset(this._dateTime.plusMinutes(minutes), this._offset); - }; - _proto.plusSeconds = function plusSeconds(seconds) { - return this._withDateTimeOffset(this._dateTime.plusSeconds(seconds), this._offset); - }; +/***/ }), - _proto.plusNanos = function plusNanos(nanos) { - return this._withDateTimeOffset(this._dateTime.plusNanos(nanos), this._offset); - }; +/***/ 15295: +/***/ ((module) => { - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount); - return amount.subtractFrom(this); - }; +module.exports = defer; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plus(-1 * amountToSubtract, unit); - }; +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); - _proto.minusYears = function minusYears(years) { - return this._withDateTimeOffset(this._dateTime.minusYears(years), this._offset); - }; + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} - _proto.minusMonths = function minusMonths(months) { - return this._withDateTimeOffset(this._dateTime.minusMonths(months), this._offset); - }; - _proto.minusWeeks = function minusWeeks(weeks) { - return this._withDateTimeOffset(this._dateTime.minusWeeks(weeks), this._offset); - }; +/***/ }), - _proto.minusDays = function minusDays(days) { - return this._withDateTimeOffset(this._dateTime.minusDays(days), this._offset); - }; +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.minusHours = function minusHours(hours) { - return this._withDateTimeOffset(this._dateTime.minusHours(hours), this._offset); - }; +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) + ; - _proto.minusMinutes = function minusMinutes(minutes) { - return this._withDateTimeOffset(this._dateTime.minusMinutes(minutes), this._offset); - }; +// API +module.exports = iterate; - _proto.minusSeconds = function minusSeconds(seconds) { - return this._withDateTimeOffset(this._dateTime.minusSeconds(seconds), this._offset); - }; +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - _proto.minusNanos = function minusNanos(nanos) { - return this._withDateTimeOffset(this._dateTime.minusNanos(nanos), this._offset); - }; + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, OffsetDateTime, 'other'); + // clean up jobs + delete state.jobs[key]; - if (this.offset().equals(other.offset())) { - return this.toLocalDateTime().compareTo(other.toLocalDateTime()); - } + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } - var cmp = MathUtil.compareNumbers(this.toEpochSecond(), other.toEpochSecond()); + // return salvaged results + callback(error, state.results); + }); +} - if (cmp === 0) { - cmp = this.toLocalTime().nano() - other.toLocalTime().nano(); +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; - if (cmp === 0) { - cmp = this.toLocalDateTime().compareTo(other.toLocalDateTime()); - } - } + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } - return cmp; - }; + return aborter; +} - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec > otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() > other.toLocalTime().nano(); - }; - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec < otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() < other.toLocalTime().nano(); - }; +/***/ }), - _proto.isEqual = function isEqual(other) { - requireNonNull(other, 'other'); - return this.toEpochSecond() === other.toEpochSecond() && this.toLocalTime().nano() === other.toLocalTime().nano(); - }; +/***/ 42474: +/***/ ((module) => { - _proto.equals = function equals(other) { - if (this === other) { - return true; - } +// API +module.exports = state; - if (other instanceof OffsetDateTime) { - return this._dateTime.equals(other._dateTime) && this._offset.equals(other._offset); - } +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; - return false; - }; + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } - _proto.hashCode = function hashCode() { - return this._dateTime.hashCode() ^ this._offset.hashCode(); - }; + return initState; +} - _proto.toString = function toString() { - return this._dateTime.toString() + this._offset.toString(); - }; - _proto.toJSON = function toJSON() { - return this.toString(); - }; +/***/ }), - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return OffsetDateTime; - }(DefaultInterfaceTemporal); - function _init$h() { - OffsetDateTime.MIN = LocalDateTime.MIN.atOffset(ZoneOffset.MAX); - OffsetDateTime.MAX = LocalDateTime.MAX.atOffset(ZoneOffset.MIN); - OffsetDateTime.FROM = createTemporalQuery('OffsetDateTime.FROM', function (temporal) { - return OffsetDateTime.from(temporal); - }); - } +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; - var DAYS_PER_CYCLE = 146097; - var DAYS_0000_TO_1970 = DAYS_PER_CYCLE * 5 - (30 * 365 + 7); - var LocalDate = function (_ChronoLocalDate) { - _inheritsLoose(LocalDate, _ChronoLocalDate); +// API +module.exports = terminator; - LocalDate.now = function now(clockOrZone) { - var clock; +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } - if (clockOrZone == null) { - clock = Clock.systemDefaultZone(); - } else if (clockOrZone instanceof ZoneId) { - clock = Clock.system(clockOrZone); - } else { - clock = clockOrZone; - } + // fast forward iteration index + this.index = this.size; - return LocalDate.ofInstant(clock.instant(), clock.zone()); - }; + // abort jobs + abort(this); - LocalDate.ofInstant = function ofInstant(instant, zone) { - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } + // send back results we have so far + async(callback)(null, this.results); +} - requireNonNull(instant, 'instant'); - var offset = zone.rules().offset(instant); - var epochSec = instant.epochSecond() + offset.totalSeconds(); - var epochDay = MathUtil.floorDiv(epochSec, LocalTime.SECONDS_PER_DAY); - return LocalDate.ofEpochDay(epochDay); - }; - LocalDate.of = function of(year, month, dayOfMonth) { - return new LocalDate(year, month, dayOfMonth); - }; +/***/ }), - LocalDate.ofYearDay = function ofYearDay(year, dayOfYear) { - ChronoField.YEAR.checkValidValue(year); - var leap = IsoChronology.isLeapYear(year); +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (dayOfYear === 366 && leap === false) { - assert(false, 'Invalid date \'DayOfYear 366\' as \'' + year + '\' is not a leap year', DateTimeException); - } - - var moy = Month.of(Math.floor((dayOfYear - 1) / 31 + 1)); - var monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1; +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - if (dayOfYear > monthEnd) { - moy = moy.plus(1); - } +// Public API +module.exports = parallel; - var dom = dayOfYear - moy.firstDayOfYear(leap) + 1; - return new LocalDate(year, moy.value(), dom); - }; +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); - LocalDate.ofEpochDay = function ofEpochDay(epochDay) { - if (epochDay === void 0) { - epochDay = 0; - } + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } - var adjust, adjustCycles, doyEst, yearEst, zeroDay; - zeroDay = epochDay + DAYS_0000_TO_1970; - zeroDay -= 60; - adjust = 0; + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); - if (zeroDay < 0) { - adjustCycles = MathUtil.intDiv(zeroDay + 1, DAYS_PER_CYCLE) - 1; - adjust = adjustCycles * 400; - zeroDay += -adjustCycles * DAYS_PER_CYCLE; - } + state.index++; + } - yearEst = MathUtil.intDiv(400 * zeroDay + 591, DAYS_PER_CYCLE); - doyEst = zeroDay - (365 * yearEst + MathUtil.intDiv(yearEst, 4) - MathUtil.intDiv(yearEst, 100) + MathUtil.intDiv(yearEst, 400)); + return terminator.bind(state, callback); +} - if (doyEst < 0) { - yearEst--; - doyEst = zeroDay - (365 * yearEst + MathUtil.intDiv(yearEst, 4) - MathUtil.intDiv(yearEst, 100) + MathUtil.intDiv(yearEst, 400)); - } - yearEst += adjust; - var marchDoy0 = doyEst; - var marchMonth0 = MathUtil.intDiv(marchDoy0 * 5 + 2, 153); - var month = (marchMonth0 + 2) % 12 + 1; - var dom = marchDoy0 - MathUtil.intDiv(marchMonth0 * 306 + 5, 10) + 1; - yearEst += MathUtil.intDiv(marchMonth0, 10); - var year = yearEst; - return new LocalDate(year, month, dom); - }; +/***/ }), - LocalDate.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - var date = temporal.query(TemporalQueries.localDate()); +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (date == null) { - throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } +var serialOrdered = __nccwpck_require__(3578); - return date; - }; +// Public API +module.exports = serial; - LocalDate.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_LOCAL_DATE; - } +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} - assert(formatter != null, 'formatter', NullPointerException); - return formatter.parse(text, LocalDate.FROM); - }; - LocalDate._resolvePreviousValid = function _resolvePreviousValid(year, month, day) { - switch (month) { - case 2: - day = Math.min(day, IsoChronology.isLeapYear(year) ? 29 : 28); - break; +/***/ }), - case 4: - case 6: - case 9: - case 11: - day = Math.min(day, 30); - break; - } +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return LocalDate.of(year, month, day); - }; +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - function LocalDate(year, month, dayOfMonth) { - var _this; +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; - _this = _ChronoLocalDate.call(this) || this; - requireNonNull(year, 'year'); - requireNonNull(month, 'month'); - requireNonNull(dayOfMonth, 'dayOfMonth'); +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); - if (month instanceof Month) { - month = month.value(); - } + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } - _this._year = MathUtil.safeToInt(year); - _this._month = MathUtil.safeToInt(month); - _this._day = MathUtil.safeToInt(dayOfMonth); + state.index++; - LocalDate._validate(_this._year, _this._month, _this._day); + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } - return _this; - } + // done here + callback(null, state.results); + }); - LocalDate._validate = function _validate(year, month, dayOfMonth) { - var dom; - ChronoField.YEAR.checkValidValue(year); - ChronoField.MONTH_OF_YEAR.checkValidValue(month); - ChronoField.DAY_OF_MONTH.checkValidValue(dayOfMonth); + return terminator.bind(state, callback); +} - if (dayOfMonth > 28) { - dom = 31; +/* + * -- Sort methods + */ - switch (month) { - case 2: - dom = IsoChronology.isLeapYear(year) ? 29 : 28; - break; +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} - case 4: - case 6: - case 9: - case 11: - dom = 30; - } +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} - if (dayOfMonth > dom) { - if (dayOfMonth === 29) { - assert(false, 'Invalid date \'February 29\' as \'' + year + '\' is not a leap year', DateTimeException); - } else { - assert(false, 'Invalid date \'' + year + '\' \'' + month + '\' \'' + dayOfMonth + '\'', DateTimeException); - } - } - } - }; - var _proto = LocalDate.prototype; +/***/ }), - _proto.isSupported = function isSupported(field) { - return _ChronoLocalDate.prototype.isSupported.call(this, field); - }; +/***/ 96342: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field.isDateBased()) { - switch (field) { - case ChronoField.DAY_OF_MONTH: - return ValueRange.of(1, this.lengthOfMonth()); - case ChronoField.DAY_OF_YEAR: - return ValueRange.of(1, this.lengthOfYear()); +/*! + * Copyright 2010 LearnBoost + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - case ChronoField.ALIGNED_WEEK_OF_MONTH: - return ValueRange.of(1, this.month() === Month.FEBRUARY && this.isLeapYear() === false ? 4 : 5); +/** + * Module dependencies. + */ - case ChronoField.YEAR_OF_ERA: - return this._year <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE); - } +var crypto = __nccwpck_require__(76417) + , parse = __nccwpck_require__(78835).parse + ; - return field.range(); - } +/** + * Valid keys. + */ - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +var keys = + [ 'acl' + , 'location' + , 'logging' + , 'notification' + , 'partNumber' + , 'policy' + , 'requestPayment' + , 'torrent' + , 'uploadId' + , 'uploads' + , 'versionId' + , 'versioning' + , 'versions' + , 'website' + ] - return field.rangeRefinedBy(this); - }; +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS :" + * + * @param {Object} options + * @return {String} + * @api private + */ - _proto.get = function get(field) { - return this.getLong(field); - }; +function authorization (options) { + return 'AWS ' + options.key + ':' + sign(options) +} - _proto.getLong = function getLong(field) { - assert(field != null, '', NullPointerException); +module.exports = authorization +module.exports.authorization = authorization - if (field instanceof ChronoField) { - return this._get0(field); - } +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ - return field.getFrom(this); - }; +function hmacSha1 (options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +} - _proto._get0 = function _get0(field) { - switch (field) { - case ChronoField.DAY_OF_WEEK: - return this.dayOfWeek().value(); +module.exports.hmacSha1 = hmacSha1 - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH: - return MathUtil.intMod(this._day - 1, 7) + 1; +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR: - return MathUtil.intMod(this.dayOfYear() - 1, 7) + 1; +function sign (options) { + options.message = stringToSign(options) + return hmacSha1(options) +} +module.exports.sign = sign - case ChronoField.DAY_OF_MONTH: - return this._day; +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ - case ChronoField.DAY_OF_YEAR: - return this.dayOfYear(); +function signQuery (options) { + options.message = queryStringToSign(options) + return hmacSha1(options) +} +module.exports.signQuery= signQuery - case ChronoField.EPOCH_DAY: - return this.toEpochDay(); +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * \n + * \n + * \n + * \n + * [headers\n] + * + * + * @param {Object} options + * @return {String} + * @api private + */ - case ChronoField.ALIGNED_WEEK_OF_MONTH: - return MathUtil.intDiv(this._day - 1, 7) + 1; +function stringToSign (options) { + var headers = options.amazonHeaders || '' + if (headers) headers += '\n' + var r = + [ options.verb + , options.md5 + , options.contentType + , options.date ? options.date.toUTCString() : '' + , headers + options.resource + ] + return r.join('\n') +} +module.exports.stringToSign = stringToSign - case ChronoField.ALIGNED_WEEK_OF_YEAR: - return MathUtil.intDiv(this.dayOfYear() - 1, 7) + 1; +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * \n + * + * + * @param {Object} options + * @return {String} + * @api private + */ - case ChronoField.MONTH_OF_YEAR: - return this._month; +function queryStringToSign (options){ + return 'GET\n\n\n' + options.date + '\n' + options.resource +} +module.exports.queryStringToSign = queryStringToSign - case ChronoField.PROLEPTIC_MONTH: - return this._prolepticMonth(); +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ - case ChronoField.YEAR_OF_ERA: - return this._year >= 1 ? this._year : 1 - this._year; +function canonicalizeHeaders (headers) { + var buf = [] + , fields = Object.keys(headers) + ; + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i] + , val = headers[field] + , field = field.toLowerCase() + ; + if (0 !== field.indexOf('x-amz')) continue + buf.push(field + ':' + val) + } + return buf.sort().join('\n') +} +module.exports.canonicalizeHeaders = canonicalizeHeaders - case ChronoField.YEAR: - return this._year; +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ - case ChronoField.ERA: - return this._year >= 1 ? 1 : 0; - } +function canonicalizeResource (resource) { + var url = parse(resource, true) + , path = url.pathname + , buf = [] + ; - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - }; + Object.keys(url.query).forEach(function(key){ + if (!~keys.indexOf(key)) return + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) + buf.push(key + val) + }) - _proto._prolepticMonth = function _prolepticMonth() { - return this._year * 12 + (this._month - 1); - }; + return path + (buf.length ? '?' + buf.sort().join('&') : '') +} +module.exports.canonicalizeResource = canonicalizeResource - _proto.chronology = function chronology() { - return IsoChronology.INSTANCE; - }; - _proto.year = function year() { - return this._year; - }; +/***/ }), - _proto.monthValue = function monthValue() { - return this._month; - }; +/***/ 16071: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _proto.month = function month() { - return Month.of(this._month); - }; +var aws4 = exports, + url = __nccwpck_require__(78835), + querystring = __nccwpck_require__(71191), + crypto = __nccwpck_require__(76417), + lru = __nccwpck_require__(74225), + credentialsCache = lru(1000) - _proto.dayOfMonth = function dayOfMonth() { - return this._day; - }; +// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html - _proto.dayOfYear = function dayOfYear() { - return this.month().firstDayOfYear(this.isLeapYear()) + this._day - 1; - }; +function hmac(key, string, encoding) { + return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) +} - _proto.dayOfWeek = function dayOfWeek() { - var dow0 = MathUtil.floorMod(this.toEpochDay() + 3, 7); - return DayOfWeek.of(dow0 + 1); - }; +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) +} - _proto.isLeapYear = function isLeapYear() { - return IsoChronology.isLeapYear(this._year); - }; +// This function assumes the string has already been percent encoded +function encodeRfc3986(urlEncodedString) { + return urlEncodedString.replace(/[!'()*]/g, function(c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} - _proto.lengthOfMonth = function lengthOfMonth() { - switch (this._month) { - case 2: - return this.isLeapYear() ? 29 : 28; +function encodeRfc3986Full(str) { + return encodeRfc3986(encodeURIComponent(str)) +} - case 4: - case 6: - case 9: - case 11: - return 30; +// A bit of a combination of: +// https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 +// https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 +// https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 +var HEADERS_TO_IGNORE = { + 'authorization': true, + 'connection': true, + 'x-amzn-trace-id': true, + 'user-agent': true, + 'expect': true, + 'presigned-expires': true, + 'range': true, +} - default: - return 31; - } - }; +// request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } +function RequestSigner(request, credentials) { - _proto.lengthOfYear = function lengthOfYear() { - return this.isLeapYear() ? 366 : 365; - }; + if (typeof request === 'string') request = url.parse(request) - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); + var headers = request.headers = (request.headers || {}), + hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) - if (adjuster instanceof LocalDate) { - return adjuster; - } + this.request = request + this.credentials = credentials || this.defaultCredentials() - assert(typeof adjuster.adjustInto === 'function', 'adjuster', IllegalArgumentException); - return adjuster.adjustInto(this); - }; + this.service = request.service || hostParts[0] || '' + this.region = request.region || hostParts[1] || 'us-east-1' - _proto.withFieldValue = function withFieldValue(field, newValue) { - assert(field != null, 'field', NullPointerException); + // SES uses a different domain from the service name + if (this.service === 'email') this.service = 'ses' - if (field instanceof ChronoField) { - var f = field; - f.checkValidValue(newValue); + if (!request.method && request.body) + request.method = 'POST' - switch (f) { - case ChronoField.DAY_OF_WEEK: - return this.plusDays(newValue - this.dayOfWeek().value()); + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost() - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH: - return this.plusDays(newValue - this.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + // If a port is specified explicitly, use it as is + if (request.port) + headers.Host += ':' + request.port + } + if (!request.hostname && !request.host) + request.hostname = headers.Host || headers.host - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR: - return this.plusDays(newValue - this.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' +} - case ChronoField.DAY_OF_MONTH: - return this.withDayOfMonth(newValue); +RequestSigner.prototype.matchHost = function(host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) + var hostParts = (match || []).slice(1, 3) - case ChronoField.DAY_OF_YEAR: - return this.withDayOfYear(newValue); + // ES's hostParts are sometimes the other way round, if the value that is expected + // to be region equals ‘es’ switch them back + // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com + if (hostParts[1] === 'es') + hostParts = hostParts.reverse() - case ChronoField.EPOCH_DAY: - return LocalDate.ofEpochDay(newValue); + if (hostParts[1] == 's3') { + hostParts[0] = 's3' + hostParts[1] = 'us-east-1' + } else { + for (var i = 0; i < 2; i++) { + if (/^s3-/.test(hostParts[i])) { + hostParts[1] = hostParts[i].slice(3) + hostParts[0] = 's3' + break + } + } + } - case ChronoField.ALIGNED_WEEK_OF_MONTH: - return this.plusWeeks(newValue - this.getLong(ChronoField.ALIGNED_WEEK_OF_MONTH)); + return hostParts +} - case ChronoField.ALIGNED_WEEK_OF_YEAR: - return this.plusWeeks(newValue - this.getLong(ChronoField.ALIGNED_WEEK_OF_YEAR)); +// http://docs.aws.amazon.com/general/latest/gr/rande.html +RequestSigner.prototype.isSingleRegion = function() { + // Special case for S3 and SimpleDB in us-east-1 + if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true - case ChronoField.MONTH_OF_YEAR: - return this.withMonth(newValue); + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] + .indexOf(this.service) >= 0 +} - case ChronoField.PROLEPTIC_MONTH: - return this.plusMonths(newValue - this.getLong(ChronoField.PROLEPTIC_MONTH)); +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : '.' + this.region, + subdomain = this.service === 'ses' ? 'email' : this.service + return subdomain + region + '.amazonaws.com' +} - case ChronoField.YEAR_OF_ERA: - return this.withYear(this._year >= 1 ? newValue : 1 - newValue); +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() - case ChronoField.YEAR: - return this.withYear(newValue); + var request = this.request, headers = request.headers, query - case ChronoField.ERA: - return this.getLong(ChronoField.ERA) === newValue ? this : this.withYear(1 - this._year); - } + if (request.signQuery) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } + this.parsedPath.query = query = this.parsedPath.query || {} - return field.adjustInto(this, newValue); - }; + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken - _proto.withYear = function withYear(year) { - if (this._year === year) { - return this; - } + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 - ChronoField.YEAR.checkValidValue(year); - return LocalDate._resolvePreviousValid(year, this._month, this._day); - }; + if (query['X-Amz-Date']) + this.datetime = query['X-Amz-Date'] + else + query['X-Amz-Date'] = this.getDateTime() - _proto.withMonth = function withMonth(month) { - var m = month instanceof Month ? month.value() : month; + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() + query['X-Amz-SignedHeaders'] = this.signedHeaders() - if (this._month === m) { - return this; - } + } else { - ChronoField.MONTH_OF_YEAR.checkValidValue(m); - return LocalDate._resolvePreviousValid(this._year, m, this._day); - }; + if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { + if (request.body && !headers['Content-Type'] && !headers['content-type']) + headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - if (this._day === dayOfMonth) { - return this; - } + if (request.body && !headers['Content-Length'] && !headers['content-length']) + headers['Content-Length'] = Buffer.byteLength(request.body) - return LocalDate.of(this._year, this._month, dayOfMonth); - }; + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - if (this.dayOfYear() === dayOfYear) { - return this; - } + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') - return LocalDate.ofYearDay(this._year, dayOfYear); - }; + if (headers['X-Amz-Date'] || headers['x-amz-date']) + this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] + else + headers['X-Amz-Date'] = this.getDateTime() + } - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; + delete headers.Authorization + delete headers.authorization + } +} - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.DAYS: - return this.plusDays(amountToAdd); + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } - case ChronoUnit.WEEKS: - return this.plusWeeks(amountToAdd); + this.request.path = this.formatPath() - case ChronoUnit.MONTHS: - return this.plusMonths(amountToAdd); + return this.request +} - case ChronoUnit.YEARS: - return this.plusYears(amountToAdd); +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) - case ChronoUnit.DECADES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 10)); + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') - case ChronoUnit.CENTURIES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 100)); + // Remove the trailing 'Z' on the timestamp string for CodeCommit git access + if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) + } + return this.datetime +} - case ChronoUnit.MILLENNIA: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 1000)); +RequestSigner.prototype.getDate = function() { + return this.getDateTime().substr(0, 8) +} - case ChronoUnit.ERAS: - return this.with(ChronoField.ERA, MathUtil.safeAdd(this.getLong(ChronoField.ERA), amountToAdd)); - } +RequestSigner.prototype.authHeader = function() { + return [ + 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), + 'SignedHeaders=' + this.signedHeaders(), + 'Signature=' + this.signature(), + ].join(', ') +} - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +RequestSigner.prototype.signature = function() { + var date = this.getDate(), + cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), + kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) + if (!kCredentials) { + kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) + kRegion = hmac(kDate, this.region) + kService = hmac(kRegion, this.service) + kCredentials = hmac(kService, 'aws4_request') + credentialsCache.set(cacheKey, kCredentials) + } + return hmac(kCredentials, this.stringToSign(), 'hex') +} - return unit.addTo(this, amountToAdd); - }; +RequestSigner.prototype.stringToSign = function() { + return [ + 'AWS4-HMAC-SHA256', + this.getDateTime(), + this.credentialString(), + hash(this.canonicalString(), 'hex'), + ].join('\n') +} - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } +RequestSigner.prototype.canonicalString = function() { + if (!this.parsedPath) this.prepareRequest() - var newYear = ChronoField.YEAR.checkValidIntValue(this._year + yearsToAdd); - return LocalDate._resolvePreviousValid(newYear, this._month, this._day); - }; + var pathStr = this.parsedPath.path, + query = this.parsedPath.query, + headers = this.request.headers, + queryStr = '', + normalizePath = this.service !== 's3', + decodePath = this.service === 's3' || this.request.doNotEncodePath, + decodeSlashesInPath = this.service === 's3', + firstValOnly = this.service === 's3', + bodyHash - _proto.plusMonths = function plusMonths(monthsToAdd) { - if (monthsToAdd === 0) { - return this; - } + if (this.service === 's3' && this.request.signQuery) { + bodyHash = 'UNSIGNED-PAYLOAD' + } else if (this.isCodeCommitGit) { + bodyHash = '' + } else { + bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || + hash(this.request.body || '', 'hex') + } - var monthCount = this._year * 12 + (this._month - 1); - var calcMonths = monthCount + monthsToAdd; - var newYear = ChronoField.YEAR.checkValidIntValue(MathUtil.floorDiv(calcMonths, 12)); - var newMonth = MathUtil.floorMod(calcMonths, 12) + 1; - return LocalDate._resolvePreviousValid(newYear, newMonth, this._day); - }; + if (query) { + var reducedQuery = Object.keys(query).reduce(function(obj, key) { + if (!key) return obj + obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : + (firstValOnly ? query[key][0] : query[key]) + return obj + }, {}) + var encodedQueryPieces = [] + Object.keys(reducedQuery).sort().forEach(function(key) { + if (!Array.isArray(reducedQuery[key])) { + encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) + } else { + reducedQuery[key].map(encodeRfc3986Full).sort() + .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) + } + }) + queryStr = encodedQueryPieces.join('&') + } + if (pathStr !== '/') { + if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') + pathStr = pathStr.split('/').reduce(function(path, piece) { + if (normalizePath && piece === '..') { + path.pop() + } else if (!normalizePath || piece !== '.') { + if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' ')) + path.push(encodeRfc3986Full(piece)) + } + return path + }, []).join('/') + if (pathStr[0] !== '/') pathStr = '/' + pathStr + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') + } + + return [ + this.request.method || 'GET', + pathStr, + queryStr, + this.canonicalHeaders() + '\n', + this.signedHeaders(), + bodyHash, + ].join('\n') +} + +RequestSigner.prototype.canonicalHeaders = function() { + var headers = this.request.headers + function trimAll(header) { + return header.toString().trim().replace(/\s+/g, ' ') + } + return Object.keys(headers) + .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) + .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) + .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) + .join('\n') +} + +RequestSigner.prototype.signedHeaders = function() { + return Object.keys(this.request.headers) + .map(function(key) { return key.toLowerCase() }) + .filter(function(key) { return HEADERS_TO_IGNORE[key] == null }) + .sort() + .join(';') +} + +RequestSigner.prototype.credentialString = function() { + return [ + this.getDate(), + this.region, + this.service, + 'aws4_request', + ].join('/') +} + +RequestSigner.prototype.defaultCredentials = function() { + var env = process.env + return { + accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, + secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, + sessionToken: env.AWS_SESSION_TOKEN, + } +} - _proto.plusWeeks = function plusWeeks(weeksToAdd) { - return this.plusDays(MathUtil.safeMultiply(weeksToAdd, 7)); - }; +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/' - _proto.plusDays = function plusDays(daysToAdd) { - if (daysToAdd === 0) { - return this; - } + // S3 doesn't always encode characters > 127 correctly and + // all services don't encode characters > 255 correctly + // So if there are non-reserved chars (and it's not already all % encoded), just encode them all + if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { + path = encodeURI(decodeURI(path)) + } - var mjDay = MathUtil.safeAdd(this.toEpochDay(), daysToAdd); - return LocalDate.ofEpochDay(mjDay); - }; + var queryIx = path.indexOf('?'), + query = null - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) + } - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; + this.parsedPath = { + path: path, + query: query, + } +} - _proto.minusYears = function minusYears(yearsToSubtract) { - return this.plusYears(yearsToSubtract * -1); - }; +RequestSigner.prototype.formatPath = function() { + var path = this.parsedPath.path, + query = this.parsedPath.query - _proto.minusMonths = function minusMonths(monthsToSubtract) { - return this.plusMonths(monthsToSubtract * -1); - }; + if (!query) return path - _proto.minusWeeks = function minusWeeks(weeksToSubtract) { - return this.plusWeeks(weeksToSubtract * -1); - }; + // Services don't support empty query string keys + if (query[''] != null) delete query[''] - _proto.minusDays = function minusDays(daysToSubtract) { - return this.plusDays(daysToSubtract * -1); - }; + return path + '?' + encodeRfc3986(querystring.stringify(query)) +} - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); +aws4.RequestSigner = RequestSigner - if (_query === TemporalQueries.localDate()) { - return this; - } +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() +} - return _ChronoLocalDate.prototype.query.call(this, _query); - }; - _proto.adjustInto = function adjustInto(temporal) { - return _ChronoLocalDate.prototype.adjustInto.call(this, temporal); - }; +/***/ }), - _proto.until = function until(p1, p2) { - if (arguments.length < 2) { - return this.until1(p1); - } else { - return this.until2(p1, p2); - } - }; +/***/ 74225: +/***/ ((module) => { - _proto.until2 = function until2(endExclusive, unit) { - var end = LocalDate.from(endExclusive); +module.exports = function(size) { + return new LruCache(size) +} - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.DAYS: - return this.daysUntil(end); +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} - case ChronoUnit.WEEKS: - return MathUtil.intDiv(this.daysUntil(end), 7); +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} - case ChronoUnit.MONTHS: - return this._monthsUntil(end); +LruCache.prototype.set = function(key, val) { + var node = this.map[key] + if (node != null) { + node.val = val + } else { + if (!this.capacity) this.prune() + if (!this.capacity) return false + node = new DoublyLinkedNode(key, val) + this.map[key] = node + this.capacity-- + } + this.used(node) + return true +} - case ChronoUnit.YEARS: - return MathUtil.intDiv(this._monthsUntil(end), 12); +LruCache.prototype.used = function(node) { + this.list.moveToFront(node) +} - case ChronoUnit.DECADES: - return MathUtil.intDiv(this._monthsUntil(end), 120); +LruCache.prototype.prune = function() { + var node = this.list.pop() + if (node != null) { + delete this.map[node.key] + this.capacity++ + } +} - case ChronoUnit.CENTURIES: - return MathUtil.intDiv(this._monthsUntil(end), 1200); - case ChronoUnit.MILLENNIA: - return MathUtil.intDiv(this._monthsUntil(end), 12000); +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} - case ChronoUnit.ERAS: - return end.getLong(ChronoField.ERA) - this.getLong(ChronoField.ERA); - } +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } + this.remove(node) - return unit.between(this, end); - }; + if (this.firstNode == null) { + this.firstNode = node + this.lastNode = node + node.prev = null + node.next = null + } else { + node.prev = null + node.next = this.firstNode + node.next.prev = node + this.firstNode = node + } +} - _proto.daysUntil = function daysUntil(end) { - return end.toEpochDay() - this.toEpochDay(); - }; +DoublyLinkedList.prototype.pop = function() { + var lastNode = this.lastNode + if (lastNode != null) { + this.remove(lastNode) + } + return lastNode +} - _proto._monthsUntil = function _monthsUntil(end) { - var packed1 = this._prolepticMonth() * 32 + this.dayOfMonth(); - var packed2 = end._prolepticMonth() * 32 + end.dayOfMonth(); - return MathUtil.intDiv(packed2 - packed1, 32); - }; +DoublyLinkedList.prototype.remove = function(node) { + if (this.firstNode == node) { + this.firstNode = node.next + } else if (node.prev != null) { + node.prev.next = node.next + } + if (this.lastNode == node) { + this.lastNode = node.prev + } else if (node.next != null) { + node.next.prev = node.prev + } +} - _proto.until1 = function until1(endDate) { - var end = LocalDate.from(endDate); - var totalMonths = end._prolepticMonth() - this._prolepticMonth(); +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = null +} - var days = end._day - this._day; - if (totalMonths > 0 && days < 0) { - totalMonths--; - var calcDate = this.plusMonths(totalMonths); - days = end.toEpochDay() - calcDate.toEpochDay(); - } else if (totalMonths < 0 && days > 0) { - totalMonths++; - days -= end.lengthOfMonth(); - } +/***/ }), - var years = MathUtil.intDiv(totalMonths, 12); - var months = MathUtil.intMod(totalMonths, 12); - return Period.of(years, months, days); - }; +/***/ 96545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.atTime = function atTime() { - if (arguments.length === 1) { - return this.atTime1.apply(this, arguments); - } else { - return this.atTime4.apply(this, arguments); - } - }; +module.exports = __nccwpck_require__(52618); - _proto.atTime1 = function atTime1(time) { - requireNonNull(time, 'time'); +/***/ }), - if (time instanceof LocalTime) { - return LocalDateTime.of(this, time); - } else if (time instanceof OffsetTime) { - return this._atTimeOffsetTime(time); - } else { - throw new IllegalArgumentException('time must be an instance of LocalTime or OffsetTime' + (time && time.constructor && time.constructor.name ? ', but is ' + time.constructor.name : '')); - } - }; +/***/ 68104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.atTime4 = function atTime4(hour, minute, second, nanoOfSecond) { - if (second === void 0) { - second = 0; - } +"use strict"; - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } - return this.atTime1(LocalTime.of(hour, minute, second, nanoOfSecond)); - }; +var utils = __nccwpck_require__(20328); +var settle = __nccwpck_require__(13211); +var buildFullPath = __nccwpck_require__(41934); +var buildURL = __nccwpck_require__(30646); +var http = __nccwpck_require__(98605); +var https = __nccwpck_require__(57211); +var httpFollow = __nccwpck_require__(67707).http; +var httpsFollow = __nccwpck_require__(67707).https; +var url = __nccwpck_require__(78835); +var zlib = __nccwpck_require__(78761); +var pkg = __nccwpck_require__(20696); +var createError = __nccwpck_require__(15226); +var enhanceError = __nccwpck_require__(21516); - _proto._atTimeOffsetTime = function _atTimeOffsetTime(time) { - return OffsetDateTime.of(LocalDateTime.of(this, time.toLocalTime()), time.offset()); - }; +var isHttps = /https:?/; - _proto.atStartOfDay = function atStartOfDay(zone) { - if (zone != null) { - return this.atStartOfDayWithZone(zone); - } else { - return LocalDateTime.of(this, LocalTime.MIDNIGHT); - } - }; +/** + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} proxy + * @param {string} location + */ +function setProxy(options, proxy, location) { + options.hostname = proxy.host; + options.host = proxy.host; + options.port = proxy.port; + options.path = location; - _proto.atStartOfDayWithZone = function atStartOfDayWithZone(zone) { - requireNonNull(zone, 'zone'); - var ldt = this.atTime(LocalTime.MIDNIGHT); + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } - if (zone instanceof ZoneOffset === false) { - var trans = zone.rules().transition(ldt); + // If a proxy is used, any redirects must also pass through the proxy + options.beforeRedirect = function beforeRedirect(redirection) { + redirection.headers.host = redirection.host; + setProxy(redirection, proxy, redirection.href); + }; +} - if (trans != null && trans.isGap()) { - ldt = trans.dateTimeAfter(); - } - } +/*eslint consistent-return:0*/ +module.exports = function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { + var resolve = function resolve(value) { + resolvePromise(value); + }; + var reject = function reject(value) { + rejectPromise(value); + }; + var data = config.data; + var headers = config.headers; - return ZonedDateTime.of(ldt, zone); - }; + // Set User-Agent (required by some servers) + // Only set header if it hasn't been set in config + // See https://github.com/axios/axios/issues/69 + if (!headers['User-Agent'] && !headers['user-agent']) { + headers['User-Agent'] = 'axios/' + pkg.version; + } - _proto.toEpochDay = function toEpochDay() { - var y = this._year; - var m = this._month; - var total = 0; - total += 365 * y; + if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(createError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + config + )); + } - if (y >= 0) { - total += MathUtil.intDiv(y + 3, 4) - MathUtil.intDiv(y + 99, 100) + MathUtil.intDiv(y + 399, 400); - } else { - total -= MathUtil.intDiv(y, -4) - MathUtil.intDiv(y, -100) + MathUtil.intDiv(y, -400); - } + // Add Content-Length header if data exists + headers['Content-Length'] = data.length; + } - total += MathUtil.intDiv(367 * m - 362, 12); - total += this.dayOfMonth() - 1; + // HTTP basic authentication + var auth = undefined; + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + auth = username + ':' + password; + } - if (m > 2) { - total--; + // Parse url + var fullPath = buildFullPath(config.baseURL, config.url); + var parsed = url.parse(fullPath); + var protocol = parsed.protocol || 'http:'; - if (!IsoChronology.isLeapYear(y)) { - total--; - } - } + if (!auth && parsed.auth) { + var urlAuth = parsed.auth.split(':'); + var urlUsername = urlAuth[0] || ''; + var urlPassword = urlAuth[1] || ''; + auth = urlUsername + ':' + urlPassword; + } - return total - DAYS_0000_TO_1970; - }; + if (auth) { + delete headers.Authorization; + } - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, LocalDate, 'other'); - return this._compareTo0(other); - }; + var isHttpsRequest = isHttps.test(protocol); + var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; - _proto._compareTo0 = function _compareTo0(otherDate) { - var cmp = this._year - otherDate._year; + var options = { + path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), + method: config.method.toUpperCase(), + headers: headers, + agent: agent, + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth: auth + }; - if (cmp === 0) { - cmp = this._month - otherDate._month; + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + } - if (cmp === 0) { - cmp = this._day - otherDate._day; - } - } + var proxy = config.proxy; + if (!proxy && proxy !== false) { + var proxyEnv = protocol.slice(0, -1) + '_proxy'; + var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; + if (proxyUrl) { + var parsedProxyUrl = url.parse(proxyUrl); + var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; + var shouldProxy = true; - return cmp; - }; + if (noProxyEnv) { + var noProxy = noProxyEnv.split(',').map(function trim(s) { + return s.trim(); + }); - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; + shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { + if (!proxyElement) { + return false; + } + if (proxyElement === '*') { + return true; + } + if (proxyElement[0] === '.' && + parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { + return true; + } - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; + return parsed.hostname === proxyElement; + }); + } - _proto.isEqual = function isEqual(other) { - return this.compareTo(other) === 0; - }; + if (shouldProxy) { + proxy = { + host: parsedProxyUrl.hostname, + port: parsedProxyUrl.port, + protocol: parsedProxyUrl.protocol + }; - _proto.equals = function equals(other) { - if (this === other) { - return true; + if (parsedProxyUrl.auth) { + var proxyUrlAuth = parsedProxyUrl.auth.split(':'); + proxy.auth = { + username: proxyUrlAuth[0], + password: proxyUrlAuth[1] + }; + } } + } + } - if (other instanceof LocalDate) { - return this._compareTo0(other) === 0; - } + if (proxy) { + options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); + setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } - return false; - }; + var transport; + var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsProxy ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + transport = isHttpsProxy ? httpsFollow : httpFollow; + } - _proto.hashCode = function hashCode() { - var yearValue = this._year; - var monthValue = this._month; - var dayValue = this._day; - return MathUtil.hash(yearValue & 0xFFFFF800 ^ (yearValue << 11) + (monthValue << 6) + dayValue); - }; + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } - _proto.toString = function toString() { - var dayString, monthString, yearString; - var yearValue = this._year; - var monthValue = this._month; - var dayValue = this._day; - var absYear = Math.abs(yearValue); + // Create the request + var req = transport.request(options, function handleResponse(res) { + if (req.aborted) return; - if (absYear < 1000) { - if (yearValue < 0) { - yearString = '-' + ('' + (yearValue - 10000)).slice(-4); - } else { - yearString = ('' + (yearValue + 10000)).slice(-4); - } - } else { - if (yearValue > 9999) { - yearString = '+' + yearValue; - } else { - yearString = '' + yearValue; - } - } + // uncompress the response body transparently if required + var stream = res; - if (monthValue < 10) { - monthString = '-0' + monthValue; - } else { - monthString = '-' + monthValue; - } + // return the last request in case of redirects + var lastRequest = res.req || req; - if (dayValue < 10) { - dayString = '-0' + dayValue; - } else { - dayString = '-' + dayValue; + + // if no content, is HEAD request or decompress disabled we should not decompress + if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { + switch (res.headers['content-encoding']) { + /*eslint default-case:0*/ + case 'gzip': + case 'compress': + case 'deflate': + // add the unzipper to the body stream processing pipeline + stream = stream.pipe(zlib.createUnzip()); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; } + } - return yearString + monthString + dayString; + var response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: res.headers, + config: config, + request: lastRequest }; - _proto.toJSON = function toJSON() { - return this.toString(); - }; + if (config.responseType === 'stream') { + response.data = stream; + settle(resolve, reject, response); + } else { + var responseBuffer = []; + stream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return _ChronoLocalDate.prototype.format.call(this, formatter); - }; + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { + stream.destroy(); + reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + config, null, lastRequest)); + } + }); - return LocalDate; - }(ChronoLocalDate); - function _init$i() { - LocalDate.MIN = LocalDate.of(YearConstants.MIN_VALUE, 1, 1); - LocalDate.MAX = LocalDate.of(YearConstants.MAX_VALUE, 12, 31); - LocalDate.EPOCH_0 = LocalDate.ofEpochDay(0); - LocalDate.FROM = createTemporalQuery('LocalDate.FROM', function (temporal) { - return LocalDate.from(temporal); - }); - } + stream.on('error', function handleStreamError(err) { + if (req.aborted) return; + reject(enhanceError(err, config, null, lastRequest)); + }); - var ChronoLocalDateTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(ChronoLocalDateTime, _DefaultInterfaceTemp); + stream.on('end', function handleStreamEnd() { + var responseData = Buffer.concat(responseBuffer); + if (config.responseType !== 'arraybuffer') { + responseData = responseData.toString(config.responseEncoding); + if (!config.responseEncoding || config.responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } - function ChronoLocalDateTime() { - return _DefaultInterfaceTemp.apply(this, arguments) || this; + response.data = responseData; + settle(resolve, reject, response); + }); } + }); - var _proto = ChronoLocalDateTime.prototype; - - _proto.chronology = function chronology() { - return this.toLocalDate().chronology(); - }; + // Handle errors + req.on('error', function handleRequestError(err) { + if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; + reject(enhanceError(err, config, null, req)); + }); - _proto.query = function query(_query) { - if (_query === TemporalQueries.chronology()) { - return this.chronology(); - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.localDate()) { - return LocalDate.ofEpochDay(this.toLocalDate().toEpochDay()); - } else if (_query === TemporalQueries.localTime()) { - return this.toLocalTime(); - } else if (_query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } + // Handle request timeout + if (config.timeout) { + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devoring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(config.timeout, function handleRequestTimeout() { + req.abort(); + reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); + }); + } - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (req.aborted) return; - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.EPOCH_DAY, this.toLocalDate().toEpochDay()).with(ChronoField.NANO_OF_DAY, this.toLocalTime().toNanoOfDay()); - }; + req.abort(); + reject(cancel); + }); + } - _proto.toInstant = function toInstant(offset) { - requireInstance(offset, ZoneOffset, 'zoneId'); - return Instant.ofEpochSecond(this.toEpochSecond(offset), this.toLocalTime().nano()); - }; + // Send the request + if (utils.isStream(data)) { + data.on('error', function handleStreamError(err) { + reject(enhanceError(err, config, null, req)); + }).pipe(req); + } else { + req.end(data); + } + }); +}; - _proto.toEpochSecond = function toEpochSecond(offset) { - requireNonNull(offset, 'offset'); - var epochDay = this.toLocalDate().toEpochDay(); - var secs = epochDay * 86400 + this.toLocalTime().toSecondOfDay(); - secs -= offset.totalSeconds(); - return MathUtil.safeToInt(secs); - }; - return ChronoLocalDateTime; - }(DefaultInterfaceTemporal); +/***/ }), - var LocalDateTime = function (_ChronoLocalDateTime) { - _inheritsLoose(LocalDateTime, _ChronoLocalDateTime); +/***/ 3454: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - LocalDateTime.now = function now(clockOrZone) { - if (clockOrZone == null) { - return LocalDateTime._now(Clock.systemDefaultZone()); - } else if (clockOrZone instanceof Clock) { - return LocalDateTime._now(clockOrZone); - } else { - return LocalDateTime._now(Clock.system(clockOrZone)); - } - }; +"use strict"; - LocalDateTime._now = function _now(clock) { - requireNonNull(clock, 'clock'); - return LocalDateTime.ofInstant(clock.instant(), clock.zone()); - }; - LocalDateTime._ofEpochMillis = function _ofEpochMillis(epochMilli, offset) { - var localSecond = MathUtil.floorDiv(epochMilli, 1000) + offset.totalSeconds(); - var localEpochDay = MathUtil.floorDiv(localSecond, LocalTime.SECONDS_PER_DAY); - var secsOfDay = MathUtil.floorMod(localSecond, LocalTime.SECONDS_PER_DAY); - var nanoOfSecond = MathUtil.floorMod(epochMilli, 1000) * 1000000; - var date = LocalDate.ofEpochDay(localEpochDay); - var time = LocalTime.ofSecondOfDay(secsOfDay, nanoOfSecond); - return new LocalDateTime(date, time); - }; +var utils = __nccwpck_require__(20328); +var settle = __nccwpck_require__(13211); +var cookies = __nccwpck_require__(21545); +var buildURL = __nccwpck_require__(30646); +var buildFullPath = __nccwpck_require__(41934); +var parseHeaders = __nccwpck_require__(86455); +var isURLSameOrigin = __nccwpck_require__(33608); +var createError = __nccwpck_require__(15226); - LocalDateTime.of = function of() { - if (arguments.length <= 2) { - return LocalDateTime.ofDateAndTime.apply(this, arguments); - } else { - return LocalDateTime.ofNumbers.apply(this, arguments); - } - }; +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; - LocalDateTime.ofNumbers = function ofNumbers(year, month, dayOfMonth, hour, minute, second, nanoOfSecond) { - if (hour === void 0) { - hour = 0; - } + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } - if (minute === void 0) { - minute = 0; - } + var request = new XMLHttpRequest(); - if (second === void 0) { - second = 0; - } + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - var date = LocalDate.of(year, month, dayOfMonth); - var time = LocalTime.of(hour, minute, second, nanoOfSecond); - return new LocalDateTime(date, time); - }; + // Set the request timeout in MS + request.timeout = config.timeout; - LocalDateTime.ofDateAndTime = function ofDateAndTime(date, time) { - requireNonNull(date, 'date'); - requireNonNull(time, 'time'); - return new LocalDateTime(date, time); - }; + // Listen for ready state + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } - LocalDateTime.ofInstant = function ofInstant(instant, zone) { - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } - requireNonNull(instant, 'instant'); - requireInstance(instant, Instant, 'instant'); - requireNonNull(zone, 'zone'); - var offset = zone.rules().offset(instant); - return LocalDateTime.ofEpochSecond(instant.epochSecond(), instant.nano(), offset); + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request }; - LocalDateTime.ofEpochSecond = function ofEpochSecond(epochSecond, nanoOfSecond, offset) { - if (epochSecond === void 0) { - epochSecond = 0; - } + settle(resolve, reject, response); - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + // Clean up request + request = null; + }; - if (arguments.length === 2 && nanoOfSecond instanceof ZoneOffset) { - offset = nanoOfSecond; - nanoOfSecond = 0; - } + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } - requireNonNull(offset, 'offset'); - var localSecond = epochSecond + offset.totalSeconds(); - var localEpochDay = MathUtil.floorDiv(localSecond, LocalTime.SECONDS_PER_DAY); - var secsOfDay = MathUtil.floorMod(localSecond, LocalTime.SECONDS_PER_DAY); - var date = LocalDate.ofEpochDay(localEpochDay); - var time = LocalTime.ofSecondOfDay(secsOfDay, nanoOfSecond); - return new LocalDateTime(date, time); - }; + reject(createError('Request aborted', config, 'ECONNABORTED', request)); - LocalDateTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); + // Clean up request + request = null; + }; - if (temporal instanceof LocalDateTime) { - return temporal; - } else if (temporal instanceof ZonedDateTime) { - return temporal.toLocalDateTime(); - } + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); - try { - var date = LocalDate.from(temporal); - var time = LocalTime.from(temporal); - return new LocalDateTime(date, time); - } catch (ex) { - throw new DateTimeException("Unable to obtain LocalDateTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } - }; + // Clean up request + request = null; + }; - LocalDateTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; - } + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', + request)); - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, LocalDateTime.FROM); - }; + // Clean up request + request = null; + }; - function LocalDateTime(date, time) { - var _this; + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; - _this = _ChronoLocalDateTime.call(this) || this; - requireInstance(date, LocalDate, 'date'); - requireInstance(time, LocalTime, 'time'); - _this._date = date; - _this._time = time; - return _this; + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; } + } - var _proto = LocalDateTime.prototype; - - _proto._withDateTime = function _withDateTime(newDate, newTime) { - if (this._date.equals(newDate) && this._time.equals(newTime)) { - return this; + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); } + }); + } - return new LocalDateTime(newDate, newTime); - }; + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); + // Add responseType to request if needed + if (config.responseType) { + try { + request.responseType = config.responseType; + } catch (e) { + // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. + // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. + if (config.responseType !== 'json') { + throw e; } + } + } - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; - - _proto.range = function range(field) { - if (field instanceof ChronoField) { - return field.isTimeBased() ? this._time.range(field) : this._date.range(field); - } + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } - return field.rangeRefinedBy(this); - }; + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } - _proto.get = function get(field) { - if (field instanceof ChronoField) { - return field.isTimeBased() ? this._time.get(field) : this._date.get(field); + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; } - return _ChronoLocalDateTime.prototype.get.call(this, field); - }; - - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } - if (field instanceof ChronoField) { - return field.isTimeBased() ? this._time.getLong(field) : this._date.getLong(field); - } + if (!requestData) { + requestData = null; + } - return field.getFrom(this); - }; + // Send the request + request.send(requestData); + }); +}; - _proto.year = function year() { - return this._date.year(); - }; - _proto.monthValue = function monthValue() { - return this._date.monthValue(); - }; +/***/ }), - _proto.month = function month() { - return this._date.month(); - }; +/***/ 52618: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.dayOfMonth = function dayOfMonth() { - return this._date.dayOfMonth(); - }; +"use strict"; - _proto.dayOfYear = function dayOfYear() { - return this._date.dayOfYear(); - }; - _proto.dayOfWeek = function dayOfWeek() { - return this._date.dayOfWeek(); - }; +var utils = __nccwpck_require__(20328); +var bind = __nccwpck_require__(77065); +var Axios = __nccwpck_require__(98178); +var mergeConfig = __nccwpck_require__(74831); +var defaults = __nccwpck_require__(98190); - _proto.hour = function hour() { - return this._time.hour(); - }; +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); - _proto.minute = function minute() { - return this._time.minute(); - }; + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); - _proto.second = function second() { - return this._time.second(); - }; + // Copy context to instance + utils.extend(instance, context); - _proto.nano = function nano() { - return this._time.nano(); - }; + return instance; +} - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); +// Create the default instance to be exported +var axios = createInstance(defaults); - if (adjuster instanceof LocalDate) { - return this._withDateTime(adjuster, this._time); - } else if (adjuster instanceof LocalTime) { - return this._withDateTime(this._date, adjuster); - } else if (adjuster instanceof LocalDateTime) { - return adjuster; - } +// Expose Axios class to allow class inheritance +axios.Axios = Axios; - assert(typeof adjuster.adjustInto === 'function', 'adjuster', IllegalArgumentException); - return adjuster.adjustInto(this); - }; +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(mergeConfig(axios.defaults, instanceConfig)); +}; - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); +// Expose Cancel & CancelToken +axios.Cancel = __nccwpck_require__(98875); +axios.CancelToken = __nccwpck_require__(71587); +axios.isCancel = __nccwpck_require__(64057); - if (field instanceof ChronoField) { - if (field.isTimeBased()) { - return this._withDateTime(this._date, this._time.with(field, newValue)); - } else { - return this._withDateTime(this._date.with(field, newValue), this._time); - } - } +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = __nccwpck_require__(74850); - return field.adjustInto(this, newValue); - }; +// Expose isAxiosError +axios.isAxiosError = __nccwpck_require__(60650); - _proto.withYear = function withYear(year) { - return this._withDateTime(this._date.withYear(year), this._time); - }; +module.exports = axios; - _proto.withMonth = function withMonth(month) { - return this._withDateTime(this._date.withMonth(month), this._time); - }; +// Allow use of default import syntax in TypeScript +module.exports.default = axios; - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - return this._withDateTime(this._date.withDayOfMonth(dayOfMonth), this._time); - }; - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - return this._withDateTime(this._date.withDayOfYear(dayOfYear), this._time); - }; +/***/ }), - _proto.withHour = function withHour(hour) { - var newTime = this._time.withHour(hour); +/***/ 98875: +/***/ ((module) => { - return this._withDateTime(this._date, newTime); - }; +"use strict"; - _proto.withMinute = function withMinute(minute) { - var newTime = this._time.withMinute(minute); - return this._withDateTime(this._date, newTime); - }; +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; +} - _proto.withSecond = function withSecond(second) { - var newTime = this._time.withSecond(second); +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; - return this._withDateTime(this._date, newTime); - }; +Cancel.prototype.__CANCEL__ = true; - _proto.withNano = function withNano(nanoOfSecond) { - var newTime = this._time.withNano(nanoOfSecond); +module.exports = Cancel; - return this._withDateTime(this._date, newTime); - }; - _proto.truncatedTo = function truncatedTo(unit) { - return this._withDateTime(this._date, this._time.truncatedTo(unit)); - }; +/***/ }), - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; +/***/ 71587: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(unit, 'unit'); +"use strict"; - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); - case ChronoUnit.MICROS: - return this.plusDays(MathUtil.intDiv(amountToAdd, LocalTime.MICROS_PER_DAY)).plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MICROS_PER_DAY) * 1000); +var Cancel = __nccwpck_require__(98875); - case ChronoUnit.MILLIS: - return this.plusDays(MathUtil.intDiv(amountToAdd, LocalTime.MILLIS_PER_DAY)).plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MILLIS_PER_DAY) * 1000000); +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); - case ChronoUnit.MINUTES: - return this.plusMinutes(amountToAdd); + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } - case ChronoUnit.HOURS: - return this.plusHours(amountToAdd); + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); +} - case ChronoUnit.HALF_DAYS: - return this.plusDays(MathUtil.intDiv(amountToAdd, 256)).plusHours(MathUtil.intMod(amountToAdd, 256) * 12); - } +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; - return this._withDateTime(this._date.plus(amountToAdd, unit), this._time); - } +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; - return unit.addTo(this, amountToAdd); - }; +module.exports = CancelToken; - _proto.plusYears = function plusYears(years) { - var newDate = this._date.plusYears(years); - return this._withDateTime(newDate, this._time); - }; +/***/ }), - _proto.plusMonths = function plusMonths(months) { - var newDate = this._date.plusMonths(months); +/***/ 64057: +/***/ ((module) => { - return this._withDateTime(newDate, this._time); - }; +"use strict"; - _proto.plusWeeks = function plusWeeks(weeks) { - var newDate = this._date.plusWeeks(weeks); - return this._withDateTime(newDate, this._time); - }; +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; - _proto.plusDays = function plusDays(days) { - var newDate = this._date.plusDays(days); - return this._withDateTime(newDate, this._time); - }; +/***/ }), - _proto.plusHours = function plusHours(hours) { - return this._plusWithOverflow(this._date, hours, 0, 0, 0, 1); - }; - - _proto.plusMinutes = function plusMinutes(minutes) { - return this._plusWithOverflow(this._date, 0, minutes, 0, 0, 1); - }; - - _proto.plusSeconds = function plusSeconds(seconds) { - return this._plusWithOverflow(this._date, 0, 0, seconds, 0, 1); - }; - - _proto.plusNanos = function plusNanos(nanos) { - return this._plusWithOverflow(this._date, 0, 0, 0, nanos, 1); - }; - - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; +/***/ 98178: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(unit, 'unit'); - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; +"use strict"; - _proto.minusYears = function minusYears(years) { - return this.plusYears(-1 * years); - }; - _proto.minusMonths = function minusMonths(months) { - return this.plusMonths(-1 * months); - }; +var utils = __nccwpck_require__(20328); +var buildURL = __nccwpck_require__(30646); +var InterceptorManager = __nccwpck_require__(3214); +var dispatchRequest = __nccwpck_require__(85062); +var mergeConfig = __nccwpck_require__(74831); - _proto.minusWeeks = function minusWeeks(weeks) { - return this.plusWeeks(-1 * weeks); - }; +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} - _proto.minusDays = function minusDays(days) { - return this.plusDays(-1 * days); - }; +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } - _proto.minusHours = function minusHours(hours) { - return this._plusWithOverflow(this._date, hours, 0, 0, 0, -1); - }; + config = mergeConfig(this.defaults, config); - _proto.minusMinutes = function minusMinutes(minutes) { - return this._plusWithOverflow(this._date, 0, minutes, 0, 0, -1); - }; + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } - _proto.minusSeconds = function minusSeconds(seconds) { - return this._plusWithOverflow(this._date, 0, 0, seconds, 0, -1); - }; + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); - _proto.minusNanos = function minusNanos(nanos) { - return this._plusWithOverflow(this._date, 0, 0, 0, nanos, -1); - }; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); - _proto._plusWithOverflow = function _plusWithOverflow(newDate, hours, minutes, seconds, nanos, sign) { - if (hours === 0 && minutes === 0 && seconds === 0 && nanos === 0) { - return this._withDateTime(newDate, this._time); - } + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); - var totDays = MathUtil.intDiv(nanos, LocalTime.NANOS_PER_DAY) + MathUtil.intDiv(seconds, LocalTime.SECONDS_PER_DAY) + MathUtil.intDiv(minutes, LocalTime.MINUTES_PER_DAY) + MathUtil.intDiv(hours, LocalTime.HOURS_PER_DAY); - totDays *= sign; - var totNanos = MathUtil.intMod(nanos, LocalTime.NANOS_PER_DAY) + MathUtil.intMod(seconds, LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + MathUtil.intMod(minutes, LocalTime.MINUTES_PER_DAY) * LocalTime.NANOS_PER_MINUTE + MathUtil.intMod(hours, LocalTime.HOURS_PER_DAY) * LocalTime.NANOS_PER_HOUR; + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } - var curNoD = this._time.toNanoOfDay(); + return promise; +}; - totNanos = totNanos * sign + curNoD; - totDays += MathUtil.floorDiv(totNanos, LocalTime.NANOS_PER_DAY); - var newNoD = MathUtil.floorMod(totNanos, LocalTime.NANOS_PER_DAY); - var newTime = newNoD === curNoD ? this._time : LocalTime.ofNanoOfDay(newNoD); - return this._withDateTime(newDate.plusDays(totDays), newTime); - }; +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); +}; - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); - if (_query === TemporalQueries.localDate()) { - return this.toLocalDate(); - } +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); - return _ChronoLocalDateTime.prototype.query.call(this, _query); - }; +module.exports = Axios; - _proto.adjustInto = function adjustInto(temporal) { - return _ChronoLocalDateTime.prototype.adjustInto.call(this, temporal); - }; - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = LocalDateTime.from(endExclusive); +/***/ }), - if (unit instanceof ChronoUnit) { - if (unit.isTimeBased()) { - var daysUntil = this._date.daysUntil(end._date); +/***/ 3214: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var timeUntil = end._time.toNanoOfDay() - this._time.toNanoOfDay(); +"use strict"; - if (daysUntil > 0 && timeUntil < 0) { - daysUntil--; - timeUntil += LocalTime.NANOS_PER_DAY; - } else if (daysUntil < 0 && timeUntil > 0) { - daysUntil++; - timeUntil -= LocalTime.NANOS_PER_DAY; - } - var amount = daysUntil; +var utils = __nccwpck_require__(20328); - switch (unit) { - case ChronoUnit.NANOS: - amount = MathUtil.safeMultiply(amount, LocalTime.NANOS_PER_DAY); - return MathUtil.safeAdd(amount, timeUntil); +function InterceptorManager() { + this.handlers = []; +} - case ChronoUnit.MICROS: - amount = MathUtil.safeMultiply(amount, LocalTime.MICROS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, 1000)); +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; +}; - case ChronoUnit.MILLIS: - amount = MathUtil.safeMultiply(amount, LocalTime.MILLIS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, 1000000)); +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; - case ChronoUnit.SECONDS: - amount = MathUtil.safeMultiply(amount, LocalTime.SECONDS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_SECOND)); +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; - case ChronoUnit.MINUTES: - amount = MathUtil.safeMultiply(amount, LocalTime.MINUTES_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_MINUTE)); +module.exports = InterceptorManager; - case ChronoUnit.HOURS: - amount = MathUtil.safeMultiply(amount, LocalTime.HOURS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_HOUR)); - case ChronoUnit.HALF_DAYS: - amount = MathUtil.safeMultiply(amount, 2); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_HOUR * 12)); - } +/***/ }), - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +/***/ 41934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var endDate = end._date; - var endTime = end._time; +"use strict"; - if (endDate.isAfter(this._date) && endTime.isBefore(this._time)) { - endDate = endDate.minusDays(1); - } else if (endDate.isBefore(this._date) && endTime.isAfter(this._time)) { - endDate = endDate.plusDays(1); - } - return this._date.until(endDate, unit); - } +var isAbsoluteURL = __nccwpck_require__(41301); +var combineURLs = __nccwpck_require__(57189); - return unit.between(this, end); - }; +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +}; - _proto.atOffset = function atOffset(offset) { - return OffsetDateTime.of(this, offset); - }; - _proto.atZone = function atZone(zone) { - return ZonedDateTime.of(this, zone); - }; +/***/ }), - _proto.toLocalDate = function toLocalDate() { - return this._date; - }; +/***/ 15226: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.toLocalTime = function toLocalTime() { - return this._time; - }; +"use strict"; - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, LocalDateTime, 'other'); - return this._compareTo0(other); - }; - _proto._compareTo0 = function _compareTo0(other) { - var cmp = this._date.compareTo(other.toLocalDate()); +var enhanceError = __nccwpck_require__(21516); - if (cmp === 0) { - cmp = this._time.compareTo(other.toLocalTime()); - } +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); +}; - return cmp; - }; - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; +/***/ }), - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; +/***/ 85062: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.isEqual = function isEqual(other) { - return this.compareTo(other) === 0; - }; +"use strict"; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - if (other instanceof LocalDateTime) { - return this._date.equals(other._date) && this._time.equals(other._time); - } +var utils = __nccwpck_require__(20328); +var transformData = __nccwpck_require__(19812); +var isCancel = __nccwpck_require__(64057); +var defaults = __nccwpck_require__(98190); - return false; - }; +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } +} - _proto.hashCode = function hashCode() { - return this._date.hashCode() ^ this._time.hashCode(); - }; +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); - _proto.toString = function toString() { - return this._date.toString() + 'T' + this._time.toString(); - }; + // Ensure headers exist + config.headers = config.headers || {}; - _proto.toJSON = function toJSON() { - return this.toString(); - }; + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); - return LocalDateTime; - }(ChronoLocalDateTime); - function _init$j() { - LocalDateTime.MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN); - LocalDateTime.MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX); - LocalDateTime.FROM = createTemporalQuery('LocalDateTime.FROM', function (temporal) { - return LocalDateTime.from(temporal); - }); + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; } + ); - var LocalTime = function (_Temporal) { - _inheritsLoose(LocalTime, _Temporal); - - LocalTime.now = function now(clockOrZone) { - if (clockOrZone == null) { - return LocalTime._now(Clock.systemDefaultZone()); - } else if (clockOrZone instanceof Clock) { - return LocalTime._now(clockOrZone); - } else { - return LocalTime._now(Clock.system(clockOrZone)); - } - }; - - LocalTime._now = function _now(clock) { - if (clock === void 0) { - clock = Clock.systemDefaultZone(); - } - - requireNonNull(clock, 'clock'); - return LocalTime.ofInstant(clock.instant(), clock.zone()); - }; - - LocalTime.ofInstant = function ofInstant(instant, zone) { - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } - - var offset = zone.rules().offset(instant); - var secsOfDay = MathUtil.intMod(instant.epochSecond(), LocalTime.SECONDS_PER_DAY); - secsOfDay = MathUtil.intMod(secsOfDay + offset.totalSeconds(), LocalTime.SECONDS_PER_DAY); - - if (secsOfDay < 0) { - secsOfDay += LocalTime.SECONDS_PER_DAY; - } - - return LocalTime.ofSecondOfDay(secsOfDay, instant.nano()); - }; + var adapter = config.adapter || defaults.adapter; - LocalTime.of = function of(hour, minute, second, nanoOfSecond) { - return new LocalTime(hour, minute, second, nanoOfSecond); - }; + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); - LocalTime.ofSecondOfDay = function ofSecondOfDay(secondOfDay, nanoOfSecond) { - if (secondOfDay === void 0) { - secondOfDay = 0; - } + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); - ChronoField.SECOND_OF_DAY.checkValidValue(secondOfDay); - ChronoField.NANO_OF_SECOND.checkValidValue(nanoOfSecond); - var hours = MathUtil.intDiv(secondOfDay, LocalTime.SECONDS_PER_HOUR); - secondOfDay -= hours * LocalTime.SECONDS_PER_HOUR; - var minutes = MathUtil.intDiv(secondOfDay, LocalTime.SECONDS_PER_MINUTE); - secondOfDay -= minutes * LocalTime.SECONDS_PER_MINUTE; - return new LocalTime(hours, minutes, secondOfDay, nanoOfSecond); - }; + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } - LocalTime.ofNanoOfDay = function ofNanoOfDay(nanoOfDay) { - if (nanoOfDay === void 0) { - nanoOfDay = 0; - } + return Promise.reject(reason); + }); +}; - ChronoField.NANO_OF_DAY.checkValidValue(nanoOfDay); - var hours = MathUtil.intDiv(nanoOfDay, LocalTime.NANOS_PER_HOUR); - nanoOfDay -= hours * LocalTime.NANOS_PER_HOUR; - var minutes = MathUtil.intDiv(nanoOfDay, LocalTime.NANOS_PER_MINUTE); - nanoOfDay -= minutes * LocalTime.NANOS_PER_MINUTE; - var seconds = MathUtil.intDiv(nanoOfDay, LocalTime.NANOS_PER_SECOND); - nanoOfDay -= seconds * LocalTime.NANOS_PER_SECOND; - return new LocalTime(hours, minutes, seconds, nanoOfDay); - }; - LocalTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - var time = temporal.query(TemporalQueries.localTime()); +/***/ }), - if (time == null) { - throw new DateTimeException("Unable to obtain LocalTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } +/***/ 21516: +/***/ ((module) => { - return time; - }; +"use strict"; - LocalTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_LOCAL_TIME; - } - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, LocalTime.FROM); - }; +/** + * Update an Error with the specified config, error code, and response. + * + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. + */ +module.exports = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } - function LocalTime(hour, minute, second, nanoOfSecond) { - var _this; + error.request = request; + error.response = response; + error.isAxiosError = true; - if (hour === void 0) { - hour = 0; - } + error.toJSON = function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; + return error; +}; - if (minute === void 0) { - minute = 0; - } - if (second === void 0) { - second = 0; - } +/***/ }), - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } +/***/ 74831: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _this = _Temporal.call(this) || this; +"use strict"; - var _hour = MathUtil.safeToInt(hour); - var _minute = MathUtil.safeToInt(minute); +var utils = __nccwpck_require__(20328); - var _second = MathUtil.safeToInt(second); +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; - var _nanoOfSecond = MathUtil.safeToInt(nanoOfSecond); + var valueFromConfig2Keys = ['url', 'method', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; + var defaultToConfig2Keys = [ + 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', + 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' + ]; + var directMergeKeys = ['validateStatus']; - LocalTime._validate(_hour, _minute, _second, _nanoOfSecond); + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } - if (_minute === 0 && _second === 0 && _nanoOfSecond === 0) { - if (!LocalTime.HOURS[_hour]) { - _this._hour = _hour; - _this._minute = _minute; - _this._second = _second; - _this._nano = _nanoOfSecond; - LocalTime.HOURS[_hour] = _assertThisInitialized(_this); - } + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + } - return LocalTime.HOURS[_hour] || _assertThisInitialized(_this); - } + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } + }); - _this._hour = _hour; - _this._minute = _minute; - _this._second = _second; - _this._nano = _nanoOfSecond; - return _this; - } + utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); - LocalTime._validate = function _validate(hour, minute, second, nanoOfSecond) { - ChronoField.HOUR_OF_DAY.checkValidValue(hour); - ChronoField.MINUTE_OF_HOUR.checkValidValue(minute); - ChronoField.SECOND_OF_MINUTE.checkValidValue(second); - ChronoField.NANO_OF_SECOND.checkValidValue(nanoOfSecond); - }; + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); - var _proto = LocalTime.prototype; + utils.forEach(directMergeKeys, function merge(prop) { + if (prop in config2) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isTimeBased(); - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isTimeBased(); - } + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys) + .concat(directMergeKeys); - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; + var otherKeys = Object + .keys(config1) + .concat(Object.keys(config2)) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); - _proto.range = function range(field) { - requireNonNull(field); - return _Temporal.prototype.range.call(this, field); - }; + utils.forEach(otherKeys, mergeDeepProperties); - _proto.get = function get(field) { - return this.getLong(field); - }; + return config; +}; - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); - if (field instanceof ChronoField) { - return this._get0(field); - } +/***/ }), - return field.getFrom(this); - }; +/***/ 13211: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto._get0 = function _get0(field) { - switch (field) { - case ChronoField.NANO_OF_SECOND: - return this._nano; +"use strict"; - case ChronoField.NANO_OF_DAY: - return this.toNanoOfDay(); - case ChronoField.MICRO_OF_SECOND: - return MathUtil.intDiv(this._nano, 1000); +var createError = __nccwpck_require__(15226); - case ChronoField.MICRO_OF_DAY: - return MathUtil.intDiv(this.toNanoOfDay(), 1000); +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + */ +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } +}; - case ChronoField.MILLI_OF_SECOND: - return MathUtil.intDiv(this._nano, 1000000); - case ChronoField.MILLI_OF_DAY: - return MathUtil.intDiv(this.toNanoOfDay(), 1000000); +/***/ }), - case ChronoField.SECOND_OF_MINUTE: - return this._second; +/***/ 19812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case ChronoField.SECOND_OF_DAY: - return this.toSecondOfDay(); +"use strict"; - case ChronoField.MINUTE_OF_HOUR: - return this._minute; - case ChronoField.MINUTE_OF_DAY: - return this._hour * 60 + this._minute; +var utils = __nccwpck_require__(20328); - case ChronoField.HOUR_OF_AMPM: - return MathUtil.intMod(this._hour, 12); +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); - case ChronoField.CLOCK_HOUR_OF_AMPM: - { - var ham = MathUtil.intMod(this._hour, 12); - return ham % 12 === 0 ? 12 : ham; - } + return data; +}; - case ChronoField.HOUR_OF_DAY: - return this._hour; - case ChronoField.CLOCK_HOUR_OF_DAY: - return this._hour === 0 ? 24 : this._hour; +/***/ }), - case ChronoField.AMPM_OF_DAY: - return MathUtil.intDiv(this._hour, 12); - } +/***/ 98190: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - }; +"use strict"; - _proto.hour = function hour() { - return this._hour; - }; - _proto.minute = function minute() { - return this._minute; - }; +var utils = __nccwpck_require__(20328); +var normalizeHeaderName = __nccwpck_require__(36240); - _proto.second = function second() { - return this._second; - }; +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; - _proto.nano = function nano() { - return this._nano; - }; +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __nccwpck_require__(3454); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __nccwpck_require__(68104); + } + return adapter; +} - if (adjuster instanceof LocalTime) { - return adjuster; - } +var defaults = { + adapter: getDefaultAdapter(), - assert(typeof adjuster.adjustInto === 'function', 'adjuster', IllegalArgumentException); - return adjuster.adjustInto(this); - }; + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], - if (field instanceof ChronoField) { - field.checkValidValue(newValue); + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, - switch (field) { - case ChronoField.NANO_OF_SECOND: - return this.withNano(newValue); + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', - case ChronoField.NANO_OF_DAY: - return LocalTime.ofNanoOfDay(newValue); + maxContentLength: -1, + maxBodyLength: -1, - case ChronoField.MICRO_OF_SECOND: - return this.withNano(newValue * 1000); + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } +}; - case ChronoField.MICRO_OF_DAY: - return LocalTime.ofNanoOfDay(newValue * 1000); +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; - case ChronoField.MILLI_OF_SECOND: - return this.withNano(newValue * 1000000); +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); - case ChronoField.MILLI_OF_DAY: - return LocalTime.ofNanoOfDay(newValue * 1000000); +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); - case ChronoField.SECOND_OF_MINUTE: - return this.withSecond(newValue); +module.exports = defaults; - case ChronoField.SECOND_OF_DAY: - return this.plusSeconds(newValue - this.toSecondOfDay()); - case ChronoField.MINUTE_OF_HOUR: - return this.withMinute(newValue); +/***/ }), - case ChronoField.MINUTE_OF_DAY: - return this.plusMinutes(newValue - (this._hour * 60 + this._minute)); +/***/ 77065: +/***/ ((module) => { - case ChronoField.HOUR_OF_AMPM: - return this.plusHours(newValue - MathUtil.intMod(this._hour, 12)); +"use strict"; - case ChronoField.CLOCK_HOUR_OF_AMPM: - return this.plusHours((newValue === 12 ? 0 : newValue) - MathUtil.intMod(this._hour, 12)); - case ChronoField.HOUR_OF_DAY: - return this.withHour(newValue); +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; - case ChronoField.CLOCK_HOUR_OF_DAY: - return this.withHour(newValue === 24 ? 0 : newValue); - case ChronoField.AMPM_OF_DAY: - return this.plusHours((newValue - MathUtil.intDiv(this._hour, 12)) * 12); - } +/***/ }), - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +/***/ 30646: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return field.adjustInto(this, newValue); - }; +"use strict"; - _proto.withHour = function withHour(hour) { - if (hour === void 0) { - hour = 0; - } - if (this._hour === hour) { - return this; - } +var utils = __nccwpck_require__(20328); - return new LocalTime(hour, this._minute, this._second, this._nano); - }; +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} - _proto.withMinute = function withMinute(minute) { - if (minute === void 0) { - minute = 0; - } +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } - if (this._minute === minute) { - return this; - } + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; - return new LocalTime(this._hour, minute, this._second, this._nano); - }; + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } - _proto.withSecond = function withSecond(second) { - if (second === void 0) { - second = 0; - } + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } - if (this._second === second) { - return this; + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); } + parts.push(encode(key) + '=' + encode(v)); + }); + }); - return new LocalTime(this._hour, this._minute, second, this._nano); - }; - - _proto.withNano = function withNano(nanoOfSecond) { - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + serializedParams = parts.join('&'); + } - if (this._nano === nanoOfSecond) { - return this; - } + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } - return new LocalTime(this._hour, this._minute, this._second, nanoOfSecond); - }; + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } - _proto.truncatedTo = function truncatedTo(unit) { - requireNonNull(unit, 'unit'); + return url; +}; - if (unit === ChronoUnit.NANOS) { - return this; - } - var unitDur = unit.duration(); +/***/ }), - if (unitDur.seconds() > LocalTime.SECONDS_PER_DAY) { - throw new DateTimeException('Unit is too large to be used for truncation'); - } +/***/ 57189: +/***/ ((module) => { - var dur = unitDur.toNanos(); +"use strict"; - if (MathUtil.intMod(LocalTime.NANOS_PER_DAY, dur) !== 0) { - throw new DateTimeException('Unit must divide into a standard day without remainder'); - } - var nod = this.toNanoOfDay(); - return LocalTime.ofNanoOfDay(MathUtil.intDiv(nod, dur) * dur); - }; +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(unit, 'unit'); +/***/ }), - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); +/***/ 21545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case ChronoUnit.MICROS: - return this.plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MICROS_PER_DAY) * 1000); +"use strict"; - case ChronoUnit.MILLIS: - return this.plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MILLIS_PER_DAY) * 1000000); - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); +var utils = __nccwpck_require__(20328); - case ChronoUnit.MINUTES: - return this.plusMinutes(amountToAdd); +module.exports = ( + utils.isStandardBrowserEnv() ? - case ChronoUnit.HOURS: - return this.plusHours(amountToAdd); + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); - case ChronoUnit.HALF_DAYS: - return this.plusHours(MathUtil.intMod(amountToAdd, 2) * 12); + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); } - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } - - return unit.addTo(this, amountToAdd); - }; - - _proto.plusHours = function plusHours(hoursToAdd) { - if (hoursToAdd === 0) { - return this; - } - - var newHour = MathUtil.intMod(MathUtil.intMod(hoursToAdd, LocalTime.HOURS_PER_DAY) + this._hour + LocalTime.HOURS_PER_DAY, LocalTime.HOURS_PER_DAY); - return new LocalTime(newHour, this._minute, this._second, this._nano); - }; - - _proto.plusMinutes = function plusMinutes(minutesToAdd) { - if (minutesToAdd === 0) { - return this; - } - - var mofd = this._hour * LocalTime.MINUTES_PER_HOUR + this._minute; - var newMofd = MathUtil.intMod(MathUtil.intMod(minutesToAdd, LocalTime.MINUTES_PER_DAY) + mofd + LocalTime.MINUTES_PER_DAY, LocalTime.MINUTES_PER_DAY); - - if (mofd === newMofd) { - return this; - } - - var newHour = MathUtil.intDiv(newMofd, LocalTime.MINUTES_PER_HOUR); - var newMinute = MathUtil.intMod(newMofd, LocalTime.MINUTES_PER_HOUR); - return new LocalTime(newHour, newMinute, this._second, this._nano); - }; - - _proto.plusSeconds = function plusSeconds(secondsToAdd) { - if (secondsToAdd === 0) { - return this; - } - - var sofd = this._hour * LocalTime.SECONDS_PER_HOUR + this._minute * LocalTime.SECONDS_PER_MINUTE + this._second; - var newSofd = MathUtil.intMod(MathUtil.intMod(secondsToAdd, LocalTime.SECONDS_PER_DAY) + sofd + LocalTime.SECONDS_PER_DAY, LocalTime.SECONDS_PER_DAY); + if (utils.isString(path)) { + cookie.push('path=' + path); + } - if (sofd === newSofd) { - return this; - } + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } - var newHour = MathUtil.intDiv(newSofd, LocalTime.SECONDS_PER_HOUR); - var newMinute = MathUtil.intMod(MathUtil.intDiv(newSofd, LocalTime.SECONDS_PER_MINUTE), LocalTime.MINUTES_PER_HOUR); - var newSecond = MathUtil.intMod(newSofd, LocalTime.SECONDS_PER_MINUTE); - return new LocalTime(newHour, newMinute, newSecond, this._nano); - }; + if (secure === true) { + cookie.push('secure'); + } - _proto.plusNanos = function plusNanos(nanosToAdd) { - if (nanosToAdd === 0) { - return this; - } + document.cookie = cookie.join('; '); + }, - var nofd = this.toNanoOfDay(); - var newNofd = MathUtil.intMod(MathUtil.intMod(nanosToAdd, LocalTime.NANOS_PER_DAY) + nofd + LocalTime.NANOS_PER_DAY, LocalTime.NANOS_PER_DAY); + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, - if (nofd === newNofd) { - return this; + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); } - - var newHour = MathUtil.intDiv(newNofd, LocalTime.NANOS_PER_HOUR); - var newMinute = MathUtil.intMod(MathUtil.intDiv(newNofd, LocalTime.NANOS_PER_MINUTE), LocalTime.MINUTES_PER_HOUR); - var newSecond = MathUtil.intMod(MathUtil.intDiv(newNofd, LocalTime.NANOS_PER_SECOND), LocalTime.SECONDS_PER_MINUTE); - var newNano = MathUtil.intMod(newNofd, LocalTime.NANOS_PER_SECOND); - return new LocalTime(newHour, newMinute, newSecond, newNano); - }; - - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(unit, 'unit'); - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; - - _proto.minusHours = function minusHours(hoursToSubtract) { - return this.plusHours(-1 * MathUtil.intMod(hoursToSubtract, LocalTime.HOURS_PER_DAY)); - }; - - _proto.minusMinutes = function minusMinutes(minutesToSubtract) { - return this.plusMinutes(-1 * MathUtil.intMod(minutesToSubtract, LocalTime.MINUTES_PER_DAY)); - }; - - _proto.minusSeconds = function minusSeconds(secondsToSubtract) { - return this.plusSeconds(-1 * MathUtil.intMod(secondsToSubtract, LocalTime.SECONDS_PER_DAY)); }; + })() : - _proto.minusNanos = function minusNanos(nanosToSubtract) { - return this.plusNanos(-1 * MathUtil.intMod(nanosToSubtract, LocalTime.NANOS_PER_DAY)); + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} }; + })() +); - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - - if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.localTime()) { - return this; - } - if (_query === TemporalQueries.chronology() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.zone() || _query === TemporalQueries.offset() || _query === TemporalQueries.localDate()) { - return null; - } +/***/ }), - return _query.queryFrom(this); - }; +/***/ 41301: +/***/ ((module) => { - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(LocalTime.NANO_OF_DAY, this.toNanoOfDay()); - }; +"use strict"; - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = LocalTime.from(endExclusive); - if (unit instanceof ChronoUnit) { - var nanosUntil = end.toNanoOfDay() - this.toNanoOfDay(); +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; - switch (unit) { - case ChronoUnit.NANOS: - return nanosUntil; - case ChronoUnit.MICROS: - return MathUtil.intDiv(nanosUntil, 1000); +/***/ }), - case ChronoUnit.MILLIS: - return MathUtil.intDiv(nanosUntil, 1000000); +/***/ 60650: +/***/ ((module) => { - case ChronoUnit.SECONDS: - return MathUtil.intDiv(nanosUntil, LocalTime.NANOS_PER_SECOND); +"use strict"; - case ChronoUnit.MINUTES: - return MathUtil.intDiv(nanosUntil, LocalTime.NANOS_PER_MINUTE); - case ChronoUnit.HOURS: - return MathUtil.intDiv(nanosUntil, LocalTime.NANOS_PER_HOUR); +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); +}; - case ChronoUnit.HALF_DAYS: - return MathUtil.intDiv(nanosUntil, 12 * LocalTime.NANOS_PER_HOUR); - } - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +/***/ }), - return unit.between(this, end); - }; +/***/ 33608: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.atDate = function atDate(date) { - return LocalDateTime.of(date, this); - }; +"use strict"; - _proto.toSecondOfDay = function toSecondOfDay() { - var total = this._hour * LocalTime.SECONDS_PER_HOUR; - total += this._minute * LocalTime.SECONDS_PER_MINUTE; - total += this._second; - return total; - }; - _proto.toNanoOfDay = function toNanoOfDay() { - var total = this._hour * LocalTime.NANOS_PER_HOUR; - total += this._minute * LocalTime.NANOS_PER_MINUTE; - total += this._second * LocalTime.NANOS_PER_SECOND; - total += this._nano; - return total; - }; +var utils = __nccwpck_require__(20328); - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, LocalTime, 'other'); - var cmp = MathUtil.compareNumbers(this._hour, other._hour); +module.exports = ( + utils.isStandardBrowserEnv() ? - if (cmp === 0) { - cmp = MathUtil.compareNumbers(this._minute, other._minute); + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; - if (cmp === 0) { - cmp = MathUtil.compareNumbers(this._second, other._second); + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; - if (cmp === 0) { - cmp = MathUtil.compareNumbers(this._nano, other._nano); - } - } + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; } - return cmp; - }; - - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; - - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; + urlParsingNode.setAttribute('href', href); - _proto.equals = function equals(other) { - if (this === other) { - return true; - } + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } - if (other instanceof LocalTime) { - return this._hour === other._hour && this._minute === other._minute && this._second === other._second && this._nano === other._nano; - } + originURL = resolveURL(window.location.href); - return false; + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); }; + })() : - _proto.hashCode = function hashCode() { - var nod = this.toNanoOfDay(); - return MathUtil.hash(nod); + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; }; + })() +); - _proto.toString = function toString() { - var buf = ''; - var hourValue = this._hour; - var minuteValue = this._minute; - var secondValue = this._second; - var nanoValue = this._nano; - buf += hourValue < 10 ? '0' : ''; - buf += hourValue; - buf += minuteValue < 10 ? ':0' : ':'; - buf += minuteValue; - - if (secondValue > 0 || nanoValue > 0) { - buf += secondValue < 10 ? ':0' : ':'; - buf += secondValue; - - if (nanoValue > 0) { - buf += '.'; - - if (MathUtil.intMod(nanoValue, 1000000) === 0) { - buf += ('' + (MathUtil.intDiv(nanoValue, 1000000) + 1000)).substring(1); - } else if (MathUtil.intMod(nanoValue, 1000) === 0) { - buf += ('' + (MathUtil.intDiv(nanoValue, 1000) + 1000000)).substring(1); - } else { - buf += ('' + (nanoValue + 1000000000)).substring(1); - } - } - } - return buf; - }; +/***/ }), - _proto.toJSON = function toJSON() { - return this.toString(); - }; +/***/ 36240: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; +"use strict"; - return LocalTime; - }(Temporal); - function _init$k() { - LocalTime.HOURS = []; - for (var hour = 0; hour < 24; hour++) { - LocalTime.of(hour, 0, 0, 0); - } +var utils = __nccwpck_require__(20328); - LocalTime.MIN = LocalTime.HOURS[0]; - LocalTime.MAX = new LocalTime(23, 59, 59, 999999999); - LocalTime.MIDNIGHT = LocalTime.HOURS[0]; - LocalTime.NOON = LocalTime.HOURS[12]; - LocalTime.FROM = createTemporalQuery('LocalTime.FROM', function (temporal) { - return LocalTime.from(temporal); - }); +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; } - LocalTime.HOURS_PER_DAY = 24; - LocalTime.MINUTES_PER_HOUR = 60; - LocalTime.MINUTES_PER_DAY = LocalTime.MINUTES_PER_HOUR * LocalTime.HOURS_PER_DAY; - LocalTime.SECONDS_PER_MINUTE = 60; - LocalTime.SECONDS_PER_HOUR = LocalTime.SECONDS_PER_MINUTE * LocalTime.MINUTES_PER_HOUR; - LocalTime.SECONDS_PER_DAY = LocalTime.SECONDS_PER_HOUR * LocalTime.HOURS_PER_DAY; - LocalTime.MILLIS_PER_DAY = LocalTime.SECONDS_PER_DAY * 1000; - LocalTime.MICROS_PER_DAY = LocalTime.SECONDS_PER_DAY * 1000000; - LocalTime.NANOS_PER_SECOND = 1000000000; - LocalTime.NANOS_PER_MINUTE = LocalTime.NANOS_PER_SECOND * LocalTime.SECONDS_PER_MINUTE; - LocalTime.NANOS_PER_HOUR = LocalTime.NANOS_PER_MINUTE * LocalTime.MINUTES_PER_HOUR; - LocalTime.NANOS_PER_DAY = LocalTime.NANOS_PER_HOUR * LocalTime.HOURS_PER_DAY; - - var NANOS_PER_MILLI = 1000000; - var Instant = function (_Temporal) { - _inheritsLoose(Instant, _Temporal); - - Instant.now = function now(clock) { - if (clock === void 0) { - clock = Clock.systemUTC(); - } - - return clock.instant(); - }; - - Instant.ofEpochSecond = function ofEpochSecond(epochSecond, nanoAdjustment) { - if (nanoAdjustment === void 0) { - nanoAdjustment = 0; - } - - var secs = epochSecond + MathUtil.floorDiv(nanoAdjustment, LocalTime.NANOS_PER_SECOND); - var nos = MathUtil.floorMod(nanoAdjustment, LocalTime.NANOS_PER_SECOND); - return Instant._create(secs, nos); - }; + }); +}; - Instant.ofEpochMilli = function ofEpochMilli(epochMilli) { - var secs = MathUtil.floorDiv(epochMilli, 1000); - var mos = MathUtil.floorMod(epochMilli, 1000); - return Instant._create(secs, mos * 1000000); - }; - Instant.from = function from(temporal) { - try { - var instantSecs = temporal.getLong(ChronoField.INSTANT_SECONDS); - var nanoOfSecond = temporal.get(ChronoField.NANO_OF_SECOND); - return Instant.ofEpochSecond(instantSecs, nanoOfSecond); - } catch (ex) { - throw new DateTimeException('Unable to obtain Instant from TemporalAccessor: ' + temporal + ', type ' + typeof temporal, ex); - } - }; +/***/ }), - Instant.parse = function parse(text) { - return DateTimeFormatter.ISO_INSTANT.parse(text, Instant.FROM); - }; +/***/ 86455: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Instant._create = function _create(seconds, nanoOfSecond) { - if (seconds === 0 && nanoOfSecond === 0) { - return Instant.EPOCH; - } +"use strict"; - return new Instant(seconds, nanoOfSecond); - }; - Instant._validate = function _validate(seconds, nanoOfSecond) { - if (seconds < Instant.MIN_SECONDS || seconds > Instant.MAX_SECONDS) { - throw new DateTimeException('Instant exceeds minimum or maximum instant'); - } +var utils = __nccwpck_require__(20328); - if (nanoOfSecond < 0 || nanoOfSecond > LocalTime.NANOS_PER_SECOND) { - throw new DateTimeException('Instant exceeds minimum or maximum instant'); - } - }; +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; - function Instant(seconds, nanoOfSecond) { - var _this; +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; - _this = _Temporal.call(this) || this; + if (!headers) { return parsed; } - Instant._validate(seconds, nanoOfSecond); + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); - _this._seconds = MathUtil.safeToInt(seconds); - _this._nanos = MathUtil.safeToInt(nanoOfSecond); - return _this; + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } + } + }); - var _proto = Instant.prototype; + return parsed; +}; - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit === ChronoField.INSTANT_SECONDS || fieldOrUnit === ChronoField.NANO_OF_SECOND || fieldOrUnit === ChronoField.MICRO_OF_SECOND || fieldOrUnit === ChronoField.MILLI_OF_SECOND; - } - if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isTimeBased() || fieldOrUnit === ChronoUnit.DAYS; - } +/***/ }), - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; +/***/ 74850: +/***/ ((module) => { - _proto.range = function range(field) { - return _Temporal.prototype.range.call(this, field); - }; +"use strict"; - _proto.get = function get(field) { - return this.getLong(field); - }; - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.NANO_OF_SECOND: - return this._nanos; +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; - case ChronoField.MICRO_OF_SECOND: - return MathUtil.intDiv(this._nanos, 1000); - case ChronoField.MILLI_OF_SECOND: - return MathUtil.intDiv(this._nanos, NANOS_PER_MILLI); +/***/ }), - case ChronoField.INSTANT_SECONDS: - return this._seconds; - } +/***/ 20328: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +"use strict"; - return field.getFrom(this); - }; - _proto.epochSecond = function epochSecond() { - return this._seconds; - }; +var bind = __nccwpck_require__(77065); - _proto.nano = function nano() { - return this._nanos; - }; +/*global toString:true*/ - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; +// utils is a library of generic helper functions non-specific to axios - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); +var toString = Object.prototype.toString; - if (field instanceof ChronoField) { - field.checkValidValue(newValue); +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} - switch (field) { - case ChronoField.MILLI_OF_SECOND: - { - var nval = newValue * NANOS_PER_MILLI; - return nval !== this._nanos ? Instant._create(this._seconds, nval) : this; - } - - case ChronoField.MICRO_OF_SECOND: - { - var _nval = newValue * 1000; - - return _nval !== this._nanos ? Instant._create(this._seconds, _nval) : this; - } - - case ChronoField.NANO_OF_SECOND: - return newValue !== this._nanos ? Instant._create(this._seconds, newValue) : this; - - case ChronoField.INSTANT_SECONDS: - return newValue !== this._seconds ? Instant._create(newValue, this._nanos) : this; - } - - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.adjustInto(this, newValue); - }; - - _proto.truncatedTo = function truncatedTo(unit) { - requireNonNull(unit, 'unit'); - - if (unit === ChronoUnit.NANOS) { - return this; - } - - var unitDur = unit.duration(); - - if (unitDur.seconds() > LocalTime.SECONDS_PER_DAY) { - throw new DateTimeException('Unit is too large to be used for truncation'); - } - - var dur = unitDur.toNanos(); - - if (MathUtil.intMod(LocalTime.NANOS_PER_DAY, dur) !== 0) { - throw new DateTimeException('Unit must divide into a standard day without remainder'); - } - - var nod = MathUtil.intMod(this._seconds, LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + this._nanos; - - var result = MathUtil.intDiv(nod, dur) * dur; - return this.plusNanos(result - nod); - }; - - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; - - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit); - - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); - - case ChronoUnit.MICROS: - return this._plus(MathUtil.intDiv(amountToAdd, 1000000), MathUtil.intMod(amountToAdd, 1000000) * 1000); - - case ChronoUnit.MILLIS: - return this.plusMillis(amountToAdd); - - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); - - case ChronoUnit.MINUTES: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_MINUTE)); - - case ChronoUnit.HOURS: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_HOUR)); - - case ChronoUnit.HALF_DAYS: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_DAY / 2)); - - case ChronoUnit.DAYS: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_DAY)); - } - - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } - - return unit.addTo(this, amountToAdd); - }; - - _proto.plusSeconds = function plusSeconds(secondsToAdd) { - return this._plus(secondsToAdd, 0); - }; - - _proto.plusMillis = function plusMillis(millisToAdd) { - return this._plus(MathUtil.intDiv(millisToAdd, 1000), MathUtil.intMod(millisToAdd, 1000) * NANOS_PER_MILLI); - }; - - _proto.plusNanos = function plusNanos(nanosToAdd) { - return this._plus(0, nanosToAdd); - }; - - _proto._plus = function _plus(secondsToAdd, nanosToAdd) { - if (secondsToAdd === 0 && nanosToAdd === 0) { - return this; - } - - var epochSec = this._seconds + secondsToAdd; - epochSec = epochSec + MathUtil.intDiv(nanosToAdd, LocalTime.NANOS_PER_SECOND); - var nanoAdjustment = this._nanos + nanosToAdd % LocalTime.NANOS_PER_SECOND; - return Instant.ofEpochSecond(epochSec, nanoAdjustment); - }; - - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; - - _proto.minusSeconds = function minusSeconds(secondsToSubtract) { - return this.plusSeconds(secondsToSubtract * -1); - }; - - _proto.minusMillis = function minusMillis(millisToSubtract) { - return this.plusMillis(-1 * millisToSubtract); - }; - - _proto.minusNanos = function minusNanos(nanosToSubtract) { - return this.plusNanos(-1 * nanosToSubtract); - }; - - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - - if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } - - if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.chronology() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.zone() || _query === TemporalQueries.offset()) { - return null; - } - - return _query.queryFrom(this); - }; - - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - return temporal.with(ChronoField.INSTANT_SECONDS, this._seconds).with(ChronoField.NANO_OF_SECOND, this._nanos); - }; - - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = Instant.from(endExclusive); - - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this._nanosUntil(end); - - case ChronoUnit.MICROS: - return MathUtil.intDiv(this._nanosUntil(end), 1000); - - case ChronoUnit.MILLIS: - return MathUtil.safeSubtract(end.toEpochMilli(), this.toEpochMilli()); - - case ChronoUnit.SECONDS: - return this._secondsUntil(end); - - case ChronoUnit.MINUTES: - return MathUtil.intDiv(this._secondsUntil(end), LocalTime.SECONDS_PER_MINUTE); - - case ChronoUnit.HOURS: - return MathUtil.intDiv(this._secondsUntil(end), LocalTime.SECONDS_PER_HOUR); - - case ChronoUnit.HALF_DAYS: - return MathUtil.intDiv(this._secondsUntil(end), 12 * LocalTime.SECONDS_PER_HOUR); - - case ChronoUnit.DAYS: - return MathUtil.intDiv(this._secondsUntil(end), LocalTime.SECONDS_PER_DAY); - } - - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} - return unit.between(this, end); - }; +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} - _proto._nanosUntil = function _nanosUntil(end) { - var secsDiff = MathUtil.safeSubtract(end.epochSecond(), this.epochSecond()); - var totalNanos = MathUtil.safeMultiply(secsDiff, LocalTime.NANOS_PER_SECOND); - return MathUtil.safeAdd(totalNanos, end.nano() - this.nano()); - }; +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} - _proto._secondsUntil = function _secondsUntil(end) { - var secsDiff = MathUtil.safeSubtract(end.epochSecond(), this.epochSecond()); - var nanosDiff = end.nano() - this.nano(); +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} - if (secsDiff > 0 && nanosDiff < 0) { - secsDiff--; - } else if (secsDiff < 0 && nanosDiff > 0) { - secsDiff++; - } +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} - return secsDiff; - }; +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} - _proto.atOffset = function atOffset(offset) { - return OffsetDateTime.ofInstant(this, offset); - }; +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} - _proto.atZone = function atZone(zone) { - return ZonedDateTime.ofInstant(this, zone); - }; +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} - _proto.toEpochMilli = function toEpochMilli() { - var millis = MathUtil.safeMultiply(this._seconds, 1000); - return millis + MathUtil.intDiv(this._nanos, NANOS_PER_MILLI); - }; +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (toString.call(val) !== '[object Object]') { + return false; + } - _proto.compareTo = function compareTo(otherInstant) { - requireNonNull(otherInstant, 'otherInstant'); - requireInstance(otherInstant, Instant, 'otherInstant'); - var cmp = MathUtil.compareNumbers(this._seconds, otherInstant._seconds); + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; +} - if (cmp !== 0) { - return cmp; - } +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} - return this._nanos - otherInstant._nanos; - }; +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} - _proto.isAfter = function isAfter(otherInstant) { - return this.compareTo(otherInstant) > 0; - }; +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} - _proto.isBefore = function isBefore(otherInstant) { - return this.compareTo(otherInstant) < 0; - }; +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} - _proto.equals = function equals(other) { - if (this === other) { - return true; - } +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} - if (other instanceof Instant) { - return this.epochSecond() === other.epochSecond() && this.nano() === other.nano(); - } +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} - return false; - }; +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +} - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._seconds, this._nanos); - }; +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} - _proto.toString = function toString() { - return DateTimeFormatter.ISO_INSTANT.format(this); - }; +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } - _proto.toJSON = function toJSON() { - return this.toString(); - }; + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } - return Instant; - }(Temporal); - function _init$l() { - Instant.MIN_SECONDS = -31619119219200; - Instant.MAX_SECONDS = 31494816403199; - Instant.EPOCH = new Instant(0, 0); - Instant.MIN = Instant.ofEpochSecond(Instant.MIN_SECONDS, 0); - Instant.MAX = Instant.ofEpochSecond(Instant.MAX_SECONDS, 999999999); - Instant.FROM = createTemporalQuery('Instant.FROM', function (temporal) { - return Instant.from(temporal); - }); + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); } - - var Clock = function () { - function Clock() {} - - Clock.systemUTC = function systemUTC() { - return new SystemClock(ZoneOffset.UTC); - }; - - Clock.systemDefaultZone = function systemDefaultZone() { - return new SystemClock(ZoneId.systemDefault()); - }; - - Clock.system = function system(zone) { - return new SystemClock(zone); - }; - - Clock.fixed = function fixed(fixedInstant, zoneId) { - return new FixedClock(fixedInstant, zoneId); - }; - - Clock.offset = function offset(baseClock, duration) { - return new OffsetClock(baseClock, duration); - }; - - var _proto = Clock.prototype; - - _proto.millis = function millis() { - abstractMethodFail('Clock.millis'); - }; - - _proto.instant = function instant() { - abstractMethodFail('Clock.instant'); - }; - - _proto.zone = function zone() { - abstractMethodFail('Clock.zone'); - }; - - _proto.withZone = function withZone() { - abstractMethodFail('Clock.withZone'); - }; - - return Clock; - }(); - - var SystemClock = function (_Clock) { - _inheritsLoose(SystemClock, _Clock); - - function SystemClock(zone) { - var _this; - - requireNonNull(zone, 'zone'); - _this = _Clock.call(this) || this; - _this._zone = zone; - return _this; - } - - var _proto2 = SystemClock.prototype; - - _proto2.zone = function zone() { - return this._zone; - }; - - _proto2.millis = function millis() { - return new Date().getTime(); - }; - - _proto2.instant = function instant() { - return Instant.ofEpochMilli(this.millis()); - }; - - _proto2.equals = function equals(obj) { - if (obj instanceof SystemClock) { - return this._zone.equals(obj._zone); - } - - return false; - }; - - _proto2.withZone = function withZone(zone) { - if (zone.equals(this._zone)) { - return this; - } - - return new SystemClock(zone); - }; - - _proto2.toString = function toString() { - return 'SystemClock[' + this._zone.toString() + ']'; - }; - - return SystemClock; - }(Clock); - - var FixedClock = function (_Clock2) { - _inheritsLoose(FixedClock, _Clock2); - - function FixedClock(fixedInstant, zoneId) { - var _this2; - - _this2 = _Clock2.call(this) || this; - _this2._instant = fixedInstant; - _this2._zoneId = zoneId; - return _this2; - } - - var _proto3 = FixedClock.prototype; - - _proto3.instant = function instant() { - return this._instant; - }; - - _proto3.millis = function millis() { - return this._instant.toEpochMilli(); - }; - - _proto3.zone = function zone() { - return this._zoneId; - }; - - _proto3.toString = function toString() { - return 'FixedClock[]'; - }; - - _proto3.equals = function equals(obj) { - if (obj instanceof FixedClock) { - return this._instant.equals(obj._instant) && this._zoneId.equals(obj._zoneId); - } - - return false; - }; - - _proto3.withZone = function withZone(zone) { - if (zone.equals(this._zoneId)) { - return this; - } - - return new FixedClock(this._instant, zone); - }; - - return FixedClock; - }(Clock); - - var OffsetClock = function (_Clock3) { - _inheritsLoose(OffsetClock, _Clock3); - - function OffsetClock(baseClock, offset) { - var _this3; - - _this3 = _Clock3.call(this) || this; - _this3._baseClock = baseClock; - _this3._offset = offset; - return _this3; - } - - var _proto4 = OffsetClock.prototype; - - _proto4.zone = function zone() { - return this._baseClock.zone(); - }; - - _proto4.withZone = function withZone(zone) { - if (zone.equals(this._baseClock.zone())) { - return this; - } - - return new OffsetClock(this._baseClock.withZone(zone), this._offset); - }; - - _proto4.millis = function millis() { - return this._baseClock.millis() + this._offset.toMillis(); - }; - - _proto4.instant = function instant() { - return this._baseClock.instant().plus(this._offset); - }; - - _proto4.equals = function equals(obj) { - if (obj instanceof OffsetClock) { - return this._baseClock.equals(obj._baseClock) && this._offset.equals(obj._offset); - } - - return false; - }; - - _proto4.toString = function toString() { - return 'OffsetClock[' + this._baseClock + ',' + this._offset + ']'; - }; - - return OffsetClock; - }(Clock); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneOffsetTransition = function () { - ZoneOffsetTransition.of = function of(transition, offsetBefore, offsetAfter) { - return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); - }; - - function ZoneOffsetTransition(transition, offsetBefore, offsetAfter) { - requireNonNull(transition, 'transition'); - requireNonNull(offsetBefore, 'offsetBefore'); - requireNonNull(offsetAfter, 'offsetAfter'); - - if (offsetBefore.equals(offsetAfter)) { - throw new IllegalArgumentException('Offsets must not be equal'); - } - - if (transition.nano() !== 0) { - throw new IllegalArgumentException('Nano-of-second must be zero'); - } - - if (transition instanceof LocalDateTime) { - this._transition = transition; - } else { - this._transition = LocalDateTime.ofEpochSecond(transition, 0, offsetBefore); - } - - this._offsetBefore = offsetBefore; - this._offsetAfter = offsetAfter; + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); } - - var _proto = ZoneOffsetTransition.prototype; - - _proto.instant = function instant() { - return this._transition.toInstant(this._offsetBefore); - }; - - _proto.toEpochSecond = function toEpochSecond() { - return this._transition.toEpochSecond(this._offsetBefore); - }; - - _proto.dateTimeBefore = function dateTimeBefore() { - return this._transition; - }; - - _proto.dateTimeAfter = function dateTimeAfter() { - return this._transition.plusSeconds(this.durationSeconds()); - }; - - _proto.offsetBefore = function offsetBefore() { - return this._offsetBefore; - }; - - _proto.offsetAfter = function offsetAfter() { - return this._offsetAfter; - }; - - _proto.duration = function duration() { - return Duration.ofSeconds(this.durationSeconds()); - }; - - _proto.durationSeconds = function durationSeconds() { - return this._offsetAfter.totalSeconds() - this._offsetBefore.totalSeconds(); - }; - - _proto.isGap = function isGap() { - return this._offsetAfter.totalSeconds() > this._offsetBefore.totalSeconds(); - }; - - _proto.isOverlap = function isOverlap() { - return this._offsetAfter.totalSeconds() < this._offsetBefore.totalSeconds(); - }; - - _proto.isValidOffset = function isValidOffset(offset) { - return this.isGap() ? false : this._offsetBefore.equals(offset) || this._offsetAfter.equals(offset); - }; - - _proto.validOffsets = function validOffsets() { - if (this.isGap()) { - return []; - } else { - return [this._offsetBefore, this._offsetAfter]; - } - }; - - _proto.compareTo = function compareTo(transition) { - return this.instant().compareTo(transition.instant()); - }; - - _proto.equals = function equals(other) { - if (other === this) { - return true; - } - - if (other instanceof ZoneOffsetTransition) { - var d = other; - return this._transition.equals(d._transition) && this._offsetBefore.equals(d.offsetBefore()) && this._offsetAfter.equals(d.offsetAfter()); - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return this._transition.hashCode() ^ this._offsetBefore.hashCode() ^ this._offsetAfter.hashCode() >>> 16; - }; - - _proto.toString = function toString() { - return 'Transition[' + (this.isGap() ? 'Gap' : 'Overlap') + ' at ' + this._transition.toString() + this._offsetBefore.toString() + ' to ' + this._offsetAfter + ']'; - }; - - return ZoneOffsetTransition; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - function _init$m() { - TemporalQueries.ZONE_ID = createTemporalQuery('ZONE_ID', function (temporal) { - return temporal.query(TemporalQueries.ZONE_ID); - }); - TemporalQueries.CHRONO = createTemporalQuery('CHRONO', function (temporal) { - return temporal.query(TemporalQueries.CHRONO); - }); - TemporalQueries.PRECISION = createTemporalQuery('PRECISION', function (temporal) { - return temporal.query(TemporalQueries.PRECISION); - }); - TemporalQueries.OFFSET = createTemporalQuery('OFFSET', function (temporal) { - if (temporal.isSupported(ChronoField.OFFSET_SECONDS)) { - return ZoneOffset.ofTotalSeconds(temporal.get(ChronoField.OFFSET_SECONDS)); - } - - return null; - }); - TemporalQueries.ZONE = createTemporalQuery('ZONE', function (temporal) { - var zone = temporal.query(TemporalQueries.ZONE_ID); - return zone != null ? zone : temporal.query(TemporalQueries.OFFSET); - }); - TemporalQueries.LOCAL_DATE = createTemporalQuery('LOCAL_DATE', function (temporal) { - if (temporal.isSupported(ChronoField.EPOCH_DAY)) { - return LocalDate.ofEpochDay(temporal.getLong(ChronoField.EPOCH_DAY)); - } - - return null; - }); - TemporalQueries.LOCAL_TIME = createTemporalQuery('LOCAL_TIME', function (temporal) { - if (temporal.isSupported(ChronoField.NANO_OF_DAY)) { - return LocalTime.ofNanoOfDay(temporal.getLong(ChronoField.NANO_OF_DAY)); - } - - return null; - }); } + } +} - var SystemDefaultZoneRules = function (_ZoneRules) { - _inheritsLoose(SystemDefaultZoneRules, _ZoneRules); - - function SystemDefaultZoneRules() { - return _ZoneRules.apply(this, arguments) || this; - } - - var _proto = SystemDefaultZoneRules.prototype; - - _proto.isFixedOffset = function isFixedOffset() { - return false; - }; +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } - _proto.offsetOfInstant = function offsetOfInstant(instant) { - var offsetInMinutes = new Date(instant.toEpochMilli()).getTimezoneOffset(); - return ZoneOffset.ofTotalMinutes(offsetInMinutes * -1); - }; + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} - _proto.offsetOfEpochMilli = function offsetOfEpochMilli(epochMilli) { - var offsetInMinutes = new Date(epochMilli).getTimezoneOffset(); - return ZoneOffset.ofTotalMinutes(offsetInMinutes * -1); - }; +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} - _proto.offsetOfLocalDateTime = function offsetOfLocalDateTime(localDateTime) { - var epochMilli = localDateTime.toEpochSecond(ZoneOffset.UTC) * 1000; - var offsetInMinutesBeforePossibleTransition = new Date(epochMilli).getTimezoneOffset(); - var epochMilliSystemZone = epochMilli + offsetInMinutesBeforePossibleTransition * 60000; - var offsetInMinutesAfterPossibleTransition = new Date(epochMilliSystemZone).getTimezoneOffset(); - return ZoneOffset.ofTotalMinutes(offsetInMinutesAfterPossibleTransition * -1); - }; +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} - _proto.validOffsets = function validOffsets(localDateTime) { - return [this.offsetOfLocalDateTime(localDateTime)]; - }; +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM +}; - _proto.transition = function transition() { - return null; - }; - _proto.standardOffset = function standardOffset(instant) { - return this.offsetOfInstant(instant); - }; +/***/ }), - _proto.daylightSavings = function daylightSavings() { - this._throwNotSupported(); - }; +/***/ 9417: +/***/ ((module) => { - _proto.isDaylightSavings = function isDaylightSavings() { - this._throwNotSupported(); - }; +"use strict"; - _proto.isValidOffset = function isValidOffset(dateTime, offset) { - return this.offsetOfLocalDateTime(dateTime).equals(offset); - }; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); - _proto.nextTransition = function nextTransition() { - this._throwNotSupported(); - }; + var r = range(a, b, str); - _proto.previousTransition = function previousTransition() { - this._throwNotSupported(); - }; + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} - _proto.transitions = function transitions() { - this._throwNotSupported(); - }; +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} - _proto.transitionRules = function transitionRules() { - this._throwNotSupported(); - }; +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; - _proto._throwNotSupported = function _throwNotSupported() { - throw new DateTimeException('not supported operation'); - }; + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; - _proto.equals = function equals(other) { - if (this === other || other instanceof SystemDefaultZoneRules) { - return true; - } else { - return false; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; } - }; - - _proto.toString = function toString() { - return 'SYSTEM'; - }; - - return SystemDefaultZoneRules; - }(ZoneRules); - var SystemDefaultZoneId = function (_ZoneId) { - _inheritsLoose(SystemDefaultZoneId, _ZoneId); - - function SystemDefaultZoneId() { - var _this; - - _this = _ZoneId.call(this) || this; - _this._rules = new SystemDefaultZoneRules(); - return _this; + bi = str.indexOf(b, i + 1); } - var _proto = SystemDefaultZoneId.prototype; - - _proto.rules = function rules() { - return this._rules; - }; - - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - - return false; - }; - - _proto.id = function id() { - return 'SYSTEM'; - }; - - return SystemDefaultZoneId; - }(ZoneId); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneIdFactory = function () { - function ZoneIdFactory() {} - - ZoneIdFactory.systemDefault = function systemDefault() { - return SYSTEM_DEFAULT_ZONE_ID_INSTANCE; - }; - - ZoneIdFactory.getAvailableZoneIds = function getAvailableZoneIds() { - return ZoneRulesProvider.getAvailableZoneIds(); - }; - - ZoneIdFactory.of = function of(zoneId) { - requireNonNull(zoneId, 'zoneId'); + i = ai < bi && ai >= 0 ? ai : bi; + } - if (zoneId === 'Z') { - return ZoneOffset.UTC; - } + if (begs.length) { + result = [ left, right ]; + } + } - if (zoneId.length === 1) { - throw new DateTimeException('Invalid zone: ' + zoneId); - } + return result; +} - if (StringUtil.startsWith(zoneId, '+') || StringUtil.startsWith(zoneId, '-')) { - return ZoneOffset.of(zoneId); - } - if (zoneId === 'UTC' || zoneId === 'GMT' || zoneId === 'GMT0' || zoneId === 'UT') { - return new ZoneRegion(zoneId, ZoneOffset.UTC.rules()); - } +/***/ }), - if (StringUtil.startsWith(zoneId, 'UTC+') || StringUtil.startsWith(zoneId, 'GMT+') || StringUtil.startsWith(zoneId, 'UTC-') || StringUtil.startsWith(zoneId, 'GMT-')) { - var offset = ZoneOffset.of(zoneId.substring(3)); +/***/ 45447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (offset.totalSeconds() === 0) { - return new ZoneRegion(zoneId.substring(0, 3), offset.rules()); - } +"use strict"; - return new ZoneRegion(zoneId.substring(0, 3) + offset.id(), offset.rules()); - } - if (StringUtil.startsWith(zoneId, 'UT+') || StringUtil.startsWith(zoneId, 'UT-')) { - var _offset = ZoneOffset.of(zoneId.substring(2)); +var crypto_hash_sha512 = __nccwpck_require__(68729).lowlevel.crypto_hash; - if (_offset.totalSeconds() === 0) { - return new ZoneRegion('UT', _offset.rules()); - } +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri + */ - return new ZoneRegion('UT' + _offset.id(), _offset.rules()); - } +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * 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. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + */ - if (zoneId === 'SYSTEM') { - return ZoneId.systemDefault(); - } +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and 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. + */ - return ZoneRegion.ofId(zoneId); - }; +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and 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. + */ - ZoneIdFactory.ofOffset = function ofOffset(prefix, offset) { - requireNonNull(prefix, 'prefix'); - requireNonNull(offset, 'offset'); +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + +var BLF_J = 0; + +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); +}; - if (prefix.length === 0) { - return offset; - } +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; - if (prefix === 'GMT' || prefix === 'UTC' || prefix === 'UT') { - if (offset.totalSeconds() === 0) { - return new ZoneRegion(prefix, offset.rules()); - } +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; +}; - return new ZoneRegion(prefix + offset.id(), offset.rules()); - } +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; - throw new IllegalArgumentException('Invalid prefix, must be GMT, UTC or UT: ' + prefix); - }; +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; - ZoneIdFactory.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - var obj = temporal.query(TemporalQueries.zone()); +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); - if (obj == null) { - throw new DateTimeException('Unable to obtain ZoneId from TemporalAccessor: ' + temporal + ', type ' + (temporal.constructor != null ? temporal.constructor.name : '')); - } + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; - return obj; - }; + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } - return ZoneIdFactory; - }(); - var SYSTEM_DEFAULT_ZONE_ID_INSTANCE = null; - function _init$n() { - SYSTEM_DEFAULT_ZONE_ID_INSTANCE = new SystemDefaultZoneId(); - ZoneId.systemDefault = ZoneIdFactory.systemDefault; - ZoneId.getAvailableZoneIds = ZoneIdFactory.getAvailableZoneIds; - ZoneId.of = ZoneIdFactory.of; - ZoneId.ofOffset = ZoneIdFactory.ofOffset; - ZoneId.from = ZoneIdFactory.from; - ZoneOffset.from = ZoneIdFactory.from; - ZoneId.SYSTEM = SYSTEM_DEFAULT_ZONE_ID_INSTANCE; - ZoneId.UTC = ZoneOffset.ofTotalSeconds(0); + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } + } +}; - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var isInit = false; - - function init() { - if (isInit) { - return; - } - - isInit = true; - _init$1(); - _init(); - _init$2(); - _init$3(); - _init$k(); - _init$8(); - _init$m(); - _init$4(); - _init$l(); - _init$i(); - _init$j(); - _init$d(); - _init$5(); - _init$c(); - _init$b(); - _init$6(); - _init$7(); - _init$g(); - _init$n(); - _init$e(); - _init$a(); - _init$9(); - _init$h(); - _init$f(); - } - - init(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - - var ToNativeJsConverter = function () { - function ToNativeJsConverter(temporal, zone) { - var zonedDateTime; - - if (temporal instanceof LocalDate) { - zone = zone == null ? ZoneId.systemDefault() : zone; - zonedDateTime = temporal.atStartOfDay(zone); - } else if (temporal instanceof LocalDateTime) { - zone = zone == null ? ZoneId.systemDefault() : zone; - zonedDateTime = temporal.atZone(zone); - } else if (temporal instanceof ZonedDateTime) { - if (zone == null) { - zonedDateTime = temporal; - } else { - zonedDateTime = temporal.withZoneSameInstant(zone); - } - } else { - throw new IllegalArgumentException('unsupported instance for convert operation:' + temporal); - } - - this.instant = zonedDateTime.toInstant(); - } - - var _proto = ToNativeJsConverter.prototype; - - _proto.toDate = function toDate() { - return new Date(this.instant.toEpochMilli()); - }; +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; - _proto.toEpochMilli = function toEpochMilli() { - return this.instant.toEpochMilli(); - }; + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } - return ToNativeJsConverter; - }(); + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } - function convert(temporal, zone) { - return new ToNativeJsConverter(temporal, zone); + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } + } + BLF_J = 0; +}; - var NativeJsTemporal = function (_TemporalAccessor) { - _inheritsLoose(NativeJsTemporal, _TemporalAccessor); - - function NativeJsTemporal(date, zone) { - var _this; - - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } - - _this = _TemporalAccessor.call(this) || this; - _this._zone = zone; - - if (date instanceof Date) { - _this._epochMilli = date.getTime(); - return _assertThisInitialized(_this); - } else if (typeof date.toDate === 'function' && date.toDate() instanceof Date) { - _this._epochMilli = date.toDate().getTime(); - return _assertThisInitialized(_this); - } +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; - assert(false, 'date must be either a javascript date or a moment'); - return _this; - } +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; - var _proto = NativeJsTemporal.prototype; +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" - if (_query === TemporalQueries.localDate()) { - return LocalDate.ofInstant(Instant.ofEpochMilli(this._epochMilli), this._zone); - } else if (_query === TemporalQueries.localTime()) { - return LocalTime.ofInstant(Instant.ofEpochMilli(this._epochMilli), this._zone); - } else if (_query === TemporalQueries.zone()) { - return this._zone; - } + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } - return _TemporalAccessor.prototype.query.call(this, _query); - }; + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); - _proto.get = function get(field) { - return this.getLong(field); - }; + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; + } +}; - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.NANO_OF_SECOND: - return MathUtil.floorMod(this._epochMilli, 1000) * 1000000; + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; - case ChronoField.INSTANT_SECONDS: - return MathUtil.floorDiv(this._epochMilli, 1000); - } + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; - return field.getFrom(this); - }; + crypto_hash_sha512(sha2pass, pass, passlen); - _proto.isSupported = function isSupported(field) { - return field === ChronoField.INSTANT_SECONDS || field === ChronoField.NANO_OF_SECOND; - }; + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; - return NativeJsTemporal; - }(TemporalAccessor); + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; - function nativeJs(date, zone) { - return new NativeJsTemporal(date, zone); + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; } - function bindUse(jsJoda) { - var used = []; - return function use(fn) { - if (!~used.indexOf(fn)) { - fn(jsJoda); - used.push(fn); - } - - return jsJoda; - }; + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; } - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var _ = { - assert: assert$1, - DateTimeBuilder: DateTimeBuilder, - DateTimeParseContext: DateTimeParseContext, - DateTimePrintContext: DateTimePrintContext, - MathUtil: MathUtil, - StringUtil: StringUtil, - StringBuilder: StringBuilder - }; - var jsJodaExports = { - _: _, - convert: convert, - nativeJs: nativeJs, - ArithmeticException: ArithmeticException, - DateTimeException: DateTimeException, - DateTimeParseException: DateTimeParseException, - IllegalArgumentException: IllegalArgumentException, - IllegalStateException: IllegalStateException, - UnsupportedTemporalTypeException: UnsupportedTemporalTypeException, - NullPointerException: NullPointerException, - Clock: Clock, - DayOfWeek: DayOfWeek, - Duration: Duration, - Instant: Instant, - LocalDate: LocalDate, - LocalTime: LocalTime, - LocalDateTime: LocalDateTime, - OffsetTime: OffsetTime, - OffsetDateTime: OffsetDateTime, - Month: Month, - MonthDay: MonthDay, - Period: Period, - Year: Year, - YearConstants: YearConstants, - YearMonth: YearMonth, - ZonedDateTime: ZonedDateTime, - ZoneOffset: ZoneOffset, - ZoneId: ZoneId, - ZoneRegion: ZoneRegion, - ZoneOffsetTransition: ZoneOffsetTransition, - ZoneRules: ZoneRules, - ZoneRulesProvider: ZoneRulesProvider, - ChronoLocalDate: ChronoLocalDate, - ChronoLocalDateTime: ChronoLocalDateTime, - ChronoZonedDateTime: ChronoZonedDateTime, - IsoChronology: IsoChronology, - ChronoField: ChronoField, - ChronoUnit: ChronoUnit, - IsoFields: IsoFields, - Temporal: Temporal, - TemporalAccessor: TemporalAccessor, - TemporalAdjuster: TemporalAdjuster, - TemporalAdjusters: TemporalAdjusters, - TemporalAmount: TemporalAmount, - TemporalField: TemporalField, - TemporalQueries: TemporalQueries, - TemporalQuery: TemporalQuery, - TemporalUnit: TemporalUnit, - ValueRange: ValueRange, - DateTimeFormatter: DateTimeFormatter, - DateTimeFormatterBuilder: DateTimeFormatterBuilder, - DecimalStyle: DecimalStyle, - ResolverStyle: ResolverStyle, - SignStyle: SignStyle, - TextStyle: TextStyle - }; - var use = bindUse(jsJodaExports); - jsJodaExports.use = use; - - exports.ArithmeticException = ArithmeticException; - exports.ChronoField = ChronoField; - exports.ChronoLocalDate = ChronoLocalDate; - exports.ChronoLocalDateTime = ChronoLocalDateTime; - exports.ChronoUnit = ChronoUnit; - exports.ChronoZonedDateTime = ChronoZonedDateTime; - exports.Clock = Clock; - exports.DateTimeException = DateTimeException; - exports.DateTimeFormatter = DateTimeFormatter; - exports.DateTimeFormatterBuilder = DateTimeFormatterBuilder; - exports.DateTimeParseException = DateTimeParseException; - exports.DayOfWeek = DayOfWeek; - exports.DecimalStyle = DecimalStyle; - exports.Duration = Duration; - exports.IllegalArgumentException = IllegalArgumentException; - exports.IllegalStateException = IllegalStateException; - exports.Instant = Instant; - exports.IsoChronology = IsoChronology; - exports.IsoFields = IsoFields; - exports.LocalDate = LocalDate; - exports.LocalDateTime = LocalDateTime; - exports.LocalTime = LocalTime; - exports.Month = Month; - exports.MonthDay = MonthDay; - exports.NullPointerException = NullPointerException; - exports.OffsetDateTime = OffsetDateTime; - exports.OffsetTime = OffsetTime; - exports.Period = Period; - exports.ResolverStyle = ResolverStyle; - exports.SignStyle = SignStyle; - exports.Temporal = Temporal; - exports.TemporalAccessor = TemporalAccessor; - exports.TemporalAdjuster = TemporalAdjuster; - exports.TemporalAdjusters = TemporalAdjusters; - exports.TemporalAmount = TemporalAmount; - exports.TemporalField = TemporalField; - exports.TemporalQueries = TemporalQueries; - exports.TemporalQuery = TemporalQuery; - exports.TemporalUnit = TemporalUnit; - exports.TextStyle = TextStyle; - exports.UnsupportedTemporalTypeException = UnsupportedTemporalTypeException; - exports.ValueRange = ValueRange; - exports.Year = Year; - exports.YearConstants = YearConstants; - exports.YearMonth = YearMonth; - exports.ZoneId = ZoneId; - exports.ZoneOffset = ZoneOffset; - exports.ZoneOffsetTransition = ZoneOffsetTransition; - exports.ZoneRegion = ZoneRegion; - exports.ZoneRules = ZoneRules; - exports.ZoneRulesProvider = ZoneRulesProvider; - exports.ZonedDateTime = ZonedDateTime; - exports._ = _; - exports.convert = convert; - exports.nativeJs = nativeJs; - exports.use = use; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); -//# sourceMappingURL=js-joda.js.map - - -/***/ }), - -/***/ 31736: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseSqlConnectionString = exports.parseConnectionString = void 0; -const connection_string_1 = __nccwpck_require__(51226); -exports.parseConnectionString = connection_string_1.default; -const sql_connection_string_1 = __nccwpck_require__(25055); -exports.parseSqlConnectionString = sql_connection_string_1.default; - - -/***/ }), - -/***/ 51226: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var CollectionMode; -(function (CollectionMode) { - CollectionMode[CollectionMode["key"] = 0] = "key"; - CollectionMode[CollectionMode["value"] = 1] = "value"; -})(CollectionMode || (CollectionMode = {})); -const CONFIG = Object.freeze({ - key: { - terminator: '=', - quotes: {}, - }, - value: { - terminator: ';', - quotes: { - '"': '"', - "'": "'", - '{': '}', - }, - }, -}); -function connectionStringParser(connectionString, parserConfig = CONFIG) { - const parsed = {}; - let collectionMode = CollectionMode.key; - let started = false; - let finished = false; - let quoted = false; - let quote = ''; - let buffer = ''; - let currentKey = ''; - let pointer = 0; - function start() { - started = true; - } - function finish() { - finished = true; - } - function reset() { - started = false; - finished = false; - quoted = false; - quote = ''; - buffer = ''; - } - function config() { - return collectionMode === CollectionMode.key ? parserConfig.key : parserConfig.value; - } - function isTerminator(char) { - return config().terminator === char; - } - function isStartQuote(char) { - return Object.keys(config().quotes).some((val) => char === val); - } - function isEndQuote(char) { - return quoted && char === config().quotes[quote]; - } - function push(char) { - buffer += char; - } - function collect() { - if (!quoted) { - buffer = buffer.trim(); - } - switch (collectionMode) { - case CollectionMode.key: - currentKey = buffer.toLowerCase(); - collectionMode = CollectionMode.value; - break; - case CollectionMode.value: - collectionMode = CollectionMode.key; - parsed[currentKey] = buffer; - currentKey = ''; - break; - } - reset(); - } - while (pointer < connectionString.length) { - const current = connectionString.charAt(pointer); - if (!finished) { - if (!started) { - if (current.trim()) { - start(); - if (isStartQuote(current)) { - quoted = true; - quote = current; - } - else { - push(current); - } - } - } - else { - if (quoted && isEndQuote(current)) { - const next = connectionString.charAt(pointer + 1); - if (current === next) { - push(current); - pointer++; - } - else { - finish(); - } - } - else if (!quoted && isTerminator(current)) { - const next = connectionString.charAt(pointer + 1); - if (current === next) { - push(current); - pointer++; - } - else { - collect(); - } - } - else { - push(current); - } - } - } - else if (isTerminator(current)) { - collect(); - } - else if (current.trim()) { - throw new Error('Malformed connection string'); - } - pointer++; - } - if (quoted && !finished) { - throw new Error('Connection string terminated unexpectedly'); - } - else { - collect(); - } - return parsed; -} -exports.default = connectionStringParser; - - -/***/ }), - -/***/ 25055: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SCHEMA = exports.SchemaTypes = void 0; -const connection_string_1 = __nccwpck_require__(51226); -var SchemaTypes; -(function (SchemaTypes) { - SchemaTypes[SchemaTypes["BOOL"] = 0] = "BOOL"; - SchemaTypes[SchemaTypes["STRING"] = 1] = "STRING"; - SchemaTypes[SchemaTypes["NUMBER"] = 2] = "NUMBER"; -})(SchemaTypes = exports.SchemaTypes || (exports.SchemaTypes = {})); -// schema for MSSQL connection strings (https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.connectionstring) -exports.SCHEMA = { - 'Application Name': { - type: SchemaTypes.STRING, - aliases: ['App'], - validator(val) { - return val.length <= 128; - }, - }, - 'ApplicationIntent': { - type: SchemaTypes.STRING, - allowedValues: ['ReadOnly', 'ReadWrite'], - default: 'ReadWrite', - }, - 'Asynchronous Processing': { - type: SchemaTypes.BOOL, - default: false, - aliases: ['Async'], - }, - 'AttachDBFilename': { - type: SchemaTypes.STRING, - aliases: ['Extended Properties', 'Initial File Name'], - }, - 'Authentication': { - type: SchemaTypes.STRING, - allowedValues: ['Active Directory Integrated', 'Active Directory Password', 'Sql Password'], - }, - 'Column Encryption Setting': { - type: SchemaTypes.STRING, - }, - 'Connection Timeout': { - type: SchemaTypes.NUMBER, - aliases: ['Connect Timeout', 'Timeout'], - default: 15, - }, - 'Connection Lifetime': { - type: SchemaTypes.NUMBER, - aliases: ['Load Balance Timeout'], - default: 0, - }, - 'ConnectRetryCount': { - type: SchemaTypes.NUMBER, - default: 1, - validator(val) { - return val > 0 && val <= 255; - }, - }, - 'ConnectRetryInterval': { - type: SchemaTypes.NUMBER, - default: 10, - }, - 'Context Connection': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Current Language': { - aliases: ['Language'], - type: SchemaTypes.STRING, - validator(val) { - return val.length <= 128; - }, - }, - 'Data Source': { - aliases: ['Addr', 'Address', 'Server', 'Network Address'], - type: SchemaTypes.STRING, - }, - 'Encrypt': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Enlist': { - type: SchemaTypes.BOOL, - default: true, - }, - 'Failover Partner': { - type: SchemaTypes.STRING, - }, - 'Initial Catalog': { - type: SchemaTypes.STRING, - aliases: ['Database'], - validator(val) { - return val.length <= 128; - }, - }, - 'Integrated Security': { - type: SchemaTypes.BOOL, - aliases: ['Trusted_Connection'], - coerce(val) { - return val === 'sspi' || null; - }, - }, - 'Max Pool Size': { - type: SchemaTypes.NUMBER, - default: 100, - validator(val) { - return val >= 1; - }, - }, - 'Min Pool Size': { - type: SchemaTypes.NUMBER, - default: 0, - validator(val) { - return val >= 0; - }, - }, - 'MultipleActiveResultSets': { - type: SchemaTypes.BOOL, - default: false, - }, - 'MultiSubnetFailover': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Network Library': { - type: SchemaTypes.STRING, - aliases: ['Network', 'Net'], - allowedValues: ['dbnmpntw', 'dbmsrpcn', 'dbmsadsn', 'dbmsgnet', 'dbmslpcn', 'dbmsspxn', 'dbmssocn', 'Dbmsvinn'], - }, - 'Packet Size': { - type: SchemaTypes.NUMBER, - default: 8000, - validator(val) { - return val >= 512 && val <= 32768; - }, - }, - 'Password': { - type: SchemaTypes.STRING, - aliases: ['PWD'], - validator(val) { - return val.length <= 128; - }, - }, - 'Persist Security Info': { - type: SchemaTypes.BOOL, - aliases: ['PersistSecurityInfo'], - default: false, - }, - 'PoolBlockingPeriod': { - type: SchemaTypes.NUMBER, - default: 0, - coerce(val) { - switch (val.toLowerCase()) { - case 'alwaysblock': - return 1; - case 'auto': - return 0; - case 'neverblock': - return 2; - } - return null; - }, - }, - 'Pooling': { - type: SchemaTypes.BOOL, - default: true, - }, - 'Replication': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Transaction Binding': { - type: SchemaTypes.STRING, - allowedValues: ['Implicit Unbind', 'Explicit Unbind'], - default: 'Implicit Unbind', - }, - 'TransparentNetworkIPResolution': { - type: SchemaTypes.BOOL, - default: true, - }, - 'TrustServerCertificate': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Type System Version': { - type: SchemaTypes.STRING, - allowedValues: ['SQL Server 2012', 'SQL Server 2008', 'SQL Server 2005', 'Latest'], - }, - 'User ID': { - type: SchemaTypes.STRING, - aliases: ['UID'], - validator(val) { - return val.length <= 128; - }, - }, - 'User Instance': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Workstation ID': { - type: SchemaTypes.STRING, - aliases: ['WSID'], - validator(val) { - return val.length <= 128; - }, - }, -}; -function guessType(value) { - if (value.trim() === '') { - return SchemaTypes.STRING; - } - if (!Number.isNaN(parseInt(value, 10))) { - return SchemaTypes.NUMBER; - } - if (['true', 'false', 'yes', 'no'].includes(value.toLowerCase())) { - return SchemaTypes.BOOL; - } - return SchemaTypes.STRING; -} -function coerce(value, type, coercer) { - if (coercer) { - const coerced = coercer(value); - if (coerced !== null) { - return coerced; - } - } - switch (type) { - case SchemaTypes.BOOL: - if (['true', 'yes', '1'].includes(value.toLowerCase())) { - return true; - } - if (['false', 'no', '0'].includes(value.toLowerCase())) { - return false; - } - return value; - case SchemaTypes.NUMBER: - return parseInt(value, 10); - } - return value; -} -function validate(value, allowedValues, validator) { - let valid = true; - if (validator) { - valid = validator(value); - } - if (valid) { - valid = (allowedValues === null || allowedValues === void 0 ? void 0 : allowedValues.includes(value)) || false; - } - return valid; -} -function parseSqlConnectionString(connectionString, canonicalProps = false, allowUnknown = false, strict = false, schema = exports.SCHEMA) { - const flattenedSchema = Object.entries(schema).reduce((flattened, [key, item]) => { - var _a; - Object.assign(flattened, { - [key.toLowerCase()]: item, - }); - return ((_a = item.aliases) === null || _a === void 0 ? void 0 : _a.reduce((accum, alias) => { - return Object.assign(accum, { - [alias.toLowerCase()]: { - ...item, - canonical: key.toLowerCase(), - }, - }); - }, flattened)) || flattened; - }, {}); - return Object.entries(connection_string_1.default(connectionString)).reduce((config, [prop, value]) => { - if (!Object.prototype.hasOwnProperty.call(flattenedSchema, prop)) { - return Object.assign(config, { - [prop]: coerce(value, guessType(value)), - }); - } - let coercedValue = coerce(value, flattenedSchema[prop].type, flattenedSchema[prop].coerce); - if (strict && !validate(coercedValue, flattenedSchema[prop].allowedValues, flattenedSchema[prop].validator)) { - coercedValue = flattenedSchema[prop].default; - } - const propName = canonicalProps ? flattenedSchema[prop].canonical || prop : prop; - return Object.assign(config, { - [propName]: coercedValue, - }); - }, {}); -} -exports.default = parseSqlConnectionString; - - -/***/ }), - -/***/ 48566: -/***/ ((module, exports) => { - -module.exports = exports = abbrev.abbrev = abbrev - -abbrev.monkeyPatch = monkeyPatch - -function monkeyPatch () { - Object.defineProperty(Array.prototype, 'abbrev', { - value: function () { return abbrev(this) }, - enumerable: false, configurable: true, writable: true - }) - - Object.defineProperty(Object.prototype, 'abbrev', { - value: function () { return abbrev(Object.keys(this)) }, - enumerable: false, configurable: true, writable: true - }) -} - -function abbrev (list) { - if (arguments.length !== 1 || !Array.isArray(list)) { - list = Array.prototype.slice.call(arguments, 0) + keylen -= i; } - for (var i = 0, l = list.length, args = [] ; i < l ; i ++) { - args[i] = typeof list[i] === "string" ? list[i] : String(list[i]) - } - - // sort them lexicographically, so that they're next to their nearest kin - args = args.sort(lexSort) - // walk through each, seeing how much it has in common with the next and previous - var abbrevs = {} - , prev = "" - for (var i = 0, l = args.length ; i < l ; i ++) { - var current = args[i] - , next = args[i + 1] || "" - , nextMatches = true - , prevMatches = true - if (current === next) continue - for (var j = 0, cl = current.length ; j < cl ; j ++) { - var curChar = current.charAt(j) - nextMatches = nextMatches && curChar === next.charAt(j) - prevMatches = prevMatches && curChar === prev.charAt(j) - if (!nextMatches && !prevMatches) { - j ++ - break - } - } - prev = current - if (j === cl) { - abbrevs[current] = current - continue - } - for (var a = current.substr(0, j) ; j <= cl ; j ++) { - abbrevs[a] = current - a += current.charAt(j) - } - } - return abbrevs -} + return 0; +}; -function lexSort (a, b) { - return a === b ? 0 : a > b ? 1 : -1 -} +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf +}; /***/ }), -/***/ 35894: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 87558: +/***/ (function(module) { -"use strict"; +;(function (globalObject) { + 'use strict'; + /* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * bignumber.js v9.0.0 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2019 Michael Mclaughlin + * MIT Licensed. * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); - -var ac = __nccwpck_require__(69775); -var authParams = __nccwpck_require__(74854); -var logging = __nccwpck_require__(92288); -var MemoryCache = __nccwpck_require__(92474); - -exports = {}; + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ -exports.Logging = logging.Logging; -exports.AuthenticationContext = ac.AuthenticationContext; -exports.setGlobalADALOptions = ac.setGlobalADALOptions; -exports.getGlobalADALOptions = ac.getGlobalADALOptions; -exports.MemoryCache = MemoryCache; -_.extend(exports, authParams); -/** - * Creates a new AuthenticationContext object. By default the authority will be checked against - * a list of known Azure Active Directory authorities. If the authority is not recognized as - * one of these well known authorities then token acquisition will fail. This behavior can be - * turned off via the validateAuthority parameter below. - * @function - * @param {string} authority A URL that identifies a token authority. - * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. - * @returns {AuthenticationContext} A new authentication context. - */ -exports.createAuthenticationContext = function(authority, validateAuthority) { - return new ac.AuthenticationContext(authority, validateAuthority); -}; + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, -module.exports = exports; - - -/***/ }), - -/***/ 62432: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, -var _ = __nccwpck_require__(83571); -var constants = __nccwpck_require__(10282); + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 -var UserCodeResponseFields = constants.UserCodeResponseFields; -var argumentValidation = { - /** - * Throws if the passed in parameter is not a string. - * @param {string} param The parameter to validate. - * @param {string} name The name of the parameter being validated. - * @throws {Error} If the parameter is not a valid string. + /* + * Create and return a BigNumber constructor. */ - validateStringParameter : function(param, name) { - if (!param) { - throw new Error('The ' + name + ' parameter is required.'); - } - if (!_.isString(param)) { - throw new Error('The ' + name + ' parameter must be of type String.'); - } - }, + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), - /** - * Validates that the callback passed in {@link AuthenticationContext.acquireToken} is a function - * @param {AcquireTokenCallback} callback - * @throws {Error} If the callback parameter is not a function - */ - validateCallbackType : function(callback) { - if (!callback || !_.isFunction(callback)) { - throw new Error('acquireToken requires a function callback parameter.'); - } - }, - validateUserCodeInfo : function(userCodeInfo) { - if (!userCodeInfo){ - throw new Error('The userCodeInfo parameter is required'); - } + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- - if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.DEVICE_CODE)){ - throw new Error('The userCodeInfo is missing device_code'); - } - if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.INTERVAL)){ - throw new Error('The userCodeInfo is missing interval'); - } + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. - if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.EXPIRES_IN)){ - throw new Error('The userCodeInfo is missing expires_in'); - } - } -}; + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX -module.exports = argumentValidation; - - -/***/ }), - -/***/ 69775: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] -var argument = __nccwpck_require__(62432); -var Authority = __nccwpck_require__(19270)/* .Authority */ .W; -var TokenRequest = __nccwpck_require__(21178); -var CodeRequest = __nccwpck_require__(66576); -var createLogContext = __nccwpck_require__(92288).createLogContext; -var MemoryCache = __nccwpck_require__(92474); -var util = __nccwpck_require__(5336); -var constants = __nccwpck_require__(10282); + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX -var globalADALOptions = {}; -var globalCache = new MemoryCache(); + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + // RANGE : [MIN_EXP, MAX_EXP] -/** - * This function is used to add or remove entries from a TokenCache - * @typedef {function} ModifyCacheFunction - * @param {Array} entries An array of entries to either add or remove from the TokenCache - * @param {function} callback A callback function to call when the add or remove operation is complete. - * This function can take a single error argument. - */ + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX -/** - * This function is called by a TokenCache when a find operation completes. - * @callback TokenCacheFindCallback - * @param {Error} [err] If an error occurred during the find operation then it should be passed here. - * @param {Array} [entries] If the find operation was succesful then the matched entries should be returned here. - */ + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX -/** - * This function is called by ADAL to query a TokenCache. The query parameter is - * a flat object which must be compared against entries in the cache. An entry - * matches if it has all of the fields in the query and the values of those fields match - * the values in the query. A matched object may have more fields than the query object. - * @typedef {function} FindCacheFunction - * @param {object} query This object should be compared to cache entries and matches should be returned. - * @param {TokenCacheFindCallback} callback This callback should be called when the find operation is complete. - */ + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false -/** - * This is an interface that can be implemented to provide custom token cache persistence. - * @public - * @class TokenCache - * @property {ModifyCacheFunction} add Called by ADAL when entries should be added to the cache. - * @property {ModifyCacheFunction} remove Called by ADAL when entries should be removed from the cache. - * @property {FindCacheFunction} find Called when ADAL needs to find entries in the cache. - */ + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX -/** - * Creates a new AuthenticationContext object. By default the authority will be checked against - * a list of known Azure Active Directory authorities. If the authority is not recognized as - * one of these well known authorities then token acquisition will fail. This behavior can be - * turned off via the validateAuthority parameter below. - * @constructor - * @param {string} authority A URL that identifies a token authority. - * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. - * @param {TokenCache} [cache] Sets the token cache used by this AuthenticationContext instance. If this parameter is not set - * then a default, in memory cache is used. The default in memory cache is global to the process and is - * shared by all AuthenticationContexts that are created with an empty cache parameter. To control the - * scope and lifetime of a cache you can either create a {@link MemoryCache} instance and pass it when - * constructing an AuthenticationContext or implement a custom {@link TokenCache} and pass that. Cache - * instances passed at AuthenticationContext construction time are only used by that instance of - * the AuthenticationContext and are not shared unless it has been manually passed during the - * construction of other AuthenticationContexts. - * - */ -function AuthenticationContext(authority, validateAuthority, cache, aadApiVersion) { - var validate = (validateAuthority === undefined || validateAuthority === null || validateAuthority); + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, - this._authority = new Authority(authority, validate); - this._authority.aadApiVersion = aadApiVersion; - this._oauth2client = null; - this._correlationId = null; - this._callContext = { options : globalADALOptions }; - this._cache = cache || globalCache; - this._tokenRequestWithUserCode = {}; -} + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; -/** - * Gets the authority url this AuthenticationContext was constructed with. - * @instance - * @memberOf AuthenticationContext - * @type {string} - * @name authority - */ -Object.defineProperty(AuthenticationContext.prototype, 'authority', { - get: function () { - return this._authority.url; - } -}); -/** - * Gets/Sets the correlation id that will be used for the next acquireToken request. - * @instance - * @memberOf AuthenticationContext - * @type {string} - * @name correlationId - */ -Object.defineProperty(AuthenticationContext.prototype, 'correlationId', { - get: function () { - return this._correlationId; - }, - set: function (id) { - this._correlationId = id; - } -}); + //------------------------------------------------------------------------------------------ -/** - * Get/Sets options that are applied to requests generated by this AuthenticationContext instance. - * @instance - * @memberOf AuthenticationContext - * @type {object} - * @name options - */ -Object.defineProperty(AuthenticationContext.prototype, 'options', { - get: function() { - return this._callContext.options; - }, - set: function (value) { - this._callContext.options = value; - } -}); -/** - * Get the token cache used by this AuthenticationContext instance. - * @instance - * @memberOf AuthenticationContext - * @type {object} - * @name cache - */ -Object.defineProperty(AuthenticationContext.prototype, 'cache', { - get: function() { - return this._cache; - }, -}); + // CONSTRUCTOR -/** - * This will be returned in case the OAuth 2 service returns an error. - * @typedef ErrorResponse - * @property {string} [error] A server error. - * @property {string} [errorDescription] A description of the error returned. - */ -/** - * Contains tokens and metadata upon successful completion of an acquireToken call. - * @typedef TokenResponse - * @property {string} tokenType The type of token returned. - * @property {string} accessToken The returned access token. - * @property {string} [refreshToken] A refresh token. - * @property {Date} [createdOn] The date on which the access token was created. - * @property {Date} expiresOn The Date on which the access token expires. - * @property {int} expiresIn The amount of time, in seconds, for which the token is valid. - * @property {string} [userId] An id for the user. May be a displayable value if is_user_id_displayable is true. - * @property {bool} [isUserIdDisplayable] Indicates whether the user_id property will be meaningful if displayed to a user. - * @property {string} [tenantId] The identifier of the tenant under which the access token was issued. - * @property {string} [givenName] The given name of the principal represented by the access token. - * @property {string} [familyName] The family name of the principal represented by the access token. - * @property {string} [identityProvider] Identifies the identity provider that issued the access token. - */ + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback AcquireTokenCallback - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {TokenResponse|ErrorResponse} [response] On a succesful request returns a {@link TokenResposne}. - */ + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); -/** - * This function implements code that is common to all acquireToken flows. - * @private - * @param {AcquireTokenCallback} callback - * @param {Function} tokenFunction This is the function to call to actually acquire the token after common flow has completed. - */ -AuthenticationContext.prototype._acquireToken = function(callback, tokenFunction) { - var self = this; - this._callContext._logContext = createLogContext(this.correlationId); - this._authority.validate(this._callContext, function(err) { - if (err) { - callback(err); - return; - } - tokenFunction.call(self); - }); -}; + if (b == null) { -AuthenticationContext.prototype._acquireUserCode = function (callback, codeFunction) { - var self = this; - this._callContext._logContext = createLogContext(this.correlationId); - this._authority.validate(this._callContext, function (err) { - if (err) { - callback(err); - return; - } + if (v && v._isBigNumber === true) { + x.s = v.s; - codeFunction.call(self); - }); -}; + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } -/** - * Gets a token for a given resource. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} [userId] The username of the user on behalf this application is authenticating. - * @param {string} [clientId] The OAuth client id of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireToken = function(resource, userId, clientId, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } + return; + } - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenFromCacheWithRefresh(userId, callback); - }); -}; + if ((isNum = typeof v == 'number') && v * 0 == 0) { -/** - * Gets a token for a given resource. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} username The username of the user on behalf this application is authenticating. - * @param {string} password The password of the user named in the username parameter. - * @param {string} clientId The OAuth client id of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithUsernamePassword = function(resource, username, password, clientId, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(username, 'username'); - argument.validateStringParameter(password, 'password'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenWithUsernamePassword(username, password, callback); - }); -}; + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); -/** - * Gets a token for a given resource. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} clientSecret The OAuth client secret of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithClientCredentials = function(resource, clientId, clientSecret, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(clientId, 'clientId'); - argument.validateStringParameter(clientSecret, 'clientSecret'); - } catch (err) { - callback(err); - return; - } + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenWithClientCredentials(clientSecret, callback); - }); -}; + return; + } -/** - * Gets a token for a given resource. - * @param {string} authorizationCode An authorization code returned from a client. - * @param {string} redirectUri The redirect uri that was used in the authorize call. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} clientSecret The OAuth client secret of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithAuthorizationCode = function(authorizationCode, redirectUri, resource, clientId, clientSecret, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(authorizationCode, 'authorizationCode'); - argument.validateStringParameter(redirectUri, 'redirectUri'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } + str = String(v); + } else { - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, redirectUri); - tokenRequest.getTokenWithAuthorizationCode(authorizationCode, clientSecret, callback); - }); -}; + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); -/** - * Gets a new access token via a previously issued refresh token. - * @param {string} refreshToken A refresh token returned in a tokne response from a previous invocation of acquireToken. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} [clientSecret] The OAuth client secret of the calling application. (Note: this parameter is a late addition. - * This parameter may be ommitted entirely so that applications built before this change will continue - * to work unchanged.) - * @param {string} resource The OAuth resource for which a token is being request. This parameter is optional and can be set to null. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithRefreshToken = function(refreshToken, clientId, clientSecret, resource, callback) { - // Fix up the arguments. Older clients may pass fewer arguments as the clientSecret paramter did not always exist. - // The code needs to make adjustments for those clients. - var clientSecretPresent = (5 === arguments.length); - var actualClientSecret = clientSecretPresent ? clientSecret : null; - var actualCallback = clientSecretPresent ? arguments[4] : arguments[3]; - var actualResource = clientSecretPresent ? arguments[3] : arguments[2]; + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } - argument.validateCallbackType(actualCallback); - try { - argument.validateStringParameter(refreshToken, 'refreshToken'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, actualResource); - tokenRequest.getTokenWithRefreshToken(refreshToken, actualClientSecret, actualCallback); - }); -}; + // Exponential form? + if ((i = str.search(/e/i)) > 0) { -/** - * Gets a new access token using via a certificate credential. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint A hex encoded thumbprint of the certificate. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithClientCertificate = function(resource, clientId, certificate, thumbprint, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(certificate, 'certificate'); - argument.validateStringParameter(thumbprint, 'thumbprint'); - } catch(err) { - callback(err); - return; - } + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenWithCertificate(certificate, thumbprint, callback); - }); -}; + // Integer. + e = str.length; + } -/** - * Gets the userCodeInfo which contains user_code, device_code for authenticating user on device. - * @param {string} resource A URI that identifies the resource for which the device_code and user_code is valid for. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} language The language code specifying how the message should be localized to. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireUserCode = function(resource, clientId, language, callback) { - argument.validateCallbackType(callback); - - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(clientId, 'clientId'); - } catch (err) { - callback(err); - return; - } + } else { - this._acquireUserCode(callback, function () { - var codeRequest = new CodeRequest(this._callContext, this, clientId, resource); - codeRequest.getUserCodeInfo(language, callback); - }); -}; + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); -/** - * Gets a new access token using via a device code. - * @note This method doesn't look up the cache, it only stores the returned token into cache. To look up cache before making a new request, - * please use acquireToken. - * @param {string} clientId The OAuth client id of the calling application. - * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithDeviceCode = function(resource, clientId, userCodeInfo, callback){ - argument.validateCallbackType(callback); + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } - try{ - argument.validateUserCodeInfo(userCodeInfo); - } catch (err) { - callback(err); - return; - } + str = String(v); - var self = this; - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, null); - self._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]] = tokenRequest; - tokenRequest.getTokenWithDeviceCode(userCodeInfo, callback); - }) -}; + if (isNum = typeof v == 'number') { -/** - * Cancels the polling request to get token with device code. - * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.cancelRequestToGetTokenWithDeviceCode = function (userCodeInfo, callback) { - argument.validateCallbackType(callback); + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); - try { - argument.validateUserCodeInfo(userCodeInfo); - } catch (err) { - callback(err); - return; - } + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; - if (!this._tokenRequestWithUserCode || !this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]) { - callback(new Error('No acquireTokenWithDeviceCodeRequest existed to be cancelled')); - return; - } + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } - var tokenRequestToBeCancelled = this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]; - tokenRequestToBeCancelled.cancelTokenRequestWithDeviceCode(); + alphabet = ALPHABET.slice(0, b); + e = i = 0; - delete this._tokenRequestWithUserCode[constants.UserCodeResponseFields.DEVICE_CODE]; -}; + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { -var exports = { - AuthenticationContext : AuthenticationContext, - setGlobalADALOptions : function(options) { - globalADALOptions = options; - }, - getGlobalADALOptions : function() { - return globalADALOptions; - } -}; + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { -util.adalInit(); -module.exports = exports; - - -/***/ }), - -/***/ 74854: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + return parseNumeric(x, String(v), isNum, b); + } + } + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); -var axios = __nccwpck_require__(96545); -var argument = __nccwpck_require__(62432); -var log = __nccwpck_require__(92288); -var util = __nccwpck_require__(5336); -var HttpErrorCode = __nccwpck_require__(10282).HttpError; + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } -/* - * Constants - */ -var consts = { - AUTHORIZATION_URI : 'authorization_uri', - RESOURCE : 'resource', - WWW_AUTHENTICATE_HEADER : 'www-authenticate' -}; + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); -/** - * The AuthenticationParameters class holds the parameters that are parsed from an OAuth challenge - * in the www-authenticate header. - * @constructor - * @param {string} authorizationUri The URI of an authority that can issues tokens for the - * resource that issued the challenge. - * @param {string} resource The resource for a which a token should be requested from the authority. - */ -function AuthenticationParameters(authorizationUri, resource) { - this._authorizationUri = authorizationUri; - this._resource = resource; -} + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); -/** - * The URI of an authority that can issues tokens for the resource that issued the challenge. - * @instance - * @memberOf AuthenticationParameters - * @type {string} - * @name authorizationUri - */ -Object.defineProperty(AuthenticationParameters.prototype, 'authorizationUri', { - get : function() { - return this._authorizationUri; - } -}); + if (str = str.slice(i, ++len)) { + len -= i; -/** - * The resource for a which a token should be requested from the authority. - * This property may be undefined if the resource was not returned in the challenge. - * @instance - * @memberOf AuthenticationParameters - * @type {string} - * @name authorizationUri - */ -Object.defineProperty(AuthenticationParameters.prototype, 'resource', { - get : function() { - return this._resource; - } -}); + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } -var exports = {}; + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { -// The 401 challenge is a standard defined in RFC6750, which is based in part on RFC2617. -// The challenge has the following form. -// WWW-Authenticate : Bearer authorization_uri="https://login.windows.net/mytenant.com/oauth2/authorize",Resource_id="00000002-0000-0000-c000-000000000000" + // Infinity. + x.c = x.e = null; -// This regex is used to validate the structure of the challenge header. -// Match whole structure: ^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$ -// ^ Start at the beginning of the string. -// \s*Bearer\s+ Match 'Bearer' surrounded by one or more amount of whitespace. -// ([^,\s="]+?) This cpatures the key which is composed of any characters except comma, whitespace or a quotes. -// = Match the = sign. -// "([^"]*?)" Captures the value can be any number of non quote characters. At this point only the first key value pair as been captured. -// \s* There can be any amount of white space after the first key value pair. -// ( Start a capture group to retrieve the rest of the key value pairs that are separated by commas. -// \s* There can be any amount of whitespace before the comma. -// , There must be a comma. -// \s* There can be any amount of whitespace after the comma. -// (([^,\s="]+?) This will capture the key that comes after the comma. It's made of a series of any character excpet comma, whitespace or quotes. -// = Match the equal sign between the key and value. -// " Match the opening quote of the value. -// ([^"]*?) This will capture the value which can be any number of non quote characters. -// " Match the values closing quote. -// \s* There can be any amount of whitespace before the next comma. -// )* Close the capture group for key value pairs. There can be any number of these. -// $ The rest of the string can be whitespace but nothing else up to the end of the string. -// -// -// In other some other languages the regex above would be all that was needed. However, in JavaScript the RegExp object does not -// return all of the captures in one go. So the regex above needs to be broken up so that captures can be retrieved -// iteratively. -// + // Underflow? + } else if (e < MIN_EXP) { -function parseChallenge(challenge) { - // This regex checks the structure of the whole challenge header. The complete - // header needs to be checked for validity before we can be certain that - // we will succeed in pulling out the individual parts. - var bearerChallengeStructureValidation = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$/; + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; - // This regex pulls out the key and value from the very first pair. - var firstKeyValuePairRegex = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*/; + // Transform base - // This regex is used to pull out all of the key value pairs after the first one. - // All of these begin with a comma. - var allOtherKeyValuePairRegex = /(?:,\s*([^,\s="]+?)="([^"]*?)"\s*)/g; + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); - if (!bearerChallengeStructureValidation.test(challenge)) { - throw new Error('The challenge is not parseable as an RFC6750 OAuth2 challenge'); - } + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } - var challengeParameters = {}; - for(var match = firstKeyValuePairRegex.exec(challenge); - match; - match = allOtherKeyValuePairRegex.exec(challenge)) { + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } - challengeParameters[match[1]] = match[2]; - } + for (; i--; str += '0'); + x.c.push(+str); + } + } else { - return challengeParameters; -} + // Zero. + x.c = [x.e = 0]; + } + } -exports.AuthenticationParameters = AuthenticationParameters; -/** - * Creates an {@link AuthenticationParameters} object from the contents of a - * www-authenticate header received from a HTTP 401 response from a resource server. - * @param {string} challenge The content fo the www-authenticate header. - * @return {AuthenticationParameters} An AuthenticationParameters object containing the parsed values from the header. - */ -exports.createAuthenticationParametersFromHeader = function(challenge) { - argument.validateStringParameter(challenge, 'challenge'); + // CONSTRUCTOR PROPERTIES - var challengeParameters = parseChallenge(challenge); - var authorizationUri = challengeParameters[consts.AUTHORIZATION_URI]; - if (!authorizationUri) { - throw new Error('Could not find \'authorization_uri\' in challenge header.'); - } + BigNumber.clone = clone; - var resource = challengeParameters[consts.RESOURCE]; + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; - return new AuthenticationParameters(authorizationUri, resource); -}; -/** - * Create an {@link AuthenticationParameters} object from a node http.IncomingMessage - * object that was created as a result of a request to a resource server. This function - * expects the response to contain a HTTP 401 error code with a www-authenticate - * header. - * @param {http.IncomingMessage} response A response from a http request to a resource server. - * @return {AuthenticationParameters} - */ -exports.createAuthenticationParametersFromResponse = function(response) { - if (!response) { - throw new Error('Mising required parameter: response'); - } + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; - if (!response.status) { - throw new Error('The response parameter does not have the expected HTTP status field'); - } + if (obj != null) { - if (HttpErrorCode.UNAUTHORIZED !== response.status) { - throw new Error('The response status code does not correspond to an OAuth challenge. ' + - 'The status is expected to be 401 but is: ' + response.status); - } + if (typeof obj == 'object') { - if (!response.headers) { - throw new Error('There were no headers found in the response.'); - } + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } - var challenge = response.headers[consts.WWW_AUTHENTICATE_HEADER]; - if (!challenge) { - throw new Error('The response does not contain a WWW-Authenticate header that can be used to determine the authority_uri and resource.'); - } + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } - return exports.createAuthenticationParametersFromHeader(challenge); -}; + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } -function validateUrlObject(url) { - if (!url || !url.href) { - throw new Error('Parameter is of wrong type: url'); - } -} + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback CreateAuthenticationParametersCallback - * @memberOf AuthenticationContext - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {AuthenticationParameters} [parameters] On a succesful request returns a {@link AuthenticationParameters}. - */ + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } -/** - * Creates an {@link AuthenticationParameters} object by sending a get request - * to the url passed to this function, and parsing the resulting http 401 - * response. - * @param {string|url} url The url of a resource server. - * @param {AuthenticationParameters} callback Called on error or request completion. - * @param {string} [correlationId] An optional correlationId to pass along with the request and to include in any logs. - */ -exports.createAuthenticationParametersFromUrl = function(url, callback, correlationId) { - argument.validateCallbackType(callback); - try { - if (!url) { - callback(new Error('Missing required parameter: url')); - return; - } - var challengeUrl; - if ('string' === typeof(url)) { - challengeUrl = url; - } else { - validateUrlObject(url); - challengeUrl = url.href; - } + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } - var logContext = log.createLogContext(correlationId); - var logger = new log.Logger('AuthenticationParameters', logContext); + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } - logger.verbose('Attempting to retrieve authentication parameters'); - logger.verbose('Attempting to retrieve authentication parameters from: ' + challengeUrl, true); - var options = util.createRequestOptions({ _callContext: { _logContext: logContext } }); - - axios.get(challengeUrl, options).then((response) => { - util.logReturnCorrelationId(logger, "Authentication Parameters", response); - var parameters; - try { - parameters = exports.createAuthenticationParametersFromResponse(response); - } catch (creationErr) { - logger.error('Unable to parse response in to authentication parameters.', creationErr, true); - callback(creationErr); - } - callback(null, parameters); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - var parameters; - util.logReturnCorrelationId(logger, "Authentication Parameters", error.response); - try { - parameters = exports.createAuthenticationParametersFromResponse(error.response); - } catch (creationErr) { - logger.error('Unable to parse response in to authentication parameters.', creationErr, true); - callback(creationErr); - return; + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if only one character, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) { + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); } - callback(null, parameters); - } - // if there is no response from the server - else if (error.request) { - logger.error('AuthenticationParameters' + ' request was made but no response was received', error.request, true); - callback(logger.createError('No response from the server')); - } - // request was never made - else { - logger.error('AuthenticationParameters http get failed.' + ' request was never made, please check', error.message, true); - callback(error.message); } - }) - } catch(err) { - callback(err); - return; - } -}; -module.exports = exports; - -/***/ }), - -/***/ 19270: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; -var axios = __nccwpck_require__(96545); -var url = __nccwpck_require__(78835); -var _ = __nccwpck_require__(83571); + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; -var AADConstants = __nccwpck_require__(10282).AADConstants; -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); + var i, n, + c = v.c, + e = v.e, + s = v.s; -/** -* Constructs an Authority object with a specific authority URL. -* @private -* @constructor -* @param {string} authorityUrl A URL that identifies a token authority. -* @param {bool} validateAuthority Indicates whether the Authority url should be validated as an actual AAD -* authority. The default is true. -*/ -function Authority(authorityUrl, validateAuthority) { - this._log = null; - this._url = url.parse(authorityUrl); - this._validateAuthorityUrl(); + out: if ({}.toString.call(c) == '[object Array]') { - this._validated = !validateAuthority; - this._host = null; - this._tenant = null; - this._parseAuthority(); + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { - this._authorizationEndpoint = null; - this._tokenEndpoint = null; - this._deviceCodeEndpoint = null; - this._isAdfsAuthority = (this._tenant.toLowerCase() === "adfs"); -} + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } -/** - * The URL of the authority - * @instance - * @type {string} - * @memberOf Authority - * @name url - */ -Object.defineProperty(Authority.prototype, 'url', { - get: function() { - return url.format(this._url); - } -}); + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; -/** - * The token endpoint that the authority uses as discovered by instance discovery. - * @instance - * @type {string} - * @memberOf Authority - * @name tokenEndpoint - */ -Object.defineProperty(Authority.prototype, 'tokenEndpoint', { - get: function() { - return this._tokenEndpoint; - } -}); + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { -Object.defineProperty(Authority.prototype, 'deviceCodeEndpoint', { - get: function() { - return this._deviceCodeEndpoint; - } -}); + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } -/** - * Checks the authority url to ensure that it meets basic requirements such as being over SSL. If it does not then - * this method will throw if any of the checks fail. - * @private - * @throws {Error} If the authority url fails to pass any validation checks. - */ -Authority.prototype._validateAuthorityUrl = function() { - if (this._url.protocol !== 'https:') { - throw new Error('The authority url must be an https endpoint.'); - } + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } - if (this._url.query) { - throw new Error('The authority url must not have a query string.'); - } -}; + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } -/** - * Parse the authority to get the tenant name. The rest of the - * URL is thrown away in favor of one of the endpoints from the validation doc. - * @private - */ -Authority.prototype._parseAuthority = function() { - this._host = this._url.host; + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; - var pathParts = this._url.pathname.split('/'); - this._tenant = pathParts[1]; - if (!this._tenant) { - throw new Error('Could not determine tenant.'); - } -}; + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, P.lt); + }; -/** - * Performs instance discovery based on a simple match against well known authorities. - * @private - * @return {bool} Returns true if the authority is recognized. - */ -Authority.prototype._performStaticInstanceDiscovery = function() { - this._log.verbose('Performing static instance discovery'); - var hostIndex = _.indexOf(AADConstants.WELL_KNOWN_AUTHORITY_HOSTS, this._url.hostname); - var found = hostIndex > -1; + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, P.gt); + }; - if (found) { - this._log.verbose('Authority validated via static instance discovery.'); - } - return found; -}; + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; -Authority.prototype._createAuthorityUrl = function() { - return 'https://' + this._url.host + '/' + encodeURIComponent(this._tenant) + AADConstants.AUTHORIZE_ENDPOINT_PATH; -}; + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; -/** - * Creates an instance discovery endpoint url for the specific authority that this object represents. - * @private - * @param {string} authorityHost The host name of a well known authority. - * @return {URL} The constructed endpoint url. - */ -Authority.prototype._createInstanceDiscoveryEndpointFromTemplate = function(authorityHost) { - var discoveryEndpoint = AADConstants.INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE; - discoveryEndpoint = discoveryEndpoint.replace('{authorize_host}', authorityHost); - discoveryEndpoint = discoveryEndpoint.replace('{authorize_endpoint}', encodeURIComponent(this._createAuthorityUrl())); - return url.parse(discoveryEndpoint); -}; + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); -/** - * Performs instance discovery via a network call to well known authorities. - * @private - * @param {Authority.InstanceDiscoveryCallback} callback The callback function. If succesful, - * this function calls the callback with the - * tenantDiscoveryEndpoint returned by the - * server. - */ -Authority.prototype._performDynamicInstanceDiscovery = function(callback) { - try { - var self = this; - var discoveryEndpoint = this._createInstanceDiscoveryEndpointFromTemplate(AADConstants.WORLD_WIDE_AUTHORITY); + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); - var getOptions = util.createRequestOptions(self); + k = mathceil(dp / LOG_BASE); - this._log.verbose('Attempting instance discover'); - this._log.verbose('Attempting instance discover at: ' + url.format(discoveryEndpoint), true); + if (CRYPTO) { - axios.get(discoveryEndpoint, getOptions).then((response) => { - util.logReturnCorrelationId(this._log, 'Instance Discovery', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Instance Discovery' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - var discoveryResponse = response.data; - if (discoveryResponse['tenant_discovery_endpoint']) { - callback(null, discoveryResponse['tenant_discovery_endpoint']); - } else { - callback(self._log.createError('Failed to parse instance discovery response')); - } - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'Instance Discovery', error.response); - this._log.error('Instance Discovery' + ' request failed with', error.response.status, true); - var returnErrorString = 'Instance Discovery' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if(error.request) { - this._log.error('Instance Discovery' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else { - this._log.error('Instance Discovery' + ' request was never made, please check', error.message, true); - callback(error.message); - } - }); - } catch(e) { - callback(e); - } -}; + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { -/** - * @callback InstanceDiscoveryCallback - * @private - * @memberOf Authority - * @param {Error} err If an error occurs during instance discovery then it will be returned here. - * @param {string} tenantDiscoveryEndpoint If instance discovery is successful then this will contain the - * tenantDiscoveryEndpoint associated with the authority. - */ + a = crypto.getRandomValues(new Uint32Array(k *= 2)); -/** - * Determines whether the authority is recognized as a trusted AAD authority. - * @private - * @param {Authority.InstanceDiscoveryCallback} callback The callback function. - */ -Authority.prototype._validateViaInstanceDiscovery = function(callback) { - if (this._performStaticInstanceDiscovery()) { - callback(); - } else { - this._performDynamicInstanceDiscovery(callback); - } -}; + for (; i < k;) { -/** - * @callback GetOauthEndpointsCallback - * @private - * @memberOf Authority - * @param {Error} error An error if one occurred. - */ + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); -/** - * Given a tenant discovery endpoint this method will attempt to discover the token endpoint. If the - * tenant discovery endpoint is unreachable for some reason then it will fall back to a algorithmic generation of the - * token endpoint url. - * @private - * @param {string} tenantDiscoveryEndpoint The url of the tenant discovery endpoint for this authority. - * @param {Authority.GetOauthEndpointsCallback} callback The callback function. - */ -Authority.prototype._getOAuthEndpoints = function(tenantDiscoveryEndpoint, callback) { - if (this._tokenEndpoint && this._deviceCodeEndpoint) { - callback(); - return; - } else { - // fallback to the well known token endpoint path. - if (!this._tokenEndpoint){ - this._tokenEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.TOKEN_ENDPOINT_PATH; - } + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { - if (!this._deviceCodeEndpoint){ - this._deviceCodeEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.DEVICE_ENDPOINT_PATH; - } + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; - callback(); - return; - } -}; + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { -/** - * @callback ValidateCallback - * @memberOf Authority - */ + // buffer + a = crypto.randomBytes(k *= 7); -/** - * Perform validation on the authority represented by this object. In addition to simple validation - * the oauth token endpoint will be retrieved. - * @param {Authority.ValidateCallback} callback The callback function. - */ -Authority.prototype.validate = function(callContext, callback) { - this._log = new Logger('Authority', callContext._logContext); - this._callContext = callContext; - var self = this; + for (; i < k;) { - if (!this._validated) { - this._log.verbose('Performing instance discovery'); - this._log.verbose('Performing instance discovery: ' + url.format(this._url), true); - this._validateViaInstanceDiscovery(function(err, tenantDiscoveryEndpoint) { - if (err) - { - callback(err); - } else { - self._validated = true; - self._getOAuthEndpoints(tenantDiscoveryEndpoint, callback); - return; - } - }); - } else { - this._log.verbose('Instance discovery/validation has either already been completed or is turned off'); - this._log.verbose('Instance discovery/validation has either already been completed or is turned off: ' + url.format(this._url), true); - this._getOAuthEndpoints(null, callback); - return; - } -}; + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; -module.exports.W = Authority; - - -/***/ }), - -/***/ 38289: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + // Use Math.random. + if (!CRYPTO) { -var _ = __nccwpck_require__(83571); -var crypto = __nccwpck_require__(76417); -__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } -var Logger = __nccwpck_require__(92288).Logger; -var constants = __nccwpck_require__(10282); -var cacheConstants = constants.Cache; -var TokenResponseFields = constants.TokenResponseFields; + k = c[--i]; + dp %= LOG_BASE; -// TODO: remove this. -// There is a PM requirement that developers be able to look in to the cache and manipulate the cache based on -// the parameters (authority, resource, clientId, userId), in any combination. They must be able find, add, and remove -// tokens based on those parameters. Any default cache that the API supplies must allow for this query pattern. -// This has the following implications: -// The developer must not be required to calculate any special fields, such as hashes or unique keys. -// -// The default cache implementation can not include optimizations that break the previous requirement. -// This means that we can only do complete scans of the data and equality can only be calculated based on -// equality of all of the individual fields. -// -// The cache interface can not make any assumption about the query efficency of the cache nor can -// it help in optimizing those queries. -// -// There is no simple sorting optimization, rather a series of indexes, and index intersection would -// be necessary. -// -// If for some reason the developer tries to update the cache with a new entry that may be a refresh -// token, they will not know that they need to update all of the refresh tokens or they may get strange -// behavior. -// -// Related to the above, there is no definition of a coherent cache. And if there was there would be -// no way for our API to enforce it. What about duplicates? -// -// there be a single cache entry per (authority, resource, clientId) -// tuple, with no special tokens (i.e. MRRT tokens) -// Required cache operations -// + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } -// Constants -var METADATA_CLIENTID = '_clientId'; -var METADATA_AUTHORITY = '_authority'; + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); -function nop(placeHolder, callback) { - callback(); -} + // Zero? + if (i < 0) { + c = [e = 0]; + } else { -/* - * This is a place holder cache that does nothing. - */ -var nopCache = { - add : nop, - addMany : nop, - remove : nop, - removeMany : nop, - find : nop -}; + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); -function createTokenHash(token) { - var hashAlg = crypto.createHash(cacheConstants.HASH_ALGORITHM); - hashAlg.update(token, 'utf8'); - return hashAlg.digest('base64'); -} + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); -function createTokenIdMessage(entry) { - var accessTokenHash = createTokenHash(entry[TokenResponseFields.ACCESS_TOKEN]); - var message = 'AccessTokenId: ' + accessTokenHash; - if (entry[TokenResponseFields.REFRESH_TOKEN]) { - var refreshTokenHash = createTokenHash(entry[TokenResponseFields.REFRESH_TOKEN]); - message += ', RefreshTokenId: ' + refreshTokenHash; - } - return message; -} + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback RefreshEntryFunction - * @memberOf CacheDriver - * @param {object} tokenResponse A token response to refresh. - * @param {string} [resource] The resource for which to obtain the token if it is different from the original token. - * @param {AcquireTokenCallback} callback Called on completion with an error or a new entry to add to the cache. - */ + rand.e = e; + rand.c = c; + return rand; + }; + })(); -/** - * Constructs a new CacheDriver object. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} authority - * @param {TokenCache} [cache] A token cache to use. If none is passed then the CacheDriver instance - * will not cache. - * @param {RefreshEntryFunction} refreshFunction - */ -function CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) { - this._callContext = callContext; - this._log = new Logger('CacheDriver', callContext._logContext); - this._authority = authority; - this._resource = resource; - this._clientId = clientId; - this._cache = cache || nopCache; - this._refreshFunction = refreshFunction; -} -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback QueryCallback - * @memberOf CacheDriver - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {Array} [response] On a succesful request returns an array of matched entries. - */ + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; -/** - * The cache driver query function. Ensures that all queries are authority specific. - * @param {object} query A query object. Can contain a clientId or userId or both. - * @param {QueryCallback} callback - */ -CacheDriver.prototype._find = function(query, callback) { - this._cache.find(query, callback); -}; -/** - * Queries for all entries that might satisfy a request for a cached token. - * @param {object} query A query object. Can contain a clientId or userId or both. - * @param {QueryCallback} callback - */ -CacheDriver.prototype._getPotentialEntries = function(query, callback) { - var self = this; - var potentialEntriesQuery = {}; + // PRIVATE FUNCTIONS - if (query.clientId) { - potentialEntriesQuery[METADATA_CLIENTID] = query.clientId; - } - if (query.userId) { - potentialEntriesQuery[TokenResponseFields.USER_ID] = query.userId; - } - this._log.verbose('Looking for potential cache entries:'); - this._log.verbose(JSON.stringify(potentialEntriesQuery), true); - this._find(potentialEntriesQuery, function(err, entries) { - self._log.verbose('Found ' + entries.length + ' potential entries.'); - callback(err, entries); - return; - }); -}; + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; -/** - * Finds all multi resource refresh tokens in the cache. - * Refresh token is bound to userId, clientId. - * @param {QueryCallback} callback - */ -CacheDriver.prototype._findMRRTTokensForUser = function(user, callback) { - this._find({ isMRRT : true, userId : user, _clientId : this._clientId}, callback); -}; + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback SingleEntryCallback - * @memberOf CacheDriver - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {object} [response] On a succesful request returns a single cache entry. - */ + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + arr[0] += alphabet.indexOf(str.charAt(i++)); -/** - * Finds a single entry that matches the query. If multiple entries are found that satisfy the query - * then an error will be returned. - * @param {object} query A query object. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._loadSingleEntryFromCache = function(query, callback) { - var self = this; - this._getPotentialEntries(query, function(err, potentialEntries) { - if (err) { - callback(err); - return; - } + for (j = 0; j < arr.length; j++) { - var returnVal; - var isResourceTenantSpecific; + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } - if (potentialEntries && 0 < potentialEntries.length) { - var resourceTenantSpecificEntries = _.where(potentialEntries, { resource : self._resource, _authority : self._authority }); + return arr.reverse(); + } - if (!resourceTenantSpecificEntries || 0 === resourceTenantSpecificEntries.length) { - self._log.verbose('No resource specific cache entries found.'); + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; - // There are no resource specific entries. Find an MRRT token. - var mrrtTokens = _.where(potentialEntries, { isMRRT : true }); - if (mrrtTokens && mrrtTokens.length > 0) { - self._log.verbose('Found an MRRT token.'); - returnVal = mrrtTokens[0]; - } else { - self._log.verbose('No MRRT tokens found.'); + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; } - } else if (resourceTenantSpecificEntries.length === 1) { - self._log.verbose('Resource specific token found.'); - returnVal = resourceTenantSpecificEntries[0]; - isResourceTenantSpecific = true; - }else { - callback(self._log.createError('More than one token matches the criteria. The result is ambiguous.')); - return; - } - } - if (returnVal) { - self._log.verbose('Returning token from cache lookup'); - self._log.verbose('Returning token from cache lookup, ' + createTokenIdMessage(returnVal), true); - } - callback(null, returnVal, isResourceTenantSpecific); - }); -}; + // Convert the number as integer. -/** - * The response from a token refresh request never contains an id_token and therefore no - * userInfo can be created from the response. This function creates a new cache entry - * combining the id_token based info and cache metadata from the cache entry that was refreshed with the - * new tokens in the refresh response. - * @param {object} entry A cache entry corresponding to the resfreshResponse. - * @param {object} refreshResponse The response from a token refresh request for the entry parameter. - * @return {object} A new cache entry. - */ -CacheDriver.prototype._createEntryFromRefresh = function(entry, refreshResponse) { - var newEntry = _.clone(entry); - newEntry = _.extend(newEntry, refreshResponse); + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); - if (entry.isMRRT && this._authority !== entry[METADATA_AUTHORITY]) { - newEntry[METADATA_AUTHORITY] = this._authority; - } + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; - this._log.verbose('Created new cache entry from refresh response.'); - return newEntry; -}; + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); -CacheDriver.prototype._replaceEntry = function(entryToReplace, newEntry, callback) { - var self = this; - this.remove(entryToReplace, function(err) { - if (err) { - callback(err); - return; - } - self.add(newEntry, callback); - }); -}; + // Zero? + if (!xc[0]) return alphabet.charAt(0); -/** - * Given an expired cache entry refreshes it and updates the cache. - * @param {object} entry A cache entry with an MRRT to refresh for another resource. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._refreshExpiredEntry = function(entry, callback) { - var self = this; - this._refreshFunction(entry, null, function(err, tokenResponse) { - if (err) { - callback(err); - return; - } + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; - var newEntry = self._createEntryFromRefresh(entry, tokenResponse); - self._replaceEntry(entry, newEntry, function(err) { - if (err) { - self._log.error('error refreshing expired token', err, true); - } else { - self._log.info('Returning token refreshed after expiry.'); - } - callback(err, newEntry); - }); - }); -}; + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } -/** - * Given a cache entry with an MRRT will acquire a new token for a new resource via the MRRT, and cache it. - * @param {object} entry A cache entry with an MRRT to refresh for another resource. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._acquireNewTokenFromMrrt = function(entry, callback) { - var self = this; - this._refreshFunction(entry, this._resource, function(err, tokenResponse) { - if (err) { - callback(err); - return; - } + // xc now represents str converted to baseOut. - var newEntry = self._createEntryFromRefresh(entry, tokenResponse); - self.add(newEntry, function(err) { - if (err) { - self._log.error('error refreshing mrrt', err, true); - } else { - self._log.info('Returning token derived from mrrt refresh.'); - } - callback(err, newEntry); - }); - }); -}; + // THe index of the rounding digit. + d = e + dp + 1; -/** - * Given a token this function will refresh it if it is either expired, or an MRRT. - * @param {object} entry A cache entry to refresh if necessary. - * @param {Boolean} isResourceSpecific Indicates whether this token is appropriate for the resource for which - * it was requested or whether it is possibly an MRRT token for which - * a resource specific access token should be acquired. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._refreshEntryIfNecessary = function(entry, isResourceSpecific, callback) { - var expiryDate = entry[TokenResponseFields.EXPIRES_ON]; + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; - // Add some buffer in to the time comparison to account for clock skew or latency. - var nowPlusBuffer = (new Date()).addMinutes(constants.Misc.CLOCK_BUFFER); + // Look at the rounding digits and mode to determine whether to round up. - if (isResourceSpecific && nowPlusBuffer.isAfter(expiryDate)) { - this._log.info('Cached token is expired. Refreshing: ' + expiryDate); - this._refreshExpiredEntry(entry, callback); - return; - } else if (!isResourceSpecific && entry.isMRRT) { - this._log.info('Acquiring new access token from MRRT token.'); - this._acquireNewTokenFromMrrt(entry, callback); - return; - } else { - callback(null, entry); - } -}; + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; -/** - * Finds a single entry in the cache that matches the query or fails if more than one match is found. - * @param {object} query A query object - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype.find = function(query, callback) { - var self = this; - query = query || {}; - this._log.verbose('finding using query'); - this._log.verbose('finding with query:' + JSON.stringify(query), true); - this._loadSingleEntryFromCache(query, function(err, entry, isResourceTenantSpecific) { - if (err) { - callback(err); - return; - } + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); - if (!entry) { - callback(); - return; - } + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { - self._refreshEntryIfNecessary(entry, isResourceTenantSpecific, function(err, newEntry) { - callback(err, newEntry); - return; - }); - }); -}; + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { -/** - * Removes a single entry from the cache. - * @param {object} entry The entry to remove. - * @param {Function} callback Called on completion. The first parameter may contain an error. - */ -CacheDriver.prototype.remove = function(entry, callback) { - this._log.verbose('Removing entry.'); - return this._cache.remove([entry], function(err) { - callback(err); - return; - }); -}; + // Truncate xc to the required number of decimal places. + xc.length = d; -/** - * Removes a collection of entries from the cache in a single batch operation. - * @param {Array} entries An array of cache entries to remove. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -CacheDriver.prototype._removeMany = function(entries, callback) { - this._log.verbose('Remove many: ' + entries.length); - this._cache.remove(entries, function(err) { - callback(err); - return; - }); -}; + // Round up? + if (r) { -/** - * Adds a collection of entries to the cache in a single batch operation. - * @param {Array} entries An array of entries to add to the cache. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -CacheDriver.prototype._addMany = function(entries, callback) { - this._log.verbose('Add many: ' + entries.length); - this._cache.add(entries, function(err) { - callback(err); - return; - }); -}; + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; -/* - * Tests whether the passed entry is a multi resource refresh token. - * Somewhat mysteriously the presense of a resource field in a returned - * token response indicates that the response is an MRRT. - * @param {object} entry - * @return {Boolean} true if the entry is an MRRT. - */ -function isMRRT(entry) { - return entry.resource ? true : false; -} + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } -/** - * Given an cache entry this function finds all of the MRRT tokens already in the cache - * and updates them with the refresh_token of the passed in entry. - * @param {object} entry The entry from which to get an updated refresh_token - * @param {Function} callback Called back on completion. The first parameter may contain an error. - */ -CacheDriver.prototype._updateRefreshTokens = function(entry, callback) { - var self = this; - if (isMRRT(entry)) { - this._findMRRTTokensForUser(entry.userId, function(err, mrrtTokens) { - if (err) { - callback(err); - return; - } + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); - if (!mrrtTokens || 0 === mrrtTokens.length) { - callback(); - return; - } + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); - self._log.verbose('Updating ' + mrrtTokens.length + ' cached refresh tokens.'); - self._removeMany(mrrtTokens, function(err) { - if (err) { - callback(err); - return; + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); } - for (var i = 0; i < mrrtTokens.length; i++) { - mrrtTokens[i][TokenResponseFields.REFRESH_TOKEN] = entry[TokenResponseFields.REFRESH_TOKEN]; - } + // The caller will add the sign. + return str; + }; + })(); - self._addMany(mrrtTokens, function(err) { - callback(err); - return; - }); - }); - }); - } else { - callback(); - return; - } -}; -/** - * Checks to see if the entry has cache metadata already. If it does - * then it probably came from a refresh operation and the metadata - * was copied from the originating entry. - * @param {object} entry The entry to check - * @return {bool} Returns true if the entry has already been augmented - * with cache metadata. - */ -CacheDriver.prototype._entryHasMetadata = function(entry) { - return (_.has(entry, METADATA_CLIENTID) && _.has(entry, METADATA_AUTHORITY)); -}; + // Perform division in the specified base. Called by div and convertBase. + div = (function () { -CacheDriver.prototype._augmentEntryWithCacheMetadata = function(entry) { - if (this._entryHasMetadata(entry)) { - return; - } + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; - if (isMRRT(entry)) { - this._log.verbose('Added entry is MRRT'); - entry.isMRRT = true; - } else { - entry.resource = this._resource; - } + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } - entry[METADATA_CLIENTID] = this._clientId; - entry[METADATA_AUTHORITY] = this._authority; -}; + if (carry) x = [carry].concat(x); -/** - * Adds a single entry to the cache. - * @param {object} entry The entry to add. - * @param {string} clientId The id of this client app. - * @param {string} resource The id of the resource for which the cached token was obtained. - * @param {Function} callback Called back on completion. The first parameter may contain an error. - */ -CacheDriver.prototype.add = function(entry, callback) { - var self = this; - this._log.verbose('Adding entry'); - this._log.verbose('Adding entry, ' + createTokenIdMessage(entry)); + return x; + } - this._augmentEntryWithCacheMetadata(entry); + function compare(a, b, aL, bL) { + var i, cmp; - this._updateRefreshTokens(entry, function(err) { - if (err) { - callback(err); - return; - } + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { - self._cache.add([entry], function(err) { - callback(err); - return; - }); - }); -}; + for (i = cmp = 0; i < aL; i++) { -module.exports = CacheDriver; - -/***/ }), - -/***/ 66576: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + return cmp; + } -var constants = __nccwpck_require__(10282); -var Logger = __nccwpck_require__(92288).Logger; -var Mex = __nccwpck_require__(27078); -var OAuth2Client = __nccwpck_require__(41602); + function subtract(a, b, aL, base) { + var i = 0; -var OAuth2Parameters = constants.OAuth2.Parameters; -var TokenResponseFields = constants.TokenResponseFields; -var OAuth2GrantType = constants.OAuth2.GrantType; -var OAuth2Scope = constants.OAuth2.Scope; + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } -/** - * Constructs a new CodeRequest object. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {AuthenticationContext} authenticationContext - * @param {string} resource - * @param {string} clientId - */ -// TODO: probably need to modify the parameter list. -function CodeRequest(callContext, authenticationContext, clientId, resource) { - this._log = new Logger('DeviceCodeRequest', callContext._logContext); - this._callContext = callContext; - this._authenticationContext = authenticationContext; - this._resource = resource; - this._clientId = clientId; - - // This should be set at the beginning of getToken - // functions that have a userId. - this._userId = null; -}; + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } -/** - * Get user code info. - * @private - * @param {object} oauthParameters containing all the parameters needed to get the user code info. - * @param {callback} callback - */ -CodeRequest.prototype._getUserCodeInfo = function (oauthParameters, callback) { - var oauth2Client = this._createOAuth2Client(); - oauth2Client.getUserCodeInfo(oauthParameters, callback); -}; + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; -CodeRequest.prototype._createOAuth2Client = function () { - return new OAuth2Client(this._callContext, this._authenticationContext._authority); -}; + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { -/** - * Creates a set of basic, common, OAuthParameters based on values that the CodeRequest was created with. - * @private - * @return {object} containing all the basic parameters. - */ -CodeRequest.prototype._createOAuthParameters = function () { - var oauthParameters = {}; - - oauthParameters[OAuth2Parameters.CLIENT_ID] = this._clientId; - oauthParameters[OAuth2Parameters.RESOURCE] = this._resource; + return new BigNumber( - return oauthParameters; -}; + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : -/** - * Get the user code information. - * @param {string} language optional parameter used to get the user code info. - * @param {callback} callback - */ -CodeRequest.prototype.getUserCodeInfo = function(language, callback) { - this._log.info('Getting user code info.'); + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } - var oauthParameters = this._createOAuthParameters(); - if (language){ - oauthParameters[OAuth2Parameters.LANGUAGE] = language; - } + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; - this._getUserCodeInfo(oauthParameters, callback); -}; -module.exports = CodeRequest; - -/***/ }), - -/***/ 10282: -/***/ ((module) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); -var Constants = { - OAuth2 : { - Parameters : { - GRANT_TYPE : 'grant_type', - CLIENT_ASSERTION : 'client_assertion', - CLIENT_ASSERTION_TYPE : 'client_assertion_type', - CLIENT_ID : 'client_id', - CLIENT_SECRET : 'client_secret', - REDIRECT_URI : 'redirect_uri', - RESOURCE : 'resource', - CODE : 'code', - SCOPE : 'scope', - ASSERTION : 'assertion', - AAD_API_VERSION : 'api-version', - USERNAME : 'username', - PASSWORD : 'password', - REFRESH_TOKEN : 'refresh_token', - LANGUAGE : 'mkt', - DEVICE_CODE : 'device_code', - }, + if (yc[i] > (xc[i] || 0)) e--; - GrantType : { - AUTHORIZATION_CODE : 'authorization_code', - REFRESH_TOKEN : 'refresh_token', - CLIENT_CREDENTIALS : 'client_credentials', - JWT_BEARER : 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - PASSWORD : 'password', - SAML1 : 'urn:ietf:params:oauth:grant-type:saml1_1-bearer', - SAML2 : 'urn:ietf:params:oauth:grant-type:saml2-bearer', - DEVICE_CODE: 'device_code' - }, + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; - ResponseParameters : { - CODE : 'code', - TOKEN_TYPE : 'token_type', - ACCESS_TOKEN : 'access_token', - ID_TOKEN : 'id_token', - REFRESH_TOKEN : 'refresh_token', - CREATED_ON : 'created_on', - EXPIRES_ON : 'expires_on', - EXPIRES_IN : 'expires_in', - RESOURCE : 'resource', - ERROR : 'error', - ERROR_DESCRIPTION : 'error_description' - }, + // Normalise xc and yc so highest order digit of yc is >= base / 2. - DeviceCodeResponseParameters : { - USER_CODE : 'user_code', - DEVICE_CODE : 'device_code', - VERIFICATION_URL : 'verification_url', - EXPIRES_IN : 'expires_in', - INTERVAL: 'interval', - MESSAGE: 'message', - ERROR: 'error', - ERROR_DESCRIPTION: 'error_description' - }, + n = mathfloor(base / (yc[0] + 1)); - Scope : { - OPENID : 'openid' - }, + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } - IdTokenMap : { - 'tid' : 'tenantId', - 'given_name' : 'givenName', - 'family_name' : 'familyName', - 'idp' : 'identityProvider', - 'oid': 'oid' - } - }, + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; - TokenResponseFields : { - TOKEN_TYPE : 'tokenType', - ACCESS_TOKEN : 'accessToken', - REFRESH_TOKEN : 'refreshToken', - CREATED_ON : 'createdOn', - EXPIRES_ON : 'expiresOn', - EXPIRES_IN : 'expiresIn', - RESOURCE : 'resource', - USER_ID : 'userId', - ERROR : 'error', - ERROR_DESCRIPTION : 'errorDescription' - }, + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; - UserCodeResponseFields : { - USER_CODE : 'userCode', - DEVICE_CODE: 'deviceCode', - VERIFICATION_URL: 'verificationUrl', - EXPIRES_IN: 'expiresIn', - INTERVAL: 'interval', - MESSAGE: 'message', - ERROR: 'error', - ERROR_DESCRIPTION: 'errorDescription' - }, + do { + n = 0; - IdTokenFields : { - USER_ID : 'userId', - IS_USER_ID_DISPLAYABLE : 'isUserIdDisplayable', - TENANT_ID : 'tenantId', - GIVE_NAME : 'givenName', - FAMILY_NAME : 'familyName', - IDENTITY_PROVIDER : 'identityProvider' - }, + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); - Misc : { - MAX_DATE : 0xffffffff, - CLOCK_BUFFER : 5 // In minutes. - }, + // If divisor < remainder. + if (cmp < 0) { - Jwt : { - SELF_SIGNED_JWT_LIFETIME : 10, // 10 mins in mins - AUDIENCE : 'aud', - ISSUER : 'iss', - SUBJECT : 'sub', - NOT_BEFORE : 'nbf', - EXPIRES_ON : 'exp', - JWT_ID : 'jti' - }, + // Calculate trial digit, n. - AADConstants : { - WORLD_WIDE_AUTHORITY : 'login.windows.net', - WELL_KNOWN_AUTHORITY_HOSTS : ['login.windows.net', 'login.microsoftonline.com', 'login.chinacloudapi.cn', 'login-us.microsoftonline.com', 'login.microsoftonline.de', 'login.microsoftonline.us'], - INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE : 'https://{authorize_host}/common/discovery/instance?authorization_endpoint={authorize_endpoint}&api-version=1.0', - AUTHORIZE_ENDPOINT_PATH : '/oauth2/authorize', - TOKEN_ENDPOINT_PATH : '/oauth2/token', - DEVICE_ENDPOINT_PATH : '/oauth2/devicecode' - }, + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - UserRealm : { - FederationProtocolType : { - WSFederation : 'wstrust', - SAML2 : 'saml20', - Unknown : 'unknown' - }, + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); - AccountType : { - Federated : 'federated', - Managed : 'managed', - Unknown : 'unknown' - } - }, + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. - Saml : { - TokenTypeV1 : 'urn:oasis:names:tc:SAML:1.0:assertion', - TokenTypeV2 : 'urn:oasis:names:tc:SAML:2.0:assertion' - }, + if (n > 1) { - XmlNamespaces : { - wsdl : 'http://schemas.xmlsoap.org/wsdl/', - sp : 'http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702', - sp2005 : 'http://schemas.xmlsoap.org/ws/2005/07/securitypolicy', - wsu : 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd', - wsa10 : 'http://www.w3.org/2005/08/addressing', - http : 'http://schemas.microsoft.com/ws/06/2004/policy/http', - soap12 : 'http://schemas.xmlsoap.org/wsdl/soap12/', - wsp : 'http://schemas.xmlsoap.org/ws/2004/09/policy', - s : 'http://www.w3.org/2003/05/soap-envelope', - wsa : 'http://www.w3.org/2005/08/addressing', - wst : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512', - t : 'http://schemas.xmlsoap.org/ws/2005/02/trust' - }, + // n may be > base only when base is 3. + if (n >= base) n = base - 1; - Cache : { - HASH_ALGORITHM : 'sha256' - }, + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; - HttpError : { - UNAUTHORIZED : 401 - }, + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; - AdalIdParameters : { - SKU : 'x-client-SKU', - VERSION : 'x-client-Ver', - OS : 'x-client-OS', - CPU : 'x-client-CPU', - NODE_SKU : 'Node' - }, + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { - WSTrustVersion : { - UNDEFINED : 'undefined', - WSTRUST13 : 'wstrust13', - WSTRUST2005 : 'wstrust2005' - } - }; + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { -module.exports = Constants; - - -/***/ }), - -/***/ 92288: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } -var _ = __nccwpck_require__(83571); -var uuid = __nccwpck_require__(19744); // want to replace with this in the future: https://gist.github.com/jed/982883 + if (prodL < remL) prod = [0].concat(prod); + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + // If product was < remainder. + if (cmp == -1) { -var LEVEL_STRING_MAP = { - 0 : 'ERROR:', - 1 : 'WARNING:', - 2 : 'INFO:', - 3 : 'VERBOSE:' -}; + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; -/** - * Methods for controling global logging options for ADAL - * @namespace - */ -var Logging = { + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 - /** - * @callback LoggingCallback - * @memberOf Logging - * @param {Logging.LOGGING_LEVEL} level The level of this log entry. - * @param {string} message The text content of the log entry. - * @param {Error} [error] An Error object if this is an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. - */ + // Add the next digit, n, to the result array. + qc[i++] = n; - /** - * @typedef LoggingOptions - * @memberOf Logging - * @property {LoggingCallback} [log] The function to call when ADAL generates a log entry. - * @property {Logging.LOGGING_LEVEL} [level] The maximum level of log entries to generate. - */ + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); - /** - * Describes the available logging levels. - * @enum - * @type {Number} - */ - LOGGING_LEVEL : { - ERROR : 0, - WARN : 1, - INFO : 2, - VERBOSE : 3 - }, + more = rem[0] != null; - /** - * Sets global logging options for ADAL. - * @param {LoggingOptions} options - */ - setLoggingOptions : function(options) { - if (!options) { - options = {}; - } + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } - if (options.log) { - if (!_.isFunction(options.log)) { - throw new Error('setLogOptions expects the log key in the options parameter to be a function'); - } - } else { - // if no log function was passed set it to a default no op function. - options.log = function() {}; - } + if (base == BASE) { - if (options.level) { - var level = options.level; - if (level < 0 || level > 3) { - throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive'); - } - } else { - options.level = this.LOGGING_LEVEL.ERROR; - } + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); - if (options.loggingWithPII != true) { - options.loggingWithPII = false; - } - - this.LogOptions = options; - }, + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); - /** - * Get's the current global logging options. - * @return {LoggingOptions} - */ - getLoggingOptions : function() { - return this.LogOptions; - }, + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } - /** - * Stores the current global logging options. - * @private - * @type {LoggingOptions} - */ - LogOptions : { - log : function() {}, - level : 0, - loggingWithPII: false - } -}; + return q; + }; + })(); -/** - * An internal logging object. - * @class - * @private - * @param {string} componentName The name of the component that created this instance. This name will be - * prepended to the beginning of all log entries generated by this instance. - */ -function Logger(componentName, logContext) { - if (!logContext) { - throw new Error('Logger: logContext is a required parameter'); - } - this._componentName = componentName; - this._logContext = logContext; -} -Object.defineProperty(Logger.prototype, 'context', { - get: function () { - return this._logContext; - } -}); + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; -/** - * Generates a log entry - * @param {Logging.LOGGING_LEVEL} level The level of this log entry - * @param {string|function} message A message string, or a function that returns a message string, to log. - * @param {Error} [error] If this is a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry then the caller - * should pass an error object in this parameter. - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.log = function (level, message, error, containsPII) { - if (containsPII == true && !Logging.LogOptions.loggingWithPII) { - return; - } + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); - if (level <= Logging.LogOptions.level) { - if (_.isFunction(message)) { - message = message(); - } + if (!n.c) return n.toString(); - var correlationId = this._logContext.correlationId || ''; - var timeStamp = new Date().toUTCString(); + c0 = n.c[0]; + ne = n.e; - var formattedMessage = timeStamp + ':' + correlationId + ' - ' + this._componentName + ': ' + LEVEL_STRING_MAP[level] + ' ' + message; - if (error) { - formattedMessage += '\nStack:\n' + error.stack; - } - Logging.LogOptions.log(level, formattedMessage, error); - } -}; + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); -/** - * Generate an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. - * @param {string} message A message to log - * @param {Error} error The Error object associated with this log entry - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.error = function (message, error, containsPII) { - this.log(Logging.LOGGING_LEVEL.ERROR, message, error, containsPII); -}; + // n.e may have changed if the value was rounded up. + e = n.e; -/** - * Generate an {@link Logging.LOGGING_LEVEL.WARN|WARN} level log entry. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.warn = function (message, containsPII) { - this.log(Logging.LOGGING_LEVEL.WARN, message, null, containsPII); -}; + str = coeffToString(n.c); + len = str.length; -/** - * Generate an {@link Logging.LOGGING_LEVEL.INFO|INFO} level log entry. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.info = function (message, containsPII) { - this.log(Logging.LOGGING_LEVEL.INFO, message, null, containsPII); -}; + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. -/** - * Generate an {@link Logging.LOGGING_LEVEL.VERBOSE|VERBOSE} level log entry. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.verbose = function (message, containsPII) { - this.log(Logging.LOGGING_LEVEL.VERBOSE, message, null, containsPII); -}; + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { -/** - * Generate a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry, as well as an - * Error object to go with it. This is a convenience method for throwing logged errors. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.createError = function(message, containsPII) { - var err = new Error(message); - this.error(message, err, containsPII); - return err; -}; + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); -/** - * Creates a new log context based on the correlationId passed in. If no correlationId is passed in - * then one is generated, by the function uuid.v4() - * @private - */ -function createLogContext(correlationId) { - var id = correlationId || uuid.v4(); - return { correlationId : id }; -} + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); -var exports = { - Logging : Logging, - Logger : Logger, - createLogContext : createLogContext -}; + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } -module.exports = exports; - -/***/ }), - -/***/ 92474: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + return n.s < 0 && c0 ? '-' + str : str; + } + // Handle BigNumber.max and BigNumber.min. + function maxOrMin(args, method) { + var n, + i = 1, + m = new BigNumber(args[0]); -var _ = __nccwpck_require__(83571); + for (; i < args.length; i++) { + n = new BigNumber(args[i]); -/** - * Constructs a new in memory token cache. - * @constructor - */ -function MemoryCache() { - this._entries = []; -} + // If any number is NaN, return NaN. + if (!n.s) { + m = n; + break; + } else if (method.call(m, n)) { + m = n; + } + } -/** - * Removes a collection of entries from the cache in a single batch operation. - * @param {Array} entries An array of cache entries to remove. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -MemoryCache.prototype.remove = function(entries, callback) { - var updatedEntries = _.filter(this._entries, function(element) { - if (_.findWhere(entries, element)) { - return false; + return m; } - return true; - }); - this._entries = updatedEntries; - callback(); -}; -/** - * Adds a collection of entries to the cache in a single batch operation. - * @param {Array} entries An array of entries to add to the cache. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -MemoryCache.prototype.add = function(entries, callback) { - // Remove any entries that are duplicates of the existing - // cache elements. - _.each(this._entries, function(element) { - _.each(entries, function(addElement, index) { - if (_.isEqual(element, addElement)) { - entries[index] = null; - } - }); - }); - - // Add the new entries to the end of the cache. - entries = _.compact(entries); - for (var i = 0; i < entries.length; i++) { - this._entries.push(entries[i]); - } - - callback(null, true); -}; - -/** - * Finds all entries in the cache that match all of the passed in values. - * @param {object} query This object will be compared to each entry in the cache. Any entries that - * match all of the values in this object will be returned. All the values - * in the passed in object must match values in a potentialy returned object - * exactly. The returned object may have more values than the passed in query - * object. - * @param {TokenCacheFindCallback} callback - */ -MemoryCache.prototype.find = function(query, callback) { - var results = _.where(this._entries, query); - callback(null, results); -}; - -module.exports = MemoryCache; - -/***/ }), - -/***/ 27078: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - -var axios = __nccwpck_require__(96545); -var url = __nccwpck_require__(78835); -var DOMParser = __nccwpck_require__(57286).DOMParser; -var _ = __nccwpck_require__(83571); -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); - -var xmlutil = __nccwpck_require__(27387); -var select = xmlutil.xpathSelect; - -var Namespaces = __nccwpck_require__(10282).XmlNamespaces; + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; -var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + // Remove trailing zeros. + for (; !c[--j]; c.pop()); -/** - * Create a new Mex object. - * @private - * @constructor - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} url The url of the mex endpoint. - */ -function Mex(callContext, url) { - this._log = new Logger('MEX', callContext._logContext); - this._callContext = callContext; - this._url = url; - this._dom = null; - this._mexDoc = null; - this._usernamePasswordPolicy = {}; - this._log.verbose('Mex created'); - this._log.verbose('Mex created with url: ' + url, true); -} + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); -/** -* Returns the policy containing IDP url and wstrust version from which a username passwowrd can be exchanged for a token. -* @instance -* @memberOf Mex -* @name usernamePasswordPolicy -*/ -Object.defineProperty(Mex.prototype, 'usernamePasswordPolicy', { - get: function() { - return this._usernamePasswordPolicy; - } -}); + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { -/** -* @callback DiscoverCallback -* @memberOf Mex -* @param {object} error -*/ + // Infinity. + n.c = n.e = null; -/** -* Performs Mex discovery. This method will retrieve the mex document, parse it, and extract -* the username password ws-trust endpoint. -* @private -* @param {Mex.DiscoverCallback} callback Called when discover is complete. -*/ -Mex.prototype.discover = function (callback) { - this._log.verbose('Retrieving mex'); - this._log.verbose('Retrieving mex at: ' + this._url); - var self = this; - var options = util.createRequestOptions(self, { headers: { 'Content-Type': 'application/soap+xml' } }); - axios.get(this._url, options).then((response) => { - util.logReturnCorrelationId(this._log, 'Mex Get', response); - - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Mex Get' + ' request returned http error: ' + response.status + ' and server response: ' + response.status;; - callback(this._log.createError(returnErrorString, true), response.data); - } + // Underflow? + } else if (e < MIN_EXP) { - // Success case: status >= 200 && < 300 - try { - self._mexDoc = response.data; - var options = { - errorHandler : self._log.error - }; - self._dom = new DOMParser(options).parseFromString(self._mexDoc); - self._parse(callback); - return; - } catch (err) { - self._log.error('Failed to parse mex response in to DOM', err, true); - callback(err); + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; } - }).catch((error) => { - // status >= 400: error case - if (error.response) { - this._log.error('Mex Get' + ' request failed with', error.response.status, true); - util.logReturnCorrelationId(this._log, 'Mex Get', error.response); - var returnErrorString = 'Mex Get' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data);; - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('Mex Get' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else { - this._log.error('Mex Get' + ' request was never made, please check', error.message, true); - callback(error.message); - } - }); -}; - -var TRANSPORT_BINDING_XPATH = 'wsp:ExactlyOne/wsp:All/sp:TransportBinding'; -var TRANSPORT_BINDING_2005_XPATH = 'wsp:ExactlyOne/wsp:All/sp2005:TransportBinding'; -/** -* Checks a DOM policy node that is a potentialy appplicable username password policy -* to ensure that it has the correct transport. -* @private -* @param {object} policyNode The policy node to check. -* @returns {string} If the policy matches the desired transport then the id of the policy is returned. -* If not then null is returned. -*/ -Mex.prototype._checkPolicy = function(policyNode) { - var policyId = null; - var id = policyNode.getAttributeNS(Namespaces.wsu, 'Id'); - var transportBindingNodes = select(policyNode, TRANSPORT_BINDING_XPATH); - if (0 === transportBindingNodes.length) { - transportBindingNodes = select(policyNode, TRANSPORT_BINDING_2005_XPATH); - } - if (0 !== transportBindingNodes.length) { - if (id) { - policyId = id; - } - } - if (policyId) { - this._log.verbose('found matching policy id'); - this._log.verbose('found matching policy id: ' + policyId, true); - } else { - if (!id) { - id = ''; - } - this._log.verbose('potential policy did not match required transport binding'); - this._log.verbose('potential policy did not match required transport binding: ' + id, true); - } - return policyId; -}; -/** -* Finds all username password policies within the mex document. -* @private -* @param xpath The xpath expression for selecting username token nodes. -* @returns {object} A map object that contains objects containing the id of username password polices. -*/ -Mex.prototype._selectUsernamePasswordPolicies = function(xpath) { - var policies = {}; - var usernameTokenNodes = select(this._dom, xpath); - if (!usernameTokenNodes.length) { - this._log.warn('no username token policy nodes found'); - return; - } - for (var i=0; i < usernameTokenNodes.length; i++) { - var policyNode = usernameTokenNodes[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; - var id = this._checkPolicy(policyNode); - if (id) { - var idRef = '#' + id; - policies[idRef] = { id : idRef }; + return n; } - } - return _.isEmpty(policies) ? null : policies; -}; -var SOAP_ACTION_XPATH = 'wsdl:operation/soap12:operation/@soapAction'; -var RST_SOAP_ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; -var RST_SOAP_ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; -var SOAP_TRANSPORT_XPATH = 'soap12:binding/@transport'; -var SOAP_HTTP_TRANSPORT_VALUE = 'http://schemas.xmlsoap.org/soap/http'; -/** -* Given a DOM binding node determines whether it matches the correct soap action and transport. -* @private -* @param {object} bindingNode The DOM node to check. -* @returns {bool} -*/ -Mex.prototype._checkSoapActionAndTransport = function(bindingNode) { - var soapTransportAttributes; - var soapAction; - var soapTransport; - var bindingName = bindingNode.getAttribute('name'); - var soapActionAttributes = select(bindingNode, SOAP_ACTION_XPATH); - if (soapActionAttributes.length) { - soapAction = soapActionAttributes[0].value; - soapTransportAttributes = select(bindingNode, SOAP_TRANSPORT_XPATH); - } - if (soapTransportAttributes.length) { - soapTransport = soapTransportAttributes[0].value; - } - if (soapTransport === SOAP_HTTP_TRANSPORT_VALUE) { - if (soapAction === RST_SOAP_ACTION_13) { - this._log.verbose('foud binding matching Action and Transport: ' + bindingName); - return WSTrustVersion.WSTRUST13; - } - else if (soapAction === RST_SOAP_ACTION_2005) { - this._log.verbose('found binding matching Action and Transport: ' + bindingName); - return WSTrustVersion.WSTRUST2005; - } - } + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - this._log.verbose('binding node did not match soap Action or Transport: ' + bindingName); - return WSTrustVersion.UNDEFINED; -}; + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); -/** -* Given a map with policy id keys, finds the bindings in the mex document that are linked to thos policies. -* @private -* @param {object} policies A map with policy id keys. -* @returns {object} a map of bindings id's to policy id's. -*/ -Mex.prototype._getMatchingBindings = function(policies) { - var bindings = {}; - var bindingPolicyRefNodes = select(this._dom, '//wsdl:definitions/wsdl:binding/wsp:PolicyReference'); - for (var i=0; i < bindingPolicyRefNodes.length; i++) { - var node = bindingPolicyRefNodes[i]; - var uri = node.getAttribute('URI'); - var policy = policies[uri]; - if (policy) { - var bindingNode = node.parentNode; - var bindingName = bindingNode.getAttribute('name'); - var version = this._checkSoapActionAndTransport(bindingNode); - if (version !== WSTrustVersion.UNDEFINED) { - var bindingPolicy = {}; - bindingPolicy.url = uri; - bindingPolicy.version = version; + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { - bindings[bindingName] = bindingPolicy; - } - } - } - return _.isEmpty(bindings) ? null : bindings; -}; + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); -/** -* Ensures that a url points to an SSL endpoint. -* @private -* @param {string} endpointUrl The url to check. -* @returns {bool} -*/ -Mex.prototype._urlIsSecure = function(endpointUrl) { - var parsedUrl = url.parse(endpointUrl); - return parsedUrl.protocol === 'https:'; -}; + if (b) { + base = b; -var PORT_XPATH = '//wsdl:definitions/wsdl:service/wsdl:port'; -var ADDRESS_XPATH = 'wsa10:EndpointReference/wsa10:Address'; -/** -* Finds all of the wsdl ports in the mex document that are associated with username password policies. Augments -* the passed in bindings with the endpoint url of the correct port. -* @private -* @param {object} bindings A map of binding id's to policy id's. -*/ -Mex.prototype._getPortsForPolicyBindings = function(bindings, policies) { - var portNodes = select(this._dom, PORT_XPATH); - if (0 === portNodes.length) { - this._log.warning('no ports found'); - } - for (var i=0; i < portNodes.length; i++) { - var portNode = portNodes[i]; - var bindingId = portNode.getAttribute('binding'); + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } - // Clear any prefix - var bindingIdParts = bindingId.split(':'); - bindingId = bindingIdParts[bindingIdParts.length - 1]; + if (str != s) return new BigNumber(s, base); + } - var trustPolicy = bindings[bindingId]; - if (trustPolicy) { - var bindingPolicy = policies[trustPolicy.url]; + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } - if (bindingPolicy && !bindingPolicy.url) { - bindingPolicy.version = trustPolicy.version; - var addressNode = select(portNode, ADDRESS_XPATH); - if (0 === addressNode) { - throw this._log.createError('no address nodes on port.'); - } - var address = xmlutil.findElementText(addressNode[0]); - if (this._urlIsSecure(address)) { - bindingPolicy.url = address; - } else { - this._log.warn('skipping insecure endpoint: ' + address); + // NaN + x.s = null; } + + x.c = x.e = null; } - } - } -}; + })(); -/** -* Given a list of username password policies chooses one of them at random as the policy chosen by this Mex instance. -* @private -* @param {object} policies A map of policy id's to an object containing username password ws-trust endpoint addresses. -*/ -Mex.prototype._selectSingleMatchingPolicy = function(policies) { - // if both wstrust13 and wstrust2005 policy exists, then choose wstrust13, otherwise choose whatever exists. - var matchingPolicies = _.filter(policies, function(policy) { return policy.url ? true : false; }); - if (!matchingPolicies) { - this._log.warn('no policies found with an url'); - return; - } - var wstrust13Policy = null, wstrust2005Policy = null; - for(var i = 0; i < matchingPolicies.length; ++i) { - var matchingPolicy = matchingPolicies[i]; - if (WSTrustVersion.WSTRUST13 === matchingPolicy.version) { - wstrust13Policy = matchingPolicy; - } - else if (WSTrustVersion.WSTRUST2005 === matchingPolicy.version) { - wstrust2005Policy = matchingPolicy; - } - } + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; - if (!wstrust13Policy && !wstrust2005Policy) { - this._log.warn('no policies found with an url'); - this._usernamePasswordPolicy = null; - return; - } + // if x is not Infinity or NaN... + if (xc) { - this._usernamePasswordPolicy = wstrust13Policy ? wstrust13Policy : wstrust2005Policy; -}; + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { -/** -* Parses the mex document previously retrieved. -* @private -* @param {Mex.DiscoverCallback} callback -*/ -Mex.prototype._parse = function(callback) { - var self = this; - var xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp:SignedEncryptedSupportingTokens/wsp:Policy/sp:UsernameToken/wsp:Policy/sp:WssUsernameToken10'; - var policies = self._selectUsernamePasswordPolicies(xpathExpression); + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; - xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10'; + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; - if (policies) { - _.extend(policies, self._selectUsernamePasswordPolicies(xpathExpression)); - } - else { - policies = self._selectUsernamePasswordPolicies(xpathExpression); - } + // Get the rounding digit at index j of n. + rd = n / pows10[d - j - 1] % 10 | 0; + } else { + ni = mathceil((i + 1) / LOG_BASE); - if (!policies) { - callback(self._log.createError('No matching policies')); - return; - } - var bindings = self._getMatchingBindings(policies); - if (!bindings) { - callback(self._log.createError('No matching bindings')); - return; - } - self._getPortsForPolicyBindings(bindings, policies); - self._selectSingleMatchingPolicy(policies); - var err = this._url ? undefined : this._log.createError('No ws-trust endpoints match requirements.'); - callback(err); -}; + if (ni >= xc.length) { -module.exports = Mex; - -/***/ }), - -/***/ 41602: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + if (r) { + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; -var _ = __nccwpck_require__(83571); -__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. -var querystring = __nccwpck_require__(71191); -var uuid = __nccwpck_require__(19744); -var axios = __nccwpck_require__(96545); -var url = __nccwpck_require__(78835); -var async = __nccwpck_require__(57888); + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); -var constants = __nccwpck_require__(10282); -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); + // Get the index of rd within n. + i %= LOG_BASE; -var OAuth2Parameters = constants.OAuth2.Parameters; -var OAuth2ResponseParameters = constants.OAuth2.ResponseParameters; -var DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters; -var IdTokenMap = constants.OAuth2.IdTokenMap; -var TokenResponseFields = constants.TokenResponseFields; -var UserCodeResponseFields = constants.UserCodeResponseFields; -var IdTokenFields = constants.IdTokenFields; + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; -var TOKEN_RESPONSE_MAP = {}; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION; + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; + } + } + r = r || sd < 0 || -var DEVICE_CODE_RESPONSE_MAP = {}; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION; + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); -/** - * Constructs an instances of OAuth2Client - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string|url} authority An url that points to an authority. - */ -function OAuth2Client(callContext, authority) { - this._aadApiVersion = authority.aadApiVersion === undefined? '1.0' : authority.aadApiVersion; - this._tokenEndpoint = authority.tokenEndpoint; - this._deviceCodeEndpoint = authority.deviceCodeEndpoint; + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && - this._log = new Logger('OAuth2Client', callContext._logContext); - this._callContext = callContext; - this._cancelPollingRequest = false; -} + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); -/** - * Constructs an OAuth 2.0 token request url. - * @private - * @return {URL} - */ -OAuth2Client.prototype._createTokenUrl = function () { - var tokenUrl = url.parse(this._tokenEndpoint); + if (sd < 1 || !xc[0]) { + xc.length = 0; - var parameters = {}; - parameters[OAuth2Parameters.AAD_API_VERSION] = this._aadApiVersion; + if (r) { - tokenUrl.search = querystring.stringify(parameters); - return tokenUrl; -}; + // Convert sd to decimal places. + sd -= x.e + 1; -/** - * Constructs the user code info request url. - * @private - * @return {URL} - */ -OAuth2Client.prototype._createDeviceCodeUrl = function () { - var deviceCodeUrl = url.parse(this._deviceCodeEndpoint); + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { - var parameters = {}; - parameters[OAuth2Parameters.AAD_API_VERSION] = this._aadApiVersion; + // Zero. + xc[0] = x.e = 0; + } - deviceCodeUrl.search = querystring.stringify(parameters); + return x; + } - return deviceCodeUrl; -}; + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; -/** - * @private - * @param {object} obj An object in which integer values may reside. - * @param {array} keys An array of strings that specify keys in which integers may need parsing. - */ -OAuth2Client.prototype._parseOptionalInts = function (obj, keys) { - var self = this; - keys.forEach(function(element) { - if (_.has(obj, element)) { - obj[element] = parseInt(obj[element], 10); - if (isNaN(obj[element])) { - throw self._log.createError(element + ' could not be parsed as an int.'); - } - } - }); -}; + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } -/** - * Parses a JWS encoded JWT into it's three parts. - * @param {string} jwtToken The token to parse. - * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined. - */ -OAuth2Client.prototype._crackJwt = function(jwtToken) { - var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; + // Round up? + if (r) { - var matches = idTokenPartsRegex.exec(jwtToken); - if (!matches || matches.length < 4) { - this._log.warn('The returned id_token is not parseable.'); - return; - } + for (; ;) { - var crackedToken = { - header : matches[1], - JWSPayload : matches[2], - JWSSig : matches[3] - }; + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { - return crackedToken; -}; + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); -/** - * Finds the value that should be used as the userId value. - * @param {object} idToken The id token that parsed. - * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field. - */ -OAuth2Client.prototype._getUserId = function(idToken) { - var userId; - var isDisplayable; + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } - if (idToken.upn) { - userId = idToken.upn; - isDisplayable = true; - } else if (idToken.email) { - userId = idToken.email; - isDisplayable = true; - } else if (idToken.sub) { - userId = idToken.sub; - } + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } - if (!userId) { - // generate a random GUID. - userId = uuid.v4(); - } + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } - var userIdVals = {}; - userIdVals[IdTokenFields.USER_ID] = userId; - if (isDisplayable) { - userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true; - } + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; - return userIdVals; -}; + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } -function mapFields(inObj, outObj, map) { - for (var key in inObj) { - if (map[key]) { - var mappedKey = map[key]; - outObj[mappedKey] = inObj[key]; + return x; } - } -} -/** - * Given a decoded id token off the wire, this function extracts the values that - * ADAL commonly returns to callers and translates the names to more user - * friendly names. - * @param {Object} idToken A decoded id token. - * @return {Object} The set of extracted values with their new names. - */ -OAuth2Client.prototype._extractIdTokenValues = function(idToken) { - var extractedValues = {}; - _.extend(extractedValues, this._getUserId(idToken)); - mapFields(idToken, extractedValues, IdTokenMap); + function valueOf(n) { + var str, + e = n.e; - return extractedValues; -}; + if (e === null) return n.toString(); -/** - * Parses the value of the id_token OAuth 2 Reponse. - * @param {string} encodedIdToken An unencrypted JWT token. - * @return {object} returns the decoded id_token or undefined. - */ -OAuth2Client.prototype._parseIdToken = function(encodedIdToken) { - var crackedToken = this._crackJwt(encodedIdToken); - if (!crackedToken) { - return; - } + str = coeffToString(n.c); - var idToken; - try { - var base64IdToken = crackedToken.JWSPayload; - var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken); - if (!base64Decoded) { - this._log.warn('The returned id_token could not be base64 url safe decoded.'); - return; + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; } - idToken = JSON.parse(base64Decoded); - } catch (err) { - this._log.warn('the returned id_token could not be decoded'); - this._log.warn('The returned id_token could not be decoded: ' + err.stack, true); - return; - } - return this._extractIdTokenValues(idToken); -}; + // PROTOTYPE/INSTANCE METHODS -/** - * Validates the response returned from an OAuth 2.0 token request. - * @private - * @param {string} body The response as a string encoded JSON object. - * @return {object} The parsed response. - */ -OAuth2Client.prototype._validateTokenResponse = function (body) { - var wireResponse; - var tokenResponse = {}; - try { - wireResponse = body; - } catch(e) { - throw new Error('The token response returned from the server is unparseable as JSON'); - } + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; - var intKeys = [ - OAuth2ResponseParameters.EXPIRES_ON, - OAuth2ResponseParameters.EXPIRES_IN, - OAuth2ResponseParameters.CREATED_ON - ]; - this._parseOptionalInts(wireResponse, intKeys); + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; - if (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) { - var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN]; - var now = new Date(); - wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn }); - } - if (wireResponse[OAuth2ResponseParameters.CREATED_ON]) { - var tempDate = new Date(); - var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON]; - tempDate.setTime(createdOn); - wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate; - } + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; - if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) { - throw this._log.createError('wireResponse is missing token_type'); - } - if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) { - throw this._log.createError('wireResponse missing access_token'); - } - - mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); - if (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) { - var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]); - if (idToken) { - _.extend(tokenResponse, idToken); - } - } + return round(new BigNumber(x), dp + x.e + 1, rm); + } - return tokenResponse; -}; + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; -/** - * Validates the response returned from an OAuth 2.0 device code request. - * @private - * @param {string} body The response as a string encoded JSON object. - * @return {object} The parsed response. - */ -OAuth2Client.prototype._validateDeviceCodeResponse = function(body) { - var wireResponse; - var deviceCodeResponse = {}; + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; - try { - wireResponse = body; - } catch(e) { - throw new Error('The device code response returned from the server is unparseable as JSON.'); - } + return n; + }; - var intKeys = [ - DeviceCodeResponseParameters.EXPIRES_IN, - DeviceCodeResponseParameters.INTERVAL - ]; - this._parseOptionalInts(wireResponse, intKeys); - - if (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){ - throw this._log.createError('wireResponse is missing expires_in'); - } + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; - if (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) { - throw this._log.createError('wireResponse is missing device code'); - } - if (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) { - throw this._log.createError('wireResponse is missing user code'); - } + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; - mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP); - return deviceCodeResponse; -}; + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; -/** - * @private - * @param {string} body The body of a http token response. - */ -OAuth2Client.prototype._handlePollingResponse = function(body) { - //handle token error response - var tokenResponse = this._handlePollingRequestErrorResponse(body); - if (_.isEmpty(tokenResponse)){ - tokenResponse = this._validateTokenResponse(body); - } + n = new BigNumber(n); - return tokenResponse; -}; + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } -/** - * @private - * @param {string} body The body of a http token response. - */ -OAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) { - var wireResponse; - var tokenResponse = {}; + if (m != null) m = new BigNumber(m); - try { - wireResponse = body; - } catch (e) { - throw new Error ('The token response returned from the server is unparsable as JSON'); - } + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; - if (wireResponse[OAuth2ResponseParameters.ERROR]) { - mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); - } + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { - return tokenResponse; -}; + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n))); + return m ? y.mod(m) : y; + } -/** - * @private - * @param {object} response An http response object. - * @param {string} body The body of a http token response. - * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed - * into this function. - */ -OAuth2Client.prototype._handleGetTokenResponse = function(body, callback) { - var tokenResponse; - try { - tokenResponse = this._validateTokenResponse(body); - } catch (e) { - this._log.error('Error validating get token response', e, true); - callback(e); - return; - } - callback(null, tokenResponse); -}; + nIsNeg = n.s < 0; -OAuth2Client.prototype._handleGetDeviceCodeResponse = function(body, callback) { - var deviceCodeResponse; - try { - deviceCodeResponse = this._validateDeviceCodeResponse(body); - } catch (e) { - this._log.error('Error validating get user code response', e, true); - callback(e); - return; - } + if (m) { - callback(null, deviceCodeResponse); -}; + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); -OAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) { - var self = this; - if (self._cancelPollingRequest === true) { - callback(null, new Error('Polling_Request_Cancelled')); - return; - } + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); - axios(postOptions).then((response) => { - var tokenResponse; - util.logReturnCorrelationId(this._log, 'GetToken', response); - try { - tokenResponse = self._handlePollingResponse(response.data); - } catch (e) { - self._log.error('Error validating get token response', e, true); - callback(null, e); - return; - } - callback(null, tokenResponse); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'GetToken', error.response); - // error response callback, for error response, it's already parsed as Json. - if (error.response && error.response.data.hasOwnProperty(TokenResponseFields.ERROR) && error.response.data[TokenResponseFields.ERROR] === 'authorization_pending') { - callback(new Error(error.response.data[TokenResponseFields.ERROR]), error.response.data); - } - } - // if there is no response from the server - else if (error.request) { - self._log.error('GetToken' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - self._log.error('GetToken http get failed.' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('GetToken' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); - } - }); -}; + if (isModExp) x = x.mod(m); -OAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) { - - var postOptions = util.createRequestOptions( - this, - { - method : 'POST', - url : url.format(postUrl), - data : urlEncodedRequestForm, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - maxRedirects: 0, - encoding: 'utf8', - } - ); - - return postOptions; -}; - -/** - * @callback GetTokenCallback - * @memberOf OAuth2Client - * @param {Error} [error] In case of an error this will hold the associated Error object. - * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request. - */ - -/** -* @param {object} oauthParameters An object whose keys come from -* Constants.OAuth2.Parameters -* @param {OAuth2Client.GetTokenCallback} callback The callback function. -*/ -OAuth2Client.prototype.getToken = function(oauthParameters, callback) { - var self = this; - var tokenUrl = self._createTokenUrl(); + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { - var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); - var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; - axios(postOptions).then((response) => { - util.logReturnCorrelationId(this._log, 'Get Token', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Get Token' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._handleGetTokenResponse(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'Get Token', error.response); - this._log.error('Get Token' + ' request failed with', error.response.status, true); - var returnErrorString = 'Get Token' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('Get Token' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - this._log.error('Get Token' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('GetToken' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); - } - }); -}; + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; -/** - * @param {object} oauthParameters An object whose keys come from - * Constants.OAuth2.Parameters - * @param {integer} refresh_interval The interval for polling request. - * @param {integer} exipres_in The timeout for polling request. - * @param {OAuth2Client.GetTokenCallback} callback The callback function. - */ -OAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){ - var self = this; - var maxTimesForRetry = Math.floor(expires_in / refresh_interval); - - var tokenUrl = self._createTokenUrl(); - var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); - var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); - var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000}; + } else if (POW_PRECISION) { - async.retry(optionsForRetry, function(retryCallback, response) { - self._getTokenWithPolling(postOptions, retryCallback); - }, function(err, response) { - if (response && response instanceof Error) { - callback(response); - return; + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); } - else if (response && response.hasOwnProperty(DeviceCodeResponseParameters.ERROR)) { - callback(response); - return; + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; } - callback(err, response); - }); -}; -OAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) { - // for now make it as a post request - var self = this; - var deviceCodeUrl = self._createDeviceCodeUrl(); + y = new BigNumber(ONE); - var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters); - - var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm); - - axios(postOptions).then((response) => { - util.logReturnCorrelationId(this._log, 'Get Device Code', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Get Device Code' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._handleGetDeviceCodeResponse(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'Get Device Code', error.response); - this._log.error('Get Device Code' + ' request failed with', error.response.status, true); - var returnErrorString = 'Get Device Code' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('Get Device Code' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - this._log.error('Get Device Code' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('Get Device Code' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); - } - }); - }; + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { -/** - * Cancel the polling request made for acquiring token by device code. - */ -OAuth2Client.prototype.cancelPollingRequest = function() { - this._cancelPollingRequest = true; -}; + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; -module.exports = OAuth2Client; - - -/***/ }), - -/***/ 60772: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); -var jwtConstants = __nccwpck_require__(10282).Jwt; -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } -__nccwpck_require__(1693); -var jws = __nccwpck_require__(4636); -var uuid = __nccwpck_require__(19744); + x = x.times(x); -/** - * JavaScript dates are in milliseconds, but JWT dates are in seconds. - * This function does the conversion. - * @param {Date} date - * @return {string} - */ -function dateGetTimeInSeconds(date) { - return Math.floor(date.getTime()/1000); -} + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } -/** - * Constructs a new SelfSignedJwt object. - * @param {object} callContext Context specific to this token request. - * @param {Authority} authority The authority to be used as the JWT audience. - * @param {string} clientId The client id of the calling app. - */ -function SelfSignedJwt(callContext, authority, clientId) { - this._log = new Logger('SelfSignedJwt', callContext._logContext); - this._callContext = callContext; + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); - this._authority = authority; - this._tokenEndpoint = authority.tokenEndpoint; - this._clientId = clientId; -} + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; -/** - * This wraps date creation in order to make unit testing easier. - * @return {Date} - */ -SelfSignedJwt.prototype._getDateNow = function() { - return new Date(); -}; -SelfSignedJwt.prototype._getNewJwtId = function() { - return uuid.v4(); -}; + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; -/** - * A regular certificate thumbprint is a hex encode string of the binary certificate - * hash. For some reason teh x5t value in a JWT is a url save base64 encoded string - * instead. This function does the conversion. - * @param {string} thumbprint A hex encoded certificate thumbprint. - * @return {string} A url safe base64 encoded certificate thumbprint. - */ -SelfSignedJwt.prototype._createx5tValue = function(thumbprint) { - var hexString = thumbprint.replace(/:/g, '').replace(/ /g, ''); - var base64 = (new Buffer(hexString, 'hex')).toString('base64'); - return util.convertRegularToUrlSafeBase64EncodedString(base64); -}; -/** - * Creates the JWT header. - * @param {string} thumbprint A hex encoded certificate thumbprint. - * @return {object} - */ -SelfSignedJwt.prototype._createHeader = function(thumbprint) { - var x5t = this._createx5tValue(thumbprint); - var header = { typ: 'JWT', alg: 'RS256', x5t : x5t }; + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; - this._log.verbose('Creating self signed JWT header'); - this._log.verbose('Creating self signed JWT header. x5t: ' + x5t, true); - return header; -}; + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; -/** - * Creates the JWT payload. - * @return {object} - */ -SelfSignedJwt.prototype._createPayload = function() { - var now = this._getDateNow(); - var expires = (new Date(now.getTime())).addMinutes(jwtConstants.SELF_SIGNED_JWT_LIFETIME); - this._log.verbose('Creating self signed JWT payload. Expires: ' + expires + ' NotBefore: ' + now); + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; - var jwtPayload = {}; - jwtPayload[jwtConstants.AUDIENCE] = this._tokenEndpoint; - jwtPayload[jwtConstants.ISSUER] = this._clientId; - jwtPayload[jwtConstants.SUBJECT] = this._clientId; - jwtPayload[jwtConstants.NOT_BEFORE] = dateGetTimeInSeconds(now); - jwtPayload[jwtConstants.EXPIRES_ON] = dateGetTimeInSeconds(expires); - jwtPayload[jwtConstants.JWT_ID] = this._getNewJwtId(); - return jwtPayload; -}; + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; -SelfSignedJwt.prototype._throwOnInvalidJwtSignature = function(jwt) { - var jwtSegments = jwt.split('.'); + }; - if (3 > jwtSegments.length || !jwtSegments[2]) { - throw this._log.createError('Failed to sign JWT. This is most likely due to an invalid certificate.'); - } - return; -}; + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; -SelfSignedJwt.prototype._signJwt = function(header, payload, certificate) { - var jwt; - try { - jwt = jws.sign({ header : header, payload : payload, secret : certificate }); - } - catch (err) { - this._log.error(err, true); - throw this._log.createError('Failed to sign JWT.This is most likely due to an invalid certificate.'); - } - - this._throwOnInvalidJwtSignature(jwt); - return jwt; -}; -SelfSignedJwt.prototype._reduceThumbprint = function(thumbprint) { - var canonical = thumbprint.toLowerCase().replace(/ /g, '').replace(/:/g, ''); - this._throwOnInvalidThumbprint(canonical); - return canonical; -}; + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; -var numCharIn128BitHexString = 128/8*2; -var numCharIn160BitHexString = 160/8*2; -var thumbprintSizes = {}; -thumbprintSizes[numCharIn128BitHexString] = true; -thumbprintSizes[numCharIn160BitHexString] = true; -var thumbprintRegExp = /^[a-f\d]*$/; -SelfSignedJwt.prototype._throwOnInvalidThumbprint = function(thumbprint) { - if (!thumbprintSizes[thumbprint.length] || !thumbprintRegExp.test(thumbprint)) { - throw this._log.createError('The thumbprint does not match a known format'); - } -}; + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; -/** - * Creates a self signed JWT that can be used as a client_assertion. - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint A hex encoded thumbprint of the certificate. - * @return {string} A self signed JWT token. - */ -SelfSignedJwt.prototype.create = function(certificate, thumbprint) { - thumbprint = this._reduceThumbprint(thumbprint); - var header = this._createHeader(thumbprint); - var payload = this._createPayload(); + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; - var jwt = this._signJwt(header, payload, certificate); - return jwt; -}; -module.exports = SelfSignedJwt; - -/***/ }), - -/***/ 21178: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; -var constants = __nccwpck_require__(10282); -var CacheDriver = __nccwpck_require__(38289); -var Logger = __nccwpck_require__(92288).Logger; -var Mex = __nccwpck_require__(27078); -var OAuth2Client = __nccwpck_require__(41602); -var SelfSignedJwt = __nccwpck_require__(60772); -var UserRealm = __nccwpck_require__(58663); -var WSTrustRequest = __nccwpck_require__(39035); + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; -var OAuth2Parameters = constants.OAuth2.Parameters; -var TokenResponseFields = constants.TokenResponseFields; -var OAuth2GrantType = constants.OAuth2.GrantType; -var OAuth2Scope = constants.OAuth2.Scope; -var Saml = constants.Saml; -var AccountType = constants.UserRealm.AccountType; -var WSTrustVersion = constants.WSTrustVersion; -var DeviceCodeResponseParameters = constants.UserCodeResponseFields; -/** - * Constructs a new TokenRequest object. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {AuthenticationContext} authenticationContext - * @param {string} resource - * @param {string} clientId - * @param {string} redirectUri - */ -function TokenRequest(callContext, authenticationContext, clientId, resource, redirectUri) { - this._log = new Logger('TokenRequest', callContext._logContext); - this._callContext = callContext; - this._authenticationContext = authenticationContext; - this._resource = resource; - this._clientId = clientId; - this._redirectUri = redirectUri; + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; - // This should be set at the beginning of getToken - // functions that have a userId. - this._userId = null; - this._userRealm = null; - this._pollingClient = {}; -} + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; -TokenRequest.prototype._createUserRealmRequest = function(username) { - return new UserRealm(this._callContext, username, this._authenticationContext.authority); -}; + y = new BigNumber(y, b); + b = y.s; -TokenRequest.prototype._createMex = function(mexEndpoint) { - return new Mex(this._callContext, mexEndpoint); -}; + // Either NaN? + if (!a || !b) return new BigNumber(NaN); -TokenRequest.prototype._createWSTrustRequest = function(wstrustEndpoint, appliesTo, wstrustEndpointVersion) { - return new WSTrustRequest(this._callContext, wstrustEndpoint, appliesTo, wstrustEndpointVersion); -}; + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } -TokenRequest.prototype._createOAuth2Client = function() { - return new OAuth2Client(this._callContext, this._authenticationContext._authority); -}; + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; -TokenRequest.prototype._createSelfSignedJwt = function() { - return new SelfSignedJwt(this._callContext, this._authenticationContext._authority, this._clientId); -}; + if (!xe || !ye) { -TokenRequest.prototype._oauthGetToken = function(oauthParameters, callback) { - var client = this._createOAuth2Client(); - client.getToken(oauthParameters, callback); -}; + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); -TokenRequest.prototype._oauthGetTokenByPolling = function(oauthParameters, refresh_interval, expires_in, callback){ - var client = this._createOAuth2Client(); - client.getTokenWithPolling(oauthParameters, refresh_interval, expires_in, callback); - this._pollingClient = client; -} + // Either zero? + if (!xc[0] || !yc[0]) { -TokenRequest.prototype._createCacheDriver = function() { - return new CacheDriver( - this._callContext, - this._authenticationContext.authority, - this._resource, - this._clientId, - this._authenticationContext.cache, - this._getTokenWithTokenResponse.bind(this) - ); -}; + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : -/** - * Used by the cache driver to refresh tokens. - * @param {TokenResponse} entry A token response to refresh. - * @param {string} resource The resource for which to get the token. - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype._getTokenWithTokenResponse = function(entry, resource, callback) { - this._log.verbose('Called to refresh a token from the cache.'); - var refreshToken = entry[TokenResponseFields.REFRESH_TOKEN]; - this._getTokenWithRefreshToken(refreshToken, resource, null, callback); -}; + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } -TokenRequest.prototype._createCacheQuery = function() { - var query = { - clientId : this._clientId - }; + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); - if (this._userId) { - query.userId = this._userId; - } else { - this._log.verbose('No userId passed for cache query.'); - } + // Determine which is the bigger number. + if (a = xe - ye) { - return query; -}; + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + t.reverse(); -TokenRequest.prototype._getTokenWithCacheWrapper = function(callback, getTokenFunc) { - var self = this; - this._cacheDriver = this._createCacheDriver(); - var cacheQuery = this._createCacheQuery(); - this._cacheDriver.find(cacheQuery, function(err, token) { - if (err) { - self._log.warn('Attempt to look for token in cahce resulted in Error'); - self._log.warn('Attempt to look for token in cache resulted in Error: ' + err.stack, true); - } + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { - if (!token) { - self._log.verbose('No appropriate cached token found.'); - getTokenFunc.call(self, function(err, tokenResponse) { - if (err) { - self._log.verbose('getTokenFunc returned with err'); - callback(err, tokenResponse); - return; + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } } + } - self._log.verbose('Successfully retrieved token from authority'); - self._cacheDriver.add(tokenResponse, function() { - callback(null, tokenResponse); - }); - }); - } else { - self._log.info('Returning cached token.'); - callback(err, token); - } - }); -}; + // x < y? Point xc to the array of the bigger number. + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; -/** - * Store token into cache. - * @param {object} tokenResponse Token response to be added into the cache. - */ -TokenRequest.prototype._addTokenIntoCache = function(tokenResponse, callback) { - this._cacheDriver = this._createCacheDriver(); - this._log.verbose('Storing retrieved token into cache'); - this._cacheDriver.add(tokenResponse, function(err) { - callback(err, tokenResponse); - }); -}; + b = (j = yc.length) - (i = xc.length); -/** - * Adds an OAuth parameter to the paramters object if the parameter is - * not null or undefined. - * @private - * @param {object} parameters OAuth parameters object. - * @param {string} key A member of the OAuth2Parameters constants. - * @param {object} value - */ -function _addParameterIfAvailable(parameters, key, value) { - if (value) { - parameters[key] = value; - } -} + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; -/** - * Creates a set of basic, common, OAuthParameters based on values that the TokenRequest - * was created with. - * @private - * @param {string} grantType A member of the OAuth2GrantType constants. - * @return {object} - */ -TokenRequest.prototype._createOAuthParameters = function(grantType) { - var oauthParameters = {}; - oauthParameters[OAuth2Parameters.GRANT_TYPE] = grantType; + // Subtract yc from xc. + for (; j > a;) { - if (OAuth2GrantType.AUTHORIZATION_CODE !== grantType && - OAuth2GrantType.CLIENT_CREDENTIALS !== grantType && - OAuth2GrantType.DEVICE_CODE != grantType) { - oauthParameters[OAuth2Parameters.SCOPE] = OAuth2Scope.OPENID; - } + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } - _addParameterIfAvailable(oauthParameters, OAuth2Parameters.CLIENT_ID, this._clientId); - _addParameterIfAvailable(oauthParameters, OAuth2Parameters.RESOURCE, this._resource); - _addParameterIfAvailable(oauthParameters, OAuth2Parameters.REDIRECT_URI, this._redirectUri); + xc[j] -= yc[j]; + } - return oauthParameters; -}; + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); -/** - * Get's a token from AAD using a username and password - * @private - * @param {string} username - * @param {string} password - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype._getTokenUsernamePasswordManaged = function(username, password, callback) { - this._log.verbose('Acquiring token with username password for managed user'); + // Zero? + if (!xc[0]) { - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.PASSWORD); + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } - oauthParameters[OAuth2Parameters.PASSWORD] = password; - oauthParameters[OAuth2Parameters.USERNAME] = username; + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; - this._oauthGetToken(oauthParameters, callback); -}; -/** - * Determines the OAuth SAML grant type to use based on the passed in TokenType - * that was returned from a RSTR. - * @param {string} wstrustResponse RSTR token type. - * @return {string} An OAuth grant type. - */ -TokenRequest.prototype._getSamlGrantType = function(wstrustResponse) { - var tokenType = wstrustResponse.tokenType; - switch (tokenType) { - case Saml.TokenTypeV1: - return OAuth2GrantType.SAML1; - case Saml.TokenTypeV2: - return OAuth2GrantType.SAML2; - default: - throw this._log.createError('RSTR returned unknown token type: ' + tokenType); - } -}; + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; -/** - * Performs an OAuth SAML Assertion grant type exchange. Uses a SAML token as the credential for getting - * an OAuth access token. - * @param {WSTrustResponse} wstrustResponse A response from a WSTrustRequest - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._performWSTrustAssertionOAuthExchange = function(wstrustResponse, callback) { - this._log.verbose('Performing OAuth assertion grant type exchange.'); + y = new BigNumber(y, b); - var oauthParameters; - try { - var grantType = this._getSamlGrantType(wstrustResponse); - var assertion = new Buffer(wstrustResponse.token).toString('base64'); - oauthParameters = this._createOAuthParameters(grantType); - oauthParameters[OAuth2Parameters.ASSERTION] = assertion; - } catch (err) { - callback(err); - return; - } + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); - this._oauthGetToken(oauthParameters, callback); -}; + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } -/** - * Exchange a username and password for a SAML token from an ADFS instance via WSTrust. - * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. - * @param {string} wstrustEndpointVersion The version of the wstrust endpoint. - * @param {string} username username - * @param {string} password password - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._performWSTrustExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { - var self = this; - var wstrust = this._createWSTrustRequest(wstrustEndpoint, 'urn:federation:MicrosoftOnline', wstrustEndpointVersion); - wstrust.acquireToken(username, password, function(rstErr, response) { - if (rstErr) { - callback(rstErr); - return; - } + if (MODULO_MODE == 9) { - if (!response.token) { - var rstrErr = self._log.createError('Unsucessful RSTR.\n\terror code: ' + response.errorCode + '\n\tfaultMessage: ' + response.faultMessage, true); - callback(rstrErr); - return; - } + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } - callback(null, response); - }); -}; + y = x.minus(q.times(y)); -/** - * Given a username and password this method invokes a WSTrust and OAuth exchange to get an access token. - * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. - * @param {string} username username - * @param {string} password password - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._performUsernamePasswordForAccessTokenExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { - var self = this; - this._performWSTrustExchange(wstrustEndpoint, wstrustEndpointVersion, username, password, function(err, wstrustResponse) { - if (err) { - callback(err); - return; - } + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; - self._performWSTrustAssertionOAuthExchange(wstrustResponse, callback); - }); -}; + return y; + }; -/** - * Returns an Error object indicating that AAD did not return a WSTrust endpoint. - * @return {Error} - */ -TokenRequest.prototype._createADWSTrustEndpointError = function() { - return this._log.createError('AAD did not return a WSTrust endpoint. Unable to proceed.'); -}; -/** - * Gets an OAuth access token using a username and password via a federated ADFS instance. - * @param {string} username username - * @param {string} password password - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._getTokenUsernamePasswordFederated = function(username, password, callback) { - this._log.verbose('Acquiring token with username password for federated user'); + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; - var self = this; - if (!this._userRealm.federationMetadataUrl) { - this._log.warn('Unable to retrieve federationMetadataUrl from AAD. Attempting fallback to AAD supplied endpoint.'); + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { - if (!this._userRealm.federationActiveAuthUrl) { - callback(this._createADWSTrustEndpointError()); - return; - } + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; - var wstrustVersion = this._parseWStrustVersionFromFederationActiveAuthUrl(this._userRealm.federationActiveAuthUrl); - this._log.verbose('Wstrust endpoint version is: ' + wstrustVersion); - this._performUsernamePasswordForAccessTokenExchange(this._userRealm.federationActiveAuthUrl, wstrustVersion, username, password, callback); - return; - } else { - var mexEndpoint = this._userRealm.federationMetadataUrl; - this._log.verbose('Attempting mex'); - this._log.verbose('Attempting mex at: ' + mexEndpoint, true); - var mex = this._createMex(mexEndpoint); - mex.discover(function(mexErr) { - var wstrustEndpoint; - wstrustVersion = WSTrustVersion.UNDEFINED; - if (mexErr) { - self._log.warn('MEX exchange failed. Attempting fallback to AAD supplied endpoint.'); + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; - wstrustEndpoint = self._userRealm.federationActiveAuthUrl; - wstrustVersion = self._parseWStrustVersionFromFederationActiveAuthUrl(self._userRealm.federationActiveAuthUrl); - if (!wstrustEndpoint) { - callback(self._createADWSTrustEndpointError()); - return; + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } } - } else { - wstrustEndpoint = mex.usernamePasswordPolicy.url; - wstrustVersion = mex.usernamePasswordPolicy.version; - } - self._performUsernamePasswordForAccessTokenExchange(wstrustEndpoint, wstrustVersion, username, password, callback); - return; - }); - } -}; + return y; + } -/** - * Gets wstrust endpoint version from the federation active auth url. - * @private - * @param {string} federationActiveAuthUrl federationActiveAuthUrl - * @return {object} The wstrust endpoint version. - */ -TokenRequest.prototype._parseWStrustVersionFromFederationActiveAuthUrl = function(federationActiveAuthUrl) { - var wstrust2005Regex = /[/trust]?[2005][/usernamemixed]?/; - var wstrust13Regex = /[/trust]?[13][/usernamemixed]?/; + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; - if (wstrust2005Regex.exec(federationActiveAuthUrl)) { - return WSTrustVersion.WSTRUST2005; - } - else if (wstrust13Regex.exec(federationActiveAuthUrl)) { - return WSTrustVersion.WSTRUST13; - } + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; - return WSTrustVersion.UNDEFINED; -}; + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); -/** - * Decides whether the username represents a managed or a federated user and then - * obtains a token using the appropriate protocol flow. - * @private - * @param {string} username - * @param {string} password - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithUsernamePassword = function(username, password, callback) { - this._log.info('Acquiring token with username password'); - this._userId = username; + base = BASE; + sqrtBase = SQRT_BASE; - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - var self = this; + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; - if(this._authenticationContext._authority._isAdfsAuthority) { - this._log.info('Skipping user realm discovery for ADFS authority'); + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } - self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); - return; + zc[j] = c; } - this._userRealm = this._createUserRealmRequest(username); - this._userRealm.discover(function(err) { - if (err) { - getTokenCompleteCallback(err); - return; + if (c) { + ++e; + } else { + zc.splice(0, 1); } - switch(self._userRealm.accountType) { - case AccountType.Managed: - self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); - return; - case AccountType.Federated: - self._getTokenUsernamePasswordFederated(username, password, getTokenCompleteCallback); - return; - default: - getTokenCompleteCallback(self._log.createError('Server returned an unknown AccountType: ' + self._userRealm.AccountType)); - } - }); - }); -}; + return normalise(y, zc, e); + }; -/** - * Obtains a token using client credentials - * @private - * @param {string} clientSecret - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithClientCredentials = function(clientSecret, callback) { - this._log.info('Getting token with client credentials.'); - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; - oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; - this._oauthGetToken(oauthParameters, getTokenCompleteCallback); - }); -}; - -/** - * Obtains a token using an authorization code. - * @private - * @param {string} authorizationCode - * @param {string} clientSecret - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithAuthorizationCode = function(authorizationCode, clientSecret, callback) { - this._log.info('Getting token with auth code.'); - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.AUTHORIZATION_CODE); - - oauthParameters[OAuth2Parameters.CODE] = authorizationCode; - oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; - this._oauthGetToken(oauthParameters, callback); -}; + y = new BigNumber(y, b); + b = y.s; -/** - * Obtains a token using a refresh token. - * @param {string} refreshToken - * @param {string} resource - * @param {string} [clientSecret] - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype._getTokenWithRefreshToken = function(refreshToken, resource, clientSecret, callback) { - this._log.info('Getting a new token from a refresh token.'); - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.REFRESH_TOKEN); + // Either NaN? + if (!a || !b) return new BigNumber(NaN); - if (resource) { - oauthParameters[OAuth2Parameters.RESOURCE] = resource; - } + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } - if (clientSecret) { - oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; - } + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; - oauthParameters[OAuth2Parameters.REFRESH_TOKEN] = refreshToken; + if (!xe || !ye) { - this._oauthGetToken(oauthParameters, callback); -}; + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); -/** - * Obtains a token using a refresh token. - * @param {string} refreshToken - * @param {string} [clientSecret] - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithRefreshToken = function(refreshToken, clientSecret, callback) { - this._getTokenWithRefreshToken(refreshToken, null, clientSecret, callback); -}; + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } -/** - * Obtains a token from the cache, refreshing it or using a MRRT if necessary. - * @param {string} [userId] The user associated with the cached token. - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenFromCacheWithRefresh = function(userId, callback) { - var self = this; - this._log.info('Getting token from cache with refresh if necessary.'); + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); - this._userId = userId; - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - // If this method was called then no cached entry was found. Since - // this particular version of acquireToken can only retrieve tokens - // from the cache, return an error. - getTokenCompleteCallback(self._log.createError('Entry not found in cache.')); - }); -}; + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } -/** - * Creates a self signed jwt. - * @param {string} authorityUrl - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint - * @return {string} A self signed JWT - */ -TokenRequest.prototype._createJwt = function(authorityUrl, certificate, thumbprint) { - var jwt; - var ssj = this._createSelfSignedJwt(); - jwt = ssj.create(certificate, thumbprint); - if (!jwt) { - throw this._log.createError('Failed to create JWT'); - } + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } - return jwt; -}; + a = xc.length; + b = yc.length; -/** - * Obtains a token via a certificate. The certificate is used to generate a self signed - * JWT token that is passed as a client_assertion. - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint A hex encoded thumbprint of the certificate. - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithCertificate = function(certificate, thumbprint, callback) { + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) t = yc, yc = xc, xc = t, b = a; - this._log.info('Getting a token via certificate.'); + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } - var authorityUrl = this._authenticationContext._authority; + if (a) { + xc = [a].concat(xc); + ++ye; + } - var jwt; - try { - jwt = this._createJwt(authorityUrl, certificate, thumbprint); - } catch (err) { - callback(err); - return; - } + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); - oauthParameters[OAuth2Parameters.CLIENT_ASSERTION_TYPE] = OAuth2GrantType.JWT_BEARER; - oauthParameters[OAuth2Parameters.CLIENT_ASSERTION] = jwt; - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - this._oauthGetToken(oauthParameters, getTokenCompleteCallback); - }); -}; + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; -TokenRequest.prototype.getTokenWithDeviceCode = function(userCodeInfo, callback) { - this._log.info('Getting a token via device code'); - var self = this; + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.DEVICE_CODE); - oauthParameters[OAuth2Parameters.CODE] = userCodeInfo[DeviceCodeResponseParameters.DEVICE_CODE]; + return round(new BigNumber(x), sd, rm); + } - var interval = userCodeInfo[DeviceCodeResponseParameters.INTERVAL]; - var expires_in = userCodeInfo[DeviceCodeResponseParameters.EXPIRES_IN]; - - if (interval <= 0) { - callback(new Error('invalid refresh interval')); - return; - } + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; - this._oauthGetTokenByPolling(oauthParameters, interval, expires_in, function(err, tokenResponse) { - if (err) { - self._log.verbose('Token polling request returend with err.'); - callback(err, tokenResponse); - } - else { - self._addTokenIntoCache(tokenResponse, callback); - } - }); -}; + if (v = c[v]) { -TokenRequest.prototype.cancelTokenRequestWithDeviceCode = function() { - this._pollingClient.cancelPollingRequest(); -}; + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); -module.exports = TokenRequest; - - -/***/ }), - -/***/ 58663: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + if (sd && x.e + 1 > n) n = x.e + 1; -var querystring = __nccwpck_require__(71191); -var axios = __nccwpck_require__(96545); -var _ = __nccwpck_require__(83571); -var url = __nccwpck_require__(78835); + return n; + }; -var constants = __nccwpck_require__(10282); -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); -var AccountType = constants.UserRealm.AccountType; -var FederationProtocolType = constants.UserRealm.FederationProtocolType; + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; -var USER_REALM_PATH_TEMPLATE = 'common/UserRealm/'; -/** - * Create a new UserRealm object - * @private - * @constructor - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} userPrinciple The username for which a realm needs to be discovered. - * @param {string} authority The string url of the authority that owns the userPrinciple. - */ -function UserRealm(callContext, userPrinciple, authority) { - this._log = new Logger('UserRealm', callContext._logContext); - this._callContext = callContext; - this._apiVersion = '1.0'; - this._federationProtocol = null; - this._accountType = null; - this._federationMetadataUrl = null; - this._federationActiveAuthUrl = null; - this._userPrinciple = userPrinciple; - this._authority = authority; -} + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); -/** -* The API version requested by UserRealm. -* @type {string} -* @instance -* @memberOf UserRealm -* @name apiVersion -*/ -Object.defineProperty(UserRealm.prototype, 'apiVersion', { - get : function() { - return this._apiVersion; - } -}); + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } -/** -* The federation protocol used by the users realm. -* @type {string} -* @instance -* @memberOf UserRealm -* @name federationProtocol -*/ -Object.defineProperty(UserRealm.prototype, 'federationProtocol', { - get : function() { - return this._federationProtocol; - } -}); + // Initial estimate. + s = Math.sqrt(+valueOf(x)); -/** -* The Type of account. Either managed or federated. -* @type {string} -* @instance -* @memberOf UserRealm -* @name accountType -*/ -Object.defineProperty(UserRealm.prototype, 'accountType', { - get : function() { - return this._accountType; - } -}); + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); -/** -* If this is a federated account then this property will contain the mex url. -* @type {string} -* @instance -* @memberOf UserRealm -* @name federationsMetadataUrl -*/ -Object.defineProperty(UserRealm.prototype, 'federationMetadataUrl', { - get : function() { - return this._federationMetadataUrl; - } -}); + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } -/** -* If the account is federated this will contain the authentication endpoint. -* @type {string} -* @instance -* @memberOf UserRealm -* @name federationActiveAuthUrl -*/ -Object.defineProperty(UserRealm.prototype, 'federationActiveAuthUrl', { - get : function() { - return this._federationActiveAuthUrl; - } -}); + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } -/** -* Given the authority url this method constructs a full user realm discovery url. -* @private -* @returns A full user realm discovery url including path and query string. -*/ -UserRealm.prototype._getUserRealmUrl = function() { - var userRealmUrl = util.copyUrl(this._authority); - var urlEncodedUser = encodeURIComponent(this._userPrinciple); - userRealmUrl.pathname = USER_REALM_PATH_TEMPLATE.replace('', urlEncodedUser); + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; - var userRealmQuery = { - 'api-version' : this._apiVersion - }; + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); - userRealmUrl.search = querystring.stringify(userRealmQuery); + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { - userRealmUrl = util.copyUrl(userRealmUrl); + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); - return userRealmUrl; -}; + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { -/** -* Given a constants object and a value, validates that the value is a key in the constants object. -* @private -* @param {object} constants An object containing constant key value pairs. -* @param {string} value A value to check against the constants -* @param {bool} caseSensitive set to true if comparisons should be made as case sensitive. Defaults to false. -* @returns {bool|string} If value passed in matches one of the constants then the return value is the matched constant. -* If a non case sensitive match was done, then the value returned may be different than the value -* passed in. If there is no match then the method returns false. -*/ -UserRealm.prototype._validateConstantValue = function(constants, value, caseSensitive) { - if (!value) { - return false; - } - if (!caseSensitive) { - value = value.toLowerCase(); - } - return _.contains(_.values(constants), value) ? value : false; -}; + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); -/** -* Checks whether an account type string is valid. -* @private -* @param {string} type An account type string. -* @returns {bool} -*/ -UserRealm.prototype._validateAccountType = function(type) { - return this._validateConstantValue(AccountType, type); -}; + if (t.times(t).eq(x)) { + r = t; + break; + } + } -/** -* Checks whether a federation protocol string is valid. -* @private -* @param {string} protocol A federation protocol string. -* @returns {bool} -*/ -UserRealm.prototype._validateFederationProtocol = function(protocol) { - return this._validateConstantValue(FederationProtocolType, protocol); -}; + dp += 4; + s += 4; + rep = 1; + } else { -/** -* Logs the values parsed as part of user realm discovery. -* @private -*/ -UserRealm.prototype._logParsedResponse = function() { - this._log.verbose('UserRealm response:'); - this._log.verbose(' AccountType: ' + this.accountType); - this._log.verbose(' FederationProtocol: ' + this.federationProtocol); - this._log.verbose(' FederationMetatdataUrl: ' + this.federationMetadataUrl, true); - this._log.verbose(' FederationActiveAuthUrl: ' + this.federationActiveAuthUrl, true); -}; + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { -/** -* Parses the response from a user realm discovery request. -* @private -* @param {string} body The body returned as part of the http user realm discovery request. -* @param {UserRealm.DiscoverCallback} callback Called when parsing is complete. -*/ -UserRealm.prototype._parseDiscoveryResponse = function(body, callback) { - this._log.verbose('Discovery response:\n' + body, true); + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } - var response; - try { - response = body; - } catch (err) { - callback(this._log.createError('Parsing realm discovery respone JSON failed: ' + body, true)); - return; - } + break; + } + } + } + } - var accountType = this._validateAccountType(response['account_type']); - if (!accountType) { - callback(this._log.createError('Cannot parse account_type: ' + accountType)); - return; - } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; - this._accountType = accountType; - if (this._accountType === AccountType.Federated) { - var protocol = this._validateFederationProtocol(response['federation_protocol']); + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; - if (!protocol) { - callback(this._log.createError('Cannot parse federation protocol: ' + protocol)); - return; - } - this._federationProtocol = protocol; - this._federationMetadataUrl = response['federation_metadata_url']; - this._federationActiveAuthUrl = response['federation_active_auth_url']; - } + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; - this._logParsedResponse(); - callback(); -}; -/** -* @callback DiscoverCallback -* @memberOf UserRealm -* @param {Error} error If an error occurs during discovery then this parameter will be used to return the error. -*/ + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; -/** -* Performs user realm discovery and fills in the properties on this object. -* @private -* @param {UserRealm.DiscoverCallback} callback Called when discovery is complete. -*/ -UserRealm.prototype.discover = function(callback) { - var self = this; - var options = util.createRequestOptions( - this, - { - headers : { - Accept : 'application/json' + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); } - } - ); - var userRealmUrl = this._getUserRealmUrl(); - this._log.verbose('Performing user realm discovery at: ' + url.format(userRealmUrl), true); + str = x.toFixed(dp, rm); - axios.get(userRealmUrl, options).then((response) => { - util.logReturnCorrelationId(this._log, 'User Realm Discovery', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'User Realm Discovery' + ' request returned http error: ' + response.status + ' and server response: ' + response.status; - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._parseDiscoveryResponse(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'User Realm Discovery', error.response); - this._log.error('User Realm Discovery' + ' request failed with', error.response.status, true); - var returnErrorString = 'User Realm Discovery' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('User Realm Discovery' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else { - this._log.error('User Realm Discovery' + ' request was never made, please check', error.message, true); - callback(error.message); - } - }); -}; + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; -module.exports = UserRealm; - -/***/ }), - -/***/ 5336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + if (g2) i = g1, g1 = g2, g2 = i, len -= i; + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } -var _ = __nccwpck_require__(83571); -var adalIdConstants = __nccwpck_require__(10282).AdalIdParameters; -var os = __nccwpck_require__(12087); -var url = __nccwpck_require__(78835); + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } -var ADAL_VERSION; + return (format.prefix || '') + str + (format.suffix || ''); + }; -/** - * @namespace Util - * @private - */ -function loadAdalVersion() { - ADAL_VERSION = __nccwpck_require__(93700)/* .version */ .i8; -} + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; -function adalInit() { - loadAdalVersion(); -} + if (md != null) { + n = new BigNumber(md); -/** - * @static - * @memberOf Util - * @param {string|int} statusCode An HTTP status code. - */ -function isHttpSuccess(statusCode) { - return statusCode >= 200 && statusCode < 300; -} + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } -function addDefaultRequestHeaders (self, options) { - if (!options.headers) { - options.headers = {}; - } - var headers = options.headers; - if (!headers['Accept-Charset']) { - headers['Accept-Charset'] = 'utf-8'; - } - headers['client-request-id'] = self._callContext._logContext.correlationId; - headers['return-client-request-id'] = 'true'; + if (!xc) return new BigNumber(x); - // ADAL Id headers - headers[adalIdConstants.SKU] = adalIdConstants.NODE_SKU; - headers[adalIdConstants.VERSION] = ADAL_VERSION; - headers[adalIdConstants.OS] = os.platform(); - headers[adalIdConstants.CPU] = os.arch(); -} + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); -/** -* Central place for housing default request options. This is a place holder -* for when SSL validation is implemented an all requests are subject to that -* policy. -* @static -* @memberOf Util -* @param {object} options A set of options that will be merged with teh default options -* These will override any default options. -* @returns {object} Returns the merged options. -*/ -function createRequestOptions(self, options) { - var defaultOptions = {}; //{ strictSSL : true }; - var mergedOptions = defaultOptions; - if (options) { - _.extend(mergedOptions, options); - } - if (self._callContext.options && self._callContext.options.http) { - _.extend(mergedOptions, self._callContext.options.http); - } + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; - addDefaultRequestHeaders(self, mergedOptions); - return mergedOptions; -} + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); -function logReturnCorrelationId(log, operationMessage, response) { - if (response && response.headers && response.headers['client-request-id']) { - log.info(operationMessage + 'Server returned this correlationId: ' + response.headers['client-request-id'], true); - } -} + // n0 = d1 = 0 + n0.c[0] = 0; -/** -* Creates a function that can be used as the callback for http request operations. This is meant -* to centralize error handling in one place. -* @static -* @memberOf Util -* @param {string} operationMessage A message to be prepended to logged error strings. This should be something like 'Mex Request' -* and summarize the purpose of the http request. -* @param {object} log A Logger object being used by the calling component. -* @param {Util.CreateRequestHandlerErrorCallback} errorCallback Called in the event of an error. -* @param {Util.CreateRequestHandlerSuccessCallabck} successCallback Called on successfull completion of the request. -*/ -function createRequestHandler(operationMessage, log, errorCallback, successCallback) { - return function(err, response, body) { - logReturnCorrelationId(log, operationMessage, response); - if (err) { - log.error(operationMessage + ' request failed with', err, true); - errorCallback(err); - return; - } - if (!isHttpSuccess(response.statusCode)) { - var returnErrorString = operationMessage + ' request returned http error: ' + response.statusCode; - var errorResponse; - if (body) { - returnErrorString += ' and server response: ' + body; - try { - errorResponse = JSON.parse(body); - } catch (e) { - // No problem if it doesn't parse. - } + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; } - errorCallback(log.createError(returnErrorString, true), errorResponse); - return; - } - successCallback(response, body); - }; -} + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; -/** -* @callback CreateRequestHandlerErrorCallback -* @memberOf Util -* @param {Error} error An error object. -*/ + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; -/** -* @callback CreateRequestHandlerSuccessCallabck -* @memberOf Util -* @param {object} response The response object returned from request. -* @param {string} body The body of the http response. -*/ + MAX_EXP = exp; -/** -* Deep copies a url object. -* @static -* @memberOf Util -* @param {URL} urlSource The source url object to copy. -* @returns {URL} A deep copy of sourceUrl. -*/ -function copyUrl(urlSource) { - return url.parse(url.format(urlSource)); -} + return r; + }; -function convertUrlSafeToRegularBase64EncodedString(str) { - return str.replace(/-/g, '+').replace(/_/g, '/'); -} -function convertRegularToUrlSafeBase64EncodedString(str) { - return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); -} + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; -function base64DecodeStringUrlSafe(str) { - var base64 = convertUrlSafeToRegularBase64EncodedString(str); - return (new Buffer(base64, 'base64')).toString('utf8'); -} -function base64EncodeStringUrlSafe(str) { - var base64 = (new Buffer(str, 'utf8').toString('base64')); - var converted = convertRegularToUrlSafeBase64EncodedString(base64); - return converted; -} + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; -module.exports.adalInit = adalInit; -module.exports.isHttpSuccess = isHttpSuccess; -module.exports.logReturnCorrelationId = logReturnCorrelationId; -module.exports.createRequestHandler = createRequestHandler; -module.exports.createRequestOptions = createRequestOptions; -module.exports.copyUrl = copyUrl; -module.exports.base64DecodeStringUrlSafe = base64DecodeStringUrlSafe; -module.exports.base64EncodeStringUrlSafe = base64EncodeStringUrlSafe; -module.exports.convertRegularToUrlSafeBase64EncodedString = convertRegularToUrlSafeBase64EncodedString; - -/***/ }), - -/***/ 39035: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; -var axios = __nccwpck_require__(96545); -var uuid = __nccwpck_require__(19744); + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); -var WSTrustResponse = __nccwpck_require__(55927); -var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + if (s < 0 && n.c[0]) str = '-' + str; + } -var USERNAME_PLACEHOLDER = '{UsernamePlaceHolder}'; -var PASSWORD_PLACEHOLDER = '{PasswordPlaceHolder}'; + return str; + }; -/** - * Creates a new instance of WSTrustRequest - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} wstrustEndpointUrl An STS WS-Trust soap endpoint. - * @param {string} appliesTo A URI that identifies a service for which the a token is to be obtained. - */ -function WSTrustRequest(callContext, wstrustEndpointUrl, appliesTo, wstrustEndpointVersion) { - this._log = new Logger('WSTrustRequest', callContext._logContext); - this._callContext = callContext; - this._wstrustEndpointUrl = wstrustEndpointUrl; - this._appliesTo = appliesTo; - this._wstrustEndpointVersion = wstrustEndpointVersion; -} - -/** -* Given a Date object adds the minutes parameter and returns a new Date object. -* @private -* @static -* @memberOf WSTrustRequest -* @param {Date} date A Date object. -* @param {Number} minutes The number of minutes to add to the date parameter. -* @returns {Date} Returns a Date object. -*/ -function _datePlusMinutes(date, minutes) { - var minutesInMilliSeconds = minutes * 60 * 1000; - var epochTime = date.getTime() + minutesInMilliSeconds; - return new Date(epochTime); -} - -/** - * Builds the soap security header for the RST message. - * @private - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @returns {string} A string that contains the soap security header. - */ -WSTrustRequest.prototype._buildSecurityHeader = function() { - var timeNow = new Date(); - var expireTime = _datePlusMinutes(timeNow, 10); - var timeNowString = timeNow.toISOString(); - var expireTimeString = expireTime.toISOString(); - - var securityHeaderXml = - '\ - \ - ' + timeNowString + '\ - ' + expireTimeString + '\ - \ - \ - ' + USERNAME_PLACEHOLDER + '\ - ' + PASSWORD_PLACEHOLDER + '\ - \ - '; - - return securityHeaderXml; -}; - -/** - * Replaces the placeholders in the RST template with the actual username and password values. - * @private - * @param {string} RSTTemplate An RST with placeholders for username and password. - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @returns {string} A string containing a complete RST soap message. - */ -WSTrustRequest.prototype._populateRSTUsernamePassword = function(RSTTemplate, username, password) { - var RST = RSTTemplate.replace(USERNAME_PLACEHOLDER, username).replace(PASSWORD_PLACEHOLDER, this._populatedEscapedPassword(password)); - return RST; -}; + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; -/** - * Escape xml characters in password. - * @private - * @param {string} password The password to be excaped with xml charaters. - */ -WSTrustRequest.prototype._populatedEscapedPassword = function (password) { - var escapedPassword = password; - return escapedPassword.replace(/&/g, '&') - .replace(/"/g, '"') - .replace(/'/g, ''') - .replace(//g, '>'); -} -/** - * Builds a WS-Trust RequestSecurityToken (RST) message using username password authentication. - * @private - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @returns {string} A string containing a complete RST soap message. - */ -WSTrustRequest.prototype._buildRST = function(username, password) { - var messageID = uuid.v4(); + P._isBigNumber = true; - // Create a template RST with placeholders for the username and password so the - // the RST can be logged without the sensitive information. - var schemaLocation = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'; - var soapAction = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; - var rstTrustNamespace = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'; - var keyType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer'; - var requestType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue'; + if (configObject != null) BigNumber.set(configObject); - if (this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005) { - soapAction = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; - rstTrustNamespace = 'http://schemas.xmlsoap.org/ws/2005/02/trust'; - keyType = 'http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey'; - requestType = 'http://schemas.xmlsoap.org/ws/2005/02/trust/Issue'; + return BigNumber; } - var RSTTemplate = - '\ - \ - ' + soapAction + '\ - urn:uuid:' + messageID + '\ - \ - http://www.w3.org/2005/08/addressing/anonymous\ - \ - ' + this._wstrustEndpointUrl + '\ - ' + this._buildSecurityHeader() + '\ - \ - \ - \ - \ - \ - ' + this._appliesTo + '\ - \ - \ - ' + keyType + '\ - ' + requestType + '\ - \ - \ - '; - - this._log.verbose('Created RST: \n' + RSTTemplate, true); - - var RST = this._populateRSTUsernamePassword(RSTTemplate, username, password); - return RST; -}; -/** - * Handles the processing of a RSTR - * @private - * @param {string} body - * @param {WSTrustRequest.AcquireTokenCallback} callback - */ -WSTrustRequest.prototype._handleRSTR = function(body, callback) { - var err; + // PRIVATE HELPER FUNCTIONS - var wstrustResponse = new WSTrustResponse(this._callContext, body, this._wstrustEndpointVersion); - try { - wstrustResponse.parse(); - } catch (error) { - err = error; - } + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. - callback(err, wstrustResponse); -}; -/** - * Performs a WS-Trust RequestSecurityToken request to obtain a federated token in exchange for a username password. - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @param {WSTrustRequest.AcquireTokenCallback} callback Called once the federated token has been retrieved or on error. -*/ -WSTrustRequest.prototype.acquireToken = function(username, password, callback) { - if (this._wstrustEndpointVersion === WSTrustVersion.UNDEFINED) { - var err = this._log.createError('Unsupported wstrust endpoint version. Current support version is wstrust2005 or wstrust13.'); - callback(err); - return; + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; } - var self = this; - var RST = this._buildRST(username, password); - - var soapAction = this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005 ? 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; - - var options = util.createRequestOptions( - this, - { - method: 'POST', - url: this._wstrustEndpointUrl, - headers : { - 'Content-Type' : 'application/soap+xml; charset=utf-8', - 'SOAPAction' : soapAction - }, - data: RST, - maxRedirects: 0, - encoding: 'utf8', - } - ); - this._log.verbose('Sending RST to: ' + this._wstrustEndpointUrl, true); + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; - axios(options).then((response) => { - util.logReturnCorrelationId(this._log, 'WS-Trust RST', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'WS-Trust RST' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._handleRSTR(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'WS-Trust RST', error.response); - this._log.error('WS-Trust RST' + ' request failed with', error.response.status, true); - var returnErrorString = 'WS-Trust RST' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('WS-Trust RST' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - this._log.error('WS-Trust RST' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('WS-Trust RST' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; } - }); -}; - -/** -* @callback AcquireTokenCallback -* @memberOf WSTrustRequest -* @param {Error} err Contains an error object if acquireToken fails. -* @param {WSTrustResponse} A successful response to the RST. -*/ - -module.exports = WSTrustRequest; - - -/***/ }), - -/***/ 55927: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - -var xmldom = __nccwpck_require__(57286); - -var xmlutil = __nccwpck_require__(27387); + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); -var Logger = __nccwpck_require__(92288).Logger; + return r.slice(0, j + 1 || 1); + } -var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; -var select = xmlutil.xpathSelect; -var DOMParser = xmldom.DOMParser; + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; -// A regular expression for finding the SAML Assertion in an RSTR. Used to remove the SAML -// assertion when logging the RSTR. -var assertionRegEx = /RequestedSecurityToken.*?((<.*?:Assertion.*?>).*<\/.*?Assertion>).*?/; + // Either NaN? + if (!i || !j) return null; -/** - * Creates a log message that contains the RSTR scrubbed of the actual SAML assertion. - * @private - * @return {string} A log message. - */ -function scrubRSTRLogMessage(RSTR) { - var scrubbedRSTR = null; + a = xc && !xc[0]; + b = yc && !yc[0]; - var singleLineRSTR = RSTR.replace(/(\r\n|\n|\r)/gm,''); + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; - var matchResult = assertionRegEx.exec(singleLineRSTR); - if (null === matchResult) { - // No Assertion was matched so just return the RSTR as is. - scrubbedRSTR = singleLineRSTR; - } else { - var samlAssertion = matchResult[1]; - var samlAssertionStartTag = matchResult[2]; + // Signs differ? + if (i != j) return i; - scrubbedRSTR = singleLineRSTR.replace(samlAssertion, samlAssertionStartTag + 'ASSERTION CONTENTS REDACTED'); - } + a = i < 0; + b = k == l; - return 'RSTR Response: ' + scrubbedRSTR; -} + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; -/** - * Creates a new WSTrustResponse instance. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} response A soap response from a WS-Trust request. - * @param {sting} wstrustVersion The version for the WS-Trust request. - */ -function WSTrustResponse(callContext, response, wstrustVersion) { - this._log = new Logger('WSTrustResponse', callContext._logContext); - this._callContext = callContext; - this._response = response; - this._dom = null; - this._errorCode = null; - this._faultMessage = null; - this._tokenType = null; - this._token = null; - this._wstrustVersion = wstrustVersion; + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; - this._log.verbose(function(){return scrubRSTRLogMessage(response);}); -} + j = (k = xc.length) < (l = yc.length) ? k : l; -/** - * If the soap response contained a soap fault then this property will contain the fault - * error code. Otherwise it will return null - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name errorCode - */ -Object.defineProperty(WSTrustResponse.prototype, 'errorCode', { - get: function() { - return this._errorCode; - } -}); + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; -/** - * @property {string} FaultMessage If the soap resopnse contained a soap fault with a fault message then it will - * be returned by this property. - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name faultMessage - */ -Object.defineProperty(WSTrustResponse.prototype, 'faultMessage', { - get: function() { - return this._faultMessage; + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; } -}); -/** - * @property {string} TokenType If the soap resonse contained a token then this property will contain - * the token type uri - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name tokenType - */ -Object.defineProperty(WSTrustResponse.prototype, 'tokenType', { - get: function() { - return this._tokenType; - } -}); -/** - * @property {string} Token If the soap response contained a token then this property will hold that token. - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name token - */ -Object.defineProperty(WSTrustResponse.prototype, 'token', { - get: function() { - return this._token; + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } } -}); - - // Sample error message - // - // - // http://www.w3.org/2005/08/addressing/soap/fault - // - - // - // 2013-07-30T00:32:21.989Z - // 2013-07-30T00:37:21.989Z - // - // - // - // - // - // - // s:Sender - // - // a:RequestFailed - // - // - // - // MSIS3127: The specified request failed. - // - // - // - // - -/** - * Attempts to parse an error from the soap response. If there is one then it - * will fill in the error related properties. Otherwsie it will do nothing. - * @private - * @returns {bool} true if an error was found and parsed in the response. - */ -WSTrustResponse.prototype._parseError = function() { - var errorFound = false; - var faultNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Reason'); - if (faultNode.length) { - this._faultMessage = xmlutil.serializeNodeChildren(faultNode[0]); - if (this._faultMessage) { - errorFound = true; - } + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; } - // Subcode has minoccurs=0 and maxoccurs=1(default) according to the http://www.w3.org/2003/05/soap-envelope - // Subcode may have another subcode as well. This is only targetting at top level subcode. - // Subcode value may have different messages not always uses http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd. - // text inside the value is not possible to select without prefix, so substring is necessary - var subcodeNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value'); - if (1 < subcodeNode.length) { - throw this._log.createError('Found too many fault code values:' + subcodeNode.length); - } - if (subcodeNode.length) { - var errorCode = subcodeNode[0].firstChild.data; - this._errorCode = (errorCode.split(':'))[1]; - errorFound = true; + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; } - return errorFound; -}; -/** - * Attempts to parse a token from the soap response. If there is one then it will fill in the - * token related properties. Otherwise it does nothing. - * @private - * @throws {Error} If the response is not parseable, or too many tokens are found. - */ -WSTrustResponse.prototype._parseToken = function() { - var xPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? '//s:Envelope/s:Body/t:RequestSecurityTokenResponse/t:TokenType' : '//s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/wst:RequestSecurityTokenResponse/wst:TokenType'; + function toFixedPoint(str, e, z) { + var len, zs; - var tokenTypeNodes = select(this._dom, xPath); - if (!tokenTypeNodes.length) { - this._log.warn('No TokenType elements found in RSTR'); - } + // Negative exponent? + if (e < 0) { - for (var i = 0, length = tokenTypeNodes.length; i < length; i++) { - if (this._token) { - this._log.warn('Found more than one returned token. Using the first.'); - break; - } + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; - var tokenTypeNode = tokenTypeNodes[i]; - var tokenType = xmlutil.findElementText(tokenTypeNode); - if (!tokenType) { - this._log.warn('Could not find token type in RSTR token'); - } + // Positive exponent + } else { + len = str.length; - var securityTokenPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? 't:RequestedSecurityToken' : 'wst:RequestedSecurityToken'; - var requestedTokenNode = select(tokenTypeNode.parentNode, securityTokenPath); - if (1 < requestedTokenNode) { - throw this._log.createError('Found too many RequestedSecurityToken nodes for token type: ' + tokenType); - } - if (!requestedTokenNode.length) { - this._log.warn('Unable to find RequestsSecurityToken element associated with TokenType element: ' + tokenType); - continue; + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } } - var token = xmlutil.serializeNodeChildren(requestedTokenNode[0]); - if (!token) { - this._log.warn('Unable to find token associated with TokenType element: ' + tokenType); - continue; - } + return str; + } - this._token = token; - this._tokenType = tokenType; - this._log.info('Found token of type: ' + this._tokenType); - } + // EXPORT - if (!this._token) { - throw this._log.createError('Unable to find any tokens in RSTR.'); - } -}; -/** - * This method parses the soap response that was passed in at construction. - * @throws {Error} If the server returned an error, or there was any failure to parse the response. - */ -WSTrustResponse.prototype.parse = function() { - if (!this._response) { - throw this._log.createError('Received empty RSTR response body.'); - } + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; - try { - try { - var options = { - errorHandler : this._log.error - }; - this._dom = new DOMParser(options).parseFromString(this._response); - } catch (err) { - throw this._log.createError('Failed to parse RSTR in to DOM', err, true); - } + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { return BigNumber; }); - var errorFound = this._parseError(); + // Node.js and other environments that support module.exports. + } else if ( true && module.exports) { + module.exports = BigNumber; - if (errorFound) { - var stringErrorCode = this.ErrorCode || 'NONE'; - var stringFaultMessage = this.FaultMessage || 'NONE'; - throw this._log.createError('Server returned error in RSTR - ErrorCode: ' + stringErrorCode + ' : FaultMessage: ' + stringFaultMessage, true); + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; } - this._parseToken(); - } catch (err) { - delete this._dom; - throw err; + globalObject.BigNumber = BigNumber; } -}; - -module.exports = WSTrustResponse; +})(this); + /***/ }), -/***/ 27387: +/***/ 20336: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http: *www.apache.org/licenses/LICENSE-2.0 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); -var select = __nccwpck_require__(74277); -var XMLSerializer = __nccwpck_require__(57286).XMLSerializer; - -var constants = __nccwpck_require__(10282); - -/** - * @namespace XmlUtil - * @private - */ - -var XPATH_PATH_TEMPLATE = '*[local-name() = \'LOCAL_NAME\' and namespace-uri() = \'NAMESPACE\']'; -/** -* The xpath implementation being used does not have a way of matching expanded namespace. -* This method takes an xpath query and expands all of the namespaces involved. It then -* re-writes the query in to a longer form that directory matches the correct namespaces. -* @private -* @static -* @memberOf XmlUtil -* @param {string} xpath The expath query string to expand. -* @returns {string} An expanded xpath query. -*/ -function expandQNames(xpath) { - var namespaces = constants.XmlNamespaces; - var pathParts = xpath.split('/'); - for (var i=0; i < pathParts.length; i++) { - if (pathParts[i].indexOf(':') !== -1) { - var QNameParts = pathParts[i].split(':'); - if (QNameParts.length !== 2) { - throw new Error('Unable to parse XPath string : ' + xpath + ' : with QName : ' + pathParts[i]); - } - var expandedPath = XPATH_PATH_TEMPLATE.replace('LOCAL_NAME', QNameParts[1]); - expandedPath = expandedPath.replace('NAMESPACE', namespaces[QNameParts[0]]); - pathParts[i] = expandedPath; - } - } - return pathParts.join('/'); -} - -var exports = { - - /** - * Performs an xpath select that does appropriate namespace matching since the imported - * xpath module does not properly handle namespaces. - * @static - * @memberOf XmlUtil - * @param {object} dom A dom object created by the xmldom module - * @param {string} xpath An xpath expression - * @return {array} An array of matching dom nodes. - */ - xpathSelect : function (dom, xpath) { - return select(dom, expandQNames(xpath)); - }, - - /** - * Given a dom node serializes all immediate children that are xml elements. - * @static - * @memberOf XmlUtil - * @param {object} node An xml dom node. - * @return {string} Serialized xml. - */ - serializeNodeChildren : function(node) { - var doc = ''; - var sibling = node.firstChild; - var serializer = new XMLSerializer(); - - while (sibling) { - if (this.isElementNode(sibling)) { - doc += serializer.serializeToString(sibling); - } - sibling = sibling.nextSibling; - } - - return doc !== '' ? doc : null; - }, - - /** - * Detects whether the passed in dom node represents an xml element. - * @static - * @memberOf XmlUtil - * @param {object} node An xml dom node. - * @return {Boolean} true if the node represents an element. - */ - isElementNode : function(node) { - return _.has(node, 'tagName'); - }, - - /** - * Given an xmldom node this function returns any text data contained within. - * @static - * @memberOf XmlUtil - * @param {object} node An xmldom node from which the data should be extracted. - * @return {string} Any data found within the element or null if none is found. - */ - findElementText : function(node) { - var sibling = node.firstChild; - while (sibling && !sibling.data) { - sibling = sibling.nextSibling; - } - - return sibling.data ? sibling.data : null; - } -}; - -module.exports = exports; -/***/ }), +var DuplexStream = __nccwpck_require__(85519).Duplex + , util = __nccwpck_require__(31669) -/***/ 19744: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function BufferList (callback) { + if (!(this instanceof BufferList)) + return new BufferList(callback) -var v1 = __nccwpck_require__(64425); -var v4 = __nccwpck_require__(85258); + this._bufs = [] + this.length = 0 -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; + if (typeof callback == 'function') { + this._callback = callback -module.exports = uuid; + var piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) + } else { + this.append(callback) + } -/***/ }), + DuplexStream.call(this) +} -/***/ 54121: -/***/ ((module) => { -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); +util.inherits(BufferList, DuplexStream) + + +BufferList.prototype._offset = function _offset (offset) { + var tot = 0, i = 0, _t + if (offset === 0) return [ 0, 0 ] + for (; i < this._bufs.length; i++) { + _t = tot + this._bufs[i].length + if (offset < _t || i == this._bufs.length - 1) { + return [ i, offset - tot ] + } + tot = _t + } } -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return ([ - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]] - ]).join(''); +BufferList.prototype._reverseOffset = function (blOffset) { + var bufferId = blOffset[0] + var offset = blOffset[1] + for (var i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } + return offset } -module.exports = bytesToUuid; +BufferList.prototype.append = function append (buf) { + var i = 0 + if (Buffer.isBuffer(buf)) { + this._appendBuffer(buf) + } else if (Array.isArray(buf)) { + for (; i < buf.length; i++) + this.append(buf[i]) + } else if (buf instanceof BufferList) { + // unwrap argument into individual BufferLists + for (; i < buf._bufs.length; i++) + this.append(buf._bufs[i]) + } else if (buf != null) { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf == 'number') + buf = buf.toString() -/***/ }), + this._appendBuffer(Buffer.from(buf)) + } -/***/ 57455: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this +} -// Unique ID creation requires a high quality random # generator. In node.js -// this is pretty straight-forward - we use the crypto API. -var crypto = __nccwpck_require__(76417); +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} -module.exports = function nodeRNG() { - return crypto.randomBytes(16); -}; +BufferList.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) -/***/ }), + if (typeof callback == 'function') + callback() +} -/***/ 64425: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var rng = __nccwpck_require__(57455); -var bytesToUuid = __nccwpck_require__(54121); +BufferList.prototype._read = function _read (size) { + if (!this.length) + return this.push(null) -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} -var _nodeId; -var _clockseq; -// Previous uuid creation time -var _lastMSecs = 0; -var _lastNSecs = 0; +BufferList.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null + } +} - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - if (node == null || clockseq == null) { - var seedBytes = rng(); - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [ - seedBytes[0] | 0x01, - seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] - ]; - } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined } + var offset = this._offset(index) + return this._bufs[offset[0]][offset[1]] +} - // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; +BufferList.prototype.slice = function slice (start, end) { + if (typeof start == 'number' && start < 0) + start += this.length + if (typeof end == 'number' && end < 0) + end += this.length + return this.copy(null, 0, start, end) +} - // Time since last uuid creation (in msecs) - var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart != 'number' || srcStart < 0) + srcStart = 0 + if (typeof srcEnd != 'number' || srcEnd > this.length) + srcEnd = this.length + if (srcStart >= this.length) + return dst || Buffer.alloc(0) + if (srcEnd <= 0) + return dst || Buffer.alloc(0) - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } + var copy = !!dst + , off = this._offset(srcStart) + , len = srcEnd - srcStart + , bytes = len + , bufoff = (copy && dstStart) || 0 + , start = off[1] + , l + , i - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); - } + // copy/slice everything + if (srcStart === 0 && srcEnd == this.length) { + if (!copy) { // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; + // copy, need to copy individual buffers + for (i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; + return dst + } - // `time_low` - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } - // `time_mid` - var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; + if (!copy) // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; + for (i = off[0]; i < this._bufs.length; i++) { + l = this._bufs[i].length - start - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + bufoff += l + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l + break + } - // `clock_seq_low` - b[i++] = clockseq & 0xff; + bytes -= l - // `node` - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; + if (start) + start = 0 } - return buf ? buf : bytesToUuid(b); -} + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) -module.exports = v1; + return dst +} +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end -/***/ }), + if (start < 0) + start += this.length + if (end < 0) + end += this.length -/***/ 85258: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (start === end) { + return new BufferList() + } + var startOffset = this._offset(start) + , endOffset = this._offset(end) + , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) -var rng = __nccwpck_require__(57455); -var bytesToUuid = __nccwpck_require__(54121); + if (endOffset[1] == 0) + buffers.pop() + else + buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) -function v4(options, buf, offset) { - var i = buf && offset || 0; + if (startOffset[1] != 0) + buffers[0] = buffers[0].slice(startOffset[1]) - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; + return new BufferList(buffers) +} - var rnds = options.random || (options.rng || rng)(); +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; +BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break } } - - return buf || bytesToUuid(rnds); + return this } -module.exports = v4; +BufferList.prototype.duplicate = function duplicate () { + var i = 0 + , copy = new BufferList() -/***/ }), + for (; i < this._bufs.length; i++) + copy.append(this._bufs[i]) -/***/ 52068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return copy +} -"use strict"; -/* module decorator */ module = __nccwpck_require__.nmd(module); +BufferList.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0 + this.length = 0 + cb(err) +} -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (search instanceof BufferList) { + search = search.slice() + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; + offset = Number(offset || 0) + if (isNaN(offset)) { + offset = 0 + } -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; + if (offset < 0) { + offset = this.length + offset + } -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); + if (offset < 0) { + offset = 0 + } - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = __nccwpck_require__(86931); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; + if (search.length === 0) { + return offset > this.length ? this.length : offset + } - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + var blOffset = this._offset(offset) + var blIndex = blOffset[0] // index of which internal buffer we're working on + var buffOffset = blOffset[1] // offset of the internal buffer we're working on - return styles; + // scan over each buffer + for (blIndex; blIndex < this._bufs.length; blIndex++) { + var buff = this._bufs[blIndex] + while(buffOffset < buff.length) { + var availableWindow = buff.length - buffOffset + if (availableWindow >= search.length) { + var nativeSearchResult = buff.indexOf(search, buffOffset) + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) + } + buffOffset = buff.length - search.length + 1 // end of native search window + } else { + var revOffset = this._reverseOffset([blIndex, buffOffset]) + if (this._match(revOffset, search)) { + return revOffset + } + buffOffset++ + } + } + buffOffset = 0 + } + return -1 } -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - +BufferList.prototype._match = function(offset, search) { + if (this.length - offset < search.length) { + return false + } + for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { + if(this.get(offset + searchOffset) !== search[searchOffset]){ + return false + } + } + return true +} -/***/ }), -/***/ 64808: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +;(function () { + var methods = { + 'readDoubleBE' : 8 + , 'readDoubleLE' : 8 + , 'readFloatBE' : 4 + , 'readFloatLE' : 4 + , 'readInt32BE' : 4 + , 'readInt32LE' : 4 + , 'readUInt32BE' : 4 + , 'readUInt32LE' : 4 + , 'readInt16BE' : 2 + , 'readInt16LE' : 2 + , 'readUInt16BE' : 2 + , 'readUInt16LE' : 2 + , 'readInt8' : 1 + , 'readUInt8' : 1 + , 'readIntBE' : null + , 'readIntLE' : null + , 'readUIntBE' : null + , 'readUIntLE' : null + } + + for (var m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + } + } + else { + BufferList.prototype[m] = function (offset) { + return this.slice(offset, offset + methods[m])[m](0) + } + } + }(m)) + } +}()) -"use strict"; +module.exports = BufferList -var lib = __nccwpck_require__(98035); -module.exports = lib(__dirname); /***/ }), -/***/ 98035: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 97713: +/***/ ((module) => { "use strict"; -module.exports = function(dirname) { - var path = __nccwpck_require__(85622); - var resolve = __nccwpck_require__(15619); - var appRootPath = resolve(dirname); - - var publicInterface = { - resolve: function(pathToModule) { - return path.join(appRootPath, pathToModule); - }, - - require: function(pathToModule) { - return require(publicInterface.resolve(pathToModule)); - }, - - toString: function() { - return appRootPath; - }, - - setPath: function(explicitlySetPath) { - appRootPath = path.resolve(explicitlySetPath); - publicInterface.path = appRootPath; - }, - - path: appRootPath - }; - - return publicInterface; -}; - -/***/ }), - -/***/ 15619: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const codes = {}; -"use strict"; +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } -// Dependencies -var path = __nccwpck_require__(85622); + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } -// Load global paths -var globalPaths = __nccwpck_require__(32282).globalPaths; + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; -// Guess at NPM's global install dir -var npmGlobalPrefix; -if ('win32' === process.platform) { - npmGlobalPrefix = path.dirname(process.execPath); -} else { - npmGlobalPrefix = path.dirname(path.dirname(process.execPath)); + codes[code] = NodeError; } -var npmGlobalModuleDir = path.resolve(npmGlobalPrefix, 'lib', 'node_modules'); - -// Save OS-specific path separator -var sep = path.sep; -// If we're in webpack, force it to use the original require() method -var requireFunction = ( true) - ? eval("require") - : 0; +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} -const isInstalledWithPNPM = function(resolved) { - const pnpmDir = sep + '.pnpm'; +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} - for (const globalPath of globalPaths) { - if (-1 !== globalPath.indexOf(pnpmDir) && -1 !== resolved.indexOf(pnpmDir)) { - return true; - } +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; } - return false; + return str.substring(this_len - search.length, this_len) === search; } -const getFirstPartFromNodeModules = function(resolved) { - const nodeModulesDir = sep + 'node_modules'; - - if (-1 !== resolved.indexOf(nodeModulesDir)) { - const parts = resolved.split(nodeModulesDir); - if (parts.length) { - return parts[0]; - } - } +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } - return null; + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } } -// Resolver -module.exports = function resolve(dirname) { - // Check for environmental variable - if (process.env.APP_ROOT_PATH) { - return path.resolve(process.env.APP_ROOT_PATH); - } +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - // Defer to Yarn Plug'n'Play if enabled - if (process.versions.pnp) { - try { - var pnp = requireFunction('pnpapi'); - return pnp.getPackageInformation(pnp.topLevel).packageLocation; - } catch (e) {} - } + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } - // Defer to main process in electron renderer - if ('undefined' !== typeof window && window.process && 'renderer' === window.process.type) { - try { - var remote = requireFunction('electron').remote; - return remote.require('app-root-path').path; - } catch (e) {} - } + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - // Defer to AWS Lambda when executing there - if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) { - return process.env.LAMBDA_TASK_ROOT; - } +module.exports.q = codes; - var resolved = path.resolve(dirname); - var alternateMethod = false; - var appRootPath = null; - // Check if the globalPaths contain some folders with '.pnpm' in the path - // If yes this means it is most likely installed with pnpm - if (isInstalledWithPNPM(resolved)) { - appRootPath = getFirstPartFromNodeModules(resolved); +/***/ }), - if (appRootPath) { - return appRootPath; - } - } +/***/ 13928: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Make sure that we're not loaded from a global include path - // Eg. $HOME/.node_modules - // $HOME/.node_libraries - // $PREFIX/lib/node - globalPaths.forEach(function(globalPath) { - if (!alternateMethod && 0 === resolved.indexOf(globalPath)) { - alternateMethod = true; - } - }); +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - // If the app-root-path library isn't loaded globally, - // and node_modules exists in the path, just split __dirname - if (!alternateMethod) { - appRootPath = getFirstPartFromNodeModules(resolved); - } +/**/ - // If the above didn't work, or this module is loaded globally, then - // resort to require.main.filename (See http://nodejs.org/api/modules.html) - if (alternateMethod || null == appRootPath) { - appRootPath = path.dirname(requireFunction.main.filename); - } +var objectKeys = Object.keys || function (obj) { + var keys = []; - // Handle global bin/ directory edge-case - if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) { - appRootPath = appRootPath.slice(0, -4); - } + for (var key in obj) { + keys.push(key); + } - // Return - return appRootPath; + return keys; }; +/**/ -/***/ }), +module.exports = Duplex; -/***/ 83278: -/***/ ((module) => { +var Readable = __nccwpck_require__(85209); -"use strict"; +var Writable = __nccwpck_require__(58729); +__nccwpck_require__(44124)(Duplex, Readable); -function isArguments (thingy) { - return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') -} +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); -var types = { - '*': {label: 'any', check: function () { return true }}, - A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }}, - S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }}, - N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }}, - F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }}, - O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }}, - B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }}, - E: {label: 'error', check: function (thingy) { return thingy instanceof Error }}, - Z: {label: 'null', check: function (thingy) { return thingy == null }} + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } } -function addSchema (schema, arity) { - var group = arity[schema.length] = arity[schema.length] || [] - if (group.indexOf(schema) === -1) group.push(schema) -} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; -var validate = module.exports = function (rawSchemas, args) { - if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) - if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') - if (!args) throw missingRequiredArg(1, 'args') - if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) - if (!types.A.check(args)) throw invalidType(1, ['array'], args) - var schemas = rawSchemas.split('|') - var arity = {} + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; - schemas.forEach(function (schema) { - for (var ii = 0; ii < schema.length; ++ii) { - var type = schema[ii] - if (!types[type]) throw unknownType(ii, type) - } - if (/E.*E/.test(schema)) throw moreThanOneError(schema) - addSchema(schema, arity) - if (/E/.test(schema)) { - addSchema(schema.replace(/E.*$/, 'E'), arity) - addSchema(schema.replace(/E/, 'Z'), arity) - if (schema.length === 1) addSchema('', arity) - } - }) - var matching = arity[args.length] - if (!matching) { - throw wrongNumberOfArgs(Object.keys(arity), args.length) - } - for (var ii = 0; ii < args.length; ++ii) { - var newMatching = matching.filter(function (schema) { - var type = schema[ii] - var typeCheck = types[type].check - return typeCheck(args[ii]) - }) - if (!newMatching.length) { - var labels = matching.map(function (schema) { - return types[schema[ii]].label - }).filter(function (schema) { return schema != null }) - throw invalidType(ii, labels, args[ii]) + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); } - matching = newMatching } } -function missingRequiredArg (num) { - return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) -} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer -function unknownType (num, type) { - return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) -} +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. -function invalidType (num, expectedTypes, value) { - var valueType - Object.keys(types).forEach(function (typeCode) { - if (types[typeCode].check(value)) valueType = types[typeCode].label - }) - return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + - englishList(expectedTypes) + ' but got ' + valueType) + process.nextTick(onEndNT, this); } -function englishList (list) { - return list.join(', ').replace(/, ([^,]+)$/, ' or $1') +function onEndNT(self) { + self.end(); } -function wrongNumberOfArgs (expected, got) { - var english = englishList(expected) - var args = expected.every(function (ex) { return ex.length === 1 }) - ? 'argument' - : 'arguments' - return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) -} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } -function moreThanOneError (schema) { - return newException('ETOOMANYERRORTYPES', - 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') -} + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed -function newException (code, msg) { - var e = new Error(msg) - e.code = code - if (Error.captureStackTrace) Error.captureStackTrace(e, validate) - return e -} + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); /***/ }), -/***/ 11083: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4991: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -exports.TrackerGroup = __nccwpck_require__(60660) -exports.Tracker = __nccwpck_require__(8074) -exports.TrackerStream = __nccwpck_require__(31375) - - -/***/ }), -/***/ 10165: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = PassThrough; -"use strict"; +var Transform = __nccwpck_require__(26753); -var EventEmitter = __nccwpck_require__(28614).EventEmitter -var util = __nccwpck_require__(31669) +__nccwpck_require__(44124)(PassThrough, Transform); -var trackerId = 0 -var TrackerBase = module.exports = function (name) { - EventEmitter.call(this) - this.id = ++trackerId - this.name = name +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); } -util.inherits(TrackerBase, EventEmitter) +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; /***/ }), -/***/ 60660: +/***/ 85209: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -var util = __nccwpck_require__(31669) -var TrackerBase = __nccwpck_require__(10165) -var Tracker = __nccwpck_require__(8074) -var TrackerStream = __nccwpck_require__(31375) - -var TrackerGroup = module.exports = function (name) { - TrackerBase.call(this, name) - this.parentGroup = null - this.trackers = [] - this.completion = {} - this.weight = {} - this.totalWeight = 0 - this.finished = false - this.bubbleChange = bubbleChange(this) -} -util.inherits(TrackerGroup, TrackerBase) - -function bubbleChange (trackerGroup) { - return function (name, completed, tracker) { - trackerGroup.completion[tracker.id] = completed - if (trackerGroup.finished) return - trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup) - } -} - -TrackerGroup.prototype.nameInTree = function () { - var names = [] - var from = this - while (from) { - names.unshift(from.name) - from = from.parentGroup - } - return names.join('/') -} - -TrackerGroup.prototype.addUnit = function (unit, weight) { - if (unit.addUnit) { - var toTest = this - while (toTest) { - if (unit === toTest) { - throw new Error( - 'Attempted to add tracker group ' + - unit.name + ' to tree that already includes it ' + - this.nameInTree(this)) - } - toTest = toTest.parentGroup - } - unit.parentGroup = this - } - this.weight[unit.id] = weight || 1 - this.totalWeight += this.weight[unit.id] - this.trackers.push(unit) - this.completion[unit.id] = unit.completed() - unit.on('change', this.bubbleChange) - if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit) - return unit -} -TrackerGroup.prototype.completed = function () { - if (this.trackers.length === 0) return 0 - var valPerWeight = 1 / this.totalWeight - var completed = 0 - for (var ii = 0; ii < this.trackers.length; ii++) { - var trackerId = this.trackers[ii].id - completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId] - } - return completed -} +module.exports = Readable; +/**/ -TrackerGroup.prototype.newGroup = function (name, weight) { - return this.addUnit(new TrackerGroup(name), weight) -} +var Duplex; +/**/ -TrackerGroup.prototype.newItem = function (name, todo, weight) { - return this.addUnit(new Tracker(name, todo), weight) -} +Readable.ReadableState = ReadableState; +/**/ -TrackerGroup.prototype.newStream = function (name, todo, weight) { - return this.addUnit(new TrackerStream(name, todo), weight) -} +var EE = __nccwpck_require__(28614).EventEmitter; -TrackerGroup.prototype.finish = function () { - this.finished = true - if (!this.trackers.length) this.addUnit(new Tracker(), 1, true) - for (var ii = 0; ii < this.trackers.length; ii++) { - var tracker = this.trackers[ii] - tracker.finish() - tracker.removeListener('change', this.bubbleChange) - } - this.emit('change', this.name, 1, this) -} +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ -var buffer = ' ' -TrackerGroup.prototype.debug = function (depth) { - depth = depth || 0 - var indent = depth ? buffer.substr(0, depth) : '' - var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n' - this.trackers.forEach(function (tracker) { - if (tracker instanceof TrackerGroup) { - output += tracker.debug(depth + 1) - } else { - output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n' - } - }) - return output -} +/**/ -/***/ }), +var Stream = __nccwpck_require__(36238); +/**/ -/***/ 31375: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var Buffer = __nccwpck_require__(64293).Buffer; -var util = __nccwpck_require__(31669) -var stream = __nccwpck_require__(51642) -var delegate = __nccwpck_require__(61318) -var Tracker = __nccwpck_require__(8074) +var OurUint8Array = global.Uint8Array || function () {}; -var TrackerStream = module.exports = function (name, size, options) { - stream.Transform.call(this, options) - this.tracker = new Tracker(name, size) - this.name = name - this.id = this.tracker.id - this.tracker.on('change', delegateChange(this)) +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); } -util.inherits(TrackerStream, stream.Transform) -function delegateChange (trackerStream) { - return function (name, completion, tracker) { - trackerStream.emit('change', name, completion, trackerStream) - } +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } +/**/ -TrackerStream.prototype._transform = function (data, encoding, cb) { - this.tracker.completeWork(data.length ? data.length : 1) - this.push(data) - cb() -} -TrackerStream.prototype._flush = function (cb) { - this.tracker.finish() - cb() +var debugUtil = __nccwpck_require__(31669); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; } +/**/ -delegate(TrackerStream.prototype, 'tracker') - .method('completed') - .method('addWork') - .method('finish') +var BufferList = __nccwpck_require__(70662); -/***/ }), +var destroyImpl = __nccwpck_require__(36994); -/***/ 8074: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var _require = __nccwpck_require__(3533), + getHighWaterMark = _require.getHighWaterMark; -"use strict"; +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. -var util = __nccwpck_require__(31669) -var TrackerBase = __nccwpck_require__(10165) -var Tracker = module.exports = function (name, todo) { - TrackerBase.call(this, name) - this.workDone = 0 - this.workTodo = todo || 0 -} -util.inherits(Tracker, TrackerBase) +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; -Tracker.prototype.completed = function () { - return this.workTodo === 0 ? 0 : this.workDone / this.workTodo -} +__nccwpck_require__(44124)(Readable, Stream); -Tracker.prototype.addWork = function (work) { - this.workTodo += work - this.emit('change', this.name, this.completed(), this) -} +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -Tracker.prototype.completeWork = function (work) { - this.workDone += work - if (this.workDone > this.workTodo) this.workDone = this.workTodo - this.emit('change', this.name, this.completed(), this) -} +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. -Tracker.prototype.finish = function () { - this.workTodo = this.workDone = 1 - this.emit('change', this.name, 1, this) + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(13928); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. -/***/ }), - -/***/ 57888: -/***/ (function(module, exports, __nccwpck_require__) { + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" -function slice(arrayLike, start) { - start = start|0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for(var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() -/** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -var apply = function(fn/*, ...args*/) { - var args = slice(arguments, 1); - return function(/*callArgs*/) { - var callArgs = slice(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. -var initialParams = function (fn) { - return function (/*...args, callback*/) { - var args = slice(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. -/** - * 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'); -} + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') -function fallback(fn) { - setTimeout(fn, 0); -} + this.autoDestroy = !!options.autoDestroy; // has it been destroyed -function wrap(defer) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. -var _defer; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled -var setImmediate$1 = wrap(_defer); + this.readingMore = false; + this.decoder = null; + this.encoding = null; -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (isObject(result) && typeof result.then === 'function') { - result.then(function(value) { - invokeCallback(callback, null, value); - }, function(err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); + if (options.encoding) { + if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } } -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - setImmediate$1(rethrow, e); - } -} +function Readable(options) { + Duplex = Duplex || __nccwpck_require__(13928); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 -function rethrow(error) { - throw error; -} + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy -var supportsSymbol = typeof Symbol === 'function'; + this.readable = true; -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + Stream.call(this); } -function applyEach$1(eachfn) { - return function(fns/*, ...args*/) { - var args = slice(arguments, 1); - var go = initialParams(function(args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - wrapAsync(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; - } - }; -} - -/** 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; +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed -/** Built-in value references. */ -var Symbol$1 = root.Symbol; -/** Used for built-in method references. */ -var objectProto = Object.prototype; + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; -/** - * 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$1), - tag = value[symToStringTag$1]; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; + skipChunkCheck = true; } + } else { + skipChunkCheck = true; } - return result; -} -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() -/** - * 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$1.call(value); -} -/** `Object#toString` result references. */ -var nullTag = '[object Null]'; -var undefinedTag = '[object Undefined]'; +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; -/** - * 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); -} + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]'; -var funcTag = '[object Function]'; -var genTag = '[object GeneratorFunction]'; -var proxyTag = '[object Proxy]'; + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } -/** - * 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; -} + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. -/** - * 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 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); + return !state.ended && (state.length < state.highWaterMark || state.length === 0); } -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -var breakLoop = {}; +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. + maybeReadMore(stream, state); } -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} +function chunkInvalid(state, chunk) { + var er; -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } -var getIterator = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; + return er; +} -/** - * 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); +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. - while (++index < n) { - result[index] = iteratee(index); - } - return 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 != null && typeof value == 'object'; -} +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: -/** - * 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; -} + var p = this._readableState.buffer.head; + var content = ''; -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + this._readableState.buffer.clear(); -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB -/** - * 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$2.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; +var MAX_HWM = 0x40000000; -/** - * 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; -} +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. -/** Detect free variable `module`. */ -var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; -/** - * 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; + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; + if (!state.ended) { + state.needReadable = true; + return 0; + } -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; + return state.length; +} // you can override either this method, or the async _read(n) below. -/** - * 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) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]'; -var arrayTag = '[object Array]'; -var boolTag = '[object Boolean]'; -var dateTag = '[object Date]'; -var errorTag = '[object Error]'; -var funcTag$1 = '[object Function]'; -var mapTag = '[object Map]'; -var numberTag = '[object Number]'; -var objectTag = '[object Object]'; -var regexpTag = '[object RegExp]'; -var setTag = '[object Set]'; -var stringTag = '[object String]'; -var weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]'; -var dataViewTag = '[object DataView]'; -var float32Tag = '[object Float32Array]'; -var float64Tag = '[object Float64Array]'; -var int8Tag = '[object Int8Array]'; -var int16Tag = '[object Int16Array]'; -var int32Tag = '[object Int32Array]'; -var uint8Tag = '[object Uint8Array]'; -var uint8ClampedTag = '[object Uint8ClampedArray]'; -var uint16Tag = '[object Uint16Array]'; -var uint32Tag = '[object Uint32Array]'; - -/** 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$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** - * 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 `_.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); - }; -} +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. -/** Detect free variable `exports`. */ -var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } -/** Detect free variable `module`. */ -var freeModule$1 = freeExports$1 && "object" == 'object' && module && !module.nodeType && module; + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports$1 && freeGlobal.process; -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - if (types) { - return types; - } + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. -/** - * 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; + if (state.length === 0) state.needReadable = true; // call internal read method -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; + this._read(state.highWaterMark); -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. -/** - * 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$1.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); - } + if (!state.reading) n = howMuchToRead(nOrig, state); } - return result; -} -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; -/** - * 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$5; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } - return value === proto; -} + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. -/** - * 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)); - }; -} + if (nOrig !== n && state.ended) endReadable(this); + } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); + if (ret !== null) this.emit('data', ret); + return ret; +}; -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + if (state.decoder) { + var chunk = state.decoder.end(); -/** - * 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$3.call(object, key) && key != 'constructor') { - result.push(key); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } } - return result; -} -/** - * 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); -} + state.ended = true; -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; - } -} + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); } -} - -function createObjectIterator(obj) { - var okeys = keys(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? {value: obj[key], key: key} : null; - }; -} + } +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. -function iterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); - } - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; -function onlyOnce(fn) { - return function() { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } } -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = once(callback || noop); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = iterator(obj); - var done = false; - var running = 0; - var looping = false; +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (value === breakLoop || (done && running <= 0)) { - done = true; - return callback(null); - } - else if (!looping) { - replenish(); - } - } + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. - function replenish () { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - looping = false; - } - replenish(); - }; -} + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); -} - -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback || noop); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop) { - callback(null); - } - } - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } } -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = doLimit(eachOfLimit, Infinity); +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -var eachOf = function(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, wrapAsync(iteratee), callback); -}; + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(eachOf, obj, wrapAsync(iteratee), callback); - }; -} -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || noop; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -var map = doParallel(_asyncMap); + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -var applyEach = applyEach$1(map); + case 1: + state.pipes = [state.pipes, dest]; + break; -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); - }; -} + default: + state.pipes.push(dest); + break; + } -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapLimit = doParallelLimit(_asyncMap); - -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapSeries = doLimit(mapLimit, 1); - -/** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. - */ -var applyEachSeries = applyEach$1(mapSeries); + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); -/** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ -function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } } - return array; -} -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); -} + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; + src.on('data', ondata); - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); -} + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } -/** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); - * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * console.log('err = ', err); - * console.log('results = ', results); - * }); - */ -var auto = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || noop); - var keys$$1 = keys(tasks); - var numTasks = keys$$1.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; + src.pause(); } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - var results = {}; - var runningTasks = 0; - var hasError = false; - var listeners = Object.create(null); + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. - var readyTasks = []; - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - baseForOwn(tasks, function (task, key) { - if (!isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; + dest.once('close', onclose); - arrayEach(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } - checkForDeadlocks(); - processQueue(); + dest.once('finish', onfinish); - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } - } + dest.emit('pipe', src); // start the flow if it hasn't been started already. - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - taskListeners.push(fn); - } + return dest; +}; - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - arrayEach(taskListeners, function (fn) { - fn(); - }); - processQueue(); +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - function runTask(key, task) { - if (hasError) return; + if (state.pipesCount === 0) return this; // just one destination. most common case. - var taskCallback = onlyOnce(function(err, result) { - runningTasks--; - if (arguments.length > 2) { - result = slice(arguments, 1); - } - if (err) { - var safeResults = {}; - baseForOwn(results, function(val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - arrayEach(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); } - function getDependents(taskName) { - var result = []; - baseForOwn(tasks, function (task, key) { - if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } -}; + return this; + } // try to find the right one. -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; -/** - * 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) && baseGetTag(value) == symbolTag); -} +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; -var symbolToString = symbolProto ? symbolProto.toString : undefined; + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); -/** - * 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 (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; + return res; +}; - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; +Readable.prototype.addListener = Readable.prototype.on; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); } - return result; -} -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} + return res; +}; -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; + return res; +}; - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } } -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff'; -var rsComboMarksRange = '\\u0300-\\u036f'; -var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange = '\\u20d0-\\u20ff'; -var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; -var rsVarRange = '\\ufe0e\\ufe0f'; +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); +Readable.prototype.resume = function () { + var state = this._readableState; -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff'; -var rsComboMarksRange$1 = '\\u0300-\\u036f'; -var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; -var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; -var rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']'; -var rsCombo = '[' + rsComboRange$1 + ']'; -var rsFitz = '\\ud83c[\\udffb-\\udfff]'; -var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; -var rsNonAstral = '[^' + rsAstralRange$1 + ']'; -var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; -var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; -var rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?'; -var rsOptVar = '[' + rsVarRange$1 + ']?'; -var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; -var rsSeq = rsOptVar + reOptMod + rsOptJoin; -var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} + state.flowing = !state.readableListening; + resume(this, state); + } -/** - * 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 convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); + state.paused = false; + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } } -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +function resume_(stream, state) { + debug('resume', state.reading); -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; + if (!state.reading) { + stream.read(0); } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - return castSlice(strSymbols, start, end).join(''); + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); } -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg){ - return trim(arg.replace(FN_ARG, '')); - }); - return func; -} + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; - - baseForOwn(tasks, function (taskFn, key) { - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); + this._readableState.paused = true; + return this; +}; - if (isArray(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. - // remove callback param - if (!fnIsAsync) params.pop(); - newTasks[key] = params.concat(newTask); - } +Readable.prototype.wrap = function (stream) { + var _this = this; - function newTask(results, taskCb) { - var newArgs = arrayMap(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - wrapAsync(taskFn).apply(null, newArgs); - } - }); + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); - auto(newTasks, callback); -} + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; -DLL.prototype.removeLink = function(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; + var ret = _this.push(chunk); - node.prev = node.next = null; - this.length -= 1; - return node; -}; + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. -DLL.prototype.empty = function () { - while(this.head) this.shift(); - return this; -}; + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. -DLL.prototype.insertAfter = function(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; -DLL.prototype.insertBefore = function(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. -DLL.prototype.unshift = function(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); -}; -DLL.prototype.push = function(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); -}; + this._read = function (n) { + debug('wrapped _read', n); -DLL.prototype.shift = function() { - return this.head && this.removeLink(this.head); -}; + if (paused) { + paused = false; + stream.resume(); + } + }; -DLL.prototype.pop = function() { - return this.tail && this.removeLink(this.tail); + return this; }; -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for(var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __nccwpck_require__(37558); } - return arr; -}; -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while(!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; + return createReadableStreamAsyncIterator(this); + }; +} -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new Error('Concurrency must not be zero'); +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; } + } +}); // exposed for testing purposes only. + +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} - var processingScheduled = false; - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || noop - }; + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(function() { - processingScheduled = false; - q.process(); - }); - } + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } } + } +} - function _next(tasks) { - return function(err){ - numRunning -= 1; +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __nccwpck_require__(57039); + } - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; + return from(Readable, iterable, opts); + }; +} - var index = baseIndexOf(workersList, task, 0); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } - task.callback.apply(task, arguments); + return -1; +} - if (err != null) { - q.error(err, task.data); - } - } +/***/ }), - if (numRunning <= (q.concurrency - q.buffer) ) { - q.unsaturated(); - } +/***/ 26753: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - var isProcessing = false; - var q = { - _tasks: new DLL(), - concurrency: concurrency, - payload: payload, - saturated: noop, - unsaturated:noop, - buffer: concurrency / 4, - empty: noop, - drain: noop, - error: noop, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = noop; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } - numRunning += 1; +module.exports = Transform; - if (q._tasks.length === 0) { - q.empty(); - } +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - if (numRunning === q.concurrency) { - q.saturated(); - } +var Duplex = __nccwpck_require__(13928); - var cb = onlyOnce(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function() { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - return q; -} - -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} payload - An `integer` for determining how many tasks - * should be process per round. This property can be changed after a `cargo` is - * created to alter the payload on-the-fly. - * @property {Function} push - Adds `task` to the `queue`. The callback is - * called once the `worker` has finished processing the task. Instead of a - * single task, an array of `tasks` can be submitted. The respective callback is - * used for every task in the list. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ - -/** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i true - */ -function identity(value) { - return value; + this.on('prefinish', prefinish); } -function _createTester(check, getResult) { - return function(eachfn, arr, iteratee, cb) { - cb = cb || noop; - var testPassed = false; - var testResult; - eachfn(arr, function(value, _, callback) { - iteratee(value, function(err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, breakLoop); - } else { - callback(); - } - }); - }, function(err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} +function prefinish() { + var _this = this; -function _findGetResult(v, x) { - return x; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } } -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -var detect = doParallel(_createTester(identity, _findGetResult)); -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectSeries = doLimit(detectLimit, 1); - -function consoleFunc(name) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - args.push(function (err/*, ...args*/) { - var args = slice(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - arrayEach(args, function (x) { - console[name](x); - }); - } - } - }); - wrapAsync(fn).apply(null, args); - }; -} +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; -/** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -var dir = consoleFunc('dir'); +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - args.push(check); - _test.apply(this, args); - } + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - check(null, true); +Transform.prototype._read = function (n) { + var ts = this._transformState; -} + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - doWhilst(iteratee, function() { - return !test.apply(this, arguments); - }, callback); -} - -/** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); - */ -function during(test, fn, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err) { - if (err) return callback(err); - _test(check); - } +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided - _test(check); + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); } -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} +/***/ }), -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} +/***/ 58729: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit$1(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -var eachSeries = doLimit(eachLimit$1, 1); - -/** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ -function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return initialParams(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - setImmediate$1(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }); -} +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. -function notId(v) { - return !v; -} -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -var every = doParallel(_createTester(notId, notId)); +module.exports = Writable; +/* */ -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everyLimit = doParallelLimit(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everySeries = doLimit(everyLimit, 1); - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({index: index, value: x}); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, arrayMap(results.sort(function (a, b) { - return a.index - b.index; - }), baseProperty('value'))); - } - }); -} +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; -function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, wrapAsync(iteratee), callback || noop); + this.finish = function () { + onCorkedFinish(_this, state); + }; } +/* */ -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -var filter = doParallel(_filter); +/**/ -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var filterLimit = doParallelLimit(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -var filterSeries = doLimit(filterLimit, 1); - -/** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. - - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ -function forever(fn, errback) { - var done = onlyOnce(errback || noop); - var task = wrapAsync(ensureAsync(fn)); - function next(err) { - if (err) return done(err); - task(next); - } - next(); -} +var Duplex; +/**/ -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupByLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err, key) { - if (err) return callback(err); - return callback(null, {key: key, val: val}); - }); - }, function(err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; +Writable.WritableState = WritableState; +/**/ - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; +var internalUtil = { + deprecate: __nccwpck_require__(65278) +}; +/**/ - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } +/**/ - return callback(err, result); - }); -}; +var Stream = __nccwpck_require__(36238); +/**/ -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -var groupBy = doLimit(groupByLimit, Infinity); -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupBySeries = doLimit(groupByLimit, 1); - -/** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -var log = consoleFunc('log'); +var Buffer = __nccwpck_require__(64293).Buffer; -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback || noop); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - eachOfLimit(obj, limit, function(val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); } -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} -var mapValues = doLimit(mapValuesLimit, Infinity); +var destroyImpl = __nccwpck_require__(36994); -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -var mapValuesSeries = doLimit(mapValuesLimit, 1); - -function has(obj, key) { - return key in obj; -} - -/** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); - */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || identity; - var _fn = wrapAsync(fn); - var memoized = initialParams(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - setImmediate$1(function() { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function(/*args*/) { - var args = slice(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} +var _require = __nccwpck_require__(3533), + getHighWaterMark = _require.getHighWaterMark; -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTick`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -var _defer$1; +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; -if (hasNextTick) { - _defer$1 = process.nextTick; -} else if (hasSetImmediate) { - _defer$1 = setImmediate; -} else { - _defer$1 = fallback; -} +var errorOrDestroy = destroyImpl.errorOrDestroy; -var nextTick = wrap(_defer$1); +__nccwpck_require__(44124)(Writable, Stream); -function _parallel(eachfn, tasks, callback) { - callback = callback || noop; - var results = isArrayLike(tasks) ? [] : {}; +function nop() {} - eachfn(tasks, function (task, key, callback) { - wrapAsync(task)(function (err, result) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(13928); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - _parallel(eachOf, tasks, callback); -} + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit$1(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); -} - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ -var queue$1 = function (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * The `unshift` method was removed. - */ -var priorityQueue = function(worker, concurrency) { - // Start with a normal queue - var q = queue$1(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function(data, priority, callback) { - if (callback == null) callback = noop; - if (typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } - - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } - } - setImmediate$1(q.process); - }; + this.finalCalled = false; // drain event flag. - // Remove unshift function - delete q.unshift; + this.needDrain = false; // at the start of calling end() - return q; -}; + this.ending = false; // when end() has been called, and returned -/** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ -function race(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } -} + this.ended = false; // when 'finish' is emitted -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight (array, memo, iteratee, callback) { - var reversed = slice(array).reverse(); - reduce(reversed, memo, iteratee, callback); -} - -/** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ -function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = slice(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); + this.finished = false; // has it been destroyed - return _fn.apply(this, args); - }); -} + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if (isArray(tasks)) { - results = arrayMap(tasks, reflect); - } else { - results = {}; - baseForOwn(tasks, function(task, key) { - results[key] = reflect.call(this, task); - }); - } - return results; -} + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. -function reject$1(eachfn, arr, iteratee, callback) { - _filter(eachfn, arr, function(value, cb) { - iteratee(value, function(err, v) { - cb(err, !v); - }); - }, callback); -} + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -var reject = doParallel(reject$1); + this.length = 0; // a flag to see when we're in the middle of a write. -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectLimit = doParallelLimit(reject$1); - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectSeries = doLimit(rejectLimit, 1); - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant$1(value) { - return function() { - return value; - }; -} + this.writing = false; // when true all writes will be buffered until .uncork() call -/** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || noop; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || noop; - } + this.writecb = null; // the amount that is being written when _write is called. - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - var _task = wrapAsync(task); + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - var attempt = 1; - function retryAttempt() { - _task(function(err) { - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); - } + this.prefinished = false; // True if the error was already emitted and should not be thrown again - retryAttempt(); -} + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ -var retryable = function (opts, task) { - if (!task) { - task = opts; - opts = null; - } - var _task = wrapAsync(task); - return initialParams(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); + this.autoDestroy = !!options.autoDestroy; // count buffered requests - }); -}; + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - _parallel(eachOfSeries, tasks, callback); + this.corkedRequestsFree = new CorkedRequest(this); } -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -var some = doParallel(_createTester(Boolean, identity)); +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someLimit = doParallelLimit(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someSeries = doLimit(someLimit, 1); - -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); - * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); - * - * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback - * }); - */ -function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - map(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, {value: x, criteria: criteria}); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); - }); + while (current) { + out.push(current); + current = current.next; + } - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } -} + return out; +}; -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); - - return initialParams(function (args, callback) { - var timedOut = false; - var timer; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); +var realHasInstance; - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeCeil = Math.ceil; -var nativeMax = Math.max; +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(13928); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. -/** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ -function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); + this.writable = true; - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; } - return result; -} -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); -} - -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ -var times = doLimit(timeLimit, Infinity); + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -var timesSeries = doLimit(timeLimit, 1); - -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = isArray(coll) ? [] : {}; - } - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); - - eachOf(coll, function(v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function(err) { - callback(err, accumulator); - }); -} -/** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || noop; - eachSeries(tasks, function(task, callback) { - wrapAsync(task)(function (err, res/*, ...args*/) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); -} +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; -/** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; -} +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - if (!test()) return callback(null); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = slice(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - whilst(function() { - return !test.apply(this, arguments); - }, iteratee, callback); -} - -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -var waterfall = function(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - args.push(onlyOnce(next)); - task.apply(null, args); - } +function validChunk(stream, state, chunk, cb) { + var er; - function next(err/*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask(slice(arguments, 1)); - } + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } - nextTask([]); -}; + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } -/** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ - -/** - * Async is a utility module which provides straight-forward, powerful functions - * for working with asynchronous JavaScript. Although originally designed for - * use with [Node.js](http://nodejs.org) and installable via - * `npm install --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ - - -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ - -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ - -/** - * A collection of `async` utility functions. - * @module Utils - */ - -var index = { - apply: apply, - applyEach: applyEach, - applyEachSeries: applyEachSeries, - asyncify: asyncify, - auto: auto, - autoInject: autoInject, - cargo: cargo, - compose: compose, - concat: concat, - concatLimit: concatLimit, - concatSeries: concatSeries, - constant: constant, - detect: detect, - detectLimit: detectLimit, - detectSeries: detectSeries, - dir: dir, - doDuring: doDuring, - doUntil: doUntil, - doWhilst: doWhilst, - during: during, - each: eachLimit, - eachLimit: eachLimit$1, - eachOf: eachOf, - eachOfLimit: eachOfLimit, - eachOfSeries: eachOfSeries, - eachSeries: eachSeries, - ensureAsync: ensureAsync, - every: every, - everyLimit: everyLimit, - everySeries: everySeries, - filter: filter, - filterLimit: filterLimit, - filterSeries: filterSeries, - forever: forever, - groupBy: groupBy, - groupByLimit: groupByLimit, - groupBySeries: groupBySeries, - log: log, - map: map, - mapLimit: mapLimit, - mapSeries: mapSeries, - mapValues: mapValues, - mapValuesLimit: mapValuesLimit, - mapValuesSeries: mapValuesSeries, - memoize: memoize, - nextTick: nextTick, - parallel: parallelLimit, - parallelLimit: parallelLimit$1, - priorityQueue: priorityQueue, - queue: queue$1, - race: race, - reduce: reduce, - reduceRight: reduceRight, - reflect: reflect, - reflectAll: reflectAll, - reject: reject, - rejectLimit: rejectLimit, - rejectSeries: rejectSeries, - retry: retry, - retryable: retryable, - seq: seq, - series: series, - setImmediate: setImmediate$1, - some: some, - someLimit: someLimit, - someSeries: someSeries, - sortBy: sortBy, - timeout: timeout, - times: times, - timesLimit: timeLimit, - timesSeries: timesSeries, - transform: transform, - tryEach: tryEach, - unmemoize: unmemoize, - until: until, - waterfall: waterfall, - whilst: whilst, - - // aliases - all: every, - allLimit: everyLimit, - allSeries: everySeries, - any: some, - anyLimit: someLimit, - anySeries: someSeries, - find: detect, - findLimit: detectLimit, - findSeries: detectSeries, - forEach: eachLimit, - forEachSeries: eachSeries, - forEachLimit: eachLimit$1, - forEachOf: eachOf, - forEachOfSeries: eachOfSeries, - forEachOfLimit: eachOfLimit, - inject: reduce, - foldl: reduce, - foldr: reduceRight, - select: filter, - selectLimit: filterLimit, - selectSeries: filterSeries, - wrapSync: asyncify -}; - -exports['default'] = index; -exports.apply = apply; -exports.applyEach = applyEach; -exports.applyEachSeries = applyEachSeries; -exports.asyncify = asyncify; -exports.auto = auto; -exports.autoInject = autoInject; -exports.cargo = cargo; -exports.compose = compose; -exports.concat = concat; -exports.concatLimit = concatLimit; -exports.concatSeries = concatSeries; -exports.constant = constant; -exports.detect = detect; -exports.detectLimit = detectLimit; -exports.detectSeries = detectSeries; -exports.dir = dir; -exports.doDuring = doDuring; -exports.doUntil = doUntil; -exports.doWhilst = doWhilst; -exports.during = during; -exports.each = eachLimit; -exports.eachLimit = eachLimit$1; -exports.eachOf = eachOf; -exports.eachOfLimit = eachOfLimit; -exports.eachOfSeries = eachOfSeries; -exports.eachSeries = eachSeries; -exports.ensureAsync = ensureAsync; -exports.every = every; -exports.everyLimit = everyLimit; -exports.everySeries = everySeries; -exports.filter = filter; -exports.filterLimit = filterLimit; -exports.filterSeries = filterSeries; -exports.forever = forever; -exports.groupBy = groupBy; -exports.groupByLimit = groupByLimit; -exports.groupBySeries = groupBySeries; -exports.log = log; -exports.map = map; -exports.mapLimit = mapLimit; -exports.mapSeries = mapSeries; -exports.mapValues = mapValues; -exports.mapValuesLimit = mapValuesLimit; -exports.mapValuesSeries = mapValuesSeries; -exports.memoize = memoize; -exports.nextTick = nextTick; -exports.parallel = parallelLimit; -exports.parallelLimit = parallelLimit$1; -exports.priorityQueue = priorityQueue; -exports.queue = queue$1; -exports.race = race; -exports.reduce = reduce; -exports.reduceRight = reduceRight; -exports.reflect = reflect; -exports.reflectAll = reflectAll; -exports.reject = reject; -exports.rejectLimit = rejectLimit; -exports.rejectSeries = rejectSeries; -exports.retry = retry; -exports.retryable = retryable; -exports.seq = seq; -exports.series = series; -exports.setImmediate = setImmediate$1; -exports.some = some; -exports.someLimit = someLimit; -exports.someSeries = someSeries; -exports.sortBy = sortBy; -exports.timeout = timeout; -exports.times = times; -exports.timesLimit = timeLimit; -exports.timesSeries = timesSeries; -exports.transform = transform; -exports.tryEach = tryEach; -exports.unmemoize = unmemoize; -exports.until = until; -exports.waterfall = waterfall; -exports.whilst = whilst; -exports.all = every; -exports.allLimit = everyLimit; -exports.allSeries = everySeries; -exports.any = some; -exports.anyLimit = someLimit; -exports.anySeries = someSeries; -exports.find = detect; -exports.findLimit = detectLimit; -exports.findSeries = detectSeries; -exports.forEach = eachLimit; -exports.forEachSeries = eachSeries; -exports.forEachLimit = eachLimit$1; -exports.forEachOf = eachOf; -exports.forEachOfSeries = eachOfSeries; -exports.forEachOfLimit = eachOfLimit; -exports.inject = reduce; -exports.foldl = reduce; -exports.foldr = reduceRight; -exports.select = filter; -exports.selectLimit = filterLimit; -exports.selectSeries = filterSeries; -exports.wrapSync = asyncify; + return true; +} -Object.defineProperty(exports, '__esModule', { value: true }); +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; -}))); + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } -/***/ }), + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -/***/ 14812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; -module.exports = -{ - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) +Writable.prototype.cork = function () { + this._writableState.corked++; }; +Writable.prototype.uncork = function () { + var state = this._writableState; -/***/ }), + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; -/***/ 1700: -/***/ ((module) => { +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; -// API -module.exports = abort; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } - // reset leftover jobs - state.jobs = {}; + return chunk; } -/** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort - */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; } -} +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); -/***/ }), + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } -/***/ 72794: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. -var defer = __nccwpck_require__(15295); + if (!ret) state.needDrain = true; -// API -module.exports = async; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; -/** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback - */ -function async(callback) -{ - var isAsync = false; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } - // check if async happened - defer(function() { isAsync = true; }); + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; + return ret; } +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} -/***/ }), - -/***/ 15295: -/***/ ((module) => { +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; -module.exports = defer; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error -/** - * Runs provided function on next iteration of the event loop - * - * @param {function} fn - function to run - */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); + finishMaybe(stream, state); } } +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -/***/ }), - -/***/ 9023: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var async = __nccwpck_require__(72794) - , abort = __nccwpck_require__(1700) - ; - -// API -module.exports = iterate; - -/** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed - */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - // clean up jobs - delete state.jobs[key]; - - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); } - - // return salvaged results - callback(error, state.results); - }); -} - -/** - * Runs iterator over provided job element - * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else - */ -function runJob(iterator, key, item, callback) -{ - var aborter; - - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); - } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); } - - return aborter; } +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. -/***/ }), -/***/ 42474: -/***/ ((module) => { +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it -// API -module.exports = state; -/** - * Creates initial state object - * for iteration over list - * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object - */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length - } - ; +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - if (sortMethod) - { - // sort array keys based on it's values - // sort object's keys just on own merit - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) - { - return sortMethod(list[a], list[b]); - }); - } + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; - return initState; -} + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite -/***/ }), + state.pendingcb++; + state.lastBufferedRequest = null; -/***/ 37942: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) - ; + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. -// API -module.exports = terminator; + if (state.writing) { + break; + } + } -/** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination - */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; + if (entry === null) state.lastBufferedRequest = null; } - // fast forward iteration index - this.index = this.size; - - // abort jobs - abort(this); - - // send back results we have so far - async(callback)(null, this.results); + state.bufferedRequest = entry; + state.bufferProcessing = false; } +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; -/***/ }), +Writable.prototype._writev = null; -/***/ 8210: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -// Public API -module.exports = parallel; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks -/** - * Runs iterator over provided array elements in parallel - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function parallel(list, iterator, callback) -{ - var state = initState(list); + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); + if (!state.ending) endWritable(this, state, cb); + return this; +}; - state.index++; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; } +}); - return terminator.bind(state, callback); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; -/***/ }), - -/***/ 50445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var serialOrdered = __nccwpck_require__(3578); - -// Public API -module.exports = serial; + if (err) { + errorOrDestroy(stream, err); + } -/** - * Runs iterator over provided array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); } +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} -/***/ }), - -/***/ 3578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function finishMaybe(stream, state) { + var need = needFinish(state); -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; + if (need) { + prefinish(stream, state); -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); -/** - * Runs iterator over provided sorted array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } } + } - state.index++; + return need; +} - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; - } +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); - // done here - callback(null, state.results); - }); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } - return terminator.bind(state, callback); + state.ended = true; + stream.writable = false; } -/* - * -- Sort methods - */ +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; -/** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; -} + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. -/** - * sort helper to sort array elements in descending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function descending(a, b) -{ - return -1 * ascending(a, b); + + state.corkedRequestsFree.next = corkReq; } +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } -/***/ }), + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed -/***/ 96545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(52618); + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; + +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; /***/ }), -/***/ 68104: +/***/ 37558: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var utils = __nccwpck_require__(20328); -var settle = __nccwpck_require__(13211); -var buildFullPath = __nccwpck_require__(41934); -var buildURL = __nccwpck_require__(30646); -var http = __nccwpck_require__(98605); -var https = __nccwpck_require__(57211); -var httpFollow = __nccwpck_require__(67707).http; -var httpsFollow = __nccwpck_require__(67707).https; -var url = __nccwpck_require__(78835); -var zlib = __nccwpck_require__(78761); -var pkg = __nccwpck_require__(20696); -var createError = __nccwpck_require__(15226); -var enhanceError = __nccwpck_require__(21516); +var _Object$setPrototypeO; -var isHttps = /https:?/; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -/** - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} proxy - * @param {string} location - */ -function setProxy(options, proxy, location) { - options.hostname = proxy.host; - options.host = proxy.host; - options.port = proxy.port; - options.path = location; +var finished = __nccwpck_require__(12659); - // Basic proxy authorization - if (proxy.auth) { - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); - // If a proxy is used, any redirects must also pass through the proxy - options.beforeRedirect = function beforeRedirect(redirection) { - redirection.headers.host = redirection.host; - setProxy(redirection, proxy, redirection.href); +function createIterResult(value, done) { + return { + value: value, + done: done }; } -/*eslint consistent-return:0*/ -module.exports = function httpAdapter(config) { - return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { - var resolve = function resolve(value) { - resolvePromise(value); - }; - var reject = function reject(value) { - rejectPromise(value); - }; - var data = config.data; - var headers = config.headers; - - // Set User-Agent (required by some servers) - // Only set header if it hasn't been set in config - // See https://github.com/axios/axios/issues/69 - if (!headers['User-Agent'] && !headers['user-agent']) { - headers['User-Agent'] = 'axios/' + pkg.version; - } +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; - if (data && !utils.isStream(data)) { - if (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(createError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - config - )); - } + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' - // Add Content-Length header if data exists - headers['Content-Length'] = data.length; + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } + } +} - // HTTP basic authentication - var auth = undefined; - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - auth = username + ':' + password; - } +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} - // Parse url - var fullPath = buildFullPath(config.baseURL, config.url); - var parsed = url.parse(fullPath); - var protocol = parsed.protocol || 'http:'; +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } - if (!auth && parsed.auth) { - var urlAuth = parsed.auth.split(':'); - var urlUsername = urlAuth[0] || ''; - var urlPassword = urlAuth[1] || ''; - auth = urlUsername + ':' + urlPassword; - } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} - if (auth) { - delete headers.Authorization; - } +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - var isHttpsRequest = isHttps.test(protocol); - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + next: function next() { + var _this = this; - var options = { - path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), - method: config.method.toUpperCase(), - headers: headers, - agent: agent, - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth: auth - }; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; + if (error !== null) { + return Promise.reject(error); } - var proxy = config.proxy; - if (!proxy && proxy !== false) { - var proxyEnv = protocol.slice(0, -1) + '_proxy'; - var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; - if (proxyUrl) { - var parsedProxyUrl = url.parse(proxyUrl); - var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; - var shouldProxy = true; + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } - if (noProxyEnv) { - var noProxy = noProxyEnv.split(',').map(function trim(s) { - return s.trim(); - }); - - shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { - if (!proxyElement) { - return false; - } - if (proxyElement === '*') { - return true; - } - if (proxyElement[0] === '.' && - parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { - return true; - } - - return parsed.hostname === proxyElement; - }); - } - - if (shouldProxy) { - proxy = { - host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port, - protocol: parsedProxyUrl.protocol - }; - - if (parsedProxyUrl.auth) { - var proxyUrlAuth = parsedProxyUrl.auth.split(':'); - proxy.auth = { - username: proxyUrlAuth[0], - password: proxyUrlAuth[1] - }; + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); } - } - } - } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time - if (proxy) { - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } - var transport; - var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsProxy ? https : http; + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); } - transport = isHttpsProxy ? httpsFollow : httpFollow; - } - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; + promise = new Promise(this[kHandlePromise]); } - // Create the request - var req = transport.request(options, function handleResponse(res) { - if (req.aborted) return; - - // uncompress the response body transparently if required - var stream = res; - - // return the last request in case of redirects - var lastRequest = res.req || req; - - - // if no content, is HEAD request or decompress disabled we should not decompress - if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { - switch (res.headers['content-encoding']) { - /*eslint default-case:0*/ - case 'gzip': - case 'compress': - case 'deflate': - // add the unzipper to the body stream processing pipeline - stream = stream.pipe(zlib.createUnzip()); + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - } + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; } - var response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: res.headers, - config: config, - request: lastRequest - }; - - if (config.responseType === 'stream') { - response.data = stream; - settle(resolve, reject, response); - } else { - var responseBuffer = []; - stream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { - stream.destroy(); - reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - config, null, lastRequest)); - } - }); + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); - stream.on('error', function handleStreamError(err) { - if (req.aborted) return; - reject(enhanceError(err, config, null, lastRequest)); - }); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; - stream.on('end', function handleStreamEnd() { - var responseData = Buffer.concat(responseBuffer); - if (config.responseType !== 'arraybuffer') { - responseData = responseData.toString(config.responseEncoding); - if (!config.responseEncoding || config.responseEncoding === 'utf8') { - responseData = utils.stripBOM(responseData); - } - } + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); - response.data = responseData; - settle(resolve, reject, response); - }); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; } - }); + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error - // Handle errors - req.on('error', function handleRequestError(err) { - if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; - reject(enhanceError(err, config, null, req)); - }); + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } - // Handle request timeout - if (config.timeout) { - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devoring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(config.timeout, function handleRequestTimeout() { - req.abort(); - reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); - }); + iterator[kError] = err; + return; } - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (req.aborted) return; + var resolve = iterator[kLastResolve]; - req.abort(); - reject(cancel); - }); + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); } - // Send the request - if (utils.isStream(data)) { - data.on('error', function handleStreamError(err) { - reject(enhanceError(err, config, null, req)); - }).pipe(req); - } else { - req.end(data); - } + iterator[kEnded] = true; }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; }; +module.exports = createReadableStreamAsyncIterator; /***/ }), -/***/ 3454: +/***/ 70662: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var utils = __nccwpck_require__(20328); -var settle = __nccwpck_require__(13211); -var cookies = __nccwpck_require__(21545); -var buildURL = __nccwpck_require__(30646); -var buildFullPath = __nccwpck_require__(41934); -var parseHeaders = __nccwpck_require__(86455); -var isURLSameOrigin = __nccwpck_require__(33608); -var createError = __nccwpck_require__(15226); - -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - - if (utils.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - var request = new XMLHttpRequest(); +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - // Set the request timeout in MS - request.timeout = config.timeout; +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - // Listen for ready state - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } +var _require = __nccwpck_require__(64293), + Buffer = _require.Buffer; - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; +var _require2 = __nccwpck_require__(31669), + inspect = _require2.inspect; - settle(resolve, reject, response); +var custom = inspect && inspect.custom || 'inspect'; - // Clean up request - request = null; - }; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); - reject(createError('Request aborted', config, 'ECONNABORTED', request)); + this.head = null; + this.tail = null; + this.length = 0; + } - // Clean up request - request = null; - }; + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); + while (p = p.next) { + ret += s + p.data; + } - // Clean up request - request = null; - }; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; } - reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', - request)); - // Clean up request - request = null; - }; + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); } - } - - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; + return ret; } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. - // Add responseType to request if needed - if (config.responseType) { - try { - request.responseType = config.responseType; - } catch (e) { - // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. - // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. - if (config.responseType !== 'json') { - throw e; - } - } - } + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (!request) { - return; + break; } - request.abort(); - reject(cancel); - // Clean up request - request = null; - }); - } + ++c; + } - if (!requestData) { - requestData = null; - } + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. - // Send the request - request.send(requestData); - }); -}; + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; -/***/ }), + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } -/***/ 52618: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + break; + } -"use strict"; + ++c; + } + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. -var utils = __nccwpck_require__(20328); -var bind = __nccwpck_require__(77065); -var Axios = __nccwpck_require__(98178); -var mergeConfig = __nccwpck_require__(74831); -var defaults = __nccwpck_require__(98190); + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind(Axios.prototype.request, context); + return BufferList; +}(); - // Copy axios.prototype to instance - utils.extend(instance, Axios.prototype, context); +/***/ }), - // Copy context to instance - utils.extend(instance, context); +/***/ 36994: +/***/ ((module) => { - return instance; -} +"use strict"; + // undocumented cb() API, needed for core, not for public API -// Create the default instance to be exported -var axios = createInstance(defaults); +function destroy(err, cb) { + var _this = this; -// Expose Axios class to allow class inheritance -axios.Axios = Axios; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; -// Factory for creating new instances -axios.create = function create(instanceConfig) { - return createInstance(mergeConfig(axios.defaults, instanceConfig)); -}; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } -// Expose Cancel & CancelToken -axios.Cancel = __nccwpck_require__(98875); -axios.CancelToken = __nccwpck_require__(71587); -axios.isCancel = __nccwpck_require__(64057); + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = __nccwpck_require__(74850); -// Expose isAxiosError -axios.isAxiosError = __nccwpck_require__(60650); + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well -module.exports = axios; -// Allow use of default import syntax in TypeScript -module.exports.default = axios; + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); -/***/ }), + return this; +} -/***/ 98875: -/***/ ((module) => { +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} -"use strict"; +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } -/** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ -function Cancel(message) { - this.message = message; + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } } -Cancel.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); -}; - -Cancel.prototype.__CANCEL__ = true; +function emitErrorNT(self, err) { + self.emit('error', err); +} -module.exports = Cancel; +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; /***/ }), -/***/ 71587: +/***/ 12659: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). -var Cancel = __nccwpck_require__(98875); - -/** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ -function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } +var ERR_STREAM_PREMATURE_CLOSE = __nccwpck_require__(97713)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE; - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; - var token = this; - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - token.reason = new Cancel(message); - resolvePromise(token.reason); - }); + callback.apply(this, args); + }; } -/** - * Throws a `Cancel` if cancellation has been requested. - */ -CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } -}; +function noop() {} -/** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ -CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); }; -}; -module.exports = CancelToken; + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; -/***/ }), + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; -/***/ 64057: -/***/ ((module) => { + var onerror = function onerror(err) { + callback.call(stream, err); + }; -"use strict"; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; /***/ }), -/***/ 98178: +/***/ 57039: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var utils = __nccwpck_require__(20328); -var buildURL = __nccwpck_require__(30646); -var InterceptorManager = __nccwpck_require__(3214); -var dispatchRequest = __nccwpck_require__(85062); -var mergeConfig = __nccwpck_require__(74831); - -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ -function Axios(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; -} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -/** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ -Axios.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - config = mergeConfig(this.defaults, config); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - // Set config.method - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - // Hook up interceptors middleware - var chain = [dispatchRequest, undefined]; - var promise = Promise.resolve(config); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - chain.unshift(interceptor.fulfilled, interceptor.rejected); - }); +var ERR_INVALID_ARG_TYPE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - chain.push(interceptor.fulfilled, interceptor.rejected); - }); +function from(Readable, iterable, opts) { + var iterator; - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); - return promise; -}; + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. -Axios.prototype.getUri = function getUri(config) { - config = mergeConfig(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); -}; + var reading = false; -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); + readable._read = function () { + if (!reading) { + reading = true; + next(); + } }; -}); -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, data, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: data - })); - }; -}); + function next() { + return _next2.apply(this, arguments); + } -module.exports = Axios; + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; +} +module.exports = from; /***/ }), -/***/ 3214: +/***/ 20740: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). -var utils = __nccwpck_require__(20328); +var eos; -function InterceptorManager() { - this.handlers = []; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } -/** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ -InterceptorManager.prototype.use = function use(fulfilled, rejected) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected - }); - return this.handlers.length - 1; -}; +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; -/** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ -InterceptorManager.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } -}; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} -/** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ -InterceptorManager.prototype.forEach = function forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); -}; +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} -module.exports = InterceptorManager; +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __nccwpck_require__(12659); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} -/***/ }), +function call(fn) { + fn(); +} -/***/ 41934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function pipe(from, to) { + return from.pipe(to); +} -"use strict"; +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } -var isAbsoluteURL = __nccwpck_require__(41301); -var combineURLs = __nccwpck_require__(57189); + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ -module.exports = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); } - return requestedURL; -}; + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} + +module.exports = pipeline; /***/ }), -/***/ 15226: +/***/ 3533: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var enhanceError = __nccwpck_require__(21516); +var ERR_INVALID_OPT_VALUE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE; -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ -module.exports = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError(error, config, code, request, response); -}; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; /***/ }), -/***/ 85062: +/***/ 36238: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +module.exports = __nccwpck_require__(92413); -var utils = __nccwpck_require__(20328); -var transformData = __nccwpck_require__(19812); -var isCancel = __nccwpck_require__(64057); -var defaults = __nccwpck_require__(98190); -/** - * Throws a `Cancel` if cancellation has been requested. - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } -} +/***/ }), -/** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ -module.exports = function dispatchRequest(config) { - throwIfCancellationRequested(config); +/***/ 85519: +/***/ ((module, exports, __nccwpck_require__) => { - // Ensure headers exist - config.headers = config.headers || {}; +var Stream = __nccwpck_require__(92413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(85209); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(58729); + exports.Duplex = __nccwpck_require__(13928); + exports.Transform = __nccwpck_require__(26753); + exports.PassThrough = __nccwpck_require__(4991); + exports.finished = __nccwpck_require__(12659); + exports.pipeline = __nccwpck_require__(20740); +} - // Transform request data - config.data = transformData( - config.data, - config.headers, - config.transformRequest - ); - // Flatten headers - config.headers = utils.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); +/***/ }), - utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; - } - ); +/***/ 33717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var adapter = config.adapter || defaults.adapter; +var concatMap = __nccwpck_require__(86891); +var balanced = __nccwpck_require__(9417); - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); +module.exports = expandTop; - // Transform response data - response.data = transformData( - response.data, - response.headers, - config.transformResponse - ); +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData( - reason.response.data, - reason.response.headers, - config.transformResponse - ); - } - } +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} - return Promise.reject(reason); - }); -}; +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} -/***/ }), +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; -/***/ 21516: -/***/ ((module) => { + var parts = []; + var m = balanced('{', '}', str); -"use strict"; + if (!m) + return str.split(','); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); -/** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ -module.exports = function enhanceError(error, config, code, request, response) { - error.config = config; - if (code) { - error.code = code; + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); } - error.request = request; - error.response = response; - error.isAxiosError = true; + parts.push.apply(parts, p); - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code - }; - }; - return error; -}; + return parts; +} +function expandTop(str) { + if (!str) + return []; -/***/ }), + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } -/***/ 74831: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return expand(escapeBraces(str), true).map(unescapeBraces); +} -"use strict"; +function identity(e) { + return e; +} +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} -var utils = __nccwpck_require__(20328); +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} -/** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; +function expand(str, isTop) { + var expansions = []; - var valueFromConfig2Keys = ['url', 'method', 'data']; - var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; - var defaultToConfig2Keys = [ - 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', - 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', - 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', - 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', - 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' - ]; - var directMergeKeys = ['validateStatus']; + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - function getMergedValue(target, source) { - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge(target, source); - } else if (utils.isPlainObject(source)) { - return utils.merge({}, source); - } else if (utils.isArray(source)) { - return source.slice(); + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); } - return source; + return [str]; } - function mergeDeepProperties(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(config1[prop], config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - config[prop] = getMergedValue(undefined, config1[prop]); + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } } } - utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(undefined, config2[prop]); - } - }); + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(undefined, config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - config[prop] = getMergedValue(undefined, config1[prop]); - } - }); + var N; - utils.forEach(directMergeKeys, function merge(prop) { - if (prop in config2) { - config[prop] = getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - config[prop] = getMergedValue(undefined, config1[prop]); + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; } - }); + var pad = n.some(isPadded); - var axiosKeys = valueFromConfig2Keys - .concat(mergeDeepPropertiesKeys) - .concat(defaultToConfig2Keys) - .concat(directMergeKeys); + N = []; - var otherKeys = Object - .keys(config1) - .concat(Object.keys(config2)) - .filter(function filterAxiosKeys(key) { - return axiosKeys.indexOf(key) === -1; - }); + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } - utils.forEach(otherKeys, mergeDeepProperties); + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} - return config; -}; /***/ }), -/***/ 13211: +/***/ 9239: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*jshint node:true */ +var Buffer = __nccwpck_require__(64293).Buffer; // browserify +var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; -var createError = __nccwpck_require__(15226); +module.exports = bufferEq; -/** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ -module.exports = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError( - 'Request failed with status code ' + response.status, - response.config, - null, - response.request, - response - )); +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; } -}; + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } -/***/ }), + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} -/***/ 19812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; -"use strict"; +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; -var utils = __nccwpck_require__(20328); +/***/ }), -/** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ -module.exports = function transformData(data, headers, fns) { - /*eslint no-param-reassign:0*/ - utils.forEach(fns, function transform(fn) { - data = fn(data, headers); - }); +/***/ 35684: +/***/ ((module) => { - return data; -}; +function Caseless (dict) { + this.dict = dict || {} +} +Caseless.prototype.set = function (name, value, clobber) { + if (typeof name === 'object') { + for (var i in name) { + this.set(i, name[i], value) + } + } else { + if (typeof clobber === 'undefined') clobber = true + var has = this.has(name) + + if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value + else this.dict[has || name] = value + return has + } +} +Caseless.prototype.has = function (name) { + var keys = Object.keys(this.dict) + , name = name.toLowerCase() + ; + for (var i=0;i { "use strict"; +const ansiStyles = __nccwpck_require__(52068); +const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = __nccwpck_require__(82415); -var utils = __nccwpck_require__(20328); -var normalizeHeaderName = __nccwpck_require__(36240); +const {isArray} = Array; -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' +]; + +const styles = Object.create(null); + +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } + + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; }; -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } } -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = __nccwpck_require__(3454); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = __nccwpck_require__(68104); - } - return adapter; -} +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); -var defaults = { - adapter: getDefaultAdapter(), + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - if (utils.isObject(data)) { - setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); - return JSON.stringify(data); - } - return data; - }], + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); - transformResponse: [function transformResponse(data) { - /*eslint no-param-reassign:0*/ - if (typeof data === 'string') { - try { - data = JSON.parse(data); - } catch (e) { /* Ignore */ } - } - return data; - }], + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, + chalk.template.Instance = ChalkClass; - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', + return chalk.template; +}; - maxContentLength: -1, - maxBodyLength: -1, +function Chalk(options) { + return chalkFactory(options); +} - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - } -}; +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; +} -defaults.headers = { - common: { - 'Accept': 'application/json, text/plain, */*' - } +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } }; -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } }); -module.exports = defaults; +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + return { + open, + close, + openAll, + closeAll, + parent + }; +}; -/***/ }), +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } -/***/ 77065: -/***/ ((module) => { + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; -"use strict"; + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - return fn.apply(thisArg, args); - }; + return builder; }; +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } -/***/ }), + let styler = self._styler; -/***/ 30646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (styler === undefined) { + return string; + } -"use strict"; + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); + styler = styler.parent; + } + } -var utils = __nccwpck_require__(20328); + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); -} + return openAll + string + closeAll; +}; -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } +let template; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; - if (utils.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); - } - parts.push(encode(key) + '=' + encode(v)); - }); - }); + if (template === undefined) { + template = __nccwpck_require__(20500); + } - serializedParams = parts.join('&'); - } + return template(chalk, parts.join('')); +}; - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } +Object.defineProperties(Chalk.prototype, styles); - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } +const chalk = Chalk(); // eslint-disable-line new-cap +chalk.supportsColor = stdoutColor; +chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap +chalk.stderr.supportsColor = stderrColor; - return url; -}; +module.exports = chalk; /***/ }), -/***/ 57189: +/***/ 20500: /***/ ((module) => { "use strict"; +const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; -/** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ -module.exports = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -}; - - -/***/ }), +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); -/***/ 21545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; -"use strict"; + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } -var utils = __nccwpck_require__(20328); + return ESCAPES.get(c) || c; +} -module.exports = ( - utils.isStandardBrowserEnv() ? +function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; - // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils.isString(path)) { - cookie.push('path=' + path); - } + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } + return results; +} - if (secure === true) { - cookie.push('secure'); - } +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; - document.cookie = cookie.join('; '); - }, + const results = []; + let matches; - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } - // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() -); + return results; +} +function buildStyle(chalk, styles) { + const enabled = {}; -/***/ }), + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } -/***/ 41301: -/***/ ((module) => { + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } -"use strict"; + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -module.exports = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); -}; + return current; +} +module.exports = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; -/***/ }), + // eslint-disable-next-line max-params + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } -/***/ 60650: -/***/ ((module) => { + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); -"use strict"; + chunks.push(chunk.join('')); + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } -/** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -module.exports = function isAxiosError(payload) { - return (typeof payload === 'object') && (payload.isAxiosError === true); + return chunks.join(''); }; /***/ }), -/***/ 33608: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 82415: +/***/ ((module) => { "use strict"; -var utils = __nccwpck_require__(20328); - -module.exports = ( - utils.isStandardBrowserEnv() ? - - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); - - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : - - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() -); - - -/***/ }), +const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } -/***/ 36240: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); -"use strict"; + returnValue += string.substr(endIndex); + return returnValue; +}; +const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); -var utils = __nccwpck_require__(20328); + returnValue += string.substr(endIndex); + return returnValue; +}; -module.exports = function normalizeHeaderName(headers, normalizedName) { - utils.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); +module.exports = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex }; /***/ }), -/***/ 86455: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 97074: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var utils = __nccwpck_require__(20328); - -// Headers whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -var ignoreDuplicateOf = [ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]; - +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.supportsLanguage = exports.listLanguages = exports.highlight = void 0; +var hljs = __importStar(__nccwpck_require__(60082)); +var parse5 = __importStar(__nccwpck_require__(88933)); +var parse5_htmlparser2_tree_adapter_1 = __importDefault(__nccwpck_require__(9759)); +var theme_1 = __nccwpck_require__(81442); +function colorizeNode(node, theme, context) { + if (theme === void 0) { theme = {}; } + switch (node.type) { + case 'text': { + var text = node.data; + if (context === undefined) { + return (theme.default || theme_1.DEFAULT_THEME.default || theme_1.plain)(text); + } + return text; + } + case 'tag': { + var hljsClass = /hljs-(\w+)/.exec(node.attribs.class); + if (hljsClass) { + var token_1 = hljsClass[1]; + var nodeData = node.childNodes + .map(function (node) { return colorizeNode(node, theme, token_1); }) + .join(''); + return (theme[token_1] || theme_1.DEFAULT_THEME[token_1] || theme_1.plain)(nodeData); + } + // Return the data itself when the class name isn't prefixed with a highlight.js token prefix. + // This is common in instances of sublanguages (JSX, Markdown Code Blocks, etc.) + return node.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); + } + } + throw new Error('Invalid node type ' + node.type); +} +function colorize(code, theme) { + if (theme === void 0) { theme = {}; } + var fragment = parse5.parseFragment(code, { + treeAdapter: parse5_htmlparser2_tree_adapter_1.default, + }); + return fragment.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); +} /** - * Parse headers into an object + * Apply syntax highlighting to `code` with ASCII color codes. The language is automatically + * detected if not set. * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked + * ```ts + * import {highlight} from 'cli-highlight'; + * import * as fs from 'fs'; + * + * fs.readFile('package.json', 'utf8', (err: any, json: string) => { + * console.log('package.json:'); + * console.log(highlight(json)); + * }); * ``` * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object + * @param code The code to highlight + * @param options Optional options */ -module.exports = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { return parsed; } - - utils.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils.trim(line.substr(0, i)).toLowerCase(); - val = utils.trim(line.substr(i + 1)); - - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } +function highlight(code, options) { + if (options === void 0) { options = {}; } + var html; + if (options.language) { + html = hljs.highlight(options.language, code, options.ignoreIllegals, options.continuation).value; } - }); - - return parsed; -}; - - -/***/ }), - -/***/ 74850: -/***/ ((module) => { - -"use strict"; - - + else { + html = hljs.highlightAuto(code, options.languageSubset).value; + } + return colorize(html, options.theme); +} +exports.highlight = highlight; /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} + * Returns all supported languages */ -module.exports = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -}; - +function listLanguages() { + return hljs.listLanguages(); +} +exports.listLanguages = listLanguages; +/** + * Returns true if the language is supported + * @param name A language name, alias or file extension + */ +function supportsLanguage(name) { + return !!hljs.getLanguage(name); +} +exports.supportsLanguage = supportsLanguage; +exports.default = highlight; +__exportStar(__nccwpck_require__(81442), exports); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 20328: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 81442: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var bind = __nccwpck_require__(77065); - -/*global toString:true*/ - -// utils is a library of generic helper functions non-specific to axios - -var toString = Object.prototype.toString; - +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parse = exports.stringify = exports.toJson = exports.fromJson = exports.DEFAULT_THEME = exports.plain = void 0; +var chalk_1 = __importDefault(__nccwpck_require__(78818)); /** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false + * Identity function for tokens that should not be styled (returns the input string as-is). + * See [[Theme]] for an example. */ -function isArray(val) { - return toString.call(val) === '[object Array]'; -} - +var plain = function (codePart) { return codePart; }; +exports.plain = plain; /** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false + * The default theme. It is possible to override just individual keys. */ -function isUndefined(val) { - return typeof val === 'undefined'; -} - +exports.DEFAULT_THEME = { + /** + * keyword in a regular Algol-style language + */ + keyword: chalk_1.default.blue, + /** + * built-in or library object (constant, class, function) + */ + built_in: chalk_1.default.cyan, + /** + * user-defined type in a language with first-class syntactically significant types, like + * Haskell + */ + type: chalk_1.default.cyan.dim, + /** + * special identifier for a built-in value ("true", "false", "null") + */ + literal: chalk_1.default.blue, + /** + * number, including units and modifiers, if any. + */ + number: chalk_1.default.green, + /** + * literal regular expression + */ + regexp: chalk_1.default.red, + /** + * literal string, character + */ + string: chalk_1.default.red, + /** + * parsed section inside a literal string + */ + subst: exports.plain, + /** + * symbolic constant, interned string, goto label + */ + symbol: exports.plain, + /** + * class or class-level declaration (interfaces, traits, modules, etc) + */ + class: chalk_1.default.blue, + /** + * function or method declaration + */ + function: chalk_1.default.yellow, + /** + * name of a class or a function at the place of declaration + */ + title: exports.plain, + /** + * block of function arguments (parameters) at the place of declaration + */ + params: exports.plain, + /** + * comment + */ + comment: chalk_1.default.green, + /** + * documentation markup within comments + */ + doctag: chalk_1.default.green, + /** + * flags, modifiers, annotations, processing instructions, preprocessor directive, etc + */ + meta: chalk_1.default.grey, + /** + * keyword or built-in within meta construct + */ + 'meta-keyword': exports.plain, + /** + * string within meta construct + */ + 'meta-string': exports.plain, + /** + * heading of a section in a config file, heading in text markup + */ + section: exports.plain, + /** + * XML/HTML tag + */ + tag: chalk_1.default.grey, + /** + * name of an XML tag, the first word in an s-expression + */ + name: chalk_1.default.blue, + /** + * s-expression name from the language standard library + */ + 'builtin-name': exports.plain, + /** + * name of an attribute with no language defined semantics (keys in JSON, setting names in + * .ini), also sub-attribute within another highlighted object, like XML tag + */ + attr: chalk_1.default.cyan, + /** + * name of an attribute followed by a structured value part, like CSS properties + */ + attribute: exports.plain, + /** + * variable in a config or a template file, environment var expansion in a script + */ + variable: exports.plain, + /** + * list item bullet in text markup + */ + bullet: exports.plain, + /** + * code block in text markup + */ + code: exports.plain, + /** + * emphasis in text markup + */ + emphasis: chalk_1.default.italic, + /** + * strong emphasis in text markup + */ + strong: chalk_1.default.bold, + /** + * mathematical formula in text markup + */ + formula: exports.plain, + /** + * hyperlink in text markup + */ + link: chalk_1.default.underline, + /** + * quotation in text markup + */ + quote: exports.plain, + /** + * tag selector in CSS + */ + 'selector-tag': exports.plain, + /** + * #id selector in CSS + */ + 'selector-id': exports.plain, + /** + * .class selector in CSS + */ + 'selector-class': exports.plain, + /** + * [attr] selector in CSS + */ + 'selector-attr': exports.plain, + /** + * :pseudo selector in CSS + */ + 'selector-pseudo': exports.plain, + /** + * tag of a template language + */ + 'template-tag': exports.plain, + /** + * variable in a template language + */ + 'template-variable': exports.plain, + /** + * added or changed line in a diff + */ + addition: chalk_1.default.green, + /** + * deleted line in a diff + */ + deletion: chalk_1.default.red, + /** + * things not matched by any token + */ + default: exports.plain, +}; /** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false + * Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]]. */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +function fromJson(json) { + var theme = {}; + for (var _i = 0, _a = Object.keys(json); _i < _a.length; _i++) { + var key = _a[_i]; + var style = json[key]; + if (Array.isArray(style)) { + ; + theme[key] = style.reduce(function (previous, current) { return (current === 'plain' ? exports.plain : previous[current]); }, chalk_1.default); + } + else { + ; + theme[key] = chalk_1.default[style]; + } + } + return theme; } - +exports.fromJson = fromJson; /** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false + * Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]]. */ -function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; +function toJson(theme) { + var jsonTheme = {}; + for (var _i = 0, _a = Object.keys(jsonTheme); _i < _a.length; _i++) { + var key = _a[_i]; + var style = jsonTheme[key]; + jsonTheme[key] = style._styles; + } + return jsonTheme; } - +exports.toJson = toJson; /** - * Determine if a value is a FormData + * Stringifies a [[Theme]] with formatter functions to a JSON string. * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ -function isFormData(val) { - return (typeof FormData !== 'undefined') && (val instanceof FormData); -} - -/** - * Determine if a value is a view on an ArrayBuffer + * ```ts + * import chalk = require('chalk'); + * import {stringify} from 'cli-highlight'; + * import * as fs from 'fs'; * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + * const myTheme: Theme = { + * keyword: chalk.red.bold, + * addition: chalk.green, + * deletion: chalk.red.strikethrough, + * number: plain + * } + * const json = stringify(myTheme); + * fs.writeFile('mytheme.json', json, (err: any) => { + * if (err) throw err; + * console.log('Theme saved'); + * }); + * ``` */ -function isArrayBufferView(val) { - var result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); - } - return result; +function stringify(theme) { + return JSON.stringify(toJson(theme)); } - +exports.stringify = stringify; /** - * Determine if a value is a String + * Parses a JSON string into a [[Theme]] with formatter functions. * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ -function isString(val) { - return typeof val === 'string'; -} - -/** - * Determine if a value is a Number + * ```ts + * import * as fs from 'fs'; + * import {parse, highlight} from 'cli-highlight'; * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false + * fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => { + * if (err) throw err; + * const code = highlight('SELECT * FROM table', {theme: parse(json)}); + * console.log(code); + * }); + * ``` */ -function isNumber(val) { - return typeof val === 'number'; +function parse(json) { + return fromJson(JSON.parse(json)); } +exports.parse = parse; +//# sourceMappingURL=theme.js.map -/** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ -function isObject(val) { - return val !== null && typeof val === 'object'; -} +/***/ }), -/** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ -function isPlainObject(val) { - if (toString.call(val) !== '[object Object]') { - return false; - } +/***/ 94281: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; -} +"use strict"; -/** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ -function isDate(val) { - return toString.call(val) === '[object Date]'; -} -/** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -function isFile(val) { - return toString.call(val) === '[object File]'; -} +const { DOCUMENT_MODE } = __nccwpck_require__(49578); -/** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ -function isBlob(val) { - return toString.call(val) === '[object Blob]'; -} +//Const +const VALID_DOCTYPE_NAME = 'html'; +const VALID_SYSTEM_ID = 'about:legacy-compat'; +const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; -/** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -function isFunction(val) { - return toString.call(val) === '[object Function]'; -} +const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ + '+//silmaril//dtd html pro v0r11 19970101//', + '-//as//dtd html 3.0 aswedit + extensions//', + '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', + '-//ietf//dtd html 2.0 level 1//', + '-//ietf//dtd html 2.0 level 2//', + '-//ietf//dtd html 2.0 strict level 1//', + '-//ietf//dtd html 2.0 strict level 2//', + '-//ietf//dtd html 2.0 strict//', + '-//ietf//dtd html 2.0//', + '-//ietf//dtd html 2.1e//', + '-//ietf//dtd html 3.0//', + '-//ietf//dtd html 3.2 final//', + '-//ietf//dtd html 3.2//', + '-//ietf//dtd html 3//', + '-//ietf//dtd html level 0//', + '-//ietf//dtd html level 1//', + '-//ietf//dtd html level 2//', + '-//ietf//dtd html level 3//', + '-//ietf//dtd html strict level 0//', + '-//ietf//dtd html strict level 1//', + '-//ietf//dtd html strict level 2//', + '-//ietf//dtd html strict level 3//', + '-//ietf//dtd html strict//', + '-//ietf//dtd html//', + '-//metrius//dtd metrius presentational//', + '-//microsoft//dtd internet explorer 2.0 html strict//', + '-//microsoft//dtd internet explorer 2.0 html//', + '-//microsoft//dtd internet explorer 2.0 tables//', + '-//microsoft//dtd internet explorer 3.0 html strict//', + '-//microsoft//dtd internet explorer 3.0 html//', + '-//microsoft//dtd internet explorer 3.0 tables//', + '-//netscape comm. corp.//dtd html//', + '-//netscape comm. corp.//dtd strict html//', + "-//o'reilly and associates//dtd html 2.0//", + "-//o'reilly and associates//dtd html extended 1.0//", + "-//o'reilly and associates//dtd html extended relaxed 1.0//", + '-//sq//dtd html 2.0 hotmetal + extensions//', + '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', + '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', + '-//spyglass//dtd html 2.0 extended//', + '-//sun microsystems corp.//dtd hotjava html//', + '-//sun microsystems corp.//dtd hotjava strict html//', + '-//w3c//dtd html 3 1995-03-24//', + '-//w3c//dtd html 3.2 draft//', + '-//w3c//dtd html 3.2 final//', + '-//w3c//dtd html 3.2//', + '-//w3c//dtd html 3.2s draft//', + '-//w3c//dtd html 4.0 frameset//', + '-//w3c//dtd html 4.0 transitional//', + '-//w3c//dtd html experimental 19960712//', + '-//w3c//dtd html experimental 970421//', + '-//w3c//dtd w3 html//', + '-//w3o//dtd w3 html 3.0//', + '-//webtechs//dtd mozilla html 2.0//', + '-//webtechs//dtd mozilla html//' +]; -/** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ -function isStream(val) { - return isObject(val) && isFunction(val.pipe); -} +const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat([ + '-//w3c//dtd html 4.01 frameset//', + '-//w3c//dtd html 4.01 transitional//' +]); -/** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; -} +const QUIRKS_MODE_PUBLIC_IDS = ['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html']; +const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//']; -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ -function trim(str) { - return str.replace(/^\s*/, '').replace(/\s*$/, ''); +const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat([ + '-//w3c//dtd html 4.01 frameset//', + '-//w3c//dtd html 4.01 transitional//' +]); + +//Utils +function enquoteDoctypeId(id) { + const quote = id.indexOf('"') !== -1 ? "'" : '"'; + + return quote + id + quote; } -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ -function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || - navigator.product === 'NativeScript' || - navigator.product === 'NS')) { +function hasPrefix(publicId, prefixes) { + for (let i = 0; i < prefixes.length; i++) { + if (publicId.indexOf(prefixes[i]) === 0) { + return true; + } + } + return false; - } - return ( - typeof window !== 'undefined' && - typeof document !== 'undefined' - ); } -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ -function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } - - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } +//API +exports.isConforming = function(token) { + return ( + token.name === VALID_DOCTYPE_NAME && + token.publicId === null && + (token.systemId === null || token.systemId === VALID_SYSTEM_ID) + ); +}; - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); +exports.getDocumentMode = function(token) { + if (token.name !== VALID_DOCTYPE_NAME) { + return DOCUMENT_MODE.QUIRKS; } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } + + const systemId = token.systemId; + + if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { + return DOCUMENT_MODE.QUIRKS; } - } -} -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; + let publicId = token.publicId; + + if (publicId !== null) { + publicId = publicId.toLowerCase(); + + if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1) { + return DOCUMENT_MODE.QUIRKS; + } + + let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES; + + if (hasPrefix(publicId, prefixes)) { + return DOCUMENT_MODE.QUIRKS; + } + + prefixes = + systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES; + + if (hasPrefix(publicId, prefixes)) { + return DOCUMENT_MODE.LIMITED_QUIRKS; + } } - } - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} + return DOCUMENT_MODE.NO_QUIRKS; +}; -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ -function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind(val, thisArg); - } else { - a[key] = val; +exports.serializeContent = function(name, publicId, systemId) { + let str = '!DOCTYPE '; + + if (name) { + str += name; } - }); - return a; -} -/** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ -function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -} + if (publicId) { + str += ' PUBLIC ' + enquoteDoctypeId(publicId); + } else if (systemId) { + str += ' SYSTEM'; + } -module.exports = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM + if (systemId !== null) { + str += ' ' + enquoteDoctypeId(systemId); + } + + return str; }; /***/ }), -/***/ 9417: +/***/ 65510: /***/ ((module) => { "use strict"; -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - var r = range(a, b, str); +module.exports = { + controlCharacterInInputStream: 'control-character-in-input-stream', + noncharacterInInputStream: 'noncharacter-in-input-stream', + surrogateInInputStream: 'surrogate-in-input-stream', + nonVoidHtmlElementStartTagWithTrailingSolidus: 'non-void-html-element-start-tag-with-trailing-solidus', + endTagWithAttributes: 'end-tag-with-attributes', + endTagWithTrailingSolidus: 'end-tag-with-trailing-solidus', + unexpectedSolidusInTag: 'unexpected-solidus-in-tag', + unexpectedNullCharacter: 'unexpected-null-character', + unexpectedQuestionMarkInsteadOfTagName: 'unexpected-question-mark-instead-of-tag-name', + invalidFirstCharacterOfTagName: 'invalid-first-character-of-tag-name', + unexpectedEqualsSignBeforeAttributeName: 'unexpected-equals-sign-before-attribute-name', + missingEndTagName: 'missing-end-tag-name', + unexpectedCharacterInAttributeName: 'unexpected-character-in-attribute-name', + unknownNamedCharacterReference: 'unknown-named-character-reference', + missingSemicolonAfterCharacterReference: 'missing-semicolon-after-character-reference', + unexpectedCharacterAfterDoctypeSystemIdentifier: 'unexpected-character-after-doctype-system-identifier', + unexpectedCharacterInUnquotedAttributeValue: 'unexpected-character-in-unquoted-attribute-value', + eofBeforeTagName: 'eof-before-tag-name', + eofInTag: 'eof-in-tag', + missingAttributeValue: 'missing-attribute-value', + missingWhitespaceBetweenAttributes: 'missing-whitespace-between-attributes', + missingWhitespaceAfterDoctypePublicKeyword: 'missing-whitespace-after-doctype-public-keyword', + missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers: + 'missing-whitespace-between-doctype-public-and-system-identifiers', + missingWhitespaceAfterDoctypeSystemKeyword: 'missing-whitespace-after-doctype-system-keyword', + missingQuoteBeforeDoctypePublicIdentifier: 'missing-quote-before-doctype-public-identifier', + missingQuoteBeforeDoctypeSystemIdentifier: 'missing-quote-before-doctype-system-identifier', + missingDoctypePublicIdentifier: 'missing-doctype-public-identifier', + missingDoctypeSystemIdentifier: 'missing-doctype-system-identifier', + abruptDoctypePublicIdentifier: 'abrupt-doctype-public-identifier', + abruptDoctypeSystemIdentifier: 'abrupt-doctype-system-identifier', + cdataInHtmlContent: 'cdata-in-html-content', + incorrectlyOpenedComment: 'incorrectly-opened-comment', + eofInScriptHtmlCommentLikeText: 'eof-in-script-html-comment-like-text', + eofInDoctype: 'eof-in-doctype', + nestedComment: 'nested-comment', + abruptClosingOfEmptyComment: 'abrupt-closing-of-empty-comment', + eofInComment: 'eof-in-comment', + incorrectlyClosedComment: 'incorrectly-closed-comment', + eofInCdata: 'eof-in-cdata', + absenceOfDigitsInNumericCharacterReference: 'absence-of-digits-in-numeric-character-reference', + nullCharacterReference: 'null-character-reference', + surrogateCharacterReference: 'surrogate-character-reference', + characterReferenceOutsideUnicodeRange: 'character-reference-outside-unicode-range', + controlCharacterReference: 'control-character-reference', + noncharacterCharacterReference: 'noncharacter-character-reference', + missingWhitespaceBeforeDoctypeName: 'missing-whitespace-before-doctype-name', + missingDoctypeName: 'missing-doctype-name', + invalidCharacterSequenceAfterDoctypeName: 'invalid-character-sequence-after-doctype-name', + duplicateAttribute: 'duplicate-attribute', + nonConformingDoctype: 'non-conforming-doctype', + missingDoctype: 'missing-doctype', + misplacedDoctype: 'misplaced-doctype', + endTagWithoutMatchingOpenElement: 'end-tag-without-matching-open-element', + closingOfElementWithOpenChildElements: 'closing-of-element-with-open-child-elements', + disallowedContentInNoscriptInHead: 'disallowed-content-in-noscript-in-head', + openElementsLeftAfterEof: 'open-elements-left-after-eof', + abandonedHeadElementChild: 'abandoned-head-element-child', + misplacedStartTagForHeadElement: 'misplaced-start-tag-for-head-element', + nestedNoscriptInHead: 'nested-noscript-in-head', + eofInElementThatCanContainOnlyText: 'eof-in-element-that-can-contain-only-text' +}; - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; + +/***/ }), + +/***/ 24320: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Tokenizer = __nccwpck_require__(66480); +const HTML = __nccwpck_require__(49578); + +//Aliases +const $ = HTML.TAG_NAMES; +const NS = HTML.NAMESPACES; +const ATTRS = HTML.ATTRS; + +//MIME types +const MIME_TYPES = { + TEXT_HTML: 'text/html', + APPLICATION_XML: 'application/xhtml+xml' +}; + +//Attributes +const DEFINITION_URL_ATTR = 'definitionurl'; +const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL'; +const SVG_ATTRS_ADJUSTMENT_MAP = { + attributename: 'attributeName', + attributetype: 'attributeType', + basefrequency: 'baseFrequency', + baseprofile: 'baseProfile', + calcmode: 'calcMode', + clippathunits: 'clipPathUnits', + diffuseconstant: 'diffuseConstant', + edgemode: 'edgeMode', + filterunits: 'filterUnits', + glyphref: 'glyphRef', + gradienttransform: 'gradientTransform', + gradientunits: 'gradientUnits', + kernelmatrix: 'kernelMatrix', + kernelunitlength: 'kernelUnitLength', + keypoints: 'keyPoints', + keysplines: 'keySplines', + keytimes: 'keyTimes', + lengthadjust: 'lengthAdjust', + limitingconeangle: 'limitingConeAngle', + markerheight: 'markerHeight', + markerunits: 'markerUnits', + markerwidth: 'markerWidth', + maskcontentunits: 'maskContentUnits', + maskunits: 'maskUnits', + numoctaves: 'numOctaves', + pathlength: 'pathLength', + patterncontentunits: 'patternContentUnits', + patterntransform: 'patternTransform', + patternunits: 'patternUnits', + pointsatx: 'pointsAtX', + pointsaty: 'pointsAtY', + pointsatz: 'pointsAtZ', + preservealpha: 'preserveAlpha', + preserveaspectratio: 'preserveAspectRatio', + primitiveunits: 'primitiveUnits', + refx: 'refX', + refy: 'refY', + repeatcount: 'repeatCount', + repeatdur: 'repeatDur', + requiredextensions: 'requiredExtensions', + requiredfeatures: 'requiredFeatures', + specularconstant: 'specularConstant', + specularexponent: 'specularExponent', + spreadmethod: 'spreadMethod', + startoffset: 'startOffset', + stddeviation: 'stdDeviation', + stitchtiles: 'stitchTiles', + surfacescale: 'surfaceScale', + systemlanguage: 'systemLanguage', + tablevalues: 'tableValues', + targetx: 'targetX', + targety: 'targetY', + textlength: 'textLength', + viewbox: 'viewBox', + viewtarget: 'viewTarget', + xchannelselector: 'xChannelSelector', + ychannelselector: 'yChannelSelector', + zoomandpan: 'zoomAndPan' +}; + +const XML_ATTRS_ADJUSTMENT_MAP = { + 'xlink:actuate': { prefix: 'xlink', name: 'actuate', namespace: NS.XLINK }, + 'xlink:arcrole': { prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK }, + 'xlink:href': { prefix: 'xlink', name: 'href', namespace: NS.XLINK }, + 'xlink:role': { prefix: 'xlink', name: 'role', namespace: NS.XLINK }, + 'xlink:show': { prefix: 'xlink', name: 'show', namespace: NS.XLINK }, + 'xlink:title': { prefix: 'xlink', name: 'title', namespace: NS.XLINK }, + 'xlink:type': { prefix: 'xlink', name: 'type', namespace: NS.XLINK }, + 'xml:base': { prefix: 'xml', name: 'base', namespace: NS.XML }, + 'xml:lang': { prefix: 'xml', name: 'lang', namespace: NS.XML }, + 'xml:space': { prefix: 'xml', name: 'space', namespace: NS.XML }, + xmlns: { prefix: '', name: 'xmlns', namespace: NS.XMLNS }, + 'xmlns:xlink': { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS } +}; + +//SVG tag names adjustment map +const SVG_TAG_NAMES_ADJUSTMENT_MAP = (exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = { + altglyph: 'altGlyph', + altglyphdef: 'altGlyphDef', + altglyphitem: 'altGlyphItem', + animatecolor: 'animateColor', + animatemotion: 'animateMotion', + animatetransform: 'animateTransform', + clippath: 'clipPath', + feblend: 'feBlend', + fecolormatrix: 'feColorMatrix', + fecomponenttransfer: 'feComponentTransfer', + fecomposite: 'feComposite', + feconvolvematrix: 'feConvolveMatrix', + fediffuselighting: 'feDiffuseLighting', + fedisplacementmap: 'feDisplacementMap', + fedistantlight: 'feDistantLight', + feflood: 'feFlood', + fefunca: 'feFuncA', + fefuncb: 'feFuncB', + fefuncg: 'feFuncG', + fefuncr: 'feFuncR', + fegaussianblur: 'feGaussianBlur', + feimage: 'feImage', + femerge: 'feMerge', + femergenode: 'feMergeNode', + femorphology: 'feMorphology', + feoffset: 'feOffset', + fepointlight: 'fePointLight', + fespecularlighting: 'feSpecularLighting', + fespotlight: 'feSpotLight', + fetile: 'feTile', + feturbulence: 'feTurbulence', + foreignobject: 'foreignObject', + glyphref: 'glyphRef', + lineargradient: 'linearGradient', + radialgradient: 'radialGradient', + textpath: 'textPath' +}); + +//Tags that causes exit from foreign content +const EXITS_FOREIGN_CONTENT = { + [$.B]: true, + [$.BIG]: true, + [$.BLOCKQUOTE]: true, + [$.BODY]: true, + [$.BR]: true, + [$.CENTER]: true, + [$.CODE]: true, + [$.DD]: true, + [$.DIV]: true, + [$.DL]: true, + [$.DT]: true, + [$.EM]: true, + [$.EMBED]: true, + [$.H1]: true, + [$.H2]: true, + [$.H3]: true, + [$.H4]: true, + [$.H5]: true, + [$.H6]: true, + [$.HEAD]: true, + [$.HR]: true, + [$.I]: true, + [$.IMG]: true, + [$.LI]: true, + [$.LISTING]: true, + [$.MENU]: true, + [$.META]: true, + [$.NOBR]: true, + [$.OL]: true, + [$.P]: true, + [$.PRE]: true, + [$.RUBY]: true, + [$.S]: true, + [$.SMALL]: true, + [$.SPAN]: true, + [$.STRONG]: true, + [$.STRIKE]: true, + [$.SUB]: true, + [$.SUP]: true, + [$.TABLE]: true, + [$.TT]: true, + [$.U]: true, + [$.UL]: true, + [$.VAR]: true +}; + +//Check exit from foreign content +exports.causesExit = function(startTagToken) { + const tn = startTagToken.tagName; + const isFontWithAttrs = + tn === $.FONT && + (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null || + Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null || + Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null); + + return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn]; +}; + +//Token adjustments +exports.adjustTokenMathMLAttrs = function(token) { + for (let i = 0; i < token.attrs.length; i++) { + if (token.attrs[i].name === DEFINITION_URL_ATTR) { + token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR; + break; + } + } +}; + +exports.adjustTokenSVGAttrs = function(token) { + for (let i = 0; i < token.attrs.length; i++) { + const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; + + if (adjustedAttrName) { + token.attrs[i].name = adjustedAttrName; + } + } +}; + +exports.adjustTokenXMLAttrs = function(token) { + for (let i = 0; i < token.attrs.length; i++) { + const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; + + if (adjustedAttrEntry) { + token.attrs[i].prefix = adjustedAttrEntry.prefix; + token.attrs[i].name = adjustedAttrEntry.name; + token.attrs[i].namespace = adjustedAttrEntry.namespace; + } + } +}; + +exports.adjustTokenSVGTagName = function(token) { + const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName]; + + if (adjustedTagName) { + token.tagName = adjustedTagName; + } +}; + +//Integration points +function isMathMLTextIntegrationPoint(tn, ns) { + return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT); } -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; +function isHtmlIntegrationPoint(tn, ns, attrs) { + if (ns === NS.MATHML && tn === $.ANNOTATION_XML) { + for (let i = 0; i < attrs.length; i++) { + if (attrs[i].name === ATTRS.ENCODING) { + const value = attrs[i].value.toLowerCase(); + + return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML; + } + } + } + + return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE); } -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; +exports.isIntegrationPoint = function(tn, ns, attrs, foreignNS) { + if ((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) { + return true; + } - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; + if ((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)) { + return true; } - begs = []; - left = str.length; - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; + return false; +}; + + +/***/ }), + +/***/ 49578: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const NS = (exports.NAMESPACES = { + HTML: 'http://www.w3.org/1999/xhtml', + MATHML: 'http://www.w3.org/1998/Math/MathML', + SVG: 'http://www.w3.org/2000/svg', + XLINK: 'http://www.w3.org/1999/xlink', + XML: 'http://www.w3.org/XML/1998/namespace', + XMLNS: 'http://www.w3.org/2000/xmlns/' +}); + +exports.ATTRS = { + TYPE: 'type', + ACTION: 'action', + ENCODING: 'encoding', + PROMPT: 'prompt', + NAME: 'name', + COLOR: 'color', + FACE: 'face', + SIZE: 'size' +}; + +exports.DOCUMENT_MODE = { + NO_QUIRKS: 'no-quirks', + QUIRKS: 'quirks', + LIMITED_QUIRKS: 'limited-quirks' +}; + +const $ = (exports.TAG_NAMES = { + A: 'a', + ADDRESS: 'address', + ANNOTATION_XML: 'annotation-xml', + APPLET: 'applet', + AREA: 'area', + ARTICLE: 'article', + ASIDE: 'aside', + + B: 'b', + BASE: 'base', + BASEFONT: 'basefont', + BGSOUND: 'bgsound', + BIG: 'big', + BLOCKQUOTE: 'blockquote', + BODY: 'body', + BR: 'br', + BUTTON: 'button', + + CAPTION: 'caption', + CENTER: 'center', + CODE: 'code', + COL: 'col', + COLGROUP: 'colgroup', + + DD: 'dd', + DESC: 'desc', + DETAILS: 'details', + DIALOG: 'dialog', + DIR: 'dir', + DIV: 'div', + DL: 'dl', + DT: 'dt', + + EM: 'em', + EMBED: 'embed', + + FIELDSET: 'fieldset', + FIGCAPTION: 'figcaption', + FIGURE: 'figure', + FONT: 'font', + FOOTER: 'footer', + FOREIGN_OBJECT: 'foreignObject', + FORM: 'form', + FRAME: 'frame', + FRAMESET: 'frameset', + + H1: 'h1', + H2: 'h2', + H3: 'h3', + H4: 'h4', + H5: 'h5', + H6: 'h6', + HEAD: 'head', + HEADER: 'header', + HGROUP: 'hgroup', + HR: 'hr', + HTML: 'html', + + I: 'i', + IMG: 'img', + IMAGE: 'image', + INPUT: 'input', + IFRAME: 'iframe', + + KEYGEN: 'keygen', + + LABEL: 'label', + LI: 'li', + LINK: 'link', + LISTING: 'listing', + + MAIN: 'main', + MALIGNMARK: 'malignmark', + MARQUEE: 'marquee', + MATH: 'math', + MENU: 'menu', + META: 'meta', + MGLYPH: 'mglyph', + MI: 'mi', + MO: 'mo', + MN: 'mn', + MS: 'ms', + MTEXT: 'mtext', + + NAV: 'nav', + NOBR: 'nobr', + NOFRAMES: 'noframes', + NOEMBED: 'noembed', + NOSCRIPT: 'noscript', + + OBJECT: 'object', + OL: 'ol', + OPTGROUP: 'optgroup', + OPTION: 'option', + + P: 'p', + PARAM: 'param', + PLAINTEXT: 'plaintext', + PRE: 'pre', + + RB: 'rb', + RP: 'rp', + RT: 'rt', + RTC: 'rtc', + RUBY: 'ruby', + + S: 's', + SCRIPT: 'script', + SECTION: 'section', + SELECT: 'select', + SOURCE: 'source', + SMALL: 'small', + SPAN: 'span', + STRIKE: 'strike', + STRONG: 'strong', + STYLE: 'style', + SUB: 'sub', + SUMMARY: 'summary', + SUP: 'sup', + + TABLE: 'table', + TBODY: 'tbody', + TEMPLATE: 'template', + TEXTAREA: 'textarea', + TFOOT: 'tfoot', + TD: 'td', + TH: 'th', + THEAD: 'thead', + TITLE: 'title', + TR: 'tr', + TRACK: 'track', + TT: 'tt', + + U: 'u', + UL: 'ul', + + SVG: 'svg', + + VAR: 'var', + + WBR: 'wbr', + + XMP: 'xmp' +}); + +exports.SPECIAL_ELEMENTS = { + [NS.HTML]: { + [$.ADDRESS]: true, + [$.APPLET]: true, + [$.AREA]: true, + [$.ARTICLE]: true, + [$.ASIDE]: true, + [$.BASE]: true, + [$.BASEFONT]: true, + [$.BGSOUND]: true, + [$.BLOCKQUOTE]: true, + [$.BODY]: true, + [$.BR]: true, + [$.BUTTON]: true, + [$.CAPTION]: true, + [$.CENTER]: true, + [$.COL]: true, + [$.COLGROUP]: true, + [$.DD]: true, + [$.DETAILS]: true, + [$.DIR]: true, + [$.DIV]: true, + [$.DL]: true, + [$.DT]: true, + [$.EMBED]: true, + [$.FIELDSET]: true, + [$.FIGCAPTION]: true, + [$.FIGURE]: true, + [$.FOOTER]: true, + [$.FORM]: true, + [$.FRAME]: true, + [$.FRAMESET]: true, + [$.H1]: true, + [$.H2]: true, + [$.H3]: true, + [$.H4]: true, + [$.H5]: true, + [$.H6]: true, + [$.HEAD]: true, + [$.HEADER]: true, + [$.HGROUP]: true, + [$.HR]: true, + [$.HTML]: true, + [$.IFRAME]: true, + [$.IMG]: true, + [$.INPUT]: true, + [$.LI]: true, + [$.LINK]: true, + [$.LISTING]: true, + [$.MAIN]: true, + [$.MARQUEE]: true, + [$.MENU]: true, + [$.META]: true, + [$.NAV]: true, + [$.NOEMBED]: true, + [$.NOFRAMES]: true, + [$.NOSCRIPT]: true, + [$.OBJECT]: true, + [$.OL]: true, + [$.P]: true, + [$.PARAM]: true, + [$.PLAINTEXT]: true, + [$.PRE]: true, + [$.SCRIPT]: true, + [$.SECTION]: true, + [$.SELECT]: true, + [$.SOURCE]: true, + [$.STYLE]: true, + [$.SUMMARY]: true, + [$.TABLE]: true, + [$.TBODY]: true, + [$.TD]: true, + [$.TEMPLATE]: true, + [$.TEXTAREA]: true, + [$.TFOOT]: true, + [$.TH]: true, + [$.THEAD]: true, + [$.TITLE]: true, + [$.TR]: true, + [$.TRACK]: true, + [$.UL]: true, + [$.WBR]: true, + [$.XMP]: true + }, + [NS.MATHML]: { + [$.MI]: true, + [$.MO]: true, + [$.MN]: true, + [$.MS]: true, + [$.MTEXT]: true, + [$.ANNOTATION_XML]: true + }, + [NS.SVG]: { + [$.TITLE]: true, + [$.FOREIGN_OBJECT]: true, + [$.DESC]: true + } +}; + + +/***/ }), + +/***/ 4736: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const UNDEFINED_CODE_POINTS = [ + 0xfffe, + 0xffff, + 0x1fffe, + 0x1ffff, + 0x2fffe, + 0x2ffff, + 0x3fffe, + 0x3ffff, + 0x4fffe, + 0x4ffff, + 0x5fffe, + 0x5ffff, + 0x6fffe, + 0x6ffff, + 0x7fffe, + 0x7ffff, + 0x8fffe, + 0x8ffff, + 0x9fffe, + 0x9ffff, + 0xafffe, + 0xaffff, + 0xbfffe, + 0xbffff, + 0xcfffe, + 0xcffff, + 0xdfffe, + 0xdffff, + 0xefffe, + 0xeffff, + 0xffffe, + 0xfffff, + 0x10fffe, + 0x10ffff +]; + +exports.REPLACEMENT_CHARACTER = '\uFFFD'; + +exports.CODE_POINTS = { + EOF: -1, + NULL: 0x00, + TABULATION: 0x09, + CARRIAGE_RETURN: 0x0d, + LINE_FEED: 0x0a, + FORM_FEED: 0x0c, + SPACE: 0x20, + EXCLAMATION_MARK: 0x21, + QUOTATION_MARK: 0x22, + NUMBER_SIGN: 0x23, + AMPERSAND: 0x26, + APOSTROPHE: 0x27, + HYPHEN_MINUS: 0x2d, + SOLIDUS: 0x2f, + DIGIT_0: 0x30, + DIGIT_9: 0x39, + SEMICOLON: 0x3b, + LESS_THAN_SIGN: 0x3c, + EQUALS_SIGN: 0x3d, + GREATER_THAN_SIGN: 0x3e, + QUESTION_MARK: 0x3f, + LATIN_CAPITAL_A: 0x41, + LATIN_CAPITAL_F: 0x46, + LATIN_CAPITAL_X: 0x58, + LATIN_CAPITAL_Z: 0x5a, + RIGHT_SQUARE_BRACKET: 0x5d, + GRAVE_ACCENT: 0x60, + LATIN_SMALL_A: 0x61, + LATIN_SMALL_F: 0x66, + LATIN_SMALL_X: 0x78, + LATIN_SMALL_Z: 0x7a, + REPLACEMENT_CHARACTER: 0xfffd +}; + +exports.CODE_POINT_SEQUENCES = { + DASH_DASH_STRING: [0x2d, 0x2d], //-- + DOCTYPE_STRING: [0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE + CDATA_START_STRING: [0x5b, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5b], //[CDATA[ + SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script + PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4c, 0x49, 0x43], //PUBLIC + SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4d] //SYSTEM +}; + +//Surrogates +exports.isSurrogate = function(cp) { + return cp >= 0xd800 && cp <= 0xdfff; +}; + +exports.isSurrogatePair = function(cp) { + return cp >= 0xdc00 && cp <= 0xdfff; +}; + +exports.getSurrogatePairCodePoint = function(cp1, cp2) { + return (cp1 - 0xd800) * 0x400 + 0x2400 + cp2; +}; + +//NOTE: excluding NULL and ASCII whitespace +exports.isControlCodePoint = function(cp) { + return ( + (cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) || + (cp >= 0x7f && cp <= 0x9f) + ); +}; + +exports.isUndefinedCodePoint = function(cp) { + return (cp >= 0xfdd0 && cp <= 0xfdef) || UNDEFINED_CODE_POINTS.indexOf(cp) > -1; +}; + + +/***/ }), + +/***/ 45686: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Mixin = __nccwpck_require__(2830); + +class ErrorReportingMixinBase extends Mixin { + constructor(host, opts) { + super(host); + + this.posTracker = null; + this.onParseError = opts.onParseError; + } + + _setErrorLocation(err) { + err.startLine = err.endLine = this.posTracker.line; + err.startCol = err.endCol = this.posTracker.col; + err.startOffset = err.endOffset = this.posTracker.offset; + } + + _reportError(code) { + const err = { + code: code, + startLine: -1, + startCol: -1, + startOffset: -1, + endLine: -1, + endCol: -1, + endOffset: -1 + }; + + this._setErrorLocation(err); + this.onParseError(err); + } + + _getOverriddenMethods(mxn) { + return { + _err(code) { + mxn._reportError(code); + } + }; + } +} + +module.exports = ErrorReportingMixinBase; + + +/***/ }), + +/***/ 60393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const ErrorReportingMixinBase = __nccwpck_require__(45686); +const ErrorReportingTokenizerMixin = __nccwpck_require__(14703); +const LocationInfoTokenizerMixin = __nccwpck_require__(29817); +const Mixin = __nccwpck_require__(2830); + +class ErrorReportingParserMixin extends ErrorReportingMixinBase { + constructor(parser, opts) { + super(parser, opts); + + this.opts = opts; + this.ctLoc = null; + this.locBeforeToken = false; + } + + _setErrorLocation(err) { + if (this.ctLoc) { + err.startLine = this.ctLoc.startLine; + err.startCol = this.ctLoc.startCol; + err.startOffset = this.ctLoc.startOffset; + + err.endLine = this.locBeforeToken ? this.ctLoc.startLine : this.ctLoc.endLine; + err.endCol = this.locBeforeToken ? this.ctLoc.startCol : this.ctLoc.endCol; + err.endOffset = this.locBeforeToken ? this.ctLoc.startOffset : this.ctLoc.endOffset; } + } - bi = str.indexOf(b, i + 1); - } + _getOverriddenMethods(mxn, orig) { + return { + _bootstrap(document, fragmentContext) { + orig._bootstrap.call(this, document, fragmentContext); - i = ai < bi && ai >= 0 ? ai : bi; + Mixin.install(this.tokenizer, ErrorReportingTokenizerMixin, mxn.opts); + Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); + }, + + _processInputToken(token) { + mxn.ctLoc = token.location; + + orig._processInputToken.call(this, token); + }, + + _err(code, options) { + mxn.locBeforeToken = options && options.beforeToken; + mxn._reportError(code); + } + }; } +} - if (begs.length) { - result = [ left, right ]; +module.exports = ErrorReportingParserMixin; + + +/***/ }), + +/***/ 96573: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const ErrorReportingMixinBase = __nccwpck_require__(45686); +const PositionTrackingPreprocessorMixin = __nccwpck_require__(3127); +const Mixin = __nccwpck_require__(2830); + +class ErrorReportingPreprocessorMixin extends ErrorReportingMixinBase { + constructor(preprocessor, opts) { + super(preprocessor, opts); + + this.posTracker = Mixin.install(preprocessor, PositionTrackingPreprocessorMixin); + this.lastErrOffset = -1; } - } - return result; + _reportError(code) { + //NOTE: avoid reporting error twice on advance/retreat + if (this.lastErrOffset !== this.posTracker.offset) { + this.lastErrOffset = this.posTracker.offset; + super._reportError(code); + } + } } +module.exports = ErrorReportingPreprocessorMixin; + /***/ }), -/***/ 87558: -/***/ (function(module) { +/***/ 14703: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -;(function (globalObject) { - 'use strict'; - -/* - * bignumber.js v9.0.0 - * A JavaScript library for arbitrary-precision arithmetic. - * https://github.com/MikeMcl/bignumber.js - * Copyright (c) 2019 Michael Mclaughlin - * MIT Licensed. - * - * BigNumber.prototype methods | BigNumber methods - * | - * absoluteValue abs | clone - * comparedTo | config set - * decimalPlaces dp | DECIMAL_PLACES - * dividedBy div | ROUNDING_MODE - * dividedToIntegerBy idiv | EXPONENTIAL_AT - * exponentiatedBy pow | RANGE - * integerValue | CRYPTO - * isEqualTo eq | MODULO_MODE - * isFinite | POW_PRECISION - * isGreaterThan gt | FORMAT - * isGreaterThanOrEqualTo gte | ALPHABET - * isInteger | isBigNumber - * isLessThan lt | maximum max - * isLessThanOrEqualTo lte | minimum min - * isNaN | random - * isNegative | sum - * isPositive | - * isZero | - * minus | - * modulo mod | - * multipliedBy times | - * negated | - * plus | - * precision sd | - * shiftedBy | - * squareRoot sqrt | - * toExponential | - * toFixed | - * toFormat | - * toFraction | - * toJSON | - * toNumber | - * toPrecision | - * toString | - * valueOf | - * - */ - - - var BigNumber, - isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, - mathceil = Math.ceil, - mathfloor = Math.floor, - - bignumberError = '[BigNumber Error] ', - tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', - - BASE = 1e14, - LOG_BASE = 14, - MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 - // MAX_INT32 = 0x7fffffff, // 2^31 - 1 - POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], - SQRT_BASE = 1e7, - - // EDITABLE - // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and - // the arguments to toExponential, toFixed, toFormat, and toPrecision. - MAX = 1E9; // 0 to MAX_INT32 - - - /* - * Create and return a BigNumber constructor. - */ - function clone(configObject) { - var div, convertBase, parseNumeric, - P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, - ONE = new BigNumber(1), - - - //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- - - - // The default values below must be integers within the inclusive ranges stated. - // The values can also be changed at run-time using BigNumber.set. - - // The maximum number of decimal places for operations involving division. - DECIMAL_PLACES = 20, // 0 to MAX - - // The rounding mode used when rounding to the above decimal places, and when using - // toExponential, toFixed, toFormat and toPrecision, and round (default value). - // UP 0 Away from zero. - // DOWN 1 Towards zero. - // CEIL 2 Towards +Infinity. - // FLOOR 3 Towards -Infinity. - // HALF_UP 4 Towards nearest neighbour. If equidistant, up. - // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. - // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. - // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. - // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. - ROUNDING_MODE = 4, // 0 to 8 - - // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] - - // The exponent value at and beneath which toString returns exponential notation. - // Number type: -7 - TO_EXP_NEG = -7, // 0 to -MAX - - // The exponent value at and above which toString returns exponential notation. - // Number type: 21 - TO_EXP_POS = 21, // 0 to MAX - - // RANGE : [MIN_EXP, MAX_EXP] - - // The minimum exponent value, beneath which underflow to zero occurs. - // Number type: -324 (5e-324) - MIN_EXP = -1e7, // -1 to -MAX - - // The maximum exponent value, above which overflow to Infinity occurs. - // Number type: 308 (1.7976931348623157e+308) - // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. - MAX_EXP = 1e7, // 1 to MAX - - // Whether to use cryptographically-secure random number generation, if available. - CRYPTO = false, // true or false - - // The modulo mode used when calculating the modulus: a mod n. - // The quotient (q = a / n) is calculated according to the corresponding rounding mode. - // The remainder (r) is calculated as: r = a - n * q. - // - // UP 0 The remainder is positive if the dividend is negative, else is negative. - // DOWN 1 The remainder has the same sign as the dividend. - // This modulo mode is commonly known as 'truncated division' and is - // equivalent to (a % n) in JavaScript. - // FLOOR 3 The remainder has the same sign as the divisor (Python %). - // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. - // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). - // The remainder is always positive. - // - // The truncated division, floored division, Euclidian division and IEEE 754 remainder - // modes are commonly used for the modulus operation. - // Although the other rounding modes can also be used, they may not give useful results. - MODULO_MODE = 1, // 0 to 9 - - // The maximum number of significant digits of the result of the exponentiatedBy operation. - // If POW_PRECISION is 0, there will be unlimited significant digits. - POW_PRECISION = 0, // 0 to MAX - - // The format specification used by the BigNumber.prototype.toFormat method. - FORMAT = { - prefix: '', - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ',', - decimalSeparator: '.', - fractionGroupSize: 0, - fractionGroupSeparator: '\xA0', // non-breaking space - suffix: '' - }, - - // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', - // '-', '.', whitespace, or repeated character. - // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' - ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; - - - //------------------------------------------------------------------------------------------ - - - // CONSTRUCTOR - - - /* - * The BigNumber constructor and exported function. - * Create and return a new instance of a BigNumber object. - * - * v {number|string|BigNumber} A numeric value. - * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. - */ - function BigNumber(v, b) { - var alphabet, c, caseChanged, e, i, isNum, len, str, - x = this; - - // Enable constructor call without `new`. - if (!(x instanceof BigNumber)) return new BigNumber(v, b); - - if (b == null) { - - if (v && v._isBigNumber === true) { - x.s = v.s; - - if (!v.c || v.e > MAX_EXP) { - x.c = x.e = null; - } else if (v.e < MIN_EXP) { - x.c = [x.e = 0]; - } else { - x.e = v.e; - x.c = v.c.slice(); - } - - return; - } - - if ((isNum = typeof v == 'number') && v * 0 == 0) { - - // Use `1 / n` to handle minus zero also. - x.s = 1 / v < 0 ? (v = -v, -1) : 1; - - // Fast path for integers, where n < 2147483648 (2**31). - if (v === ~~v) { - for (e = 0, i = v; i >= 10; i /= 10, e++); - - if (e > MAX_EXP) { - x.c = x.e = null; - } else { - x.e = e; - x.c = [v]; - } - - return; - } - - str = String(v); - } else { - - if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); - - x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - - // Exponential form? - if ((i = str.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e < 0) { - - // Integer. - e = str.length; - } - - } else { - - // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' - intCheck(b, 2, ALPHABET.length, 'Base'); - - // Allow exponential notation to be used with base 10 argument, while - // also rounding to DECIMAL_PLACES as with other bases. - if (b == 10) { - x = new BigNumber(v); - return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); - } - - str = String(v); - - if (isNum = typeof v == 'number') { - - // Avoid potential interpretation of Infinity and NaN as base 44+ values. - if (v * 0 != 0) return parseNumeric(x, str, isNum, b); - - x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; - - // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' - if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { - throw Error - (tooManyDigits + v); - } - } else { - x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - - alphabet = ALPHABET.slice(0, b); - e = i = 0; - - // Check that str is a valid base b number. - // Don't use RegExp, so alphabet can contain special characters. - for (len = str.length; i < len; i++) { - if (alphabet.indexOf(c = str.charAt(i)) < 0) { - if (c == '.') { - - // If '.' is not the first character and it has not be found before. - if (i > e) { - e = len; - continue; - } - } else if (!caseChanged) { - - // Allow e.g. hexadecimal 'FF' as well as 'ff'. - if (str == str.toUpperCase() && (str = str.toLowerCase()) || - str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i = -1; - e = 0; - continue; - } - } - - return parseNumeric(x, String(v), isNum, b); - } - } - - // Prevent later check for length on converted number. - isNum = false; - str = convertBase(str, b, 10, x.s); - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - else e = str.length; - } - - // Determine leading zeros. - for (i = 0; str.charCodeAt(i) === 48; i++); - - // Determine trailing zeros. - for (len = str.length; str.charCodeAt(--len) === 48;); - - if (str = str.slice(i, ++len)) { - len -= i; - - // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' - if (isNum && BigNumber.DEBUG && - len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { - throw Error - (tooManyDigits + (x.s * v)); - } - - // Overflow? - if ((e = e - i - 1) > MAX_EXP) { - - // Infinity. - x.c = x.e = null; - - // Underflow? - } else if (e < MIN_EXP) { - - // Zero. - x.c = [x.e = 0]; - } else { - x.e = e; - x.c = []; - - // Transform base - - // e is the base 10 exponent. - // i is where to slice str to get the first element of the coefficient array. - i = (e + 1) % LOG_BASE; - if (e < 0) i += LOG_BASE; // i < 1 - - if (i < len) { - if (i) x.c.push(+str.slice(0, i)); - - for (len -= LOG_BASE; i < len;) { - x.c.push(+str.slice(i, i += LOG_BASE)); - } - - i = LOG_BASE - (str = str.slice(i)).length; - } else { - i -= len; - } - - for (; i--; str += '0'); - x.c.push(+str); - } - } else { - - // Zero. - x.c = [x.e = 0]; - } - } - - - // CONSTRUCTOR PROPERTIES - - - BigNumber.clone = clone; - - BigNumber.ROUND_UP = 0; - BigNumber.ROUND_DOWN = 1; - BigNumber.ROUND_CEIL = 2; - BigNumber.ROUND_FLOOR = 3; - BigNumber.ROUND_HALF_UP = 4; - BigNumber.ROUND_HALF_DOWN = 5; - BigNumber.ROUND_HALF_EVEN = 6; - BigNumber.ROUND_HALF_CEIL = 7; - BigNumber.ROUND_HALF_FLOOR = 8; - BigNumber.EUCLID = 9; - - - /* - * Configure infrequently-changing library-wide settings. - * - * Accept an object with the following optional properties (if the value of a property is - * a number, it must be an integer within the inclusive range stated): - * - * DECIMAL_PLACES {number} 0 to MAX - * ROUNDING_MODE {number} 0 to 8 - * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] - * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] - * CRYPTO {boolean} true or false - * MODULO_MODE {number} 0 to 9 - * POW_PRECISION {number} 0 to MAX - * ALPHABET {string} A string of two or more unique characters which does - * not contain '.'. - * FORMAT {object} An object with some of the following properties: - * prefix {string} - * groupSize {number} - * secondaryGroupSize {number} - * groupSeparator {string} - * decimalSeparator {string} - * fractionGroupSize {number} - * fractionGroupSeparator {string} - * suffix {string} - * - * (The values assigned to the above FORMAT object properties are not checked for validity.) - * - * E.g. - * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) - * - * Ignore properties/parameters set to null or undefined, except for ALPHABET. - * - * Return an object with the properties current values. - */ - BigNumber.config = BigNumber.set = function (obj) { - var p, v; - - if (obj != null) { - - if (typeof obj == 'object') { - - // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. - // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { - v = obj[p]; - intCheck(v, 0, MAX, p); - DECIMAL_PLACES = v; - } - - // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. - // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { - v = obj[p]; - intCheck(v, 0, 8, p); - ROUNDING_MODE = v; - } - - // EXPONENTIAL_AT {number|number[]} - // Integer, -MAX to MAX inclusive or - // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. - // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { - v = obj[p]; - if (v && v.pop) { - intCheck(v[0], -MAX, 0, p); - intCheck(v[1], 0, MAX, p); - TO_EXP_NEG = v[0]; - TO_EXP_POS = v[1]; - } else { - intCheck(v, -MAX, MAX, p); - TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); - } - } - - // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or - // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. - // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' - if (obj.hasOwnProperty(p = 'RANGE')) { - v = obj[p]; - if (v && v.pop) { - intCheck(v[0], -MAX, -1, p); - intCheck(v[1], 1, MAX, p); - MIN_EXP = v[0]; - MAX_EXP = v[1]; - } else { - intCheck(v, -MAX, MAX, p); - if (v) { - MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); - } else { - throw Error - (bignumberError + p + ' cannot be zero: ' + v); - } - } - } - - // CRYPTO {boolean} true or false. - // '[BigNumber Error] CRYPTO not true or false: {v}' - // '[BigNumber Error] crypto unavailable' - if (obj.hasOwnProperty(p = 'CRYPTO')) { - v = obj[p]; - if (v === !!v) { - if (v) { - if (typeof crypto != 'undefined' && crypto && - (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v; - } else { - CRYPTO = !v; - throw Error - (bignumberError + 'crypto unavailable'); - } - } else { - CRYPTO = v; - } - } else { - throw Error - (bignumberError + p + ' not true or false: ' + v); - } - } - - // MODULO_MODE {number} Integer, 0 to 9 inclusive. - // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'MODULO_MODE')) { - v = obj[p]; - intCheck(v, 0, 9, p); - MODULO_MODE = v; - } - - // POW_PRECISION {number} Integer, 0 to MAX inclusive. - // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'POW_PRECISION')) { - v = obj[p]; - intCheck(v, 0, MAX, p); - POW_PRECISION = v; - } - - // FORMAT {object} - // '[BigNumber Error] FORMAT not an object: {v}' - if (obj.hasOwnProperty(p = 'FORMAT')) { - v = obj[p]; - if (typeof v == 'object') FORMAT = v; - else throw Error - (bignumberError + p + ' not an object: ' + v); - } - - // ALPHABET {string} - // '[BigNumber Error] ALPHABET invalid: {v}' - if (obj.hasOwnProperty(p = 'ALPHABET')) { - v = obj[p]; - - // Disallow if only one character, - // or if it contains '+', '-', '.', whitespace, or a repeated character. - if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) { - ALPHABET = v; - } else { - throw Error - (bignumberError + p + ' invalid: ' + v); - } - } - - } else { - - // '[BigNumber Error] Object expected: {v}' - throw Error - (bignumberError + 'Object expected: ' + obj); - } - } - - return { - DECIMAL_PLACES: DECIMAL_PLACES, - ROUNDING_MODE: ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO: CRYPTO, - MODULO_MODE: MODULO_MODE, - POW_PRECISION: POW_PRECISION, - FORMAT: FORMAT, - ALPHABET: ALPHABET - }; - }; - - - /* - * Return true if v is a BigNumber instance, otherwise return false. - * - * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. - * - * v {any} - * - * '[BigNumber Error] Invalid BigNumber: {v}' - */ - BigNumber.isBigNumber = function (v) { - if (!v || v._isBigNumber !== true) return false; - if (!BigNumber.DEBUG) return true; - - var i, n, - c = v.c, - e = v.e, - s = v.s; - - out: if ({}.toString.call(c) == '[object Array]') { - - if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { - - // If the first element is zero, the BigNumber value must be zero. - if (c[0] === 0) { - if (e === 0 && c.length === 1) return true; - break out; - } - - // Calculate number of digits that c[0] should have, based on the exponent. - i = (e + 1) % LOG_BASE; - if (i < 1) i += LOG_BASE; - - // Calculate number of digits of c[0]. - //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { - if (String(c[0]).length == i) { - - for (i = 0; i < c.length; i++) { - n = c[i]; - if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; - } - - // Last element cannot be zero, unless it is the only element. - if (n !== 0) return true; - } - } - - // Infinity/NaN - } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { - return true; - } - - throw Error - (bignumberError + 'Invalid BigNumber: ' + v); - }; - - - /* - * Return a new BigNumber whose value is the maximum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.maximum = BigNumber.max = function () { - return maxOrMin(arguments, P.lt); - }; - - - /* - * Return a new BigNumber whose value is the minimum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.minimum = BigNumber.min = function () { - return maxOrMin(arguments, P.gt); - }; - - - /* - * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, - * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing - * zeros are produced). - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' - * '[BigNumber Error] crypto unavailable' - */ - BigNumber.random = (function () { - var pow2_53 = 0x20000000000000; - - // Return a 53 bit integer n, where 0 <= n < 9007199254740992. - // Check if Math.random() produces more than 32 bits of randomness. - // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. - // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. - var random53bitInt = (Math.random() * pow2_53) & 0x1fffff - ? function () { return mathfloor(Math.random() * pow2_53); } - : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + - (Math.random() * 0x800000 | 0); }; - - return function (dp) { - var a, b, e, k, v, - i = 0, - c = [], - rand = new BigNumber(ONE); - - if (dp == null) dp = DECIMAL_PLACES; - else intCheck(dp, 0, MAX); - - k = mathceil(dp / LOG_BASE); - - if (CRYPTO) { - - // Browsers supporting crypto.getRandomValues. - if (crypto.getRandomValues) { - - a = crypto.getRandomValues(new Uint32Array(k *= 2)); - - for (; i < k;) { - - // 53 bits: - // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) - // 11111 11111111 11111111 11111111 11100000 00000000 00000000 - // ((Math.pow(2, 32) - 1) >>> 11).toString(2) - // 11111 11111111 11111111 - // 0x20000 is 2^21. - v = a[i] * 0x20000 + (a[i + 1] >>> 11); - - // Rejection sampling: - // 0 <= v < 9007199254740992 - // Probability that v >= 9e15, is - // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 - if (v >= 9e15) { - b = crypto.getRandomValues(new Uint32Array(2)); - a[i] = b[0]; - a[i + 1] = b[1]; - } else { - - // 0 <= v <= 8999999999999999 - // 0 <= (v % 1e14) <= 99999999999999 - c.push(v % 1e14); - i += 2; - } - } - i = k / 2; - - // Node.js supporting crypto.randomBytes. - } else if (crypto.randomBytes) { - - // buffer - a = crypto.randomBytes(k *= 7); - - for (; i < k;) { - - // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 - // 0x100000000 is 2^32, 0x1000000 is 2^24 - // 11111 11111111 11111111 11111111 11111111 11111111 11111111 - // 0 <= v < 9007199254740992 - v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + - (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + - (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; - - if (v >= 9e15) { - crypto.randomBytes(7).copy(a, i); - } else { - - // 0 <= (v % 1e14) <= 99999999999999 - c.push(v % 1e14); - i += 7; - } - } - i = k / 7; - } else { - CRYPTO = false; - throw Error - (bignumberError + 'crypto unavailable'); - } - } - - // Use Math.random. - if (!CRYPTO) { - - for (; i < k;) { - v = random53bitInt(); - if (v < 9e15) c[i++] = v % 1e14; - } - } - - k = c[--i]; - dp %= LOG_BASE; - - // Convert trailing digits to zeros according to dp. - if (k && dp) { - v = POWS_TEN[LOG_BASE - dp]; - c[i] = mathfloor(k / v) * v; - } - - // Remove trailing elements which are zero. - for (; c[i] === 0; c.pop(), i--); - - // Zero? - if (i < 0) { - c = [e = 0]; - } else { - - // Remove leading elements which are zero and adjust exponent accordingly. - for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); - - // Count the digits of the first element of c to determine leading zeros, and... - for (i = 1, v = c[0]; v >= 10; v /= 10, i++); - - // adjust the exponent accordingly. - if (i < LOG_BASE) e -= LOG_BASE - i; - } - - rand.e = e; - rand.c = c; - return rand; - }; - })(); - - - /* - * Return a BigNumber whose value is the sum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.sum = function () { - var i = 1, - args = arguments, - sum = new BigNumber(args[0]); - for (; i < args.length;) sum = sum.plus(args[i++]); - return sum; - }; - - - // PRIVATE FUNCTIONS - - - // Called by BigNumber and BigNumber.prototype.toString. - convertBase = (function () { - var decimal = '0123456789'; - - /* - * Convert string of baseIn to an array of numbers of baseOut. - * Eg. toBaseOut('255', 10, 16) returns [15, 15]. - * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. - */ - function toBaseOut(str, baseIn, baseOut, alphabet) { - var j, - arr = [0], - arrL, - i = 0, - len = str.length; - - for (; i < len;) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); - - arr[0] += alphabet.indexOf(str.charAt(i++)); - - for (j = 0; j < arr.length; j++) { - - if (arr[j] > baseOut - 1) { - if (arr[j + 1] == null) arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - - return arr.reverse(); - } - - // Convert a numeric string of baseIn to a numeric string of baseOut. - // If the caller is toString, we are converting from base 10 to baseOut. - // If the caller is BigNumber, we are converting from baseIn to base 10. - return function (str, baseIn, baseOut, sign, callerIsToString) { - var alphabet, d, e, k, r, x, xc, y, - i = str.indexOf('.'), - dp = DECIMAL_PLACES, - rm = ROUNDING_MODE; - - // Non-integer. - if (i >= 0) { - k = POW_PRECISION; - - // Unlimited precision. - POW_PRECISION = 0; - str = str.replace('.', ''); - y = new BigNumber(baseIn); - x = y.pow(str.length - i); - POW_PRECISION = k; - - // Convert str as if an integer, then restore the fraction part by dividing the - // result by its base raised to a power. - - y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), - 10, baseOut, decimal); - y.e = y.c.length; - } - - // Convert the number as integer. - - xc = toBaseOut(str, baseIn, baseOut, callerIsToString - ? (alphabet = ALPHABET, decimal) - : (alphabet = decimal, ALPHABET)); - - // xc now represents str as an integer and converted to baseOut. e is the exponent. - e = k = xc.length; - - // Remove trailing zeros. - for (; xc[--k] == 0; xc.pop()); - - // Zero? - if (!xc[0]) return alphabet.charAt(0); - - // Does str represent an integer? If so, no need for the division. - if (i < 0) { - --e; - } else { - x.c = xc; - x.e = e; - - // The sign is needed for correct rounding. - x.s = sign; - x = div(x, y, dp, rm, baseOut); - xc = x.c; - r = x.r; - e = x.e; - } - - // xc now represents str converted to baseOut. - - // THe index of the rounding digit. - d = e + dp + 1; - - // The rounding digit: the digit to the right of the digit that may be rounded up. - i = xc[d]; - - // Look at the rounding digits and mode to determine whether to round up. - - k = baseOut / 2; - r = r || d < 0 || xc[d + 1] != null; - - r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || - rm == (x.s < 0 ? 8 : 7)); - - // If the index of the rounding digit is not greater than zero, or xc represents - // zero, then the result of the base conversion is zero or, if rounding up, a value - // such as 0.00001. - if (d < 1 || !xc[0]) { - - // 1^-dp or 0 - str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); - } else { - - // Truncate xc to the required number of decimal places. - xc.length = d; - - // Round up? - if (r) { - - // Rounding up may mean the previous digit has to be rounded up and so on. - for (--baseOut; ++xc[--d] > baseOut;) { - xc[d] = 0; - - if (!d) { - ++e; - xc = [1].concat(xc); - } - } - } - - // Determine trailing zeros. - for (k = xc.length; !xc[--k];); - - // E.g. [4, 11, 15] becomes 4bf. - for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); - - // Add leading zeros, decimal point and trailing zeros as required. - str = toFixedPoint(str, e, alphabet.charAt(0)); - } - - // The caller will add the sign. - return str; - }; - })(); - - - // Perform division in the specified base. Called by div and convertBase. - div = (function () { - - // Assume non-zero x and k. - function multiply(x, k, base) { - var m, temp, xlo, xhi, - carry = 0, - i = x.length, - klo = k % SQRT_BASE, - khi = k / SQRT_BASE | 0; - - for (x = x.slice(); i--;) { - xlo = x[i] % SQRT_BASE; - xhi = x[i] / SQRT_BASE | 0; - m = khi * xlo + xhi * klo; - temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; - carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; - x[i] = temp % base; - } - - if (carry) x = [carry].concat(x); - - return x; - } - - function compare(a, b, aL, bL) { - var i, cmp; - - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - - for (i = cmp = 0; i < aL; i++) { - - if (a[i] != b[i]) { - cmp = a[i] > b[i] ? 1 : -1; - break; - } - } - } - - return cmp; - } - - function subtract(a, b, aL, base) { - var i = 0; - - // Subtract b from a. - for (; aL--;) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - - // Remove leading zeros. - for (; !a[0] && a.length > 1; a.splice(0, 1)); - } - - // x: dividend, y: divisor. - return function (x, y, dp, rm, base) { - var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, - yL, yz, - s = x.s == y.s ? 1 : -1, - xc = x.c, - yc = y.c; - - // Either NaN, Infinity or 0? - if (!xc || !xc[0] || !yc || !yc[0]) { - - return new BigNumber( - - // Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : - - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s * 0 : s / 0 - ); - } - - q = new BigNumber(s); - qc = q.c = []; - e = x.e - y.e; - s = dp + e + 1; - - if (!base) { - base = BASE; - e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); - s = s / LOG_BASE | 0; - } - - // Result exponent may be one less then the current value of e. - // The coefficients of the BigNumbers from convertBase may have trailing zeros. - for (i = 0; yc[i] == (xc[i] || 0); i++); - - if (yc[i] > (xc[i] || 0)) e--; - - if (s < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i = 0; - s += 2; - - // Normalise xc and yc so highest order digit of yc is >= base / 2. - - n = mathfloor(base / (yc[0] + 1)); - - // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. - // if (n > 1 || n++ == 1 && yc[0] < base / 2) { - if (n > 1) { - yc = multiply(yc, n, base); - xc = multiply(xc, n, base); - yL = yc.length; - xL = xc.length; - } - - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - - // Add zeros to make remainder as long as divisor. - for (; remL < yL; rem[remL++] = 0); - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base / 2) yc0++; - // Not necessary, but to prevent trial digit n > base, when using base 3. - // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; - - do { - n = 0; - - // Compare divisor and remainder. - cmp = compare(yc, rem, yL, remL); - - // If divisor < remainder. - if (cmp < 0) { - - // Calculate trial digit, n. - - rem0 = rem[0]; - if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - - // n is how many times the divisor goes into the current remainder. - n = mathfloor(rem0 / yc0); - - // Algorithm: - // product = divisor multiplied by trial digit (n). - // Compare product and remainder. - // If product is greater than remainder: - // Subtract divisor from product, decrement trial digit. - // Subtract product from remainder. - // If product was less than remainder at the last compare: - // Compare new remainder and divisor. - // If remainder is greater than divisor: - // Subtract divisor from remainder, increment trial digit. - - if (n > 1) { - - // n may be > base only when base is 3. - if (n >= base) n = base - 1; - - // product = divisor * trial digit. - prod = multiply(yc, n, base); - prodL = prod.length; - remL = rem.length; - - // Compare product and remainder. - // If product > remainder then trial digit n too high. - // n is 1 too high about 5% of the time, and is not known to have - // ever been more than 1 too high. - while (compare(prod, rem, prodL, remL) == 1) { - n--; - - // Subtract divisor from product. - subtract(prod, yL < prodL ? yz : yc, prodL, base); - prodL = prod.length; - cmp = 1; - } - } else { - - // n is 0 or 1, cmp is -1. - // If n is 0, there is no need to compare yc and rem again below, - // so change cmp to 1 to avoid it. - // If n is 1, leave cmp as -1, so yc and rem are compared again. - if (n == 0) { - - // divisor < remainder, so n must be at least 1. - cmp = n = 1; - } - - // product = divisor - prod = yc.slice(); - prodL = prod.length; - } - - if (prodL < remL) prod = [0].concat(prod); - - // Subtract product from remainder. - subtract(rem, prod, remL, base); - remL = rem.length; - - // If product was < remainder. - if (cmp == -1) { - - // Compare divisor and new remainder. - // If divisor < new remainder, subtract divisor from remainder. - // Trial digit n too low. - // n is 1 too low about 5% of the time, and very rarely 2 too low. - while (compare(yc, rem, yL, remL) < 1) { - n++; - - // Subtract divisor from remainder. - subtract(rem, yL < remL ? yz : yc, remL, base); - remL = rem.length; - } - } - } else if (cmp === 0) { - n++; - rem = [0]; - } // else cmp === 1 and n will be 0 - - // Add the next digit, n, to the result array. - qc[i++] = n; - - // Update the remainder. - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s--); - - more = rem[0] != null; - - // Leading zero? - if (!qc[0]) qc.splice(0, 1); - } - - if (base == BASE) { - - // To calculate q.e, first get the number of digits of qc[0]. - for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); - - round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); - - // Caller is convertBase. - } else { - q.e = e; - q.r = +more; - } - - return q; - }; - })(); - - - /* - * Return a string representing the value of BigNumber n in fixed-point or exponential - * notation rounded to the specified decimal places or significant digits. - * - * n: a BigNumber. - * i: the index of the last digit required (i.e. the digit that may be rounded up). - * rm: the rounding mode. - * id: 1 (toExponential) or 2 (toPrecision). - */ - function format(n, i, rm, id) { - var c0, e, ne, len, str; - - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - - if (!n.c) return n.toString(); - - c0 = n.c[0]; - ne = n.e; - - if (i == null) { - str = coeffToString(n.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) - ? toExponential(str, ne) - : toFixedPoint(str, ne, '0'); - } else { - n = round(new BigNumber(n), i, rm); - - // n.e may have changed if the value was rounded up. - e = n.e; - - str = coeffToString(n.c); - len = str.length; - - // toPrecision returns exponential notation if the number of significant digits - // specified is less than the number of digits necessary to represent the integer - // part of the value in fixed-point notation. - - // Exponential notation. - if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { - - // Append zeros? - for (; len < i; str += '0', len++); - str = toExponential(str, e); - - // Fixed-point notation. - } else { - i -= ne; - str = toFixedPoint(str, e, '0'); - - // Append zeros? - if (e + 1 > len) { - if (--i > 0) for (str += '.'; i--; str += '0'); - } else { - i += e - len; - if (i > 0) { - if (e + 1 == len) str += '.'; - for (; i--; str += '0'); - } - } - } - } - - return n.s < 0 && c0 ? '-' + str : str; - } - - - // Handle BigNumber.max and BigNumber.min. - function maxOrMin(args, method) { - var n, - i = 1, - m = new BigNumber(args[0]); - - for (; i < args.length; i++) { - n = new BigNumber(args[i]); - - // If any number is NaN, return NaN. - if (!n.s) { - m = n; - break; - } else if (method.call(m, n)) { - m = n; - } - } - - return m; - } - - - /* - * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. - * Called by minus, plus and times. - */ - function normalise(n, c, e) { - var i = 1, - j = c.length; - - // Remove trailing zeros. - for (; !c[--j]; c.pop()); - - // Calculate the base 10 exponent. First get the number of digits of c[0]. - for (j = c[0]; j >= 10; j /= 10, i++); - - // Overflow? - if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { - - // Infinity. - n.c = n.e = null; - - // Underflow? - } else if (e < MIN_EXP) { - - // Zero. - n.c = [n.e = 0]; - } else { - n.e = e; - n.c = c; - } - - return n; - } - - - // Handle values that fail the validity test in BigNumber. - parseNumeric = (function () { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, - dotAfter = /^([^.]+)\.$/, - dotBefore = /^\.([^.]+)$/, - isInfinityOrNaN = /^-?(Infinity|NaN)$/, - whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - - return function (x, str, isNum, b) { - var base, - s = isNum ? str : str.replace(whitespaceOrPlus, ''); - - // No exception on ±Infinity or NaN. - if (isInfinityOrNaN.test(s)) { - x.s = isNaN(s) ? null : s < 0 ? -1 : 1; - } else { - if (!isNum) { - - // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i - s = s.replace(basePrefix, function (m, p1, p2) { - base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; - return !b || b == base ? p1 : m; - }); - - if (b) { - base = b; - - // E.g. '1.' to '1', '.1' to '0.1' - s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); - } - - if (str != s) return new BigNumber(s, base); - } - - // '[BigNumber Error] Not a number: {n}' - // '[BigNumber Error] Not a base {b} number: {n}' - if (BigNumber.DEBUG) { - throw Error - (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); - } - - // NaN - x.s = null; - } - - x.c = x.e = null; - } - })(); - - - /* - * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. - * If r is truthy, it is known that there are more digits after the rounding digit. - */ - function round(x, sd, rm, r) { - var d, i, j, k, n, ni, rd, - xc = x.c, - pows10 = POWS_TEN; - - // if x is not Infinity or NaN... - if (xc) { - - // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. - // n is a base 1e14 number, the value of the element of array x.c containing rd. - // ni is the index of n within x.c. - // d is the number of digits of n. - // i is the index of rd within n including leading zeros. - // j is the actual index of rd within n (if < 0, rd is a leading zero). - out: { - - // Get the number of digits of the first element of xc. - for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); - i = sd - d; - - // If the rounding digit is in the first element of xc... - if (i < 0) { - i += LOG_BASE; - j = sd; - n = xc[ni = 0]; - - // Get the rounding digit at index j of n. - rd = n / pows10[d - j - 1] % 10 | 0; - } else { - ni = mathceil((i + 1) / LOG_BASE); - - if (ni >= xc.length) { - - if (r) { - - // Needed by sqrt. - for (; xc.length <= ni; xc.push(0)); - n = rd = 0; - d = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; - } else { - break out; - } - } else { - n = k = xc[ni]; - - // Get the number of digits of n. - for (d = 1; k >= 10; k /= 10, d++); - - // Get the index of rd within n. - i %= LOG_BASE; - - // Get the index of rd within n, adjusted for leading zeros. - // The number of leading zeros of n is given by LOG_BASE - d. - j = i - LOG_BASE + d; - - // Get the rounding digit at index j of n. - rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; - } - } - - r = r || sd < 0 || - - // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); - - r = rm < 4 - ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && - - // Check whether the digit to the left of the rounding digit is odd. - ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || - rm == (x.s < 0 ? 8 : 7)); - - if (sd < 1 || !xc[0]) { - xc.length = 0; - - if (r) { - - // Convert sd to decimal places. - sd -= x.e + 1; - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; - x.e = -sd || 0; - } else { - - // Zero. - xc[0] = x.e = 0; - } - - return x; - } - - // Remove excess digits. - if (i == 0) { - xc.length = ni; - k = 1; - ni--; - } else { - xc.length = ni + 1; - k = pows10[LOG_BASE - i]; - - // E.g. 56700 becomes 56000 if 7 is the rounding digit. - // j > 0 means i > number of leading zeros of n. - xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; - } - - // Round up? - if (r) { - - for (; ;) { - - // If the digit to be rounded up is in the first element of xc... - if (ni == 0) { - - // i will be the length of xc[0] before k is added. - for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); - j = xc[0] += k; - for (k = 1; j >= 10; j /= 10, k++); - - // if i != k the length has increased. - if (i != k) { - x.e++; - if (xc[0] == BASE) xc[0] = 1; - } - - break; - } else { - xc[ni] += k; - if (xc[ni] != BASE) break; - xc[ni--] = 0; - k = 1; - } - } - } - - // Remove trailing zeros. - for (i = xc.length; xc[--i] === 0; xc.pop()); - } - - // Overflow? Infinity. - if (x.e > MAX_EXP) { - x.c = x.e = null; - - // Underflow? Zero. - } else if (x.e < MIN_EXP) { - x.c = [x.e = 0]; - } - } - - return x; - } - - - function valueOf(n) { - var str, - e = n.e; - - if (e === null) return n.toString(); - - str = coeffToString(n.c); - - str = e <= TO_EXP_NEG || e >= TO_EXP_POS - ? toExponential(str, e) - : toFixedPoint(str, e, '0'); - - return n.s < 0 ? '-' + str : str; - } - - - // PROTOTYPE/INSTANCE METHODS - - - /* - * Return a new BigNumber whose value is the absolute value of this BigNumber. - */ - P.absoluteValue = P.abs = function () { - var x = new BigNumber(this); - if (x.s < 0) x.s = 1; - return x; - }; - - - /* - * Return - * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), - * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), - * 0 if they have the same value, - * or null if the value of either is NaN. - */ - P.comparedTo = function (y, b) { - return compare(this, new BigNumber(y, b)); - }; - - - /* - * If dp is undefined or null or true or false, return the number of decimal places of the - * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. - * - * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this - * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or - * ROUNDING_MODE if rm is omitted. - * - * [dp] {number} Decimal places: integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.decimalPlaces = P.dp = function (dp, rm) { - var c, n, v, - x = this; - - if (dp != null) { - intCheck(dp, 0, MAX); - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - - return round(new BigNumber(x), dp + x.e + 1, rm); - } - - if (!(c = x.c)) return null; - n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; - - // Subtract the number of trailing zeros of the last number. - if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); - if (n < 0) n = 0; - - return n; - }; - - - /* - * n / 0 = I - * n / N = N - * n / I = 0 - * 0 / n = 0 - * 0 / 0 = N - * 0 / N = N - * 0 / I = 0 - * N / n = N - * N / 0 = N - * N / N = N - * N / I = N - * I / n = I - * I / 0 = I - * I / N = N - * I / I = N - * - * Return a new BigNumber whose value is the value of this BigNumber divided by the value of - * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. - */ - P.dividedBy = P.div = function (y, b) { - return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); - }; - - - /* - * Return a new BigNumber whose value is the integer part of dividing the value of this - * BigNumber by the value of BigNumber(y, b). - */ - P.dividedToIntegerBy = P.idiv = function (y, b) { - return div(this, new BigNumber(y, b), 0, 1); - }; - - - /* - * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. - * - * If m is present, return the result modulo m. - * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. - * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. - * - * The modular power operation works efficiently when x, n, and m are integers, otherwise it - * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. - * - * n {number|string|BigNumber} The exponent. An integer. - * [m] {number|string|BigNumber} The modulus. - * - * '[BigNumber Error] Exponent not an integer: {n}' - */ - P.exponentiatedBy = P.pow = function (n, m) { - var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, - x = this; - - n = new BigNumber(n); - - // Allow NaN and ±Infinity, but not other non-integers. - if (n.c && !n.isInteger()) { - throw Error - (bignumberError + 'Exponent not an integer: ' + valueOf(n)); - } - - if (m != null) m = new BigNumber(m); - - // Exponent of MAX_SAFE_INTEGER is 15. - nIsBig = n.e > 14; - - // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. - if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { - - // The sign of the result of pow when x is negative depends on the evenness of n. - // If +n overflows to ±Infinity, the evenness of n would be not be known. - y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n))); - return m ? y.mod(m) : y; - } - - nIsNeg = n.s < 0; - - if (m) { - - // x % m returns NaN if abs(m) is zero, or m is NaN. - if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); - - isModExp = !nIsNeg && x.isInteger() && m.isInteger(); - - if (isModExp) x = x.mod(m); - - // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. - // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. - } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 - // [1, 240000000] - ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 - // [80000000000000] [99999750000000] - : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { - - // If x is negative and n is odd, k = -0, else k = 0. - k = x.s < 0 && isOdd(n) ? -0 : 0; - - // If x >= 1, k = ±Infinity. - if (x.e > -1) k = 1 / k; - - // If n is negative return ±0, else return ±Infinity. - return new BigNumber(nIsNeg ? 1 / k : k); - - } else if (POW_PRECISION) { - - // Truncating each coefficient array to a length of k after each multiplication - // equates to truncating significant digits to POW_PRECISION + [28, 41], - // i.e. there will be a minimum of 28 guard digits retained. - k = mathceil(POW_PRECISION / LOG_BASE + 2); - } - - if (nIsBig) { - half = new BigNumber(0.5); - if (nIsNeg) n.s = 1; - nIsOdd = isOdd(n); - } else { - i = Math.abs(+valueOf(n)); - nIsOdd = i % 2; - } - - y = new BigNumber(ONE); - - // Performs 54 loop iterations for n of 9007199254740991. - for (; ;) { - - if (nIsOdd) { - y = y.times(x); - if (!y.c) break; - - if (k) { - if (y.c.length > k) y.c.length = k; - } else if (isModExp) { - y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); - } - } - - if (i) { - i = mathfloor(i / 2); - if (i === 0) break; - nIsOdd = i % 2; - } else { - n = n.times(half); - round(n, n.e + 1, 1); - - if (n.e > 14) { - nIsOdd = isOdd(n); - } else { - i = +valueOf(n); - if (i === 0) break; - nIsOdd = i % 2; - } - } - - x = x.times(x); - - if (k) { - if (x.c && x.c.length > k) x.c.length = k; - } else if (isModExp) { - x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); - } - } - - if (isModExp) return y; - if (nIsNeg) y = ONE.div(y); - - return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer - * using rounding mode rm, or ROUNDING_MODE if rm is omitted. - * - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' - */ - P.integerValue = function (rm) { - var n = new BigNumber(this); - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - return round(n, n.e + 1, rm); - }; - - - /* - * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), - * otherwise return false. - */ - P.isEqualTo = P.eq = function (y, b) { - return compare(this, new BigNumber(y, b)) === 0; - }; - - - /* - * Return true if the value of this BigNumber is a finite number, otherwise return false. - */ - P.isFinite = function () { - return !!this.c; - }; - - - /* - * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), - * otherwise return false. - */ - P.isGreaterThan = P.gt = function (y, b) { - return compare(this, new BigNumber(y, b)) > 0; - }; - - - /* - * Return true if the value of this BigNumber is greater than or equal to the value of - * BigNumber(y, b), otherwise return false. - */ - P.isGreaterThanOrEqualTo = P.gte = function (y, b) { - return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; - - }; - - - /* - * Return true if the value of this BigNumber is an integer, otherwise return false. - */ - P.isInteger = function () { - return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; - }; - - - /* - * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), - * otherwise return false. - */ - P.isLessThan = P.lt = function (y, b) { - return compare(this, new BigNumber(y, b)) < 0; - }; - - - /* - * Return true if the value of this BigNumber is less than or equal to the value of - * BigNumber(y, b), otherwise return false. - */ - P.isLessThanOrEqualTo = P.lte = function (y, b) { - return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; - }; - - - /* - * Return true if the value of this BigNumber is NaN, otherwise return false. - */ - P.isNaN = function () { - return !this.s; - }; - - - /* - * Return true if the value of this BigNumber is negative, otherwise return false. - */ - P.isNegative = function () { - return this.s < 0; - }; - - - /* - * Return true if the value of this BigNumber is positive, otherwise return false. - */ - P.isPositive = function () { - return this.s > 0; - }; - - - /* - * Return true if the value of this BigNumber is 0 or -0, otherwise return false. - */ - P.isZero = function () { - return !!this.c && this.c[0] == 0; - }; - - - /* - * n - 0 = n - * n - N = N - * n - I = -I - * 0 - n = -n - * 0 - 0 = 0 - * 0 - N = N - * 0 - I = -I - * N - n = N - * N - 0 = N - * N - N = N - * N - I = N - * I - n = I - * I - 0 = I - * I - N = N - * I - I = N - * - * Return a new BigNumber whose value is the value of this BigNumber minus the value of - * BigNumber(y, b). - */ - P.minus = function (y, b) { - var i, j, t, xLTy, - x = this, - a = x.s; - - y = new BigNumber(y, b); - b = y.s; - - // Either NaN? - if (!a || !b) return new BigNumber(NaN); - - // Signs differ? - if (a != b) { - y.s = -b; - return x.plus(y); - } - - var xe = x.e / LOG_BASE, - ye = y.e / LOG_BASE, - xc = x.c, - yc = y.c; - - if (!xe || !ye) { - - // Either Infinity? - if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); - - // Either zero? - if (!xc[0] || !yc[0]) { - - // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. - return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : - - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0); - } - } - - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - - // Determine which is the bigger number. - if (a = xe - ye) { - - if (xLTy = a < 0) { - a = -a; - t = xc; - } else { - ye = xe; - t = yc; - } - - t.reverse(); - - // Prepend zeros to equalise exponents. - for (b = a; b--; t.push(0)); - t.reverse(); - } else { - - // Exponents equal. Check digit by digit. - j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; - - for (a = b = 0; b < j; b++) { - - if (xc[b] != yc[b]) { - xLTy = xc[b] < yc[b]; - break; - } - } - } - - // x < y? Point xc to the array of the bigger number. - if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; - - b = (j = yc.length) - (i = xc.length); - - // Append zeros to xc if shorter. - // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. - if (b > 0) for (; b--; xc[i++] = 0); - b = BASE - 1; - - // Subtract yc from xc. - for (; j > a;) { - - if (xc[--j] < yc[j]) { - for (i = j; i && !xc[--i]; xc[i] = b); - --xc[i]; - xc[j] += BASE; - } - - xc[j] -= yc[j]; - } - - // Remove leading zeros and adjust exponent accordingly. - for (; xc[0] == 0; xc.splice(0, 1), --ye); - - // Zero? - if (!xc[0]) { - - // Following IEEE 754 (2008) 6.3, - // n - n = +0 but n - n = -0 when rounding towards -Infinity. - y.s = ROUNDING_MODE == 3 ? -1 : 1; - y.c = [y.e = 0]; - return y; - } - - // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity - // for finite x and y. - return normalise(y, xc, ye); - }; - - - /* - * n % 0 = N - * n % N = N - * n % I = n - * 0 % n = 0 - * -0 % n = -0 - * 0 % 0 = N - * 0 % N = N - * 0 % I = 0 - * N % n = N - * N % 0 = N - * N % N = N - * N % I = N - * I % n = N - * I % 0 = N - * I % N = N - * I % I = N - * - * Return a new BigNumber whose value is the value of this BigNumber modulo the value of - * BigNumber(y, b). The result depends on the value of MODULO_MODE. - */ - P.modulo = P.mod = function (y, b) { - var q, s, - x = this; - - y = new BigNumber(y, b); - - // Return NaN if x is Infinity or NaN, or y is NaN or zero. - if (!x.c || !y.s || y.c && !y.c[0]) { - return new BigNumber(NaN); - - // Return x if y is Infinity or x is zero. - } else if (!y.c || x.c && !x.c[0]) { - return new BigNumber(x); - } - - if (MODULO_MODE == 9) { - - // Euclidian division: q = sign(y) * floor(x / abs(y)) - // r = x - qy where 0 <= r < abs(y) - s = y.s; - y.s = 1; - q = div(x, y, 0, 3); - y.s = s; - q.s *= s; - } else { - q = div(x, y, 0, MODULO_MODE); - } - - y = x.minus(q.times(y)); - - // To match JavaScript %, ensure sign of zero is sign of dividend. - if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; - - return y; - }; - - - /* - * n * 0 = 0 - * n * N = N - * n * I = I - * 0 * n = 0 - * 0 * 0 = 0 - * 0 * N = N - * 0 * I = N - * N * n = N - * N * 0 = N - * N * N = N - * N * I = N - * I * n = I - * I * 0 = N - * I * N = N - * I * I = I - * - * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value - * of BigNumber(y, b). - */ - P.multipliedBy = P.times = function (y, b) { - var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, - base, sqrtBase, - x = this, - xc = x.c, - yc = (y = new BigNumber(y, b)).c; - - // Either NaN, ±Infinity or ±0? - if (!xc || !yc || !xc[0] || !yc[0]) { - - // Return NaN if either is NaN, or one is 0 and the other is Infinity. - if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y.c = y.e = y.s = null; - } else { - y.s *= x.s; - - // Return ±Infinity if either is ±Infinity. - if (!xc || !yc) { - y.c = y.e = null; - - // Return ±0 if either is ±0. - } else { - y.c = [0]; - y.e = 0; - } - } - - return y; - } - - e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); - y.s *= x.s; - xcL = xc.length; - ycL = yc.length; - - // Ensure xc points to longer array and xcL to its length. - if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; - - // Initialise the result array with zeros. - for (i = xcL + ycL, zc = []; i--; zc.push(0)); - - base = BASE; - sqrtBase = SQRT_BASE; - - for (i = ycL; --i >= 0;) { - c = 0; - ylo = yc[i] % sqrtBase; - yhi = yc[i] / sqrtBase | 0; - - for (k = xcL, j = i + k; j > i;) { - xlo = xc[--k] % sqrtBase; - xhi = xc[k] / sqrtBase | 0; - m = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; - c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; - zc[j--] = xlo % base; - } - - zc[j] = c; - } - - if (c) { - ++e; - } else { - zc.splice(0, 1); - } - - return normalise(y, zc, e); - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber negated, - * i.e. multiplied by -1. - */ - P.negated = function () { - var x = new BigNumber(this); - x.s = -x.s || null; - return x; - }; - - - /* - * n + 0 = n - * n + N = N - * n + I = I - * 0 + n = n - * 0 + 0 = 0 - * 0 + N = N - * 0 + I = I - * N + n = N - * N + 0 = N - * N + N = N - * N + I = N - * I + n = I - * I + 0 = I - * I + N = N - * I + I = I - * - * Return a new BigNumber whose value is the value of this BigNumber plus the value of - * BigNumber(y, b). - */ - P.plus = function (y, b) { - var t, - x = this, - a = x.s; - - y = new BigNumber(y, b); - b = y.s; - - // Either NaN? - if (!a || !b) return new BigNumber(NaN); - - // Signs differ? - if (a != b) { - y.s = -b; - return x.minus(y); - } - - var xe = x.e / LOG_BASE, - ye = y.e / LOG_BASE, - xc = x.c, - yc = y.c; - - if (!xe || !ye) { - - // Return ±Infinity if either ±Infinity. - if (!xc || !yc) return new BigNumber(a / 0); - - // Either zero? - // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. - if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); - } - - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - - // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. - if (a = xe - ye) { - if (a > 0) { - ye = xe; - t = yc; - } else { - a = -a; - t = xc; - } - - t.reverse(); - for (; a--; t.push(0)); - t.reverse(); - } - - a = xc.length; - b = yc.length; - - // Point xc to the longer array, and b to the shorter length. - if (a - b < 0) t = yc, yc = xc, xc = t, b = a; - - // Only start adding at yc.length - 1 as the further digits of xc can be ignored. - for (a = 0; b;) { - a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; - xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; - } - - if (a) { - xc = [a].concat(xc); - ++ye; - } - - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - // ye = MAX_EXP + 1 possible - return normalise(y, xc, ye); - }; - - - /* - * If sd is undefined or null or true or false, return the number of significant digits of - * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. - * If sd is true include integer-part trailing zeros in the count. - * - * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this - * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or - * ROUNDING_MODE if rm is omitted. - * - * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. - * boolean: whether to count integer-part trailing zeros: true or false. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' - */ - P.precision = P.sd = function (sd, rm) { - var c, n, v, - x = this; - - if (sd != null && sd !== !!sd) { - intCheck(sd, 1, MAX); - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - - return round(new BigNumber(x), sd, rm); - } - - if (!(c = x.c)) return null; - v = c.length - 1; - n = v * LOG_BASE + 1; - - if (v = c[v]) { - - // Subtract the number of trailing zeros of the last element. - for (; v % 10 == 0; v /= 10, n--); - - // Add the number of digits of the first element. - for (v = c[0]; v >= 10; v /= 10, n++); - } - - if (sd && x.e + 1 > n) n = x.e + 1; - - return n; - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber shifted by k places - * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. - * - * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' - */ - P.shiftedBy = function (k) { - intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); - return this.times('1e' + k); - }; - - - /* - * sqrt(-n) = N - * sqrt(N) = N - * sqrt(-I) = N - * sqrt(I) = I - * sqrt(0) = 0 - * sqrt(-0) = -0 - * - * Return a new BigNumber whose value is the square root of the value of this BigNumber, - * rounded according to DECIMAL_PLACES and ROUNDING_MODE. - */ - P.squareRoot = P.sqrt = function () { - var m, n, r, rep, t, - x = this, - c = x.c, - s = x.s, - e = x.e, - dp = DECIMAL_PLACES + 4, - half = new BigNumber('0.5'); - - // Negative/NaN/Infinity/zero? - if (s !== 1 || !c || !c[0]) { - return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); - } - - // Initial estimate. - s = Math.sqrt(+valueOf(x)); - - // Math.sqrt underflow/overflow? - // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - if (s == 0 || s == 1 / 0) { - n = coeffToString(c); - if ((n.length + e) % 2 == 0) n += '0'; - s = Math.sqrt(+n); - e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); - - if (s == 1 / 0) { - n = '1e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new BigNumber(n); - } else { - r = new BigNumber(s + ''); - } - - // Check for zero. - // r could be zero if MIN_EXP is changed after the this value was created. - // This would cause a division by zero (x/t) and hence Infinity below, which would cause - // coeffToString to throw. - if (r.c[0]) { - e = r.e; - s = e + dp; - if (s < 3) s = 0; - - // Newton-Raphson iteration. - for (; ;) { - t = r; - r = half.times(t.plus(div(x, t, dp, 1))); - - if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { - - // The exponent of r may here be one less than the final result exponent, - // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits - // are indexed correctly. - if (r.e < e) --s; - n = n.slice(s - 3, s + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits - // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the - // iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the - // exact result as the nines may infinitely repeat. - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - - if (t.times(t).eq(x)) { - r = t; - break; - } - } - - dp += 4; - s += 4; - rep = 1; - } else { - - // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact - // result. If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - round(r, r.e + DECIMAL_PLACES + 2, 1); - m = !r.times(r).eq(x); - } - - break; - } - } - } - } - - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); - }; - - - /* - * Return a string representing the value of this BigNumber in exponential notation and - * rounded using ROUNDING_MODE to dp fixed decimal places. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toExponential = function (dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp++; - } - return format(this, dp, rm, 1); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounding - * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. - * - * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', - * but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toFixed = function (dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounded - * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties - * of the format or FORMAT object (see BigNumber.set). - * - * The formatting object may contain some or all of the properties shown below. - * - * FORMAT = { - * prefix: '', - * groupSize: 3, - * secondaryGroupSize: 0, - * groupSeparator: ',', - * decimalSeparator: '.', - * fractionGroupSize: 0, - * fractionGroupSeparator: '\xA0', // non-breaking space - * suffix: '' - * }; - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * [format] {object} Formatting options. See FORMAT pbject above. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - * '[BigNumber Error] Argument not an object: {format}' - */ - P.toFormat = function (dp, rm, format) { - var str, - x = this; - - if (format == null) { - if (dp != null && rm && typeof rm == 'object') { - format = rm; - rm = null; - } else if (dp && typeof dp == 'object') { - format = dp; - dp = rm = null; - } else { - format = FORMAT; - } - } else if (typeof format != 'object') { - throw Error - (bignumberError + 'Argument not an object: ' + format); - } - - str = x.toFixed(dp, rm); - - if (x.c) { - var i, - arr = str.split('.'), - g1 = +format.groupSize, - g2 = +format.secondaryGroupSize, - groupSeparator = format.groupSeparator || '', - intPart = arr[0], - fractionPart = arr[1], - isNeg = x.s < 0, - intDigits = isNeg ? intPart.slice(1) : intPart, - len = intDigits.length; - - if (g2) i = g1, g1 = g2, g2 = i, len -= i; - - if (g1 > 0 && len > 0) { - i = len % g1 || g1; - intPart = intDigits.substr(0, i); - for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); - if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); - if (isNeg) intPart = '-' + intPart; - } - - str = fractionPart - ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) - ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), - '$&' + (format.fractionGroupSeparator || '')) - : fractionPart) - : intPart; - } - - return (format.prefix || '') + str + (format.suffix || ''); - }; - - - /* - * Return an array of two BigNumbers representing the value of this BigNumber as a simple - * fraction with an integer numerator and an integer denominator. - * The denominator will be a positive non-zero value less than or equal to the specified - * maximum denominator. If a maximum denominator is not specified, the denominator will be - * the lowest value necessary to represent the number exactly. - * - * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. - * - * '[BigNumber Error] Argument {not an integer|out of range} : {md}' - */ - P.toFraction = function (md) { - var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, - x = this, - xc = x.c; - - if (md != null) { - n = new BigNumber(md); - - // Throw if md is less than one or is not an integer, unless it is Infinity. - if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { - throw Error - (bignumberError + 'Argument ' + - (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); - } - } - - if (!xc) return new BigNumber(x); - - d = new BigNumber(ONE); - n1 = d0 = new BigNumber(ONE); - d1 = n0 = new BigNumber(ONE); - s = coeffToString(xc); - - // Determine initial denominator. - // d is a power of 10 and the minimum max denominator that specifies the value exactly. - e = d.e = s.length - x.e - 1; - d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; - md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; - - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n = new BigNumber(s); - - // n0 = d1 = 0 - n0.c[0] = 0; - - for (; ;) { - q = div(n, d, 0, 1); - d2 = d0.plus(q.times(d1)); - if (d2.comparedTo(md) == 1) break; - d0 = d1; - d1 = d2; - n1 = n0.plus(q.times(d2 = n1)); - n0 = d2; - d = n.minus(q.times(d2 = d)); - n = d2; - } - - d2 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - e = e * 2; - - // Determine which fraction is closer to x, n0/d0 or n1/d1 - r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( - div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; - - MAX_EXP = exp; - - return r; - }; - - - /* - * Return the value of this BigNumber converted to a number primitive. - */ - P.toNumber = function () { - return +valueOf(this); - }; - - - /* - * Return a string representing the value of this BigNumber rounded to sd significant digits - * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits - * necessary to represent the integer part of the value in fixed-point notation, then use - * exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' - */ - P.toPrecision = function (sd, rm) { - if (sd != null) intCheck(sd, 1, MAX); - return format(this, sd, rm, 2); - }; - - - /* - * Return a string representing the value of this BigNumber in base b, or base 10 if b is - * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and - * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent - * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than - * TO_EXP_NEG, return exponential notation. - * - * [b] {number} Integer, 2 to ALPHABET.length inclusive. - * - * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' - */ - P.toString = function (b) { - var str, - n = this, - s = n.s, - e = n.e; - - // Infinity or NaN? - if (e === null) { - if (s) { - str = 'Infinity'; - if (s < 0) str = '-' + str; - } else { - str = 'NaN'; - } - } else { - if (b == null) { - str = e <= TO_EXP_NEG || e >= TO_EXP_POS - ? toExponential(coeffToString(n.c), e) - : toFixedPoint(coeffToString(n.c), e, '0'); - } else if (b === 10) { - n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); - str = toFixedPoint(coeffToString(n.c), n.e, '0'); - } else { - intCheck(b, 2, ALPHABET.length, 'Base'); - str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); - } - - if (s < 0 && n.c[0]) str = '-' + str; - } - - return str; - }; - - - /* - * Return as toString, but do not accept a base argument, and include the minus sign for - * negative zero. - */ - P.valueOf = P.toJSON = function () { - return valueOf(this); - }; - - - P._isBigNumber = true; - - if (configObject != null) BigNumber.set(configObject); - - return BigNumber; - } - - - // PRIVATE HELPER FUNCTIONS - - // These functions don't need access to variables, - // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. - - - function bitFloor(n) { - var i = n | 0; - return n > 0 || n === i ? i : i - 1; - } - - - // Return a coefficient array as a string of base 10 digits. - function coeffToString(a) { - var s, z, - i = 1, - j = a.length, - r = a[0] + ''; - - for (; i < j;) { - s = a[i++] + ''; - z = LOG_BASE - s.length; - for (; z--; s = '0' + s); - r += s; - } - - // Determine trailing zeros. - for (j = r.length; r.charCodeAt(--j) === 48;); - - return r.slice(0, j + 1 || 1); - } - - - // Compare the value of BigNumbers x and y. - function compare(x, y) { - var a, b, - xc = x.c, - yc = y.c, - i = x.s, - j = y.s, - k = x.e, - l = y.e; - - // Either NaN? - if (!i || !j) return null; - - a = xc && !xc[0]; - b = yc && !yc[0]; - - // Either zero? - if (a || b) return a ? b ? 0 : -j : i; - - // Signs differ? - if (i != j) return i; - - a = i < 0; - b = k == l; - - // Either Infinity? - if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; - - // Compare exponents. - if (!b) return k > l ^ a ? 1 : -1; - - j = (k = xc.length) < (l = yc.length) ? k : l; - - // Compare digit by digit. - for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; - - // Compare lengths. - return k == l ? 0 : k > l ^ a ? 1 : -1; - } - - - /* - * Check that n is a primitive number, an integer, and in range, otherwise throw. - */ - function intCheck(n, min, max, name) { - if (n < min || n > max || n !== mathfloor(n)) { - throw Error - (bignumberError + (name || 'Argument') + (typeof n == 'number' - ? n < min || n > max ? ' out of range: ' : ' not an integer: ' - : ' not a primitive number: ') + String(n)); - } - } - - - // Assumes finite n. - function isOdd(n) { - var k = n.c.length - 1; - return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; - } - - - function toExponential(str, e) { - return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + - (e < 0 ? 'e' : 'e+') + e; - } - - - function toFixedPoint(str, e, z) { - var len, zs; - - // Negative exponent? - if (e < 0) { - - // Prepend zeros. - for (zs = z + '.'; ++e; zs += z); - str = zs + str; - - // Positive exponent - } else { - len = str.length; - - // Append zeros. - if (++e > len) { - for (zs = z, e -= len; --e; zs += z); - str += zs; - } else if (e < len) { - str = str.slice(0, e) + '.' + str.slice(e); - } - } - - return str; - } - - - // EXPORT - - - BigNumber = clone(); - BigNumber['default'] = BigNumber.BigNumber = BigNumber; - - // AMD. - if (typeof define == 'function' && define.amd) { - define(function () { return BigNumber; }); - - // Node.js and other environments that support module.exports. - } else if ( true && module.exports) { - module.exports = BigNumber; - - // Browser. - } else { - if (!globalObject) { - globalObject = typeof self != 'undefined' && self ? self : window; - } - - globalObject.BigNumber = BigNumber; - } -})(this); - - -/***/ }), - -/***/ 23664: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Buffer } = __nccwpck_require__(64293) -const symbol = Symbol.for('BufferList') - -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) - } - - BufferList._init.call(this, buf) -} - -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) - - this._bufs = [] - this.length = 0 - - if (buf) { - this.append(buf) - } -} - -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) -} - -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] - } - - let tot = 0 - - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] - } - tot = _t - } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] - - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - - return offset -} - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - - const offset = this._offset(index) - - return this._bufs[offset[0]][offset[1]] -} - -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length - } - - if (typeof end === 'number' && end < 0) { - end += this.length - } - - return this.copy(null, 0, start, end) -} - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } - - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } - - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } - - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } - - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] - - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } - - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } - - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start - - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } - - bytes -= l - - if (start) { - start = 0 - } - } - - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) - - return dst -} - -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - - if (start < 0) { - start += this.length - } - - if (end < 0) { - end += this.length - } - - if (start === end) { - return this._new() - } - - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - - if (endOffset[1] === 0) { - buffers.pop() - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) - } - - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } - - return this._new(buffers) -} - -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} - -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this - - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } - - return this -} - -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() - - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) - } - - return copy -} - -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this - } - - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() - } - - this._appendBuffer(Buffer.from(buf)) - } - - return this -} - -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} - -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } - - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - - offset = Number(offset || 0) - - if (isNaN(offset)) { - offset = 0 - } - - if (offset < 0) { - offset = this.length + offset - } - - if (offset < 0) { - offset = 0 - } - - if (search.length === 0) { - return offset > this.length ? this.length : offset - } - - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on - - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] - - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset - - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) - - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } - - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) - - if (this._match(revOffset, search)) { - return revOffset - } - - buffOffset++ - } - } - - buffOffset = 0 - } - - return -1 -} - -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } - - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false - } - } - return true -} - -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - } - - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) - -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) -} - -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] -} - -module.exports = BufferList - - -/***/ }), - -/***/ 20336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const DuplexStream = __nccwpck_require__(85519).Duplex -const inherits = __nccwpck_require__(44124) -const BufferList = __nccwpck_require__(23664) - -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) - } - - if (typeof callback === 'function') { - this._callback = callback - - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) - - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - - callback = null - } - - BufferList._init.call(this, callback) - DuplexStream.call(this) -} - -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) - -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) -} - -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback === 'function') { - callback() - } -} - -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } - - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} - -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} - -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} - -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} - -BufferListStream.isBufferList = BufferList.isBufferList - -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList - - -/***/ }), - -/***/ 97713: -/***/ ((module) => { - -"use strict"; - - -const codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error - } - - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } - } - - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; -} - -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - -module.exports.q = codes; - - -/***/ }), - -/***/ 13928: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = __nccwpck_require__(85209); - -var Writable = __nccwpck_require__(58729); - -__nccwpck_require__(44124)(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); - -/***/ }), - -/***/ 4991: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - - -module.exports = PassThrough; - -var Transform = __nccwpck_require__(26753); - -__nccwpck_require__(44124)(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; - -/***/ }), - -/***/ 85209: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = __nccwpck_require__(28614).EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = __nccwpck_require__(36238); -/**/ - - -var Buffer = __nccwpck_require__(64293).Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = __nccwpck_require__(31669); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = __nccwpck_require__(70662); - -var destroyImpl = __nccwpck_require__(36994); - -var _require = __nccwpck_require__(3533), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -__nccwpck_require__(44124)(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(13928); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(13928); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = __nccwpck_require__(37558); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = __nccwpck_require__(57039); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} - -/***/ }), - -/***/ 26753: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - -module.exports = Transform; - -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = __nccwpck_require__(13928); - -__nccwpck_require__(44124)(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} - -/***/ }), - -/***/ 58729: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: __nccwpck_require__(65278) -}; -/**/ - -/**/ - -var Stream = __nccwpck_require__(36238); -/**/ - - -var Buffer = __nccwpck_require__(64293).Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = __nccwpck_require__(36994); - -var _require = __nccwpck_require__(3533), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -__nccwpck_require__(44124)(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(13928); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(13928); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; - -/***/ }), - -/***/ 37558: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = __nccwpck_require__(12659); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; - -/***/ }), - -/***/ 70662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = __nccwpck_require__(64293), - Buffer = _require.Buffer; - -var _require2 = __nccwpck_require__(31669), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); - -/***/ }), - -/***/ 36994: -/***/ ((module) => { - -"use strict"; - // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; - -/***/ }), - -/***/ 12659: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). - - -var ERR_STREAM_PREMATURE_CLOSE = __nccwpck_require__(97713)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; - -/***/ }), - -/***/ 57039: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var ERR_INVALID_ARG_TYPE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE; - -function from(Readable, iterable, opts) { - var iterator; - - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); - - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. - - var reading = false; - - readable._read = function () { - if (!reading) { - reading = true; - next(); - } - }; - - function next() { - return _next2.apply(this, arguments); - } - - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; - - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - - return readable; -} - -module.exports = from; - -/***/ }), - -/***/ 20740: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). - - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = __nccwpck_require__(12659); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; - -/***/ }), - -/***/ 3533: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var ERR_INVALID_OPT_VALUE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; - -/***/ }), - -/***/ 36238: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(92413); - - -/***/ }), - -/***/ 85519: -/***/ ((module, exports, __nccwpck_require__) => { - -var Stream = __nccwpck_require__(92413); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(85209); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(58729); - exports.Duplex = __nccwpck_require__(13928); - exports.Transform = __nccwpck_require__(26753); - exports.PassThrough = __nccwpck_require__(4991); - exports.finished = __nccwpck_require__(12659); - exports.pipeline = __nccwpck_require__(20740); -} - - -/***/ }), - -/***/ 33717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var concatMap = __nccwpck_require__(86891); -var balanced = __nccwpck_require__(9417); - -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; -} - -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - - return expand(escapeBraces(str), true).map(unescapeBraces); -} - -function identity(e) { - return e; -} - -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} - -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} - -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } - - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - - return expansions; -} - - - -/***/ }), - -/***/ 9239: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*jshint node:true */ - -var Buffer = __nccwpck_require__(64293).Buffer; // browserify -var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; - -module.exports = bufferEq; - -function bufferEq(a, b) { - - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } - - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; - } - - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; -} - -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; - -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; - - -/***/ }), - -/***/ 78818: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const ansiStyles = __nccwpck_require__(52068); -const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); -const { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -} = __nccwpck_require__(82415); - -const {isArray} = Array; - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m' -]; - -const styles = Object.create(null); - -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); - } - - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; - -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} - -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; - - chalk.template.Instance = ChalkClass; - - return chalk.template; -}; - -function Chalk(options) { - return chalkFactory(options); -} - -for (const [styleName, style] of Object.entries(ansiStyles)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - } - }; -} - -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } -}; - -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; - -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} - -for (const model of usedModels) { - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); - -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } - - return { - open, - close, - openAll, - closeAll, - parent - }; -}; - -const createBuilder = (self, _styler, _isEmpty) => { - const builder = (...arguments_) => { - if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { - // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` - return applyStyle(builder, chalkTag(builder, ...arguments_)); - } - - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - }; - - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto); - - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; - - return builder; -}; - -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } - - let styler = self._styler; - - if (styler === undefined) { - return string; - } - - const {openAll, closeAll} = styler; - if (string.indexOf('\u001B') !== -1) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); - - styler = styler.parent; - } - } - - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); - } - - return openAll + string + closeAll; -}; - -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; - - if (!isArray(firstString) || !isArray(firstString.raw)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return strings.join(' '); - } - - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; - - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); - } - - if (template === undefined) { - template = __nccwpck_require__(20500); - } - - return template(chalk, parts.join('')); -}; - -Object.defineProperties(Chalk.prototype, styles); - -const chalk = Chalk(); // eslint-disable-line new-cap -chalk.supportsColor = stdoutColor; -chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap -chalk.stderr.supportsColor = stderrColor; - -module.exports = chalk; - - -/***/ }), - -/***/ 20500: -/***/ ((module) => { - -"use strict"; - -const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; - -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); - -function unescape(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; - - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } - - return ESCAPES.get(c) || c; -} - -function parseArguments(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; - - for (const chunk of chunks) { - const number = Number(chunk); - if (!Number.isNaN(number)) { - results.push(number); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } - - return results; -} - -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; - - const results = []; - let matches; - - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; - - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; -} - -function buildStyle(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } - - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } - - return current; -} - -module.exports = (chalk, temporary) => { - const styles = []; - const chunks = []; - let chunk = []; - - // eslint-disable-next-line max-params - temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { - if (escapeCharacter) { - chunk.push(unescape(escapeCharacter)); - } else if (style) { - const string = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } - - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(character); - } - }); - - chunks.push(chunk.join('')); - - if (styles.length > 0) { - const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMessage); - } - - return chunks.join(''); -}; - - -/***/ }), - -/***/ 82415: -/***/ ((module) => { - -"use strict"; - - -const stringReplaceAll = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } - - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -module.exports = { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -}; - - -/***/ }), - -/***/ 97074: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.supportsLanguage = exports.listLanguages = exports.highlight = void 0; -var hljs = __importStar(__nccwpck_require__(60082)); -var parse5 = __importStar(__nccwpck_require__(88933)); -var parse5_htmlparser2_tree_adapter_1 = __importDefault(__nccwpck_require__(9759)); -var theme_1 = __nccwpck_require__(81442); -function colorizeNode(node, theme, context) { - if (theme === void 0) { theme = {}; } - switch (node.type) { - case 'text': { - var text = node.data; - if (context === undefined) { - return (theme.default || theme_1.DEFAULT_THEME.default || theme_1.plain)(text); - } - return text; - } - case 'tag': { - var hljsClass = /hljs-(\w+)/.exec(node.attribs.class); - if (hljsClass) { - var token_1 = hljsClass[1]; - var nodeData = node.childNodes - .map(function (node) { return colorizeNode(node, theme, token_1); }) - .join(''); - return (theme[token_1] || theme_1.DEFAULT_THEME[token_1] || theme_1.plain)(nodeData); - } - // Return the data itself when the class name isn't prefixed with a highlight.js token prefix. - // This is common in instances of sublanguages (JSX, Markdown Code Blocks, etc.) - return node.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); - } - } - throw new Error('Invalid node type ' + node.type); -} -function colorize(code, theme) { - if (theme === void 0) { theme = {}; } - var fragment = parse5.parseFragment(code, { - treeAdapter: parse5_htmlparser2_tree_adapter_1.default, - }); - return fragment.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); -} -/** - * Apply syntax highlighting to `code` with ASCII color codes. The language is automatically - * detected if not set. - * - * ```ts - * import {highlight} from 'cli-highlight'; - * import * as fs from 'fs'; - * - * fs.readFile('package.json', 'utf8', (err: any, json: string) => { - * console.log('package.json:'); - * console.log(highlight(json)); - * }); - * ``` - * - * @param code The code to highlight - * @param options Optional options - */ -function highlight(code, options) { - if (options === void 0) { options = {}; } - var html; - if (options.language) { - html = hljs.highlight(code, { language: options.language, ignoreIllegals: options.ignoreIllegals }).value; - } - else { - html = hljs.highlightAuto(code, options.languageSubset).value; - } - return colorize(html, options.theme); -} -exports.highlight = highlight; -/** - * Returns all supported languages - */ -function listLanguages() { - return hljs.listLanguages(); -} -exports.listLanguages = listLanguages; -/** - * Returns true if the language is supported - * @param name A language name, alias or file extension - */ -function supportsLanguage(name) { - return !!hljs.getLanguage(name); -} -exports.supportsLanguage = supportsLanguage; -exports.default = highlight; -__exportStar(__nccwpck_require__(81442), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 81442: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parse = exports.stringify = exports.toJson = exports.fromJson = exports.DEFAULT_THEME = exports.plain = void 0; -var chalk_1 = __importDefault(__nccwpck_require__(78818)); -/** - * Identity function for tokens that should not be styled (returns the input string as-is). - * See [[Theme]] for an example. - */ -var plain = function (codePart) { return codePart; }; -exports.plain = plain; -/** - * The default theme. It is possible to override just individual keys. - */ -exports.DEFAULT_THEME = { - /** - * keyword in a regular Algol-style language - */ - keyword: chalk_1.default.blue, - /** - * built-in or library object (constant, class, function) - */ - built_in: chalk_1.default.cyan, - /** - * user-defined type in a language with first-class syntactically significant types, like - * Haskell - */ - type: chalk_1.default.cyan.dim, - /** - * special identifier for a built-in value ("true", "false", "null") - */ - literal: chalk_1.default.blue, - /** - * number, including units and modifiers, if any. - */ - number: chalk_1.default.green, - /** - * literal regular expression - */ - regexp: chalk_1.default.red, - /** - * literal string, character - */ - string: chalk_1.default.red, - /** - * parsed section inside a literal string - */ - subst: exports.plain, - /** - * symbolic constant, interned string, goto label - */ - symbol: exports.plain, - /** - * class or class-level declaration (interfaces, traits, modules, etc) - */ - class: chalk_1.default.blue, - /** - * function or method declaration - */ - function: chalk_1.default.yellow, - /** - * name of a class or a function at the place of declaration - */ - title: exports.plain, - /** - * block of function arguments (parameters) at the place of declaration - */ - params: exports.plain, - /** - * comment - */ - comment: chalk_1.default.green, - /** - * documentation markup within comments - */ - doctag: chalk_1.default.green, - /** - * flags, modifiers, annotations, processing instructions, preprocessor directive, etc - */ - meta: chalk_1.default.grey, - /** - * keyword or built-in within meta construct - */ - 'meta-keyword': exports.plain, - /** - * string within meta construct - */ - 'meta-string': exports.plain, - /** - * heading of a section in a config file, heading in text markup - */ - section: exports.plain, - /** - * XML/HTML tag - */ - tag: chalk_1.default.grey, - /** - * name of an XML tag, the first word in an s-expression - */ - name: chalk_1.default.blue, - /** - * s-expression name from the language standard library - */ - 'builtin-name': exports.plain, - /** - * name of an attribute with no language defined semantics (keys in JSON, setting names in - * .ini), also sub-attribute within another highlighted object, like XML tag - */ - attr: chalk_1.default.cyan, - /** - * name of an attribute followed by a structured value part, like CSS properties - */ - attribute: exports.plain, - /** - * variable in a config or a template file, environment var expansion in a script - */ - variable: exports.plain, - /** - * list item bullet in text markup - */ - bullet: exports.plain, - /** - * code block in text markup - */ - code: exports.plain, - /** - * emphasis in text markup - */ - emphasis: chalk_1.default.italic, - /** - * strong emphasis in text markup - */ - strong: chalk_1.default.bold, - /** - * mathematical formula in text markup - */ - formula: exports.plain, - /** - * hyperlink in text markup - */ - link: chalk_1.default.underline, - /** - * quotation in text markup - */ - quote: exports.plain, - /** - * tag selector in CSS - */ - 'selector-tag': exports.plain, - /** - * #id selector in CSS - */ - 'selector-id': exports.plain, - /** - * .class selector in CSS - */ - 'selector-class': exports.plain, - /** - * [attr] selector in CSS - */ - 'selector-attr': exports.plain, - /** - * :pseudo selector in CSS - */ - 'selector-pseudo': exports.plain, - /** - * tag of a template language - */ - 'template-tag': exports.plain, - /** - * variable in a template language - */ - 'template-variable': exports.plain, - /** - * added or changed line in a diff - */ - addition: chalk_1.default.green, - /** - * deleted line in a diff - */ - deletion: chalk_1.default.red, - /** - * things not matched by any token - */ - default: exports.plain, -}; -/** - * Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]]. - */ -function fromJson(json) { - var theme = {}; - for (var _i = 0, _a = Object.keys(json); _i < _a.length; _i++) { - var key = _a[_i]; - var style = json[key]; - if (Array.isArray(style)) { - ; - theme[key] = style.reduce(function (previous, current) { return (current === 'plain' ? exports.plain : previous[current]); }, chalk_1.default); - } - else { - ; - theme[key] = chalk_1.default[style]; - } - } - return theme; -} -exports.fromJson = fromJson; -/** - * Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]]. - */ -function toJson(theme) { - var jsonTheme = {}; - for (var _i = 0, _a = Object.keys(jsonTheme); _i < _a.length; _i++) { - var key = _a[_i]; - var style = jsonTheme[key]; - jsonTheme[key] = style._styles; - } - return jsonTheme; -} -exports.toJson = toJson; -/** - * Stringifies a [[Theme]] with formatter functions to a JSON string. - * - * ```ts - * import chalk = require('chalk'); - * import {stringify} from 'cli-highlight'; - * import * as fs from 'fs'; - * - * const myTheme: Theme = { - * keyword: chalk.red.bold, - * addition: chalk.green, - * deletion: chalk.red.strikethrough, - * number: plain - * } - * const json = stringify(myTheme); - * fs.writeFile('mytheme.json', json, (err: any) => { - * if (err) throw err; - * console.log('Theme saved'); - * }); - * ``` - */ -function stringify(theme) { - return JSON.stringify(toJson(theme)); -} -exports.stringify = stringify; -/** - * Parses a JSON string into a [[Theme]] with formatter functions. - * - * ```ts - * import * as fs from 'fs'; - * import {parse, highlight} from 'cli-highlight'; - * - * fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => { - * if (err) throw err; - * const code = highlight('SELECT * FROM table', {theme: parse(json)}); - * console.log(code); - * }); - * ``` - */ -function parse(json) { - return fromJson(JSON.parse(json)); -} -exports.parse = parse; -//# sourceMappingURL=theme.js.map - -/***/ }), - -/***/ 94281: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const { DOCUMENT_MODE } = __nccwpck_require__(49578); - -//Const -const VALID_DOCTYPE_NAME = 'html'; -const VALID_SYSTEM_ID = 'about:legacy-compat'; -const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; - -const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ - '+//silmaril//dtd html pro v0r11 19970101//', - '-//as//dtd html 3.0 aswedit + extensions//', - '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', - '-//ietf//dtd html 2.0 level 1//', - '-//ietf//dtd html 2.0 level 2//', - '-//ietf//dtd html 2.0 strict level 1//', - '-//ietf//dtd html 2.0 strict level 2//', - '-//ietf//dtd html 2.0 strict//', - '-//ietf//dtd html 2.0//', - '-//ietf//dtd html 2.1e//', - '-//ietf//dtd html 3.0//', - '-//ietf//dtd html 3.2 final//', - '-//ietf//dtd html 3.2//', - '-//ietf//dtd html 3//', - '-//ietf//dtd html level 0//', - '-//ietf//dtd html level 1//', - '-//ietf//dtd html level 2//', - '-//ietf//dtd html level 3//', - '-//ietf//dtd html strict level 0//', - '-//ietf//dtd html strict level 1//', - '-//ietf//dtd html strict level 2//', - '-//ietf//dtd html strict level 3//', - '-//ietf//dtd html strict//', - '-//ietf//dtd html//', - '-//metrius//dtd metrius presentational//', - '-//microsoft//dtd internet explorer 2.0 html strict//', - '-//microsoft//dtd internet explorer 2.0 html//', - '-//microsoft//dtd internet explorer 2.0 tables//', - '-//microsoft//dtd internet explorer 3.0 html strict//', - '-//microsoft//dtd internet explorer 3.0 html//', - '-//microsoft//dtd internet explorer 3.0 tables//', - '-//netscape comm. corp.//dtd html//', - '-//netscape comm. corp.//dtd strict html//', - "-//o'reilly and associates//dtd html 2.0//", - "-//o'reilly and associates//dtd html extended 1.0//", - "-//o'reilly and associates//dtd html extended relaxed 1.0//", - '-//sq//dtd html 2.0 hotmetal + extensions//', - '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', - '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', - '-//spyglass//dtd html 2.0 extended//', - '-//sun microsystems corp.//dtd hotjava html//', - '-//sun microsystems corp.//dtd hotjava strict html//', - '-//w3c//dtd html 3 1995-03-24//', - '-//w3c//dtd html 3.2 draft//', - '-//w3c//dtd html 3.2 final//', - '-//w3c//dtd html 3.2//', - '-//w3c//dtd html 3.2s draft//', - '-//w3c//dtd html 4.0 frameset//', - '-//w3c//dtd html 4.0 transitional//', - '-//w3c//dtd html experimental 19960712//', - '-//w3c//dtd html experimental 970421//', - '-//w3c//dtd w3 html//', - '-//w3o//dtd w3 html 3.0//', - '-//webtechs//dtd mozilla html 2.0//', - '-//webtechs//dtd mozilla html//' -]; - -const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat([ - '-//w3c//dtd html 4.01 frameset//', - '-//w3c//dtd html 4.01 transitional//' -]); - -const QUIRKS_MODE_PUBLIC_IDS = ['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html']; -const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//']; - -const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat([ - '-//w3c//dtd html 4.01 frameset//', - '-//w3c//dtd html 4.01 transitional//' -]); - -//Utils -function enquoteDoctypeId(id) { - const quote = id.indexOf('"') !== -1 ? "'" : '"'; - - return quote + id + quote; -} - -function hasPrefix(publicId, prefixes) { - for (let i = 0; i < prefixes.length; i++) { - if (publicId.indexOf(prefixes[i]) === 0) { - return true; - } - } - - return false; -} - -//API -exports.isConforming = function(token) { - return ( - token.name === VALID_DOCTYPE_NAME && - token.publicId === null && - (token.systemId === null || token.systemId === VALID_SYSTEM_ID) - ); -}; - -exports.getDocumentMode = function(token) { - if (token.name !== VALID_DOCTYPE_NAME) { - return DOCUMENT_MODE.QUIRKS; - } - - const systemId = token.systemId; - - if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { - return DOCUMENT_MODE.QUIRKS; - } - - let publicId = token.publicId; - - if (publicId !== null) { - publicId = publicId.toLowerCase(); - - if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1) { - return DOCUMENT_MODE.QUIRKS; - } - - let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES; - - if (hasPrefix(publicId, prefixes)) { - return DOCUMENT_MODE.QUIRKS; - } - - prefixes = - systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES; - - if (hasPrefix(publicId, prefixes)) { - return DOCUMENT_MODE.LIMITED_QUIRKS; - } - } - - return DOCUMENT_MODE.NO_QUIRKS; -}; - -exports.serializeContent = function(name, publicId, systemId) { - let str = '!DOCTYPE '; - - if (name) { - str += name; - } - - if (publicId) { - str += ' PUBLIC ' + enquoteDoctypeId(publicId); - } else if (systemId) { - str += ' SYSTEM'; - } - - if (systemId !== null) { - str += ' ' + enquoteDoctypeId(systemId); - } - - return str; -}; - - -/***/ }), - -/***/ 65510: -/***/ ((module) => { - -"use strict"; - - -module.exports = { - controlCharacterInInputStream: 'control-character-in-input-stream', - noncharacterInInputStream: 'noncharacter-in-input-stream', - surrogateInInputStream: 'surrogate-in-input-stream', - nonVoidHtmlElementStartTagWithTrailingSolidus: 'non-void-html-element-start-tag-with-trailing-solidus', - endTagWithAttributes: 'end-tag-with-attributes', - endTagWithTrailingSolidus: 'end-tag-with-trailing-solidus', - unexpectedSolidusInTag: 'unexpected-solidus-in-tag', - unexpectedNullCharacter: 'unexpected-null-character', - unexpectedQuestionMarkInsteadOfTagName: 'unexpected-question-mark-instead-of-tag-name', - invalidFirstCharacterOfTagName: 'invalid-first-character-of-tag-name', - unexpectedEqualsSignBeforeAttributeName: 'unexpected-equals-sign-before-attribute-name', - missingEndTagName: 'missing-end-tag-name', - unexpectedCharacterInAttributeName: 'unexpected-character-in-attribute-name', - unknownNamedCharacterReference: 'unknown-named-character-reference', - missingSemicolonAfterCharacterReference: 'missing-semicolon-after-character-reference', - unexpectedCharacterAfterDoctypeSystemIdentifier: 'unexpected-character-after-doctype-system-identifier', - unexpectedCharacterInUnquotedAttributeValue: 'unexpected-character-in-unquoted-attribute-value', - eofBeforeTagName: 'eof-before-tag-name', - eofInTag: 'eof-in-tag', - missingAttributeValue: 'missing-attribute-value', - missingWhitespaceBetweenAttributes: 'missing-whitespace-between-attributes', - missingWhitespaceAfterDoctypePublicKeyword: 'missing-whitespace-after-doctype-public-keyword', - missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers: - 'missing-whitespace-between-doctype-public-and-system-identifiers', - missingWhitespaceAfterDoctypeSystemKeyword: 'missing-whitespace-after-doctype-system-keyword', - missingQuoteBeforeDoctypePublicIdentifier: 'missing-quote-before-doctype-public-identifier', - missingQuoteBeforeDoctypeSystemIdentifier: 'missing-quote-before-doctype-system-identifier', - missingDoctypePublicIdentifier: 'missing-doctype-public-identifier', - missingDoctypeSystemIdentifier: 'missing-doctype-system-identifier', - abruptDoctypePublicIdentifier: 'abrupt-doctype-public-identifier', - abruptDoctypeSystemIdentifier: 'abrupt-doctype-system-identifier', - cdataInHtmlContent: 'cdata-in-html-content', - incorrectlyOpenedComment: 'incorrectly-opened-comment', - eofInScriptHtmlCommentLikeText: 'eof-in-script-html-comment-like-text', - eofInDoctype: 'eof-in-doctype', - nestedComment: 'nested-comment', - abruptClosingOfEmptyComment: 'abrupt-closing-of-empty-comment', - eofInComment: 'eof-in-comment', - incorrectlyClosedComment: 'incorrectly-closed-comment', - eofInCdata: 'eof-in-cdata', - absenceOfDigitsInNumericCharacterReference: 'absence-of-digits-in-numeric-character-reference', - nullCharacterReference: 'null-character-reference', - surrogateCharacterReference: 'surrogate-character-reference', - characterReferenceOutsideUnicodeRange: 'character-reference-outside-unicode-range', - controlCharacterReference: 'control-character-reference', - noncharacterCharacterReference: 'noncharacter-character-reference', - missingWhitespaceBeforeDoctypeName: 'missing-whitespace-before-doctype-name', - missingDoctypeName: 'missing-doctype-name', - invalidCharacterSequenceAfterDoctypeName: 'invalid-character-sequence-after-doctype-name', - duplicateAttribute: 'duplicate-attribute', - nonConformingDoctype: 'non-conforming-doctype', - missingDoctype: 'missing-doctype', - misplacedDoctype: 'misplaced-doctype', - endTagWithoutMatchingOpenElement: 'end-tag-without-matching-open-element', - closingOfElementWithOpenChildElements: 'closing-of-element-with-open-child-elements', - disallowedContentInNoscriptInHead: 'disallowed-content-in-noscript-in-head', - openElementsLeftAfterEof: 'open-elements-left-after-eof', - abandonedHeadElementChild: 'abandoned-head-element-child', - misplacedStartTagForHeadElement: 'misplaced-start-tag-for-head-element', - nestedNoscriptInHead: 'nested-noscript-in-head', - eofInElementThatCanContainOnlyText: 'eof-in-element-that-can-contain-only-text' -}; - - -/***/ }), - -/***/ 24320: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Tokenizer = __nccwpck_require__(66480); -const HTML = __nccwpck_require__(49578); - -//Aliases -const $ = HTML.TAG_NAMES; -const NS = HTML.NAMESPACES; -const ATTRS = HTML.ATTRS; - -//MIME types -const MIME_TYPES = { - TEXT_HTML: 'text/html', - APPLICATION_XML: 'application/xhtml+xml' -}; - -//Attributes -const DEFINITION_URL_ATTR = 'definitionurl'; -const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL'; -const SVG_ATTRS_ADJUSTMENT_MAP = { - attributename: 'attributeName', - attributetype: 'attributeType', - basefrequency: 'baseFrequency', - baseprofile: 'baseProfile', - calcmode: 'calcMode', - clippathunits: 'clipPathUnits', - diffuseconstant: 'diffuseConstant', - edgemode: 'edgeMode', - filterunits: 'filterUnits', - glyphref: 'glyphRef', - gradienttransform: 'gradientTransform', - gradientunits: 'gradientUnits', - kernelmatrix: 'kernelMatrix', - kernelunitlength: 'kernelUnitLength', - keypoints: 'keyPoints', - keysplines: 'keySplines', - keytimes: 'keyTimes', - lengthadjust: 'lengthAdjust', - limitingconeangle: 'limitingConeAngle', - markerheight: 'markerHeight', - markerunits: 'markerUnits', - markerwidth: 'markerWidth', - maskcontentunits: 'maskContentUnits', - maskunits: 'maskUnits', - numoctaves: 'numOctaves', - pathlength: 'pathLength', - patterncontentunits: 'patternContentUnits', - patterntransform: 'patternTransform', - patternunits: 'patternUnits', - pointsatx: 'pointsAtX', - pointsaty: 'pointsAtY', - pointsatz: 'pointsAtZ', - preservealpha: 'preserveAlpha', - preserveaspectratio: 'preserveAspectRatio', - primitiveunits: 'primitiveUnits', - refx: 'refX', - refy: 'refY', - repeatcount: 'repeatCount', - repeatdur: 'repeatDur', - requiredextensions: 'requiredExtensions', - requiredfeatures: 'requiredFeatures', - specularconstant: 'specularConstant', - specularexponent: 'specularExponent', - spreadmethod: 'spreadMethod', - startoffset: 'startOffset', - stddeviation: 'stdDeviation', - stitchtiles: 'stitchTiles', - surfacescale: 'surfaceScale', - systemlanguage: 'systemLanguage', - tablevalues: 'tableValues', - targetx: 'targetX', - targety: 'targetY', - textlength: 'textLength', - viewbox: 'viewBox', - viewtarget: 'viewTarget', - xchannelselector: 'xChannelSelector', - ychannelselector: 'yChannelSelector', - zoomandpan: 'zoomAndPan' -}; - -const XML_ATTRS_ADJUSTMENT_MAP = { - 'xlink:actuate': { prefix: 'xlink', name: 'actuate', namespace: NS.XLINK }, - 'xlink:arcrole': { prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK }, - 'xlink:href': { prefix: 'xlink', name: 'href', namespace: NS.XLINK }, - 'xlink:role': { prefix: 'xlink', name: 'role', namespace: NS.XLINK }, - 'xlink:show': { prefix: 'xlink', name: 'show', namespace: NS.XLINK }, - 'xlink:title': { prefix: 'xlink', name: 'title', namespace: NS.XLINK }, - 'xlink:type': { prefix: 'xlink', name: 'type', namespace: NS.XLINK }, - 'xml:base': { prefix: 'xml', name: 'base', namespace: NS.XML }, - 'xml:lang': { prefix: 'xml', name: 'lang', namespace: NS.XML }, - 'xml:space': { prefix: 'xml', name: 'space', namespace: NS.XML }, - xmlns: { prefix: '', name: 'xmlns', namespace: NS.XMLNS }, - 'xmlns:xlink': { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS } -}; - -//SVG tag names adjustment map -const SVG_TAG_NAMES_ADJUSTMENT_MAP = (exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = { - altglyph: 'altGlyph', - altglyphdef: 'altGlyphDef', - altglyphitem: 'altGlyphItem', - animatecolor: 'animateColor', - animatemotion: 'animateMotion', - animatetransform: 'animateTransform', - clippath: 'clipPath', - feblend: 'feBlend', - fecolormatrix: 'feColorMatrix', - fecomponenttransfer: 'feComponentTransfer', - fecomposite: 'feComposite', - feconvolvematrix: 'feConvolveMatrix', - fediffuselighting: 'feDiffuseLighting', - fedisplacementmap: 'feDisplacementMap', - fedistantlight: 'feDistantLight', - feflood: 'feFlood', - fefunca: 'feFuncA', - fefuncb: 'feFuncB', - fefuncg: 'feFuncG', - fefuncr: 'feFuncR', - fegaussianblur: 'feGaussianBlur', - feimage: 'feImage', - femerge: 'feMerge', - femergenode: 'feMergeNode', - femorphology: 'feMorphology', - feoffset: 'feOffset', - fepointlight: 'fePointLight', - fespecularlighting: 'feSpecularLighting', - fespotlight: 'feSpotLight', - fetile: 'feTile', - feturbulence: 'feTurbulence', - foreignobject: 'foreignObject', - glyphref: 'glyphRef', - lineargradient: 'linearGradient', - radialgradient: 'radialGradient', - textpath: 'textPath' -}); - -//Tags that causes exit from foreign content -const EXITS_FOREIGN_CONTENT = { - [$.B]: true, - [$.BIG]: true, - [$.BLOCKQUOTE]: true, - [$.BODY]: true, - [$.BR]: true, - [$.CENTER]: true, - [$.CODE]: true, - [$.DD]: true, - [$.DIV]: true, - [$.DL]: true, - [$.DT]: true, - [$.EM]: true, - [$.EMBED]: true, - [$.H1]: true, - [$.H2]: true, - [$.H3]: true, - [$.H4]: true, - [$.H5]: true, - [$.H6]: true, - [$.HEAD]: true, - [$.HR]: true, - [$.I]: true, - [$.IMG]: true, - [$.LI]: true, - [$.LISTING]: true, - [$.MENU]: true, - [$.META]: true, - [$.NOBR]: true, - [$.OL]: true, - [$.P]: true, - [$.PRE]: true, - [$.RUBY]: true, - [$.S]: true, - [$.SMALL]: true, - [$.SPAN]: true, - [$.STRONG]: true, - [$.STRIKE]: true, - [$.SUB]: true, - [$.SUP]: true, - [$.TABLE]: true, - [$.TT]: true, - [$.U]: true, - [$.UL]: true, - [$.VAR]: true -}; - -//Check exit from foreign content -exports.causesExit = function(startTagToken) { - const tn = startTagToken.tagName; - const isFontWithAttrs = - tn === $.FONT && - (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null || - Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null || - Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null); - - return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn]; -}; - -//Token adjustments -exports.adjustTokenMathMLAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - if (token.attrs[i].name === DEFINITION_URL_ATTR) { - token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR; - break; - } - } -}; - -exports.adjustTokenSVGAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; - - if (adjustedAttrName) { - token.attrs[i].name = adjustedAttrName; - } - } -}; - -exports.adjustTokenXMLAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; - - if (adjustedAttrEntry) { - token.attrs[i].prefix = adjustedAttrEntry.prefix; - token.attrs[i].name = adjustedAttrEntry.name; - token.attrs[i].namespace = adjustedAttrEntry.namespace; - } - } -}; - -exports.adjustTokenSVGTagName = function(token) { - const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName]; - - if (adjustedTagName) { - token.tagName = adjustedTagName; - } -}; - -//Integration points -function isMathMLTextIntegrationPoint(tn, ns) { - return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT); -} - -function isHtmlIntegrationPoint(tn, ns, attrs) { - if (ns === NS.MATHML && tn === $.ANNOTATION_XML) { - for (let i = 0; i < attrs.length; i++) { - if (attrs[i].name === ATTRS.ENCODING) { - const value = attrs[i].value.toLowerCase(); - - return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML; - } - } - } - - return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE); -} - -exports.isIntegrationPoint = function(tn, ns, attrs, foreignNS) { - if ((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) { - return true; - } - - if ((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)) { - return true; - } - - return false; -}; - - -/***/ }), - -/***/ 49578: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const NS = (exports.NAMESPACES = { - HTML: 'http://www.w3.org/1999/xhtml', - MATHML: 'http://www.w3.org/1998/Math/MathML', - SVG: 'http://www.w3.org/2000/svg', - XLINK: 'http://www.w3.org/1999/xlink', - XML: 'http://www.w3.org/XML/1998/namespace', - XMLNS: 'http://www.w3.org/2000/xmlns/' -}); - -exports.ATTRS = { - TYPE: 'type', - ACTION: 'action', - ENCODING: 'encoding', - PROMPT: 'prompt', - NAME: 'name', - COLOR: 'color', - FACE: 'face', - SIZE: 'size' -}; - -exports.DOCUMENT_MODE = { - NO_QUIRKS: 'no-quirks', - QUIRKS: 'quirks', - LIMITED_QUIRKS: 'limited-quirks' -}; - -const $ = (exports.TAG_NAMES = { - A: 'a', - ADDRESS: 'address', - ANNOTATION_XML: 'annotation-xml', - APPLET: 'applet', - AREA: 'area', - ARTICLE: 'article', - ASIDE: 'aside', - - B: 'b', - BASE: 'base', - BASEFONT: 'basefont', - BGSOUND: 'bgsound', - BIG: 'big', - BLOCKQUOTE: 'blockquote', - BODY: 'body', - BR: 'br', - BUTTON: 'button', - - CAPTION: 'caption', - CENTER: 'center', - CODE: 'code', - COL: 'col', - COLGROUP: 'colgroup', - - DD: 'dd', - DESC: 'desc', - DETAILS: 'details', - DIALOG: 'dialog', - DIR: 'dir', - DIV: 'div', - DL: 'dl', - DT: 'dt', - - EM: 'em', - EMBED: 'embed', - - FIELDSET: 'fieldset', - FIGCAPTION: 'figcaption', - FIGURE: 'figure', - FONT: 'font', - FOOTER: 'footer', - FOREIGN_OBJECT: 'foreignObject', - FORM: 'form', - FRAME: 'frame', - FRAMESET: 'frameset', - - H1: 'h1', - H2: 'h2', - H3: 'h3', - H4: 'h4', - H5: 'h5', - H6: 'h6', - HEAD: 'head', - HEADER: 'header', - HGROUP: 'hgroup', - HR: 'hr', - HTML: 'html', - - I: 'i', - IMG: 'img', - IMAGE: 'image', - INPUT: 'input', - IFRAME: 'iframe', - - KEYGEN: 'keygen', - - LABEL: 'label', - LI: 'li', - LINK: 'link', - LISTING: 'listing', - - MAIN: 'main', - MALIGNMARK: 'malignmark', - MARQUEE: 'marquee', - MATH: 'math', - MENU: 'menu', - META: 'meta', - MGLYPH: 'mglyph', - MI: 'mi', - MO: 'mo', - MN: 'mn', - MS: 'ms', - MTEXT: 'mtext', - - NAV: 'nav', - NOBR: 'nobr', - NOFRAMES: 'noframes', - NOEMBED: 'noembed', - NOSCRIPT: 'noscript', - - OBJECT: 'object', - OL: 'ol', - OPTGROUP: 'optgroup', - OPTION: 'option', - - P: 'p', - PARAM: 'param', - PLAINTEXT: 'plaintext', - PRE: 'pre', - - RB: 'rb', - RP: 'rp', - RT: 'rt', - RTC: 'rtc', - RUBY: 'ruby', - - S: 's', - SCRIPT: 'script', - SECTION: 'section', - SELECT: 'select', - SOURCE: 'source', - SMALL: 'small', - SPAN: 'span', - STRIKE: 'strike', - STRONG: 'strong', - STYLE: 'style', - SUB: 'sub', - SUMMARY: 'summary', - SUP: 'sup', - - TABLE: 'table', - TBODY: 'tbody', - TEMPLATE: 'template', - TEXTAREA: 'textarea', - TFOOT: 'tfoot', - TD: 'td', - TH: 'th', - THEAD: 'thead', - TITLE: 'title', - TR: 'tr', - TRACK: 'track', - TT: 'tt', - - U: 'u', - UL: 'ul', - - SVG: 'svg', - - VAR: 'var', - - WBR: 'wbr', - - XMP: 'xmp' -}); - -exports.SPECIAL_ELEMENTS = { - [NS.HTML]: { - [$.ADDRESS]: true, - [$.APPLET]: true, - [$.AREA]: true, - [$.ARTICLE]: true, - [$.ASIDE]: true, - [$.BASE]: true, - [$.BASEFONT]: true, - [$.BGSOUND]: true, - [$.BLOCKQUOTE]: true, - [$.BODY]: true, - [$.BR]: true, - [$.BUTTON]: true, - [$.CAPTION]: true, - [$.CENTER]: true, - [$.COL]: true, - [$.COLGROUP]: true, - [$.DD]: true, - [$.DETAILS]: true, - [$.DIR]: true, - [$.DIV]: true, - [$.DL]: true, - [$.DT]: true, - [$.EMBED]: true, - [$.FIELDSET]: true, - [$.FIGCAPTION]: true, - [$.FIGURE]: true, - [$.FOOTER]: true, - [$.FORM]: true, - [$.FRAME]: true, - [$.FRAMESET]: true, - [$.H1]: true, - [$.H2]: true, - [$.H3]: true, - [$.H4]: true, - [$.H5]: true, - [$.H6]: true, - [$.HEAD]: true, - [$.HEADER]: true, - [$.HGROUP]: true, - [$.HR]: true, - [$.HTML]: true, - [$.IFRAME]: true, - [$.IMG]: true, - [$.INPUT]: true, - [$.LI]: true, - [$.LINK]: true, - [$.LISTING]: true, - [$.MAIN]: true, - [$.MARQUEE]: true, - [$.MENU]: true, - [$.META]: true, - [$.NAV]: true, - [$.NOEMBED]: true, - [$.NOFRAMES]: true, - [$.NOSCRIPT]: true, - [$.OBJECT]: true, - [$.OL]: true, - [$.P]: true, - [$.PARAM]: true, - [$.PLAINTEXT]: true, - [$.PRE]: true, - [$.SCRIPT]: true, - [$.SECTION]: true, - [$.SELECT]: true, - [$.SOURCE]: true, - [$.STYLE]: true, - [$.SUMMARY]: true, - [$.TABLE]: true, - [$.TBODY]: true, - [$.TD]: true, - [$.TEMPLATE]: true, - [$.TEXTAREA]: true, - [$.TFOOT]: true, - [$.TH]: true, - [$.THEAD]: true, - [$.TITLE]: true, - [$.TR]: true, - [$.TRACK]: true, - [$.UL]: true, - [$.WBR]: true, - [$.XMP]: true - }, - [NS.MATHML]: { - [$.MI]: true, - [$.MO]: true, - [$.MN]: true, - [$.MS]: true, - [$.MTEXT]: true, - [$.ANNOTATION_XML]: true - }, - [NS.SVG]: { - [$.TITLE]: true, - [$.FOREIGN_OBJECT]: true, - [$.DESC]: true - } -}; - - -/***/ }), - -/***/ 4736: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const UNDEFINED_CODE_POINTS = [ - 0xfffe, - 0xffff, - 0x1fffe, - 0x1ffff, - 0x2fffe, - 0x2ffff, - 0x3fffe, - 0x3ffff, - 0x4fffe, - 0x4ffff, - 0x5fffe, - 0x5ffff, - 0x6fffe, - 0x6ffff, - 0x7fffe, - 0x7ffff, - 0x8fffe, - 0x8ffff, - 0x9fffe, - 0x9ffff, - 0xafffe, - 0xaffff, - 0xbfffe, - 0xbffff, - 0xcfffe, - 0xcffff, - 0xdfffe, - 0xdffff, - 0xefffe, - 0xeffff, - 0xffffe, - 0xfffff, - 0x10fffe, - 0x10ffff -]; - -exports.REPLACEMENT_CHARACTER = '\uFFFD'; - -exports.CODE_POINTS = { - EOF: -1, - NULL: 0x00, - TABULATION: 0x09, - CARRIAGE_RETURN: 0x0d, - LINE_FEED: 0x0a, - FORM_FEED: 0x0c, - SPACE: 0x20, - EXCLAMATION_MARK: 0x21, - QUOTATION_MARK: 0x22, - NUMBER_SIGN: 0x23, - AMPERSAND: 0x26, - APOSTROPHE: 0x27, - HYPHEN_MINUS: 0x2d, - SOLIDUS: 0x2f, - DIGIT_0: 0x30, - DIGIT_9: 0x39, - SEMICOLON: 0x3b, - LESS_THAN_SIGN: 0x3c, - EQUALS_SIGN: 0x3d, - GREATER_THAN_SIGN: 0x3e, - QUESTION_MARK: 0x3f, - LATIN_CAPITAL_A: 0x41, - LATIN_CAPITAL_F: 0x46, - LATIN_CAPITAL_X: 0x58, - LATIN_CAPITAL_Z: 0x5a, - RIGHT_SQUARE_BRACKET: 0x5d, - GRAVE_ACCENT: 0x60, - LATIN_SMALL_A: 0x61, - LATIN_SMALL_F: 0x66, - LATIN_SMALL_X: 0x78, - LATIN_SMALL_Z: 0x7a, - REPLACEMENT_CHARACTER: 0xfffd -}; - -exports.CODE_POINT_SEQUENCES = { - DASH_DASH_STRING: [0x2d, 0x2d], //-- - DOCTYPE_STRING: [0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE - CDATA_START_STRING: [0x5b, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5b], //[CDATA[ - SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script - PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4c, 0x49, 0x43], //PUBLIC - SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4d] //SYSTEM -}; - -//Surrogates -exports.isSurrogate = function(cp) { - return cp >= 0xd800 && cp <= 0xdfff; -}; - -exports.isSurrogatePair = function(cp) { - return cp >= 0xdc00 && cp <= 0xdfff; -}; - -exports.getSurrogatePairCodePoint = function(cp1, cp2) { - return (cp1 - 0xd800) * 0x400 + 0x2400 + cp2; -}; - -//NOTE: excluding NULL and ASCII whitespace -exports.isControlCodePoint = function(cp) { - return ( - (cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) || - (cp >= 0x7f && cp <= 0x9f) - ); -}; - -exports.isUndefinedCodePoint = function(cp) { - return (cp >= 0xfdd0 && cp <= 0xfdef) || UNDEFINED_CODE_POINTS.indexOf(cp) > -1; -}; - - -/***/ }), - -/***/ 45686: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Mixin = __nccwpck_require__(2830); - -class ErrorReportingMixinBase extends Mixin { - constructor(host, opts) { - super(host); - - this.posTracker = null; - this.onParseError = opts.onParseError; - } - - _setErrorLocation(err) { - err.startLine = err.endLine = this.posTracker.line; - err.startCol = err.endCol = this.posTracker.col; - err.startOffset = err.endOffset = this.posTracker.offset; - } - - _reportError(code) { - const err = { - code: code, - startLine: -1, - startCol: -1, - startOffset: -1, - endLine: -1, - endCol: -1, - endOffset: -1 - }; - - this._setErrorLocation(err); - this.onParseError(err); - } - - _getOverriddenMethods(mxn) { - return { - _err(code) { - mxn._reportError(code); - } - }; - } -} - -module.exports = ErrorReportingMixinBase; - - -/***/ }), - -/***/ 60393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const ErrorReportingMixinBase = __nccwpck_require__(45686); -const ErrorReportingTokenizerMixin = __nccwpck_require__(14703); -const LocationInfoTokenizerMixin = __nccwpck_require__(29817); -const Mixin = __nccwpck_require__(2830); - -class ErrorReportingParserMixin extends ErrorReportingMixinBase { - constructor(parser, opts) { - super(parser, opts); - - this.opts = opts; - this.ctLoc = null; - this.locBeforeToken = false; - } - - _setErrorLocation(err) { - if (this.ctLoc) { - err.startLine = this.ctLoc.startLine; - err.startCol = this.ctLoc.startCol; - err.startOffset = this.ctLoc.startOffset; - - err.endLine = this.locBeforeToken ? this.ctLoc.startLine : this.ctLoc.endLine; - err.endCol = this.locBeforeToken ? this.ctLoc.startCol : this.ctLoc.endCol; - err.endOffset = this.locBeforeToken ? this.ctLoc.startOffset : this.ctLoc.endOffset; - } - } - - _getOverriddenMethods(mxn, orig) { - return { - _bootstrap(document, fragmentContext) { - orig._bootstrap.call(this, document, fragmentContext); - - Mixin.install(this.tokenizer, ErrorReportingTokenizerMixin, mxn.opts); - Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); - }, - - _processInputToken(token) { - mxn.ctLoc = token.location; - - orig._processInputToken.call(this, token); - }, - - _err(code, options) { - mxn.locBeforeToken = options && options.beforeToken; - mxn._reportError(code); - } - }; - } -} - -module.exports = ErrorReportingParserMixin; - - -/***/ }), - -/***/ 96573: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const ErrorReportingMixinBase = __nccwpck_require__(45686); -const PositionTrackingPreprocessorMixin = __nccwpck_require__(3127); -const Mixin = __nccwpck_require__(2830); - -class ErrorReportingPreprocessorMixin extends ErrorReportingMixinBase { - constructor(preprocessor, opts) { - super(preprocessor, opts); - - this.posTracker = Mixin.install(preprocessor, PositionTrackingPreprocessorMixin); - this.lastErrOffset = -1; - } - - _reportError(code) { - //NOTE: avoid reporting error twice on advance/retreat - if (this.lastErrOffset !== this.posTracker.offset) { - this.lastErrOffset = this.posTracker.offset; - super._reportError(code); - } - } -} - -module.exports = ErrorReportingPreprocessorMixin; - - -/***/ }), - -/***/ 14703: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const ErrorReportingMixinBase = __nccwpck_require__(45686); -const ErrorReportingPreprocessorMixin = __nccwpck_require__(96573); -const Mixin = __nccwpck_require__(2830); - -class ErrorReportingTokenizerMixin extends ErrorReportingMixinBase { - constructor(tokenizer, opts) { - super(tokenizer, opts); - - const preprocessorMixin = Mixin.install(tokenizer.preprocessor, ErrorReportingPreprocessorMixin, opts); - - this.posTracker = preprocessorMixin.posTracker; - } -} - -module.exports = ErrorReportingTokenizerMixin; - - -/***/ }), - -/***/ 78020: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Mixin = __nccwpck_require__(2830); - -class LocationInfoOpenElementStackMixin extends Mixin { - constructor(stack, opts) { - super(stack); - - this.onItemPop = opts.onItemPop; - } - - _getOverriddenMethods(mxn, orig) { - return { - pop() { - mxn.onItemPop(this.current); - orig.pop.call(this); - }, - - popAllUpToHtmlElement() { - for (let i = this.stackTop; i > 0; i--) { - mxn.onItemPop(this.items[i]); - } - - orig.popAllUpToHtmlElement.call(this); - }, - - remove(element) { - mxn.onItemPop(this.current); - orig.remove.call(this, element); - } - }; - } -} - -module.exports = LocationInfoOpenElementStackMixin; - - -/***/ }), - -/***/ 703: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Mixin = __nccwpck_require__(2830); -const Tokenizer = __nccwpck_require__(66480); -const LocationInfoTokenizerMixin = __nccwpck_require__(29817); -const LocationInfoOpenElementStackMixin = __nccwpck_require__(78020); -const HTML = __nccwpck_require__(49578); - -//Aliases -const $ = HTML.TAG_NAMES; - -class LocationInfoParserMixin extends Mixin { - constructor(parser) { - super(parser); - - this.parser = parser; - this.treeAdapter = this.parser.treeAdapter; - this.posTracker = null; - this.lastStartTagToken = null; - this.lastFosterParentingLocation = null; - this.currentToken = null; - } - - _setStartLocation(element) { - let loc = null; - - if (this.lastStartTagToken) { - loc = Object.assign({}, this.lastStartTagToken.location); - loc.startTag = this.lastStartTagToken.location; - } - - this.treeAdapter.setNodeSourceCodeLocation(element, loc); - } - - _setEndLocation(element, closingToken) { - const loc = this.treeAdapter.getNodeSourceCodeLocation(element); - - if (loc) { - if (closingToken.location) { - const ctLoc = closingToken.location; - const tn = this.treeAdapter.getTagName(element); - - // NOTE: For cases like

- First 'p' closes without a closing - // tag and for cases like

- 'p' closes without a closing tag. - const isClosingEndTag = closingToken.type === Tokenizer.END_TAG_TOKEN && tn === closingToken.tagName; - - if (isClosingEndTag) { - loc.endTag = Object.assign({}, ctLoc); - loc.endLine = ctLoc.endLine; - loc.endCol = ctLoc.endCol; - loc.endOffset = ctLoc.endOffset; - } else { - loc.endLine = ctLoc.startLine; - loc.endCol = ctLoc.startCol; - loc.endOffset = ctLoc.startOffset; - } - } - } - } - - _getOverriddenMethods(mxn, orig) { - return { - _bootstrap(document, fragmentContext) { - orig._bootstrap.call(this, document, fragmentContext); - - mxn.lastStartTagToken = null; - mxn.lastFosterParentingLocation = null; - mxn.currentToken = null; - - const tokenizerMixin = Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); - - mxn.posTracker = tokenizerMixin.posTracker; - - Mixin.install(this.openElements, LocationInfoOpenElementStackMixin, { - onItemPop: function(element) { - mxn._setEndLocation(element, mxn.currentToken); - } - }); - }, - - _runParsingLoop(scriptHandler) { - orig._runParsingLoop.call(this, scriptHandler); - - // NOTE: generate location info for elements - // that remains on open element stack - for (let i = this.openElements.stackTop; i >= 0; i--) { - mxn._setEndLocation(this.openElements.items[i], mxn.currentToken); - } - }, - - //Token processing - _processTokenInForeignContent(token) { - mxn.currentToken = token; - orig._processTokenInForeignContent.call(this, token); - }, - - _processToken(token) { - mxn.currentToken = token; - orig._processToken.call(this, token); - - //NOTE: and are never popped from the stack, so we need to updated - //their end location explicitly. - const requireExplicitUpdate = - token.type === Tokenizer.END_TAG_TOKEN && - (token.tagName === $.HTML || (token.tagName === $.BODY && this.openElements.hasInScope($.BODY))); - - if (requireExplicitUpdate) { - for (let i = this.openElements.stackTop; i >= 0; i--) { - const element = this.openElements.items[i]; - - if (this.treeAdapter.getTagName(element) === token.tagName) { - mxn._setEndLocation(element, token); - break; - } - } - } - }, - - //Doctype - _setDocumentType(token) { - orig._setDocumentType.call(this, token); - - const documentChildren = this.treeAdapter.getChildNodes(this.document); - const cnLength = documentChildren.length; - - for (let i = 0; i < cnLength; i++) { - const node = documentChildren[i]; - - if (this.treeAdapter.isDocumentTypeNode(node)) { - this.treeAdapter.setNodeSourceCodeLocation(node, token.location); - break; - } - } - }, - - //Elements - _attachElementToTree(element) { - //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods. - //So we will use token location stored in this methods for the element. - mxn._setStartLocation(element); - mxn.lastStartTagToken = null; - orig._attachElementToTree.call(this, element); - }, - - _appendElement(token, namespaceURI) { - mxn.lastStartTagToken = token; - orig._appendElement.call(this, token, namespaceURI); - }, - - _insertElement(token, namespaceURI) { - mxn.lastStartTagToken = token; - orig._insertElement.call(this, token, namespaceURI); - }, - - _insertTemplate(token) { - mxn.lastStartTagToken = token; - orig._insertTemplate.call(this, token); - - const tmplContent = this.treeAdapter.getTemplateContent(this.openElements.current); - - this.treeAdapter.setNodeSourceCodeLocation(tmplContent, null); - }, - - _insertFakeRootElement() { - orig._insertFakeRootElement.call(this); - this.treeAdapter.setNodeSourceCodeLocation(this.openElements.current, null); - }, - - //Comments - _appendCommentNode(token, parent) { - orig._appendCommentNode.call(this, token, parent); - - const children = this.treeAdapter.getChildNodes(parent); - const commentNode = children[children.length - 1]; - - this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location); - }, - - //Text - _findFosterParentingLocation() { - //NOTE: store last foster parenting location, so we will be able to find inserted text - //in case of foster parenting - mxn.lastFosterParentingLocation = orig._findFosterParentingLocation.call(this); - - return mxn.lastFosterParentingLocation; - }, - - _insertCharacters(token) { - orig._insertCharacters.call(this, token); - - const hasFosterParent = this._shouldFosterParentOnInsertion(); - - const parent = - (hasFosterParent && mxn.lastFosterParentingLocation.parent) || - this.openElements.currentTmplContent || - this.openElements.current; - - const siblings = this.treeAdapter.getChildNodes(parent); - - const textNodeIdx = - hasFosterParent && mxn.lastFosterParentingLocation.beforeElement - ? siblings.indexOf(mxn.lastFosterParentingLocation.beforeElement) - 1 - : siblings.length - 1; - - const textNode = siblings[textNodeIdx]; - - //NOTE: if we have location assigned by another token, then just update end position - const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode); - - if (tnLoc) { - tnLoc.endLine = token.location.endLine; - tnLoc.endCol = token.location.endCol; - tnLoc.endOffset = token.location.endOffset; - } else { - this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location); - } - } - }; - } -} - -module.exports = LocationInfoParserMixin; - - -/***/ }), - -/***/ 29817: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Mixin = __nccwpck_require__(2830); -const Tokenizer = __nccwpck_require__(66480); -const PositionTrackingPreprocessorMixin = __nccwpck_require__(3127); - -class LocationInfoTokenizerMixin extends Mixin { - constructor(tokenizer) { - super(tokenizer); - - this.tokenizer = tokenizer; - this.posTracker = Mixin.install(tokenizer.preprocessor, PositionTrackingPreprocessorMixin); - this.currentAttrLocation = null; - this.ctLoc = null; - } - - _getCurrentLocation() { - return { - startLine: this.posTracker.line, - startCol: this.posTracker.col, - startOffset: this.posTracker.offset, - endLine: -1, - endCol: -1, - endOffset: -1 - }; - } - - _attachCurrentAttrLocationInfo() { - this.currentAttrLocation.endLine = this.posTracker.line; - this.currentAttrLocation.endCol = this.posTracker.col; - this.currentAttrLocation.endOffset = this.posTracker.offset; - - const currentToken = this.tokenizer.currentToken; - const currentAttr = this.tokenizer.currentAttr; - - if (!currentToken.location.attrs) { - currentToken.location.attrs = Object.create(null); - } - - currentToken.location.attrs[currentAttr.name] = this.currentAttrLocation; - } - - _getOverriddenMethods(mxn, orig) { - const methods = { - _createStartTagToken() { - orig._createStartTagToken.call(this); - this.currentToken.location = mxn.ctLoc; - }, - - _createEndTagToken() { - orig._createEndTagToken.call(this); - this.currentToken.location = mxn.ctLoc; - }, - - _createCommentToken() { - orig._createCommentToken.call(this); - this.currentToken.location = mxn.ctLoc; - }, - - _createDoctypeToken(initialName) { - orig._createDoctypeToken.call(this, initialName); - this.currentToken.location = mxn.ctLoc; - }, - - _createCharacterToken(type, ch) { - orig._createCharacterToken.call(this, type, ch); - this.currentCharacterToken.location = mxn.ctLoc; - }, - - _createEOFToken() { - orig._createEOFToken.call(this); - this.currentToken.location = mxn._getCurrentLocation(); - }, - - _createAttr(attrNameFirstCh) { - orig._createAttr.call(this, attrNameFirstCh); - mxn.currentAttrLocation = mxn._getCurrentLocation(); - }, - - _leaveAttrName(toState) { - orig._leaveAttrName.call(this, toState); - mxn._attachCurrentAttrLocationInfo(); - }, - - _leaveAttrValue(toState) { - orig._leaveAttrValue.call(this, toState); - mxn._attachCurrentAttrLocationInfo(); - }, - - _emitCurrentToken() { - const ctLoc = this.currentToken.location; - - //NOTE: if we have pending character token make it's end location equal to the - //current token's start location. - if (this.currentCharacterToken) { - this.currentCharacterToken.location.endLine = ctLoc.startLine; - this.currentCharacterToken.location.endCol = ctLoc.startCol; - this.currentCharacterToken.location.endOffset = ctLoc.startOffset; - } - - if (this.currentToken.type === Tokenizer.EOF_TOKEN) { - ctLoc.endLine = ctLoc.startLine; - ctLoc.endCol = ctLoc.startCol; - ctLoc.endOffset = ctLoc.startOffset; - } else { - ctLoc.endLine = mxn.posTracker.line; - ctLoc.endCol = mxn.posTracker.col + 1; - ctLoc.endOffset = mxn.posTracker.offset + 1; - } - - orig._emitCurrentToken.call(this); - }, - - _emitCurrentCharacterToken() { - const ctLoc = this.currentCharacterToken && this.currentCharacterToken.location; - - //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(), - //then set it's location at the current preprocessor position. - //We don't need to increment preprocessor position, since character token - //emission is always forced by the start of the next character token here. - //So, we already have advanced position. - if (ctLoc && ctLoc.endOffset === -1) { - ctLoc.endLine = mxn.posTracker.line; - ctLoc.endCol = mxn.posTracker.col; - ctLoc.endOffset = mxn.posTracker.offset; - } - - orig._emitCurrentCharacterToken.call(this); - } - }; - - //NOTE: patch initial states for each mode to obtain token start position - Object.keys(Tokenizer.MODE).forEach(modeName => { - const state = Tokenizer.MODE[modeName]; - - methods[state] = function(cp) { - mxn.ctLoc = mxn._getCurrentLocation(); - orig[state].call(this, cp); - }; - }); - - return methods; - } -} - -module.exports = LocationInfoTokenizerMixin; - - -/***/ }), - -/***/ 3127: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Mixin = __nccwpck_require__(2830); - -class PositionTrackingPreprocessorMixin extends Mixin { - constructor(preprocessor) { - super(preprocessor); - - this.preprocessor = preprocessor; - this.isEol = false; - this.lineStartPos = 0; - this.droppedBufferSize = 0; - - this.offset = 0; - this.col = 0; - this.line = 1; - } - - _getOverriddenMethods(mxn, orig) { - return { - advance() { - const pos = this.pos + 1; - const ch = this.html[pos]; - - //NOTE: LF should be in the last column of the line - if (mxn.isEol) { - mxn.isEol = false; - mxn.line++; - mxn.lineStartPos = pos; - } - - if (ch === '\n' || (ch === '\r' && this.html[pos + 1] !== '\n')) { - mxn.isEol = true; - } - - mxn.col = pos - mxn.lineStartPos + 1; - mxn.offset = mxn.droppedBufferSize + pos; - - return orig.advance.call(this); - }, - - retreat() { - orig.retreat.call(this); - - mxn.isEol = false; - mxn.col = this.pos - mxn.lineStartPos + 1; - }, - - dropParsedChunk() { - const prevPos = this.pos; - - orig.dropParsedChunk.call(this); - - const reduction = prevPos - this.pos; - - mxn.lineStartPos -= reduction; - mxn.droppedBufferSize += reduction; - mxn.offset = mxn.droppedBufferSize + this.pos; - } - }; - } -} - -module.exports = PositionTrackingPreprocessorMixin; - - -/***/ }), - -/***/ 88933: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Parser = __nccwpck_require__(66225); -const Serializer = __nccwpck_require__(14786); - -// Shorthands -exports.parse = function parse(html, options) { - const parser = new Parser(options); - - return parser.parse(html); -}; - -exports.parseFragment = function parseFragment(fragmentContext, html, options) { - if (typeof fragmentContext === 'string') { - options = html; - html = fragmentContext; - fragmentContext = null; - } - - const parser = new Parser(options); - - return parser.parseFragment(html, fragmentContext); -}; - -exports.serialize = function(node, options) { - const serializer = new Serializer(node, options); - - return serializer.serialize(); -}; - - -/***/ }), - -/***/ 9545: -/***/ ((module) => { - -"use strict"; - - -//Const -const NOAH_ARK_CAPACITY = 3; - -//List of formatting elements -class FormattingElementList { - constructor(treeAdapter) { - this.length = 0; - this.entries = []; - this.treeAdapter = treeAdapter; - this.bookmark = null; - } - - //Noah Ark's condition - //OPTIMIZATION: at first we try to find possible candidates for exclusion using - //lightweight heuristics without thorough attributes check. - _getNoahArkConditionCandidates(newElement) { - const candidates = []; - - if (this.length >= NOAH_ARK_CAPACITY) { - const neAttrsLength = this.treeAdapter.getAttrList(newElement).length; - const neTagName = this.treeAdapter.getTagName(newElement); - const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); - - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; - - if (entry.type === FormattingElementList.MARKER_ENTRY) { - break; - } - - const element = entry.element; - const elementAttrs = this.treeAdapter.getAttrList(element); - - const isCandidate = - this.treeAdapter.getTagName(element) === neTagName && - this.treeAdapter.getNamespaceURI(element) === neNamespaceURI && - elementAttrs.length === neAttrsLength; - - if (isCandidate) { - candidates.push({ idx: i, attrs: elementAttrs }); - } - } - } - - return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates; - } - - _ensureNoahArkCondition(newElement) { - const candidates = this._getNoahArkConditionCandidates(newElement); - let cLength = candidates.length; - - if (cLength) { - const neAttrs = this.treeAdapter.getAttrList(newElement); - const neAttrsLength = neAttrs.length; - const neAttrsMap = Object.create(null); - - //NOTE: build attrs map for the new element so we can perform fast lookups - for (let i = 0; i < neAttrsLength; i++) { - const neAttr = neAttrs[i]; - - neAttrsMap[neAttr.name] = neAttr.value; - } - - for (let i = 0; i < neAttrsLength; i++) { - for (let j = 0; j < cLength; j++) { - const cAttr = candidates[j].attrs[i]; - - if (neAttrsMap[cAttr.name] !== cAttr.value) { - candidates.splice(j, 1); - cLength--; - } - - if (candidates.length < NOAH_ARK_CAPACITY) { - return; - } - } - } - - //NOTE: remove bottommost candidates until Noah's Ark condition will not be met - for (let i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) { - this.entries.splice(candidates[i].idx, 1); - this.length--; - } - } - } - - //Mutations - insertMarker() { - this.entries.push({ type: FormattingElementList.MARKER_ENTRY }); - this.length++; - } - - pushElement(element, token) { - this._ensureNoahArkCondition(element); - - this.entries.push({ - type: FormattingElementList.ELEMENT_ENTRY, - element: element, - token: token - }); - - this.length++; - } - - insertElementAfterBookmark(element, token) { - let bookmarkIdx = this.length - 1; - - for (; bookmarkIdx >= 0; bookmarkIdx--) { - if (this.entries[bookmarkIdx] === this.bookmark) { - break; - } - } - - this.entries.splice(bookmarkIdx + 1, 0, { - type: FormattingElementList.ELEMENT_ENTRY, - element: element, - token: token - }); - - this.length++; - } - - removeEntry(entry) { - for (let i = this.length - 1; i >= 0; i--) { - if (this.entries[i] === entry) { - this.entries.splice(i, 1); - this.length--; - break; - } - } - } - - clearToLastMarker() { - while (this.length) { - const entry = this.entries.pop(); - - this.length--; - - if (entry.type === FormattingElementList.MARKER_ENTRY) { - break; - } - } - } - - //Search - getElementEntryInScopeWithTagName(tagName) { - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; - - if (entry.type === FormattingElementList.MARKER_ENTRY) { - return null; - } - - if (this.treeAdapter.getTagName(entry.element) === tagName) { - return entry; - } - } - - return null; - } - - getElementEntry(element) { - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; - - if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element) { - return entry; - } - } - - return null; - } -} - -//Entry types -FormattingElementList.MARKER_ENTRY = 'MARKER_ENTRY'; -FormattingElementList.ELEMENT_ENTRY = 'ELEMENT_ENTRY'; - -module.exports = FormattingElementList; - - -/***/ }), - -/***/ 66225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Tokenizer = __nccwpck_require__(66480); -const OpenElementStack = __nccwpck_require__(31827); -const FormattingElementList = __nccwpck_require__(9545); -const LocationInfoParserMixin = __nccwpck_require__(703); -const ErrorReportingParserMixin = __nccwpck_require__(60393); -const Mixin = __nccwpck_require__(2830); -const defaultTreeAdapter = __nccwpck_require__(37269); -const mergeOptions = __nccwpck_require__(57382); -const doctype = __nccwpck_require__(94281); -const foreignContent = __nccwpck_require__(24320); -const ERR = __nccwpck_require__(65510); -const unicode = __nccwpck_require__(4736); -const HTML = __nccwpck_require__(49578); - -//Aliases -const $ = HTML.TAG_NAMES; -const NS = HTML.NAMESPACES; -const ATTRS = HTML.ATTRS; - -const DEFAULT_OPTIONS = { - scriptingEnabled: true, - sourceCodeLocationInfo: false, - onParseError: null, - treeAdapter: defaultTreeAdapter -}; - -//Misc constants -const HIDDEN_INPUT_TYPE = 'hidden'; - -//Adoption agency loops iteration count -const AA_OUTER_LOOP_ITER = 8; -const AA_INNER_LOOP_ITER = 3; - -//Insertion modes -const INITIAL_MODE = 'INITIAL_MODE'; -const BEFORE_HTML_MODE = 'BEFORE_HTML_MODE'; -const BEFORE_HEAD_MODE = 'BEFORE_HEAD_MODE'; -const IN_HEAD_MODE = 'IN_HEAD_MODE'; -const IN_HEAD_NO_SCRIPT_MODE = 'IN_HEAD_NO_SCRIPT_MODE'; -const AFTER_HEAD_MODE = 'AFTER_HEAD_MODE'; -const IN_BODY_MODE = 'IN_BODY_MODE'; -const TEXT_MODE = 'TEXT_MODE'; -const IN_TABLE_MODE = 'IN_TABLE_MODE'; -const IN_TABLE_TEXT_MODE = 'IN_TABLE_TEXT_MODE'; -const IN_CAPTION_MODE = 'IN_CAPTION_MODE'; -const IN_COLUMN_GROUP_MODE = 'IN_COLUMN_GROUP_MODE'; -const IN_TABLE_BODY_MODE = 'IN_TABLE_BODY_MODE'; -const IN_ROW_MODE = 'IN_ROW_MODE'; -const IN_CELL_MODE = 'IN_CELL_MODE'; -const IN_SELECT_MODE = 'IN_SELECT_MODE'; -const IN_SELECT_IN_TABLE_MODE = 'IN_SELECT_IN_TABLE_MODE'; -const IN_TEMPLATE_MODE = 'IN_TEMPLATE_MODE'; -const AFTER_BODY_MODE = 'AFTER_BODY_MODE'; -const IN_FRAMESET_MODE = 'IN_FRAMESET_MODE'; -const AFTER_FRAMESET_MODE = 'AFTER_FRAMESET_MODE'; -const AFTER_AFTER_BODY_MODE = 'AFTER_AFTER_BODY_MODE'; -const AFTER_AFTER_FRAMESET_MODE = 'AFTER_AFTER_FRAMESET_MODE'; - -//Insertion mode reset map -const INSERTION_MODE_RESET_MAP = { - [$.TR]: IN_ROW_MODE, - [$.TBODY]: IN_TABLE_BODY_MODE, - [$.THEAD]: IN_TABLE_BODY_MODE, - [$.TFOOT]: IN_TABLE_BODY_MODE, - [$.CAPTION]: IN_CAPTION_MODE, - [$.COLGROUP]: IN_COLUMN_GROUP_MODE, - [$.TABLE]: IN_TABLE_MODE, - [$.BODY]: IN_BODY_MODE, - [$.FRAMESET]: IN_FRAMESET_MODE -}; - -//Template insertion mode switch map -const TEMPLATE_INSERTION_MODE_SWITCH_MAP = { - [$.CAPTION]: IN_TABLE_MODE, - [$.COLGROUP]: IN_TABLE_MODE, - [$.TBODY]: IN_TABLE_MODE, - [$.TFOOT]: IN_TABLE_MODE, - [$.THEAD]: IN_TABLE_MODE, - [$.COL]: IN_COLUMN_GROUP_MODE, - [$.TR]: IN_TABLE_BODY_MODE, - [$.TD]: IN_ROW_MODE, - [$.TH]: IN_ROW_MODE -}; - -//Token handlers map for insertion modes -const TOKEN_HANDLERS = { - [INITIAL_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInInitialMode, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInInitialMode, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: doctypeInInitialMode, - [Tokenizer.START_TAG_TOKEN]: tokenInInitialMode, - [Tokenizer.END_TAG_TOKEN]: tokenInInitialMode, - [Tokenizer.EOF_TOKEN]: tokenInInitialMode - }, - [BEFORE_HTML_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHtml, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHtml, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagBeforeHtml, - [Tokenizer.END_TAG_TOKEN]: endTagBeforeHtml, - [Tokenizer.EOF_TOKEN]: tokenBeforeHtml - }, - [BEFORE_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagBeforeHead, - [Tokenizer.END_TAG_TOKEN]: endTagBeforeHead, - [Tokenizer.EOF_TOKEN]: tokenBeforeHead - }, - [IN_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagInHead, - [Tokenizer.END_TAG_TOKEN]: endTagInHead, - [Tokenizer.EOF_TOKEN]: tokenInHead - }, - [IN_HEAD_NO_SCRIPT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInHeadNoScript, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHeadNoScript, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagInHeadNoScript, - [Tokenizer.END_TAG_TOKEN]: endTagInHeadNoScript, - [Tokenizer.EOF_TOKEN]: tokenInHeadNoScript - }, - [AFTER_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagAfterHead, - [Tokenizer.END_TAG_TOKEN]: endTagAfterHead, - [Tokenizer.EOF_TOKEN]: tokenAfterHead - }, - [IN_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInBody, - [Tokenizer.END_TAG_TOKEN]: endTagInBody, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [TEXT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: ignoreToken, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: ignoreToken, - [Tokenizer.END_TAG_TOKEN]: endTagInText, - [Tokenizer.EOF_TOKEN]: eofInText - }, - [IN_TABLE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTable, - [Tokenizer.END_TAG_TOKEN]: endTagInTable, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TABLE_TEXT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTableText, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInTableText, - [Tokenizer.COMMENT_TOKEN]: tokenInTableText, - [Tokenizer.DOCTYPE_TOKEN]: tokenInTableText, - [Tokenizer.START_TAG_TOKEN]: tokenInTableText, - [Tokenizer.END_TAG_TOKEN]: tokenInTableText, - [Tokenizer.EOF_TOKEN]: tokenInTableText - }, - [IN_CAPTION_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInCaption, - [Tokenizer.END_TAG_TOKEN]: endTagInCaption, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_COLUMN_GROUP_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInColumnGroup, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInColumnGroup, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInColumnGroup, - [Tokenizer.END_TAG_TOKEN]: endTagInColumnGroup, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TABLE_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTableBody, - [Tokenizer.END_TAG_TOKEN]: endTagInTableBody, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_ROW_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInRow, - [Tokenizer.END_TAG_TOKEN]: endTagInRow, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_CELL_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInCell, - [Tokenizer.END_TAG_TOKEN]: endTagInCell, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_SELECT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInSelect, - [Tokenizer.END_TAG_TOKEN]: endTagInSelect, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_SELECT_IN_TABLE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInSelectInTable, - [Tokenizer.END_TAG_TOKEN]: endTagInSelectInTable, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TEMPLATE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTemplate, - [Tokenizer.END_TAG_TOKEN]: endTagInTemplate, - [Tokenizer.EOF_TOKEN]: eofInTemplate - }, - [AFTER_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterBody, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToRootHtmlElement, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterBody, - [Tokenizer.END_TAG_TOKEN]: endTagAfterBody, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [IN_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInFrameset, - [Tokenizer.END_TAG_TOKEN]: endTagInFrameset, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterFrameset, - [Tokenizer.END_TAG_TOKEN]: endTagAfterFrameset, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_AFTER_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterAfterBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterAfterBody, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterBody, - [Tokenizer.END_TAG_TOKEN]: tokenAfterAfterBody, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_AFTER_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterFrameset, - [Tokenizer.END_TAG_TOKEN]: ignoreToken, - [Tokenizer.EOF_TOKEN]: stopParsing - } -}; - -//Parser -class Parser { - constructor(options) { - this.options = mergeOptions(DEFAULT_OPTIONS, options); - - this.treeAdapter = this.options.treeAdapter; - this.pendingScript = null; - - if (this.options.sourceCodeLocationInfo) { - Mixin.install(this, LocationInfoParserMixin); - } - - if (this.options.onParseError) { - Mixin.install(this, ErrorReportingParserMixin, { onParseError: this.options.onParseError }); - } - } - - // API - parse(html) { - const document = this.treeAdapter.createDocument(); - - this._bootstrap(document, null); - this.tokenizer.write(html, true); - this._runParsingLoop(null); - - return document; - } - - parseFragment(html, fragmentContext) { - //NOTE: use