diff --git a/.env.development b/.env.development index 21974f265..6f8e53c42 100644 --- a/.env.development +++ b/.env.development @@ -17,7 +17,7 @@ STUDIO_BASE_URL=http://localhost:18010 MARKETING_SITE_BASE_URL=http://localhost:18000 ORDER_HISTORY_URL=http://localhost:1996/orders REFRESH_ACCESS_TOKEN_ENDPOINT=http://localhost:18000/login_refresh -SEGMENT_KEY='' +SEGMENT_KEY= SITE_NAME=localhost USER_INFO_COOKIE_NAME=edx-user-info LOGO_URL=https://edx-cdn.org/v3/default/logo.svg @@ -27,4 +27,5 @@ FAVICON_URL=https://edx-cdn.org/v3/default/favicon.ico IGNORED_ERROR_REGEX= MFE_CONFIG_API_URL= APP_ID= -SUPPORT_URL=https://support.edx.org \ No newline at end of file +SUPPORT_URL=https://support.edx.org +PARAGON_THEME_URLS={} diff --git a/.env.test b/.env.test index f25231a3b..ab3fd28bf 100644 --- a/.env.test +++ b/.env.test @@ -28,3 +28,4 @@ IGNORED_ERROR_REGEX= MFE_CONFIG_API_URL= APP_ID= SUPPORT_URL=https://support.edx.org +PARAGON_THEME_URLS={} diff --git a/.gitignore b/.gitignore index 00b0d34c5..505b4cc39 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .idea .vscode coverage -dist src/i18n/transifex_input.json node_modules /docs/api diff --git a/dist/LICENSE b/dist/LICENSE new file mode 100644 index 000000000..dbbe35581 --- /dev/null +++ b/dist/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/dist/README.md b/dist/README.md new file mode 100644 index 000000000..9c42ab660 --- /dev/null +++ b/dist/README.md @@ -0,0 +1,155 @@ +[![Build Status](https://github.com/openedx/frontend-platform/actions/workflows/ci.yml/badge.svg)](https://github.com/openedx/frontend-platform/actions/workflows/ci.yml) +[![Codecov](https://img.shields.io/codecov/c/github/edx/frontend-platform)](https://codecov.io/gh/edx/frontend-platform) +[![NPM Version](https://img.shields.io/npm/v/@edx/frontend-platform.svg)](https://www.npmjs.com/package/@edx/frontend-platform) +[![npm_downloads](https://img.shields.io/npm/dt/@edx/frontend-platform.svg)](https://www.npmjs.com/package/@edx/frontend-platform) +[![license](https://img.shields.io/npm/l/@edx/frontend-platform.svg)](https://github.com/openedx/frontend-platform/blob/master/LICENSE) +[![semantic release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) + +# Overview + +See the [GitHub Pages site for the complete documentation](https://openedx.github.io/frontend-platform/). + +frontend-platform is a modest application framework for Open edX micro-frontend applications and their supporting libraries. It provides several foundational services that all Open edX micro-frontends should have: + +| Service | Module location | +|------------------------------------|----------------------------------| +| Analytics | @edx/frontend-platform/analytics | +| Logging | @edx/frontend-platform/logging | +| Authenticated API client (auth) | @edx/frontend-platform/auth | +| Internationalization (i18n) | @edx/frontend-platform/i18n | +| Misc (init, config, pubSub, utils) | @edx/frontend-platform | + +------------------------------------------------------------------------- + +In addition, frontend-platform provides an extensible application initialization lifecycle to help manage the configuration of the above services, freeing application developers to focus on feature development. + +## Getting started + +### One-time setup if you have not upgraded node/npm +IMPORTANT: There is now a new node/npm version being used by frontend-platform as of +https://github.com/openedx/frontend-platform/pull/259 + +#### Install nvm +This is highly recommended to be able to leverage different node/npm versions. +For a some time, different repositories may be using different versions of node/npm. + +Alternatively, please install node16 and npm8 for use with this repository. + +#### Switch to node/npm version for this repo +```nvm use``` +if you don't have the right node/npm versions, nvm will instruct you to install those + +#### Clean out old node modules and reinstall +This step is needed because node now uses a different package lock format, and it's important to reinstall +dependencies based on this new package file. Delete node_modules, and issue an `npm ci` + + +### Standard getting started steps + +1. `npm install` +2. `npm start` +3. Open http://localhost:8080 to view the example app. + +## Architecture + +The four foundational services listed above (analytics, auth, i18n, and logging) are provided as imports to applications via frontend-platform's API layer. The initialization sequence creates an instance of each service and exposes its methods as functional exports, creating a layer of abstraction between service implementations and their usage in application code. + +Each type of service has a documented API contract which service implementations must fulfill. This allows different service implementations to be used as necessary without updates to consuming applications. + +### Service architecture + +Internally, service implementations are strictly isolated from the rest of the platform. They are classes that take their dependencies as arguments to their constructor. This means, for instance, if analytics depends on logging, it takes a reference to an instance fulfilling the `LoggingService` interface as an option when it's instantiated. It cannot import from the logging module directly. Put another way, the default service implementations may be co-located with the service interfaces for convenience, but they can theoretically live in their own repository and it wouldn't require any refactoring. + +Likewise, platform code should not make use of service methods that are not part of the documented interface for the same reasons. + +### Application initialization + +frontend-platform provides an `initialize()` function which bootstraps and configures an application. The `initialize()` function uses a set of [sensible defaults](https://en.wikipedia.org/wiki/Convention_over_configuration) unless otherwise specified, bootstrapping the application with services reflecting Open edX's best practices around analytics, authentication, internationalization, and logging. + +The initialization process proceeds in a series of phases, giving the initializing application code opportunities to hook into the process and do custom setup as desired: + +- Before initialization +- Pub/Sub initialized +- Environment config document loaded +- Logging service initialized +- Authentication service initialized +- Analytics service initialized +- Internationalization service initialized +- Application ready + +Most applications won't need to do anything special at all. + +### Application configuration + +When the application loads, a list of known environment variables is loaded from `process.env` into an object which it exposes via `getConfig` - the point here is primarily to isolate our code from usages of `process.env` which may not always be the way we choose to configure our apps. The application initialization lifecycle supports runtime configuration as well via the `config` handler, documented in the [initialize function](https://edx.github.io/frontend-platform/module-Initialization.html#~initialize). If you want to get a variable into the config that it’s not expecting, you can use [`mergeConfig`](https://edx.github.io/frontend-platform/module-Config.html#~mergeConfig) during initialization to add it in from `process.env`. + +Such an example might look like this: + +``` +initialize({ + // ... other initialization options + handlers: { + config: () => { + mergeConfig({ + CUSTOM_VARIABLE: process.env.CUSTOM_VARIABLE || null, + }, 'Custom app config'); + }, + }, +}); +``` + +When using runtime configuration via `mergeConfig` noted above, `getConfig` must be called within a component's render lifecycle for the added keys and values to be returned in the configuration object. If `getConfig` is called outside of a component's render lifecycle, the custom configuration key/value pairs will not initially be part of the object returned by `getConfig`. For example: + +```jsx +import { getConfig } from '@edx/frontend-platform/config'; + +// The runtime configuration `CUSTOM_VARIABLE` added in the above code snippet will not appear here. This is +// because `getConfig` is called before `mergeConfig` is executed to add the custom runtime configuration. +console.log(getConfig().CUSTOM_VARIABLE); // returns undefined + +const ExampleComponent = () => { + // This returns the value as expected since it is called after `mergeConfig` has already been executed. + console.log(getConfig().CUSTOM_VARIABLE) +}; +``` + +### Service interfaces + +Each service (analytics, auth, i18n, logging) provided by frontend-platform has an API contract which all implementations of that service are guaranteed to fulfill. Applications that use frontend-platform can use its configured services via a convenient set of exported functions. An application that wants to use the service interfaces need only initialize them via the initialize() function, optionally providing custom service interfaces as desired (you probably won't need to). + +![Service interface](service-interface.png) + +### Service implementations + +This repository contains default service implementations for convenience. These implementations are co-located with their consuming service interfaces for ease of development, though the two should remain _strictly_ modular and separate. + +The included service implementations are: + +- New Relic (logging) +- Segment (analytics) +- Axios/JWT (auth) +- React Intl (i18n) + +NOTE: As of this writing, i18n is _not_ configurable. The `initialize()` function does not allow applications to supply an alternate i18n implementation; this is because the interface and implementation for i18n has not yet been separated and modularized. + +# Local Development & Testing Locally + +When making changes to frontend-platform, be sure to manually run the included example app located in `./example`. The example app includes 2 routes to test for both unauthenticated and authenticated users. To start the example app, run `npm start` from the root directory. + +If you want to test changes to frontend-platform against a micro-frontend locally, follow the directions here: https://github.com/openedx/frontend-build#local-module-configuration-for-webpack + +# Production Deployment Strategy + +For any MFE built on top of the frontend-platform, the deployment strategy will be something like the following: + +1. Run the build script with environment variables on the command line to pass in any relevant config. Example: + + ```bash + NODE_ENV=development BASE_URL=open.edx.org ETC=etc npm run build + ``` + + This will create a dist/ directory that contains the deployable artifacts. + +2. Copy the contents of dist/ to a web server. + +3. Configure the platform to point at your MFE. (details on this coming soon) diff --git a/dist/analytics/MockAnalyticsService.js b/dist/analytics/MockAnalyticsService.js new file mode 100644 index 000000000..4022df1b1 --- /dev/null +++ b/dist/analytics/MockAnalyticsService.js @@ -0,0 +1,75 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * The MockAnalyticsService implements all functions of AnalyticsService as Jest mocks (jest.fn())). + * It emulates the behavior of a real analytics service but witohut making any requests. It has no + * other functionality. + * + * @implements {AnalyticsService} + * @memberof module:Analytics + */ +var MockAnalyticsService = /*#__PURE__*/_createClass(function MockAnalyticsService(_ref) { + var _this = this; + var httpClient = _ref.httpClient, + loggingService = _ref.loggingService; + _classCallCheck(this, MockAnalyticsService); + _defineProperty(this, "checkIdentifyCalled", jest.fn(function () { + if (!_this.hasIdentifyBeenCalled) { + _this.loggingService.logError('Identify must be called before other tracking events.'); + } + })); + /** + * Returns a resolved promise. + * + * @returns {Promise} The promise returned by HttpClient.post. + */ + _defineProperty(this, "sendTrackingLogEvent", jest.fn(function () { + return Promise.resolve(); + })); + /** + * No-op, but records that identify has been called. + * + * @param {string} userId + * @throws {Error} If userId argument is not supplied. + */ + _defineProperty(this, "identifyAuthenticatedUser", jest.fn(function (userId) { + if (!userId) { + throw new Error('UserId is required for identifyAuthenticatedUser.'); + } + _this.hasIdentifyBeenCalled = true; + })); + /** + * No-op, but records that it has been called to prevent double-identification. + * @returns {Promise} A resolved promise. + */ + _defineProperty(this, "identifyAnonymousUser", jest.fn(function () { + _this.hasIdentifyBeenCalled = true; + return Promise.resolve(); + })); + /** + * Logs the event to the console. + * + * Checks whether identify has been called, logging an error to the logging service if not. + */ + _defineProperty(this, "sendTrackEvent", jest.fn(function () { + _this.checkIdentifyCalled(); + })); + /** + * Logs the event to the console. + * + * Checks whether identify has been called, logging an error to the logging service if not. + */ + _defineProperty(this, "sendPageEvent", jest.fn(function () { + _this.checkIdentifyCalled(); + })); + this.loggingService = loggingService; + this.httpClient = httpClient; +}); +_defineProperty(MockAnalyticsService, "hasIdentifyBeenCalled", false); +export default MockAnalyticsService; +//# sourceMappingURL=MockAnalyticsService.js.map \ No newline at end of file diff --git a/dist/analytics/MockAnalyticsService.js.map b/dist/analytics/MockAnalyticsService.js.map new file mode 100644 index 000000000..7af4b6695 --- /dev/null +++ b/dist/analytics/MockAnalyticsService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MockAnalyticsService.js","names":["MockAnalyticsService","_createClass","_ref","_this","httpClient","loggingService","_classCallCheck","_defineProperty","jest","fn","hasIdentifyBeenCalled","logError","Promise","resolve","userId","Error","checkIdentifyCalled"],"sources":["../../src/analytics/MockAnalyticsService.js"],"sourcesContent":["/**\n * The MockAnalyticsService implements all functions of AnalyticsService as Jest mocks (jest.fn())).\n * It emulates the behavior of a real analytics service but witohut making any requests. It has no\n * other functionality.\n *\n * @implements {AnalyticsService}\n * @memberof module:Analytics\n */\nclass MockAnalyticsService {\n static hasIdentifyBeenCalled = false;\n\n constructor({ httpClient, loggingService }) {\n this.loggingService = loggingService;\n this.httpClient = httpClient;\n }\n\n checkIdentifyCalled = jest.fn(() => {\n if (!this.hasIdentifyBeenCalled) {\n this.loggingService.logError('Identify must be called before other tracking events.');\n }\n });\n\n /**\n * Returns a resolved promise.\n *\n * @returns {Promise} The promise returned by HttpClient.post.\n */\n sendTrackingLogEvent = jest.fn(() => Promise.resolve());\n\n /**\n * No-op, but records that identify has been called.\n *\n * @param {string} userId\n * @throws {Error} If userId argument is not supplied.\n */\n identifyAuthenticatedUser = jest.fn((userId) => {\n if (!userId) {\n throw new Error('UserId is required for identifyAuthenticatedUser.');\n }\n this.hasIdentifyBeenCalled = true;\n });\n\n /**\n * No-op, but records that it has been called to prevent double-identification.\n * @returns {Promise} A resolved promise.\n */\n identifyAnonymousUser = jest.fn(() => {\n this.hasIdentifyBeenCalled = true;\n return Promise.resolve();\n });\n\n /**\n * Logs the event to the console.\n *\n * Checks whether identify has been called, logging an error to the logging service if not.\n */\n sendTrackEvent = jest.fn(() => {\n this.checkIdentifyCalled();\n });\n\n /**\n * Logs the event to the console.\n *\n * Checks whether identify has been called, logging an error to the logging service if not.\n */\n sendPageEvent = jest.fn(() => {\n this.checkIdentifyCalled();\n });\n}\n\nexport default MockAnalyticsService;\n"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAPA,IAQMA,oBAAoB,gBAAAC,YAAA,CAGxB,SAAAD,qBAAAE,IAAA,EAA4C;EAAA,IAAAC,KAAA;EAAA,IAA9BC,UAAU,GAAAF,IAAA,CAAVE,UAAU;IAAEC,cAAc,GAAAH,IAAA,CAAdG,cAAc;EAAAC,eAAA,OAAAN,oBAAA;EAAAO,eAAA,8BAKlBC,IAAI,CAACC,EAAE,CAAC,YAAM;IAClC,IAAI,CAACN,KAAI,CAACO,qBAAqB,EAAE;MAC/BP,KAAI,CAACE,cAAc,CAACM,QAAQ,CAAC,uDAAuD,CAAC;IACvF;EACF,CAAC,CAAC;EAEF;AACF;AACA;AACA;AACA;EAJEJ,eAAA,+BAKuBC,IAAI,CAACC,EAAE,CAAC;IAAA,OAAMG,OAAO,CAACC,OAAO,CAAC,CAAC;EAAA,EAAC;EAEvD;AACF;AACA;AACA;AACA;AACA;EALEN,eAAA,oCAM4BC,IAAI,CAACC,EAAE,CAAC,UAACK,MAAM,EAAK;IAC9C,IAAI,CAACA,MAAM,EAAE;MACX,MAAM,IAAIC,KAAK,CAAC,mDAAmD,CAAC;IACtE;IACAZ,KAAI,CAACO,qBAAqB,GAAG,IAAI;EACnC,CAAC,CAAC;EAEF;AACF;AACA;AACA;EAHEH,eAAA,gCAIwBC,IAAI,CAACC,EAAE,CAAC,YAAM;IACpCN,KAAI,CAACO,qBAAqB,GAAG,IAAI;IACjC,OAAOE,OAAO,CAACC,OAAO,CAAC,CAAC;EAC1B,CAAC,CAAC;EAEF;AACF;AACA;AACA;AACA;EAJEN,eAAA,yBAKiBC,IAAI,CAACC,EAAE,CAAC,YAAM;IAC7BN,KAAI,CAACa,mBAAmB,CAAC,CAAC;EAC5B,CAAC,CAAC;EAEF;AACF;AACA;AACA;AACA;EAJET,eAAA,wBAKgBC,IAAI,CAACC,EAAE,CAAC,YAAM;IAC5BN,KAAI,CAACa,mBAAmB,CAAC,CAAC;EAC5B,CAAC,CAAC;EAvDA,IAAI,CAACX,cAAc,GAAGA,cAAc;EACpC,IAAI,CAACD,UAAU,GAAGA,UAAU;AAC9B,CAAC;AAAAG,eAAA,CANGP,oBAAoB,2BACO,KAAK;AA6DtC,eAAeA,oBAAoB","ignoreList":[]} \ No newline at end of file diff --git a/dist/analytics/SegmentAnalyticsService.js b/dist/analytics/SegmentAnalyticsService.js new file mode 100644 index 000000000..d49fc585e --- /dev/null +++ b/dist/analytics/SegmentAnalyticsService.js @@ -0,0 +1,258 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +import formurlencoded from 'form-urlencoded'; +import { snakeCaseObject } from '../utils'; + +/** + * @implements {AnalyticsService} + * @memberof module:Analytics + */ +var SegmentAnalyticsService = /*#__PURE__*/function () { + function SegmentAnalyticsService(_ref) { + var httpClient = _ref.httpClient, + loggingService = _ref.loggingService, + config = _ref.config; + _classCallCheck(this, SegmentAnalyticsService); + this.loggingService = loggingService; + this.httpClient = httpClient; + this.trackingLogApiUrl = "".concat(config.LMS_BASE_URL, "/event"); + this.segmentKey = config.SEGMENT_KEY; + this.hasIdentifyBeenCalled = false; + this.segmentInitialized = false; + if (this.segmentKey) { + this.initializeSegment(); + } + } + + // The code in this function is from Segment's website, with a few updates: + // - It uses the segmentKey from the SegmentAnalyticsService instance. + // - It also saves a "segmentInitialized" variable on the SegmentAnalyticsService instance so + // that the service can keep track of its own initialization state. + // Reference: + // https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/quickstart/ + return _createClass(SegmentAnalyticsService, [{ + key: "initializeSegment", + value: function initializeSegment() { + var _this = this; + // Create a queue, but don't obliterate an existing one! + global.analytics = global.analytics || []; + var _global = global, + analytics = _global.analytics; + + // If the real analytics.js is already on the page return. + if (analytics.initialize) { + this.segmentInitialized = true; + return; + } + + // If the snippet was invoked do nothing. + if (analytics.invoked) { + this.segmentInitialized = true; + return; + } + + // Invoked flag, to make sure the snippet + // is never invoked twice. + analytics.invoked = true; + + // A list of the methods in Analytics.js to stub. + analytics.methods = ['trackSubmit', 'trackClick', 'trackLink', 'trackForm', 'pageview', 'identify', 'reset', 'group', 'track', 'ready', 'alias', 'debug', 'page', 'once', 'off', 'on']; + + // Define a factory to create stubs. These are placeholders + // for methods in Analytics.js so that you never have to wait + // for it to load to actually record data. The `method` is + // stored as the first argument, so we can replay the data. + analytics.factory = function (method) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + args.unshift(method); + analytics.push(args); + return analytics; + }; + }; + + // For each of our methods, generate a queueing stub. + analytics.methods.forEach(function (key) { + analytics[key] = analytics.factory(key); + }); + + // Define a method to load Analytics.js from our CDN, + // and that will be sure to only ever load it once. + analytics.load = function (key, options) { + // Create an async script element based on your key. + var script = document.createElement('script'); + script.type = 'text/javascript'; + script.onerror = function () { + _this.segmentInitialized = false; + var event = new Event('segmentFailed'); + document.dispatchEvent(event); + }; + script.async = true; + script.src = "https://cdn.segment.com/analytics.js/v1/".concat(key, "/analytics.min.js"); + + // Insert our script next to the first script element. + var first = document.getElementsByTagName('script')[0]; + first.parentNode.insertBefore(script, first); + analytics._loadOptions = options; // eslint-disable-line no-underscore-dangle + + _this.segmentInitialized = true; + }; + + // Add a version to keep track of what's in the wild. + analytics.SNIPPET_VERSION = '4.1.0'; + + // Load Analytics.js with your key, which will automatically + // load the tools you've enabled for your account. Boosh! + analytics.load(this.segmentKey); + } + + /** + * Checks that identify was first called. Otherwise, logs error. + * + */ + }, { + key: "checkIdentifyCalled", + value: function checkIdentifyCalled() { + if (!this.hasIdentifyBeenCalled) { + this.loggingService.logError('Identify must be called before other tracking events.'); + } + } + + /** + * Logs events to tracking log and downstream. + * For tracking log event documentation, see + * https://openedx.atlassian.net/wiki/spaces/AN/pages/13205895/Event+Design+and+Review+Process + * + * @param {string} eventName (event_type on backend, but named to match Segment api) + * @param {Object} properties (event on backend, but named properties to match Segment api) + * @returns {Promise} The promise returned by HttpClient.post. + */ + }, { + key: "sendTrackingLogEvent", + value: function sendTrackingLogEvent(eventName, properties) { + var _this2 = this; + var snakeEventData = snakeCaseObject(properties, { + deep: true + }); + var serverData = { + event_type: eventName, + event: JSON.stringify(snakeEventData), + page: global.location.href + }; + return this.httpClient.post(this.trackingLogApiUrl, formurlencoded(serverData), { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + })["catch"](function (error) { + _this2.loggingService.logError(error); + }); + } + + /** + * * Send identify call to Segment. + * + * @param {string} userId + * @param {*} [traits] + */ + }, { + key: "identifyAuthenticatedUser", + value: function identifyAuthenticatedUser(userId, traits) { + if (!userId) { + throw new Error('UserId is required for identifyAuthenticatedUser.'); + } + if (!this.segmentInitialized) { + return; + } + global.analytics.identify(userId, traits); + this.hasIdentifyBeenCalled = true; + } + + /** + * Send anonymous identify call to Segment's identify. + * + * @param {*} [traits] + * @returns {Promise} Promise that will resolve once the document readyState is complete + */ + }, { + key: "identifyAnonymousUser", + value: function identifyAnonymousUser(traits) { + var _this3 = this; + // eslint-disable-line no-unused-vars + if (!this.segmentInitialized) { + return Promise.resolve(); + } + // if we do not have an authenticated user (indicated by being in this method), + // but we still have a user id associated in segment, reset the local segment state + // This has to be wrapped in the analytics.ready() callback because the analytics.user() + // function isn't available until the analytics.js package has finished initializing. + return new Promise(function (resolve, reject) { + // eslint-disable-line no-unused-vars + global.analytics.ready(function () { + if (global.analytics.user().id()) { + global.analytics.reset(); + } + // We don’t need to call `identify` for anonymous users and can just make the value of + // hasIdentifyBeenCalled true. Segment automatically assigns them an anonymousId, so + // just calling `page` and `track` works fine without identify. + _this3.hasIdentifyBeenCalled = true; + resolve(); + }); + + // this is added to handle a specific use-case where if a user has blocked the analytics + // tools in their browser, this promise does not get resolved and user sees a blank + // page. Dispatching this event in script.onerror callback in analytics.load. + document.addEventListener('segmentFailed', resolve); + // This is added to handle the google analytics blocked case which is injected into + // the DOM by segment.min.js. + setTimeout(function () { + if (!global.ga || !global.ga.create || !global.google_tag_manager) { + _this3.segmentInitialized = false; + resolve(); + } + }, 2000); + }); + } + + /** + * Sends a track event to Segment and downstream. + * Note: For links and forms, you should use trackLink and trackForm instead. + * + * @param {*} eventName + * @param {*} [properties] + */ + }, { + key: "sendTrackEvent", + value: function sendTrackEvent(eventName, properties) { + if (!this.segmentInitialized) { + return; + } + this.checkIdentifyCalled(); + global.analytics.track(eventName, properties); + } + + /** + * Sends a page event to Segment and downstream. + * + * @param {*} [name] If only one string arg provided, assumed to be name. + * @param {*} [category] Name is required to pass a category. + * @param {*} [properties] + */ + }, { + key: "sendPageEvent", + value: function sendPageEvent(category, name, properties) { + if (!this.segmentInitialized) { + return; + } + this.checkIdentifyCalled(); + global.analytics.page(category, name, properties); + } + }]); +}(); +export default SegmentAnalyticsService; +//# sourceMappingURL=SegmentAnalyticsService.js.map \ No newline at end of file diff --git a/dist/analytics/SegmentAnalyticsService.js.map b/dist/analytics/SegmentAnalyticsService.js.map new file mode 100644 index 000000000..a8bef5829 --- /dev/null +++ b/dist/analytics/SegmentAnalyticsService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SegmentAnalyticsService.js","names":["formurlencoded","snakeCaseObject","SegmentAnalyticsService","_ref","httpClient","loggingService","config","_classCallCheck","trackingLogApiUrl","concat","LMS_BASE_URL","segmentKey","SEGMENT_KEY","hasIdentifyBeenCalled","segmentInitialized","initializeSegment","_createClass","key","value","_this","global","analytics","_global","initialize","invoked","methods","factory","method","_len","arguments","length","args","Array","_key","unshift","push","forEach","load","options","script","document","createElement","type","onerror","event","Event","dispatchEvent","async","src","first","getElementsByTagName","parentNode","insertBefore","_loadOptions","SNIPPET_VERSION","checkIdentifyCalled","logError","sendTrackingLogEvent","eventName","properties","_this2","snakeEventData","deep","serverData","event_type","JSON","stringify","page","location","href","post","headers","error","identifyAuthenticatedUser","userId","traits","Error","identify","identifyAnonymousUser","_this3","Promise","resolve","reject","ready","user","id","reset","addEventListener","setTimeout","ga","create","google_tag_manager","sendTrackEvent","track","sendPageEvent","category","name"],"sources":["../../src/analytics/SegmentAnalyticsService.js"],"sourcesContent":["import formurlencoded from 'form-urlencoded';\nimport { snakeCaseObject } from '../utils';\n\n/**\n * @implements {AnalyticsService}\n * @memberof module:Analytics\n */\nclass SegmentAnalyticsService {\n constructor({ httpClient, loggingService, config }) {\n this.loggingService = loggingService;\n this.httpClient = httpClient;\n this.trackingLogApiUrl = `${config.LMS_BASE_URL}/event`;\n this.segmentKey = config.SEGMENT_KEY;\n this.hasIdentifyBeenCalled = false;\n this.segmentInitialized = false;\n\n if (this.segmentKey) {\n this.initializeSegment();\n }\n }\n\n // The code in this function is from Segment's website, with a few updates:\n // - It uses the segmentKey from the SegmentAnalyticsService instance.\n // - It also saves a \"segmentInitialized\" variable on the SegmentAnalyticsService instance so\n // that the service can keep track of its own initialization state.\n // Reference:\n // https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/quickstart/\n initializeSegment() {\n // Create a queue, but don't obliterate an existing one!\n global.analytics = global.analytics || [];\n const { analytics } = global;\n\n // If the real analytics.js is already on the page return.\n if (analytics.initialize) {\n this.segmentInitialized = true;\n return;\n }\n\n // If the snippet was invoked do nothing.\n if (analytics.invoked) {\n this.segmentInitialized = true;\n return;\n }\n\n // Invoked flag, to make sure the snippet\n // is never invoked twice.\n analytics.invoked = true;\n\n // A list of the methods in Analytics.js to stub.\n analytics.methods = [\n 'trackSubmit',\n 'trackClick',\n 'trackLink',\n 'trackForm',\n 'pageview',\n 'identify',\n 'reset',\n 'group',\n 'track',\n 'ready',\n 'alias',\n 'debug',\n 'page',\n 'once',\n 'off',\n 'on',\n ];\n\n // Define a factory to create stubs. These are placeholders\n // for methods in Analytics.js so that you never have to wait\n // for it to load to actually record data. The `method` is\n // stored as the first argument, so we can replay the data.\n analytics.factory = method => ((...args) => {\n args.unshift(method);\n analytics.push(args);\n return analytics;\n });\n\n // For each of our methods, generate a queueing stub.\n analytics.methods.forEach((key) => {\n analytics[key] = analytics.factory(key);\n });\n\n // Define a method to load Analytics.js from our CDN,\n // and that will be sure to only ever load it once.\n analytics.load = (key, options) => {\n // Create an async script element based on your key.\n const script = document.createElement('script');\n script.type = 'text/javascript';\n script.onerror = () => {\n this.segmentInitialized = false;\n const event = new Event('segmentFailed');\n document.dispatchEvent(event);\n };\n script.async = true;\n script.src = `https://cdn.segment.com/analytics.js/v1/${key}/analytics.min.js`;\n\n // Insert our script next to the first script element.\n const first = document.getElementsByTagName('script')[0];\n first.parentNode.insertBefore(script, first);\n analytics._loadOptions = options; // eslint-disable-line no-underscore-dangle\n\n this.segmentInitialized = true;\n };\n\n // Add a version to keep track of what's in the wild.\n analytics.SNIPPET_VERSION = '4.1.0';\n\n // Load Analytics.js with your key, which will automatically\n // load the tools you've enabled for your account. Boosh!\n analytics.load(this.segmentKey);\n }\n\n /**\n * Checks that identify was first called. Otherwise, logs error.\n *\n */\n checkIdentifyCalled() {\n if (!this.hasIdentifyBeenCalled) {\n this.loggingService.logError('Identify must be called before other tracking events.');\n }\n }\n\n /**\n * Logs events to tracking log and downstream.\n * For tracking log event documentation, see\n * https://openedx.atlassian.net/wiki/spaces/AN/pages/13205895/Event+Design+and+Review+Process\n *\n * @param {string} eventName (event_type on backend, but named to match Segment api)\n * @param {Object} properties (event on backend, but named properties to match Segment api)\n * @returns {Promise} The promise returned by HttpClient.post.\n */\n sendTrackingLogEvent(eventName, properties) {\n const snakeEventData = snakeCaseObject(properties, { deep: true });\n const serverData = {\n event_type: eventName,\n event: JSON.stringify(snakeEventData),\n page: global.location.href,\n };\n return this.httpClient.post(\n this.trackingLogApiUrl,\n formurlencoded(serverData),\n {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n },\n ).catch((error) => {\n this.loggingService.logError(error);\n });\n }\n\n /**\n * * Send identify call to Segment.\n *\n * @param {string} userId\n * @param {*} [traits]\n */\n identifyAuthenticatedUser(userId, traits) {\n if (!userId) {\n throw new Error('UserId is required for identifyAuthenticatedUser.');\n }\n\n if (!this.segmentInitialized) {\n return;\n }\n global.analytics.identify(userId, traits);\n this.hasIdentifyBeenCalled = true;\n }\n\n /**\n * Send anonymous identify call to Segment's identify.\n *\n * @param {*} [traits]\n * @returns {Promise} Promise that will resolve once the document readyState is complete\n */\n identifyAnonymousUser(traits) { // eslint-disable-line no-unused-vars\n if (!this.segmentInitialized) {\n return Promise.resolve();\n }\n // if we do not have an authenticated user (indicated by being in this method),\n // but we still have a user id associated in segment, reset the local segment state\n // This has to be wrapped in the analytics.ready() callback because the analytics.user()\n // function isn't available until the analytics.js package has finished initializing.\n return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars\n global.analytics.ready(() => {\n if (global.analytics.user().id()) {\n global.analytics.reset();\n }\n // We don’t need to call `identify` for anonymous users and can just make the value of\n // hasIdentifyBeenCalled true. Segment automatically assigns them an anonymousId, so\n // just calling `page` and `track` works fine without identify.\n this.hasIdentifyBeenCalled = true;\n resolve();\n });\n\n // this is added to handle a specific use-case where if a user has blocked the analytics\n // tools in their browser, this promise does not get resolved and user sees a blank\n // page. Dispatching this event in script.onerror callback in analytics.load.\n document.addEventListener('segmentFailed', resolve);\n // This is added to handle the google analytics blocked case which is injected into\n // the DOM by segment.min.js.\n setTimeout(() => {\n if (!global.ga || !global.ga.create || !global.google_tag_manager) {\n this.segmentInitialized = false;\n resolve();\n }\n }, 2000);\n });\n }\n\n /**\n * Sends a track event to Segment and downstream.\n * Note: For links and forms, you should use trackLink and trackForm instead.\n *\n * @param {*} eventName\n * @param {*} [properties]\n */\n sendTrackEvent(eventName, properties) {\n if (!this.segmentInitialized) {\n return;\n }\n this.checkIdentifyCalled();\n global.analytics.track(eventName, properties);\n }\n\n /**\n * Sends a page event to Segment and downstream.\n *\n * @param {*} [name] If only one string arg provided, assumed to be name.\n * @param {*} [category] Name is required to pass a category.\n * @param {*} [properties]\n */\n sendPageEvent(category, name, properties) {\n if (!this.segmentInitialized) {\n return;\n }\n this.checkIdentifyCalled();\n global.analytics.page(category, name, properties);\n }\n}\n\nexport default SegmentAnalyticsService;\n"],"mappings":";;;;;;AAAA,OAAOA,cAAc,MAAM,iBAAiB;AAC5C,SAASC,eAAe,QAAQ,UAAU;;AAE1C;AACA;AACA;AACA;AAHA,IAIMC,uBAAuB;EAC3B,SAAAA,wBAAAC,IAAA,EAAoD;IAAA,IAAtCC,UAAU,GAAAD,IAAA,CAAVC,UAAU;MAAEC,cAAc,GAAAF,IAAA,CAAdE,cAAc;MAAEC,MAAM,GAAAH,IAAA,CAANG,MAAM;IAAAC,eAAA,OAAAL,uBAAA;IAC9C,IAAI,CAACG,cAAc,GAAGA,cAAc;IACpC,IAAI,CAACD,UAAU,GAAGA,UAAU;IAC5B,IAAI,CAACI,iBAAiB,MAAAC,MAAA,CAAMH,MAAM,CAACI,YAAY,WAAQ;IACvD,IAAI,CAACC,UAAU,GAAGL,MAAM,CAACM,WAAW;IACpC,IAAI,CAACC,qBAAqB,GAAG,KAAK;IAClC,IAAI,CAACC,kBAAkB,GAAG,KAAK;IAE/B,IAAI,IAAI,CAACH,UAAU,EAAE;MACnB,IAAI,CAACI,iBAAiB,CAAC,CAAC;IAC1B;EACF;;EAEA;EACA;EACA;EACA;EACA;EACA;EAAA,OAAAC,YAAA,CAAAd,uBAAA;IAAAe,GAAA;IAAAC,KAAA,EACA,SAAAH,iBAAiBA,CAAA,EAAG;MAAA,IAAAI,KAAA;MAClB;MACAC,MAAM,CAACC,SAAS,GAAGD,MAAM,CAACC,SAAS,IAAI,EAAE;MACzC,IAAAC,OAAA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C,EAAE;YAChCjE,MAAM,CAACC,SAAS,CAACiE,KAAK,CAAC,CAAC;UAC1B;UACA;UACA;UACA;UACAP,MAAI,CAAClE,qBAAqB,GAAG,IAAI;UACjCoE,OAAO,CAAC,CAAC;QACX,CAAC,CAAC;;QAEF;QACA;QACA;QACAzC,QAAQ,CAAC+C,gBAAgB,CAAC,eAAe,EAAEN,OAAO,CAAC;QACnD;QACA;QACAO,UAAU,CAAC,YAAM;UACf,IAAI,CAACpE,MAAM,CAACqE,EAAE,IAAI,CAACrE,MAAM,CAACqE,EAAE,CAACC,MAAM,IAAI,CAACtE,MAAM,CAACuE,kBAAkB,EAAE;YACjEZ,MAAI,CAACjE,kBAAkB,GAAG,KAAK;YAC/BmE,OAAO,CAAC,CAAC;UACX;QACF,CAAC,EAAE,IAAI,CAAC;MACV,CAAC,CAAC;IACJ;;IAEA;AACF;AACA;AACA;AACA;AACA;AACA;EANE;IAAAhE,GAAA;IAAAC,KAAA,EAOA,SAAA0E,cAAcA,CAAClC,SAAS,EAAEC,UAAU,EAAE;MACpC,IAAI,CAAC,IAAI,CAAC7C,kBAAkB,EAAE;QAC5B;MACF;MACA,IAAI,CAACyC,mBAAmB,CAAC,CAAC;MAC1BnC,MAAM,CAACC,SAAS,CAACwE,KAAK,CAACnC,SAAS,EAAEC,UAAU,CAAC;IAC/C;;IAEA;AACF;AACA;AACA;AACA;AACA;AACA;EANE;IAAA1C,GAAA;IAAAC,KAAA,EAOA,SAAA4E,aAAaA,CAACC,QAAQ,EAAEC,IAAI,EAAErC,UAAU,EAAE;MACxC,IAAI,CAAC,IAAI,CAAC7C,kBAAkB,EAAE;QAC5B;MACF;MACA,IAAI,CAACyC,mBAAmB,CAAC,CAAC;MAC1BnC,MAAM,CAACC,SAAS,CAAC8C,IAAI,CAAC4B,QAAQ,EAAEC,IAAI,EAAErC,UAAU,CAAC;IACnD;EAAC;AAAA;AAGH,eAAezD,uBAAuB","ignoreList":[]} \ No newline at end of file diff --git a/dist/analytics/index.js b/dist/analytics/index.js new file mode 100644 index 000000000..d3fff0e04 --- /dev/null +++ b/dist/analytics/index.js @@ -0,0 +1,4 @@ +export { configure, identifyAnonymousUser, identifyAuthenticatedUser, sendPageEvent, sendTrackEvent, sendTrackingLogEvent, getAnalyticsService, resetAnalyticsService } from './interface'; +export { default as SegmentAnalyticsService } from './SegmentAnalyticsService'; +export { default as MockAnalyticsService } from './MockAnalyticsService'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/analytics/index.js.map b/dist/analytics/index.js.map new file mode 100644 index 000000000..271c71d03 --- /dev/null +++ b/dist/analytics/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["configure","identifyAnonymousUser","identifyAuthenticatedUser","sendPageEvent","sendTrackEvent","sendTrackingLogEvent","getAnalyticsService","resetAnalyticsService","default","SegmentAnalyticsService","MockAnalyticsService"],"sources":["../../src/analytics/index.js"],"sourcesContent":["export {\n configure,\n identifyAnonymousUser,\n identifyAuthenticatedUser,\n sendPageEvent,\n sendTrackEvent,\n sendTrackingLogEvent,\n getAnalyticsService,\n resetAnalyticsService,\n} from './interface';\nexport { default as SegmentAnalyticsService } from './SegmentAnalyticsService';\nexport { default as MockAnalyticsService } from './MockAnalyticsService';\n"],"mappings":"AAAA,SACEA,SAAS,EACTC,qBAAqB,EACrBC,yBAAyB,EACzBC,aAAa,EACbC,cAAc,EACdC,oBAAoB,EACpBC,mBAAmB,EACnBC,qBAAqB,QAChB,aAAa;AACpB,SAASC,OAAO,IAAIC,uBAAuB,QAAQ,2BAA2B;AAC9E,SAASD,OAAO,IAAIE,oBAAoB,QAAQ,wBAAwB","ignoreList":[]} \ No newline at end of file diff --git a/dist/analytics/interface.js b/dist/analytics/interface.js new file mode 100755 index 000000000..e590bf0dc --- /dev/null +++ b/dist/analytics/interface.js @@ -0,0 +1,139 @@ +/** + * #### Import members from **@edx/frontend-platform/analytics** + * + * Contains a shared interface for tracking events. Has a default implementation of + * SegmentAnalyticsService, which supports Segment and the Tracking Log API (hosted in LMS). + * + * The `initialize` function performs much of the analytics configuration for you. If, however, + * you're not using the `initialize` function, analytics can be configured via: + * + * ``` + * import { configure, SegmentAnalyticsService } from '@edx/frontend-platform/analytics'; + * import { getConfig } from '@edx/frontend-platform'; + * import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth'; + * import { getLoggingService } from '@edx/frontend-platform/logging'; + * + * configure(SegmentAnalyticsService, { + * config: getConfig(), + * loggingService: getLoggingService(), + * httpClient: getAuthenticatedHttpClient(), + * }); + * ``` + * + * As shown in this example, analytics depends on the configuration document, logging, and having + * an authenticated HTTP client. + * + * @module Analytics + */ +import PropTypes from 'prop-types'; +var optionsShape = { + config: PropTypes.object.isRequired, + httpClient: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired, + loggingService: PropTypes.shape({ + logError: PropTypes.func.isRequired, + logInfo: PropTypes.func.isRequired + }).isRequired +}; +var serviceShape = { + sendTrackingLogEvent: PropTypes.func.isRequired, + identifyAuthenticatedUser: PropTypes.func.isRequired, + identifyAnonymousUser: PropTypes.func.isRequired, + sendTrackEvent: PropTypes.func.isRequired, + sendPageEvent: PropTypes.func.isRequired +}; +var service; + +/** + * + * @param {class} AnalyticsService + * @param {*} options + * @returns {AnalyticsService} + */ +export function configure(AnalyticsService, options) { + PropTypes.checkPropTypes(optionsShape, options, 'property', 'Analytics'); + service = new AnalyticsService(options); + PropTypes.checkPropTypes(serviceShape, service, 'property', 'AnalyticsService'); + return service; +} + +/** + * + * @param {*} eventName + * @param {*} properties + * @returns {Promise} + */ +export function sendTrackingLogEvent(eventName, properties) { + return service.sendTrackingLogEvent(eventName, properties); +} + +/** + * + * + * @param {*} userId + * @param {*} traits + */ +export function identifyAuthenticatedUser(userId, traits) { + service.identifyAuthenticatedUser(userId, traits); +} + +/** + * + * + * @param {*} traits + * @returns {Promise} + */ +export function identifyAnonymousUser(traits) { + return service.identifyAnonymousUser(traits); +} + +/** + * + * + * @param {*} eventName + * @param {*} properties + */ +export function sendTrackEvent(eventName, properties) { + service.sendTrackEvent(eventName, properties); +} + +/** + * + * + * @param {*} category + * @param {*} name + * @param {*} properties + */ +export function sendPageEvent(category, name, properties) { + service.sendPageEvent(category, name, properties); +} + +/** + * + * + * @returns {AnalyticsService} + */ +export function getAnalyticsService() { + if (!service) { + throw Error('You must first configure the analytics service.'); + } + return service; +} + +/** + * + */ +export function resetAnalyticsService() { + service = null; +} + +/** + * @name AnalyticsService + * @interface + * @memberof module:Analytics + * @property {function} identifyAnonymousUser + * @property {function} identifyAuthenticatedUser + * @property {function} sendPageEvent + * @property {function} sendTrackEvent + * @property {function} sendTrackingLogEvent + */ +//# sourceMappingURL=interface.js.map \ No newline at end of file diff --git a/dist/analytics/interface.js.map b/dist/analytics/interface.js.map new file mode 100644 index 000000000..31e4febd7 --- /dev/null +++ b/dist/analytics/interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interface.js","names":["PropTypes","optionsShape","config","object","isRequired","httpClient","oneOfType","func","loggingService","shape","logError","logInfo","serviceShape","sendTrackingLogEvent","identifyAuthenticatedUser","identifyAnonymousUser","sendTrackEvent","sendPageEvent","service","configure","AnalyticsService","options","checkPropTypes","eventName","properties","userId","traits","category","name","getAnalyticsService","Error","resetAnalyticsService"],"sources":["../../src/analytics/interface.js"],"sourcesContent":["/**\n * #### Import members from **@edx/frontend-platform/analytics**\n *\n * Contains a shared interface for tracking events. Has a default implementation of\n * SegmentAnalyticsService, which supports Segment and the Tracking Log API (hosted in LMS).\n *\n * The `initialize` function performs much of the analytics configuration for you. If, however,\n * you're not using the `initialize` function, analytics can be configured via:\n *\n * ```\n * import { configure, SegmentAnalyticsService } from '@edx/frontend-platform/analytics';\n * import { getConfig } from '@edx/frontend-platform';\n * import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';\n * import { getLoggingService } from '@edx/frontend-platform/logging';\n *\n * configure(SegmentAnalyticsService, {\n * config: getConfig(),\n * loggingService: getLoggingService(),\n * httpClient: getAuthenticatedHttpClient(),\n * });\n * ```\n *\n * As shown in this example, analytics depends on the configuration document, logging, and having\n * an authenticated HTTP client.\n *\n * @module Analytics\n */\nimport PropTypes from 'prop-types';\n\nconst optionsShape = {\n config: PropTypes.object.isRequired,\n httpClient: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n loggingService: PropTypes.shape({\n logError: PropTypes.func.isRequired,\n logInfo: PropTypes.func.isRequired,\n }).isRequired,\n};\n\nconst serviceShape = {\n sendTrackingLogEvent: PropTypes.func.isRequired,\n identifyAuthenticatedUser: PropTypes.func.isRequired,\n identifyAnonymousUser: PropTypes.func.isRequired,\n sendTrackEvent: PropTypes.func.isRequired,\n sendPageEvent: PropTypes.func.isRequired,\n};\n\nlet service;\n\n/**\n *\n * @param {class} AnalyticsService\n * @param {*} options\n * @returns {AnalyticsService}\n */\nexport function configure(AnalyticsService, options) {\n PropTypes.checkPropTypes(optionsShape, options, 'property', 'Analytics');\n service = new AnalyticsService(options);\n PropTypes.checkPropTypes(serviceShape, service, 'property', 'AnalyticsService');\n return service;\n}\n\n/**\n *\n * @param {*} eventName\n * @param {*} properties\n * @returns {Promise}\n */\nexport function sendTrackingLogEvent(eventName, properties) {\n return service.sendTrackingLogEvent(eventName, properties);\n}\n\n/**\n *\n *\n * @param {*} userId\n * @param {*} traits\n */\nexport function identifyAuthenticatedUser(userId, traits) {\n service.identifyAuthenticatedUser(userId, traits);\n}\n\n/**\n *\n *\n * @param {*} traits\n * @returns {Promise}\n */\nexport function identifyAnonymousUser(traits) {\n return service.identifyAnonymousUser(traits);\n}\n\n/**\n *\n *\n * @param {*} eventName\n * @param {*} properties\n */\nexport function sendTrackEvent(eventName, properties) {\n service.sendTrackEvent(eventName, properties);\n}\n\n/**\n *\n *\n * @param {*} category\n * @param {*} name\n * @param {*} properties\n */\nexport function sendPageEvent(category, name, properties) {\n service.sendPageEvent(category, name, properties);\n}\n\n/**\n *\n *\n * @returns {AnalyticsService}\n */\nexport function getAnalyticsService() {\n if (!service) {\n throw Error('You must first configure the analytics service.');\n }\n\n return service;\n}\n\n/**\n *\n */\nexport function resetAnalyticsService() {\n service = null;\n}\n\n/**\n * @name AnalyticsService\n * @interface\n * @memberof module:Analytics\n * @property {function} identifyAnonymousUser\n * @property {function} identifyAuthenticatedUser\n * @property {function} sendPageEvent\n * @property {function} sendTrackEvent\n * @property {function} sendTrackingLogEvent\n */\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAOA,SAAS,MAAM,YAAY;AAElC,IAAMC,YAAY,GAAG;EACnBC,MAAM,EAAEF,SAAS,CAACG,MAAM,CAACC,UAAU;EACnCC,UAAU,EAAEL,SAAS,CAACM,SAAS,CAAC,CAACN,SAAS,CAACO,IAAI,EAAEP,SAAS,CAACG,MAAM,CAAC,CAAC,CAACC,UAAU;EAC9EI,cAAc,EAAER,SAAS,CAACS,KAAK,CAAC;IAC9BC,QAAQ,EAAEV,SAAS,CAACO,IAAI,CAACH,UAAU;IACnCO,OAAO,EAAEX,SAAS,CAACO,IAAI,CAACH;EAC1B,CAAC,CAAC,CAACA;AACL,CAAC;AAED,IAAMQ,YAAY,GAAG;EACnBC,oBAAoB,EAAEb,SAAS,CAACO,IAAI,CAACH,UAAU;EAC/CU,yBAAyB,EAAEd,SAAS,CAACO,IAAI,CAACH,UAAU;EACpDW,qBAAqB,EAAEf,SAAS,CAACO,IAAI,CAACH,UAAU;EAChDY,cAAc,EAAEhB,SAAS,CAACO,IAAI,CAACH,UAAU;EACzCa,aAAa,EAAEjB,SAAS,CAACO,IAAI,CAACH;AAChC,CAAC;AAED,IAAIc,OAAO;;AAEX;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,SAASA,CAACC,gBAAgB,EAAEC,OAAO,EAAE;EACnDrB,SAAS,CAACsB,cAAc,CAACrB,YAAY,EAAEoB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IAAI;AAChB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/AxiosCsrfTokenService.js b/dist/auth/AxiosCsrfTokenService.js new file mode 100644 index 000000000..bc1ef10e8 --- /dev/null +++ b/dist/auth/AxiosCsrfTokenService.js @@ -0,0 +1,84 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +import axios from 'axios'; +import { getUrlParts, processAxiosErrorAndThrow } from './utils'; +var AxiosCsrfTokenService = /*#__PURE__*/function () { + function AxiosCsrfTokenService(csrfTokenApiPath) { + _classCallCheck(this, AxiosCsrfTokenService); + this.csrfTokenApiPath = csrfTokenApiPath; + this.httpClient = axios.create(); + // Set withCredentials to true. Enables cross-site Access-Control requests + // to be made using cookies, authorization headers or TLS client + // certificates. More on MDN: + // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials + this.httpClient.defaults.withCredentials = true; + this.httpClient.defaults.headers['USE-JWT-COOKIE'] = true; + this.csrfTokenCache = {}; + this.csrfTokenRequestPromises = {}; + } + return _createClass(AxiosCsrfTokenService, [{ + key: "getCsrfToken", + value: function () { + var _getCsrfToken = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(url) { + var _this = this; + var urlParts, _urlParts, protocol, domain, csrfToken; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + try { + urlParts = getUrlParts(url); + } catch (e) { + // If the url is not parsable it's likely because a relative + // path was supplied as the url. This is acceptable and in + // this case we should use the current origin of the page. + urlParts = getUrlParts(global.location.origin); + } + _urlParts = urlParts, protocol = _urlParts.protocol, domain = _urlParts.domain; + csrfToken = this.csrfTokenCache[domain]; + if (!csrfToken) { + _context.next = 5; + break; + } + return _context.abrupt("return", csrfToken); + case 5: + if (!this.csrfTokenRequestPromises[domain]) { + this.csrfTokenRequestPromises[domain] = this.httpClient.get("".concat(protocol, "://").concat(domain).concat(this.csrfTokenApiPath)).then(function (response) { + _this.csrfTokenCache[domain] = response.data.csrfToken; + return _this.csrfTokenCache[domain]; + })["catch"](processAxiosErrorAndThrow)["finally"](function () { + delete _this.csrfTokenRequestPromises[domain]; + }); + } + return _context.abrupt("return", this.csrfTokenRequestPromises[domain]); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getCsrfToken(_x) { + return _getCsrfToken.apply(this, arguments); + } + return getCsrfToken; + }() + }, { + key: "clearCsrfTokenCache", + value: function clearCsrfTokenCache() { + this.csrfTokenCache = {}; + } + }, { + key: "getHttpClient", + value: function getHttpClient() { + return this.httpClient; + } + }]); +}(); +export { AxiosCsrfTokenService as default }; +//# sourceMappingURL=AxiosCsrfTokenService.js.map \ No newline at end of file diff --git a/dist/auth/AxiosCsrfTokenService.js.map b/dist/auth/AxiosCsrfTokenService.js.map new file mode 100644 index 000000000..9e9d009af --- /dev/null +++ b/dist/auth/AxiosCsrfTokenService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AxiosCsrfTokenService.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","_classCallCheck","_defineProperties","_toPropertyKey","key","_createClass","_toPrimitive","toPrimitive","String","Number","axios","getUrlParts","processAxiosErrorAndThrow","AxiosCsrfTokenService","csrfTokenApiPath","httpClient","defaults","withCredentials","headers","csrfTokenCache","csrfTokenRequestPromises","_getCsrfToken","_callee","url","_this","urlParts","_urlParts","protocol","domain","csrfToken","_callee$","_context","global","location","origin","get","concat","response","data","getCsrfToken","_x","clearCsrfTokenCache","getHttpClient","default"],"sources":["../../src/auth/AxiosCsrfTokenService.js"],"sourcesContent":["import axios from 'axios';\nimport { getUrlParts, processAxiosErrorAndThrow } from './utils';\n\nexport default class AxiosCsrfTokenService {\n constructor(csrfTokenApiPath) {\n this.csrfTokenApiPath = csrfTokenApiPath;\n this.httpClient = axios.create();\n // Set withCredentials to true. Enables cross-site Access-Control requests\n // to be made using cookies, authorization headers or TLS client\n // certificates. More on MDN:\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials\n this.httpClient.defaults.withCredentials = true;\n this.httpClient.defaults.headers['USE-JWT-COOKIE'] = true;\n\n this.csrfTokenCache = {};\n this.csrfTokenRequestPromises = {};\n }\n\n async getCsrfToken(url) {\n let urlParts;\n try {\n urlParts = getUrlParts(url);\n } catch (e) {\n // If the url is not parsable it's likely because a relative\n // path was supplied as the url. This is acceptable and in\n // this case we should use the current origin of the page.\n urlParts = getUrlParts(global.location.origin);\n }\n\n const { protocol, domain } = urlParts;\n const csrfToken = this.csrfTokenCache[domain];\n\n if (csrfToken) {\n return csrfToken;\n }\n\n if (!this.csrfTokenRequestPromises[domain]) {\n this.csrfTokenRequestPromises[domain] = this.httpClient\n .get(`${protocol}://${domain}${this.csrfTokenApiPath}`)\n .then((response) => {\n this.csrfTokenCache[domain] = response.data.csrfToken;\n return this.csrfTokenCache[domain];\n })\n .catch(processAxiosErrorAndThrow)\n .finally(() => {\n delete this.csrfTokenRequestPromises[domain];\n });\n }\n\n return this.csrfTokenRequestPromises[domain];\n }\n\n clearCsrfTokenCache() {\n this.csrfTokenCache = {};\n }\n\n getHttpClient() {\n return this.httpClient;\n }\n}\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,CAAA,SAAAC,CAAA,EAAAD,CAAA,OAAAE,CAAA,GAAAC,MAAA,CAAAC,SAAA,EAAAC,CAAA,GAAAH,CAAA,CAAAI,cAAA,EAAAC,CAAA,GAAAJ,MAAA,CAAAK,cAAA,cAAAP,CAAA,EAAAD,CAAA,EAAAE,CAAA,IAAAD,CAA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Q,SAAAS,MAAA,CAAMR,MAAM,EAAAQ,MAAA,CAAG,IAAI,CAACtB,gBAAgB,CAAE,CAAC,CACtDrE,IAAI,CAAC,UAAC4F,QAAQ,EAAK;kBAClBb,KAAI,CAACL,cAAc,CAACS,MAAM,CAAC,GAAGS,QAAQ,CAACC,IAAI,CAACT,SAAS;kBACrD,OAAOL,KAAI,CAACL,cAAc,CAACS,MAAM,CAAC;gBACpC,CAAC,CAAC,SACI,CAAChB,yBAAyB,CAAC,WACzB,CAAC,YAAM;kBACb,OAAOY,KAAI,CAACJ,wBAAwB,CAACQ,MAAM,CAAC;gBAC9C,CAAC,CAAC;cACN;cAAC,OAAAG,QAAA,CAAA5E,MAAA,WAEM,IAAI,CAACiE,wBAAwB,CAACQ,MAAM,CAAC;YAAA;YAAA;cAAA,OAAAG,QAAA,CAAA3C,IAAA;UAAA;QAAA,GAAAkC,OAAA;MAAA,CAC7C;MAAA,SAhCKiB,YAAYA,CAAAC,EAAA;QAAA,OAAAnB,aAAA,CAAAvB,KAAA,OAAAD,SAAA;MAAA;MAAA,OAAZ0C,YAAY;IAAA;EAAA;IAAAnC,GAAA;IAAAtG,KAAA,EAkClB,SAAA2I,mBAAmBA,CAAA,EAAG;MACpB,IAAI,CAACtB,cAAc,GAAG,CAAC,CAAC;IAC1B;EAAC;IAAAf,GAAA;IAAAtG,KAAA,EAED,SAAA4I,aAAaA,CAAA,EAAG;MACd,OAAO,IAAI,CAAC3B,UAAU;IACxB;EAAC;AAAA;AAAA,SAvDkBF,qBAAqB,IAAA8B,OAAA","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/AxiosJwtAuthService.js b/dist/auth/AxiosJwtAuthService.js new file mode 100644 index 000000000..23b235eef --- /dev/null +++ b/dist/auth/AxiosJwtAuthService.js @@ -0,0 +1,464 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +import axios from 'axios'; +import PropTypes from 'prop-types'; +import { logFrontendAuthError } from './utils'; +import { camelCaseObject, ensureDefinedConfig } from '../utils'; +import createJwtTokenProviderInterceptor from './interceptors/createJwtTokenProviderInterceptor'; +import createCsrfTokenProviderInterceptor from './interceptors/createCsrfTokenProviderInterceptor'; +import createProcessAxiosRequestErrorInterceptor from './interceptors/createProcessAxiosRequestErrorInterceptor'; +import AxiosJwtTokenService from './AxiosJwtTokenService'; +import AxiosCsrfTokenService from './AxiosCsrfTokenService'; +import configureCache from './LocalForageCache'; +var optionsPropTypes = { + config: PropTypes.shape({ + BASE_URL: PropTypes.string.isRequired, + LMS_BASE_URL: PropTypes.string.isRequired, + LOGIN_URL: PropTypes.string.isRequired, + LOGOUT_URL: PropTypes.string.isRequired, + REFRESH_ACCESS_TOKEN_ENDPOINT: PropTypes.string.isRequired, + ACCESS_TOKEN_COOKIE_NAME: PropTypes.string.isRequired, + CSRF_TOKEN_API_PATH: PropTypes.string.isRequired + }).isRequired, + loggingService: PropTypes.shape({ + logError: PropTypes.func.isRequired, + logInfo: PropTypes.func.isRequired + }).isRequired +}; + +/** + * @implements {AuthService} + * @memberof module:Auth + */ +var AxiosJwtAuthService = /*#__PURE__*/function () { + /** + * @param {Object} options + * @param {Object} options.config + * @param {string} options.config.BASE_URL + * @param {string} options.config.LMS_BASE_URL + * @param {string} options.config.LOGIN_URL + * @param {string} options.config.LOGOUT_URL + * @param {string} options.config.REFRESH_ACCESS_TOKEN_ENDPOINT + * @param {string} options.config.ACCESS_TOKEN_COOKIE_NAME + * @param {string} options.config.CSRF_TOKEN_API_PATH + * @param {Object} options.loggingService requires logError and logInfo methods + */ + function AxiosJwtAuthService(options) { + var _this = this; + _classCallCheck(this, AxiosJwtAuthService); + this.authenticatedHttpClient = null; + this.httpClient = null; + this.cachedAuthenticatedHttpClient = null; + this.cachedHttpClient = null; + this.authenticatedUser = null; + ensureDefinedConfig(options, 'AuthService'); + PropTypes.checkPropTypes(optionsPropTypes, options, 'options', 'AuthService'); + this.config = options.config; + this.loggingService = options.loggingService; + this.jwtTokenService = new AxiosJwtTokenService(this.loggingService, this.config.ACCESS_TOKEN_COOKIE_NAME, this.config.REFRESH_ACCESS_TOKEN_ENDPOINT); + this.csrfTokenService = new AxiosCsrfTokenService(this.config.CSRF_TOKEN_API_PATH); + this.authenticatedHttpClient = this.addAuthenticationToHttpClient(axios.create()); + this.httpClient = axios.create(); + configureCache().then(function (cachedAxiosClient) { + _this.cachedAuthenticatedHttpClient = _this.addAuthenticationToHttpClient(cachedAxiosClient); + _this.cachedHttpClient = cachedAxiosClient; + })["catch"](function (e) { + // fallback to non-cached HTTP clients and log error + _this.cachedAuthenticatedHttpClient = _this.authenticatedHttpClient; + _this.cachedHttpClient = _this.httpClient; + logFrontendAuthError(_this.loggingService, "configureCache failed with error: ".concat(e.message)); + })["finally"](function () { + _this.middleware = options.middleware; + _this.applyMiddleware(options.middleware); + }); + } + + /** + * Applies middleware to the axios instances in this service. + * + * @param {Array} middleware Middleware to apply. + */ + return _createClass(AxiosJwtAuthService, [{ + key: "applyMiddleware", + value: function applyMiddleware() { + var middleware = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var clients = [this.authenticatedHttpClient, this.httpClient, this.cachedAuthenticatedHttpClient, this.cachedHttpClient]; + try { + middleware.forEach(function (middlewareFn) { + clients.forEach(function (client) { + return client && middlewareFn(client); + }); + }); + } catch (error) { + logFrontendAuthError(this.loggingService, error); + throw error; + } + } + + /** + * Gets the authenticated HTTP client for the service. This is an axios instance. + * + * @param {Object} [options] Optional options for how the HTTP client should be configured. + * @param {boolean} [options.useCache] Whether to use front end caching for all requests made + * with the returned client. + * + * @returns {HttpClient} A configured axios http client which can be used for authenticated + * requests. + */ + }, { + key: "getAuthenticatedHttpClient", + value: function getAuthenticatedHttpClient() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (options.useCache) { + return this.cachedAuthenticatedHttpClient; + } + return this.authenticatedHttpClient; + } + + /** + * Gets the unauthenticated HTTP client for the service. This is an axios instance. + * + * @param {Object} [options] Optional options for how the HTTP client should be configured. + * @param {boolean} [options.useCache] Whether to use front end caching for all requests made + * with the returned client. + * @returns {HttpClient} A configured axios http client. + */ + }, { + key: "getHttpClient", + value: function getHttpClient() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (options.useCache) { + return this.cachedHttpClient; + } + return this.httpClient; + } + + /** + * Used primarily for testing. + * + * @ignore + */ + }, { + key: "getJwtTokenService", + value: function getJwtTokenService() { + return this.jwtTokenService; + } + + /** + * Used primarily for testing. + * + * @ignore + */ + }, { + key: "getCsrfTokenService", + value: function getCsrfTokenService() { + return this.csrfTokenService; + } + + /** + * Builds a URL to the login page with a post-login redirect URL attached as a query parameter. + * + * ``` + * const url = getLoginRedirectUrl('http://localhost/mypage'); + * console.log(url); // http://localhost/login?next=http%3A%2F%2Flocalhost%2Fmypage + * ``` + * + * @param {string} redirectUrl The URL the user should be redirected to after logging in. + */ + }, { + key: "getLoginRedirectUrl", + value: function getLoginRedirectUrl() { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.config.BASE_URL; + return "".concat(this.config.LOGIN_URL, "?next=").concat(encodeURIComponent(redirectUrl)); + } + + /** + * Redirects the user to the login page. + * + * @param {string} redirectUrl The URL the user should be redirected to after logging in. + */ + }, { + key: "redirectToLogin", + value: function redirectToLogin() { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.config.BASE_URL; + global.location.assign(this.getLoginRedirectUrl(redirectUrl)); + } + + /** + * Builds a URL to the logout page with a post-logout redirect URL attached as a query parameter. + * + * ``` + * const url = getLogoutRedirectUrl('http://localhost/mypage'); + * console.log(url); // http://localhost/logout?next=http%3A%2F%2Flocalhost%2Fmypage + * ``` + * + * @param {string} redirectUrl The URL the user should be redirected to after logging out. + */ + }, { + key: "getLogoutRedirectUrl", + value: function getLogoutRedirectUrl() { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.config.BASE_URL; + return "".concat(this.config.LOGOUT_URL, "?redirect_url=").concat(encodeURIComponent(redirectUrl)); + } + + /** + * Redirects the user to the logout page. + * + * @param {string} redirectUrl The URL the user should be redirected to after logging out. + */ + }, { + key: "redirectToLogout", + value: function redirectToLogout() { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.config.BASE_URL; + global.location.assign(this.getLogoutRedirectUrl(redirectUrl)); + } + + /** + * If it exists, returns the user data representing the currently authenticated user. If the + * user is anonymous, returns null. + * + * @returns {UserData|null} + */ + }, { + key: "getAuthenticatedUser", + value: function getAuthenticatedUser() { + return this.authenticatedUser; + } + + /** + * Sets the authenticated user to the provided value. + * + * @param {UserData} authUser + */ + }, { + key: "setAuthenticatedUser", + value: function setAuthenticatedUser(authUser) { + this.authenticatedUser = authUser; + } + + /** + * Reads the authenticated user's access token. Resolves to null if the user is + * unauthenticated. + * + * @returns {Promise|Promise} Resolves to the user's access token if they are + * logged in. + */ + }, { + key: "fetchAuthenticatedUser", + value: (function () { + var _fetchAuthenticatedUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var options, + decodedAccessToken, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + options = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + _context.next = 3; + return this.jwtTokenService.getJwtToken(options.forceRefresh || false); + case 3: + decodedAccessToken = _context.sent; + if (decodedAccessToken !== null) { + this.setAuthenticatedUser({ + email: decodedAccessToken.email, + userId: decodedAccessToken.user_id, + username: decodedAccessToken.preferred_username, + roles: decodedAccessToken.roles || [], + administrator: decodedAccessToken.administrator, + name: decodedAccessToken.name + }); + // Sets userId as a custom attribute that will be included with all subsequent log messages. + // Very helpful for debugging. + this.loggingService.setCustomAttribute('userId', decodedAccessToken.user_id); + } else { + this.setAuthenticatedUser(null); + // Intentionally not setting `userId` in the logging service here because it would be useful + // to know the previously logged in user for debugging refresh issues. + } + return _context.abrupt("return", this.getAuthenticatedUser()); + case 6: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchAuthenticatedUser() { + return _fetchAuthenticatedUser.apply(this, arguments); + } + return fetchAuthenticatedUser; + }() + /** + * Ensures a user is authenticated. It will redirect to login when not + * authenticated. + * + * @param {string} [redirectUrl=config.BASE_URL] to return user after login when not + * authenticated. + * @returns {Promise} + */ + ) + }, { + key: "ensureAuthenticatedUser", + value: (function () { + var _ensureAuthenticatedUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var redirectUrl, + isRedirectFromLoginPage, + redirectLoopError, + unauthorizedError, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + redirectUrl = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : this.config.BASE_URL; + _context2.next = 3; + return this.fetchAuthenticatedUser(); + case 3: + if (!(this.getAuthenticatedUser() === null)) { + _context2.next = 13; + break; + } + isRedirectFromLoginPage = global.document.referrer && global.document.referrer.startsWith(this.config.LOGIN_URL); + if (!isRedirectFromLoginPage) { + _context2.next = 9; + break; + } + redirectLoopError = new Error('Redirect from login page. Rejecting to avoid infinite redirect loop.'); + logFrontendAuthError(this.loggingService, redirectLoopError); + throw redirectLoopError; + case 9: + // The user is not authenticated, send them to the login page. + this.redirectToLogin(redirectUrl); + unauthorizedError = new Error('Failed to ensure the user is authenticated'); + unauthorizedError.isRedirecting = true; + throw unauthorizedError; + case 13: + return _context2.abrupt("return", this.getAuthenticatedUser()); + case 14: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function ensureAuthenticatedUser() { + return _ensureAuthenticatedUser.apply(this, arguments); + } + return ensureAuthenticatedUser; + }() + /** + * Fetches additional user account information for the authenticated user and merges it into the + * existing authenticatedUser object, available via getAuthenticatedUser(). + * + * ``` + * console.log(authenticatedUser); // Will be sparse and only contain basic information. + * await hydrateAuthenticatedUser() + * const authenticatedUser = getAuthenticatedUser(); + * console.log(authenticatedUser); // Will contain additional user information + * ``` + * + * @returns {Promise} + */ + ) + }, { + key: "hydrateAuthenticatedUser", + value: (function () { + var _hydrateAuthenticatedUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + var user, response; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + user = this.getAuthenticatedUser(); + if (!(user !== null)) { + _context3.next = 6; + break; + } + _context3.next = 4; + return this.authenticatedHttpClient.get("".concat(this.config.LMS_BASE_URL, "/api/user/v1/accounts/").concat(user.username)); + case 4: + response = _context3.sent; + this.setAuthenticatedUser(_objectSpread(_objectSpread({}, user), camelCaseObject(response.data))); + case 6: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function hydrateAuthenticatedUser() { + return _hydrateAuthenticatedUser.apply(this, arguments); + } + return hydrateAuthenticatedUser; + }() + /** + * Adds authentication defaults and interceptors to an HTTP client instance. + * + * @param {HttpClient} newHttpClient + * @param {Object} config + * @param {string} [config.REFRESH_ACCESS_TOKEN_ENDPOINT] + * @param {string} [config.ACCESS_TOKEN_COOKIE_NAME] + * @param {string} [config.CSRF_TOKEN_API_PATH] + * @returns {HttpClient} A configured Axios HTTP client. + */ + ) + }, { + key: "addAuthenticationToHttpClient", + value: function addAuthenticationToHttpClient(newHttpClient) { + var httpClient = Object.create(newHttpClient); + // Set withCredentials to true. Enables cross-site Access-Control requests + // to be made using cookies, authorization headers or TLS client + // certificates. More on MDN: + // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials + httpClient.defaults.withCredentials = true; + + // Axios interceptors + + // The JWT access token interceptor attempts to refresh the user's jwt token + // before any request unless the isPublic flag is set on the request config. + var refreshAccessTokenInterceptor = createJwtTokenProviderInterceptor({ + jwtTokenService: this.jwtTokenService, + shouldSkip: function shouldSkip(axiosRequestConfig) { + return axiosRequestConfig.isPublic; + } + }); + // The CSRF token intercepter fetches and caches a csrf token for any post, + // put, patch, or delete request. That token is then added to the request + // headers. + var attachCsrfTokenInterceptor = createCsrfTokenProviderInterceptor({ + csrfTokenService: this.csrfTokenService, + CSRF_TOKEN_API_PATH: this.config.CSRF_TOKEN_API_PATH, + shouldSkip: function shouldSkip(axiosRequestConfig) { + var method = axiosRequestConfig.method, + isCsrfExempt = axiosRequestConfig.isCsrfExempt; + var CSRF_PROTECTED_METHODS = ['post', 'put', 'patch', 'delete']; + return isCsrfExempt || !CSRF_PROTECTED_METHODS.includes(method); + } + }); + var processAxiosRequestErrorInterceptor = createProcessAxiosRequestErrorInterceptor({ + loggingService: this.loggingService + }); + + // Request interceptors: Axios runs the interceptors in reverse order from + // how they are listed. After fetching csrf tokens no longer require jwt + // authentication, it won't matter which happens first. This change is + // coming soon in edx-platform. Nov. 2019 + httpClient.interceptors.request.use(attachCsrfTokenInterceptor); + httpClient.interceptors.request.use(refreshAccessTokenInterceptor); + + // Response interceptor: moves axios response error data into the error + // object at error.customAttributes + httpClient.interceptors.response.use(function (response) { + return response; + }, processAxiosRequestErrorInterceptor); + return httpClient; + } + }]); +}(); +export default AxiosJwtAuthService; +//# sourceMappingURL=AxiosJwtAuthService.js.map \ No newline at end of file diff --git a/dist/auth/AxiosJwtAuthService.js.map b/dist/auth/AxiosJwtAuthService.js.map new file mode 100644 index 000000000..824d50fc0 --- /dev/null +++ b/dist/auth/AxiosJwtAuthService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AxiosJwtAuthService.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","_classCallCheck","_defineProperties","_toPropertyKey","key","_createClass","_toPrimitive","toPrimitive","String","Number","axios","PropTypes","logFrontendAuthError","camelCaseObject","ensureDefinedConfig","createJwtTokenProviderInterceptor","createCsrfTokenProviderInterceptor","createProcessAxiosRequestErrorInterceptor","AxiosJwtTokenService","AxiosCsrfTokenService","configureCache","optionsPropTypes","config","shape","BASE_URL","string","isRequired","LMS_BASE_URL","LOGIN_URL","LOGOUT_URL","REFRESH_ACCESS_TOKEN_ENDPOINT","ACCESS_TOKEN_COOKIE_NAME","CSRF_TOKEN_API_PATH","loggingService","logError","func","logInfo","AxiosJwtAuthService","options","_this","authenticatedHttpClient","httpClient","cachedAuthenticatedHttpClient","cachedHttpClient","authenticatedUser","checkPropTypes","jwtTokenService","csrfTokenService","addAuthenticationToHttpClient","cachedAxiosClient","concat","message","middleware","applyMiddleware","undefined","clients","middlewareFn","client","error","getAuthenticatedHttpClient","useCache","getHttpClient","getJwtTokenService","getCsrfTokenService","getLoginRedirectUrl","redirectUrl","encodeURIComponent","redirectToLogin","global","location","assign","getLogoutRedirectUrl","redirectToLogout","getAuthenticatedUser","setAuthenticatedUser","authUser","_fetchAuthenticatedUser","_callee","decodedAccessToken","_args","_callee$","_context","getJwtToken","forceRefresh","email","userId","user_id","username","preferred_username","roles","administrator","setCustomAttribute","fetchAuthenticatedUser","_ensureAuthenticatedUser","_callee2","isRedirectFromLoginPage","redirectLoopError","unauthorizedError","_args2","_callee2$","_context2","document","referrer","startsWith","isRedirecting","ensureAuthenticatedUser","_hydrateAuthenticatedUser","_callee3","user","response","_callee3$","_context3","get","_objectSpread","data","hydrateAuthenticatedUser","newHttpClient","defaults","withCredentials","refreshAccessTokenInterceptor","shouldSkip","axiosRequestConfig","isPublic","attachCsrfTokenInterceptor","isCsrfExempt","CSRF_PROTECTED_METHODS","includes","processAxiosRequestErrorInterceptor","interceptors","request","use"],"sources":["../../src/auth/AxiosJwtAuthService.js"],"sourcesContent":["import axios from 'axios';\nimport PropTypes from 'prop-types';\nimport { logFrontendAuthError } from './utils';\nimport { camelCaseObject, ensureDefinedConfig } from '../utils';\nimport createJwtTokenProviderInterceptor from './interceptors/createJwtTokenProviderInterceptor';\nimport createCsrfTokenProviderInterceptor from './interceptors/createCsrfTokenProviderInterceptor';\nimport createProcessAxiosRequestErrorInterceptor from './interceptors/createProcessAxiosRequestErrorInterceptor';\nimport AxiosJwtTokenService from './AxiosJwtTokenService';\nimport AxiosCsrfTokenService from './AxiosCsrfTokenService';\nimport configureCache from './LocalForageCache';\n\nconst optionsPropTypes = {\n config: PropTypes.shape({\n BASE_URL: PropTypes.string.isRequired,\n LMS_BASE_URL: PropTypes.string.isRequired,\n LOGIN_URL: PropTypes.string.isRequired,\n LOGOUT_URL: PropTypes.string.isRequired,\n REFRESH_ACCESS_TOKEN_ENDPOINT: PropTypes.string.isRequired,\n ACCESS_TOKEN_COOKIE_NAME: PropTypes.string.isRequired,\n CSRF_TOKEN_API_PATH: PropTypes.string.isRequired,\n }).isRequired,\n loggingService: PropTypes.shape({\n logError: PropTypes.func.isRequired,\n logInfo: PropTypes.func.isRequired,\n }).isRequired,\n};\n\n/**\n * @implements {AuthService}\n * @memberof module:Auth\n */\nclass AxiosJwtAuthService {\n /**\n * @param {Object} options\n * @param {Object} options.config\n * @param {string} options.config.BASE_URL\n * @param {string} options.config.LMS_BASE_URL\n * @param {string} options.config.LOGIN_URL\n * @param {string} options.config.LOGOUT_URL\n * @param {string} options.config.REFRESH_ACCESS_TOKEN_ENDPOINT\n * @param {string} options.config.ACCESS_TOKEN_COOKIE_NAME\n * @param {string} options.config.CSRF_TOKEN_API_PATH\n * @param {Object} options.loggingService requires logError and logInfo methods\n */\n constructor(options) {\n this.authenticatedHttpClient = null;\n this.httpClient = null;\n this.cachedAuthenticatedHttpClient = null;\n this.cachedHttpClient = null;\n this.authenticatedUser = null;\n\n ensureDefinedConfig(options, 'AuthService');\n PropTypes.checkPropTypes(optionsPropTypes, options, 'options', 'AuthService');\n\n this.config = options.config;\n this.loggingService = options.loggingService;\n this.jwtTokenService = new AxiosJwtTokenService(\n this.loggingService,\n this.config.ACCESS_TOKEN_COOKIE_NAME,\n this.config.REFRESH_ACCESS_TOKEN_ENDPOINT,\n );\n this.csrfTokenService = new AxiosCsrfTokenService(this.config.CSRF_TOKEN_API_PATH);\n this.authenticatedHttpClient = this.addAuthenticationToHttpClient(axios.create());\n this.httpClient = axios.create();\n configureCache()\n .then((cachedAxiosClient) => {\n this.cachedAuthenticatedHttpClient = this.addAuthenticationToHttpClient(cachedAxiosClient);\n this.cachedHttpClient = cachedAxiosClient;\n })\n .catch((e) => {\n // fallback to non-cached HTTP clients and log error\n this.cachedAuthenticatedHttpClient = this.authenticatedHttpClient;\n this.cachedHttpClient = this.httpClient;\n logFrontendAuthError(this.loggingService, `configureCache failed with error: ${e.message}`);\n }).finally(() => {\n this.middleware = options.middleware;\n this.applyMiddleware(options.middleware);\n });\n }\n\n /**\n * Applies middleware to the axios instances in this service.\n *\n * @param {Array} middleware Middleware to apply.\n */\n applyMiddleware(middleware = []) {\n const clients = [\n this.authenticatedHttpClient, this.httpClient,\n this.cachedAuthenticatedHttpClient, this.cachedHttpClient,\n ];\n try {\n (middleware).forEach((middlewareFn) => {\n clients.forEach((client) => client && middlewareFn(client));\n });\n } catch (error) {\n logFrontendAuthError(this.loggingService, error);\n throw error;\n }\n }\n\n /**\n * Gets the authenticated HTTP client for the service. This is an axios instance.\n *\n * @param {Object} [options] Optional options for how the HTTP client should be configured.\n * @param {boolean} [options.useCache] Whether to use front end caching for all requests made\n * with the returned client.\n *\n * @returns {HttpClient} A configured axios http client which can be used for authenticated\n * requests.\n */\n getAuthenticatedHttpClient(options = {}) {\n if (options.useCache) {\n return this.cachedAuthenticatedHttpClient;\n }\n\n return this.authenticatedHttpClient;\n }\n\n /**\n * Gets the unauthenticated HTTP client for the service. This is an axios instance.\n *\n * @param {Object} [options] Optional options for how the HTTP client should be configured.\n * @param {boolean} [options.useCache] Whether to use front end caching for all requests made\n * with the returned client.\n * @returns {HttpClient} A configured axios http client.\n */\n getHttpClient(options = {}) {\n if (options.useCache) {\n return this.cachedHttpClient;\n }\n\n return this.httpClient;\n }\n\n /**\n * Used primarily for testing.\n *\n * @ignore\n */\n getJwtTokenService() {\n return this.jwtTokenService;\n }\n\n /**\n * Used primarily for testing.\n *\n * @ignore\n */\n getCsrfTokenService() {\n return this.csrfTokenService;\n }\n\n /**\n * Builds a URL to the login page with a post-login redirect URL attached as a query parameter.\n *\n * ```\n * const url = getLoginRedirectUrl('http://localhost/mypage');\n * console.log(url); // http://localhost/login?next=http%3A%2F%2Flocalhost%2Fmypage\n * ```\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging in.\n */\n getLoginRedirectUrl(redirectUrl = this.config.BASE_URL) {\n return `${this.config.LOGIN_URL}?next=${encodeURIComponent(redirectUrl)}`;\n }\n\n /**\n * Redirects the user to the login page.\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging in.\n */\n redirectToLogin(redirectUrl = this.config.BASE_URL) {\n global.location.assign(this.getLoginRedirectUrl(redirectUrl));\n }\n\n /**\n * Builds a URL to the logout page with a post-logout redirect URL attached as a query parameter.\n *\n * ```\n * const url = getLogoutRedirectUrl('http://localhost/mypage');\n * console.log(url); // http://localhost/logout?next=http%3A%2F%2Flocalhost%2Fmypage\n * ```\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging out.\n */\n getLogoutRedirectUrl(redirectUrl = this.config.BASE_URL) {\n return `${this.config.LOGOUT_URL}?redirect_url=${encodeURIComponent(redirectUrl)}`;\n }\n\n /**\n * Redirects the user to the logout page.\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging out.\n */\n redirectToLogout(redirectUrl = this.config.BASE_URL) {\n global.location.assign(this.getLogoutRedirectUrl(redirectUrl));\n }\n\n /**\n * If it exists, returns the user data representing the currently authenticated user. If the\n * user is anonymous, returns null.\n *\n * @returns {UserData|null}\n */\n getAuthenticatedUser() {\n return this.authenticatedUser;\n }\n\n /**\n * Sets the authenticated user to the provided value.\n *\n * @param {UserData} authUser\n */\n setAuthenticatedUser(authUser) {\n this.authenticatedUser = authUser;\n }\n\n /**\n * Reads the authenticated user's access token. Resolves to null if the user is\n * unauthenticated.\n *\n * @returns {Promise|Promise} Resolves to the user's access token if they are\n * logged in.\n */\n async fetchAuthenticatedUser(options = {}) {\n const decodedAccessToken = await this.jwtTokenService.getJwtToken(options.forceRefresh || false);\n\n if (decodedAccessToken !== null) {\n this.setAuthenticatedUser({\n email: decodedAccessToken.email,\n userId: decodedAccessToken.user_id,\n username: decodedAccessToken.preferred_username,\n roles: decodedAccessToken.roles || [],\n administrator: decodedAccessToken.administrator,\n name: decodedAccessToken.name,\n });\n // Sets userId as a custom attribute that will be included with all subsequent log messages.\n // Very helpful for debugging.\n this.loggingService.setCustomAttribute('userId', decodedAccessToken.user_id);\n } else {\n this.setAuthenticatedUser(null);\n // Intentionally not setting `userId` in the logging service here because it would be useful\n // to know the previously logged in user for debugging refresh issues.\n }\n\n return this.getAuthenticatedUser();\n }\n\n /**\n * Ensures a user is authenticated. It will redirect to login when not\n * authenticated.\n *\n * @param {string} [redirectUrl=config.BASE_URL] to return user after login when not\n * authenticated.\n * @returns {Promise}\n */\n async ensureAuthenticatedUser(redirectUrl = this.config.BASE_URL) {\n await this.fetchAuthenticatedUser();\n\n if (this.getAuthenticatedUser() === null) {\n const isRedirectFromLoginPage = global.document.referrer\n && global.document.referrer.startsWith(this.config.LOGIN_URL);\n\n if (isRedirectFromLoginPage) {\n const redirectLoopError = new Error('Redirect from login page. Rejecting to avoid infinite redirect loop.');\n logFrontendAuthError(this.loggingService, redirectLoopError);\n throw redirectLoopError;\n }\n\n // The user is not authenticated, send them to the login page.\n this.redirectToLogin(redirectUrl);\n\n const unauthorizedError = new Error('Failed to ensure the user is authenticated');\n unauthorizedError.isRedirecting = true;\n throw unauthorizedError;\n }\n\n return this.getAuthenticatedUser();\n }\n\n /**\n * Fetches additional user account information for the authenticated user and merges it into the\n * existing authenticatedUser object, available via getAuthenticatedUser().\n *\n * ```\n * console.log(authenticatedUser); // Will be sparse and only contain basic information.\n * await hydrateAuthenticatedUser()\n * const authenticatedUser = getAuthenticatedUser();\n * console.log(authenticatedUser); // Will contain additional user information\n * ```\n *\n * @returns {Promise}\n */\n async hydrateAuthenticatedUser() {\n const user = this.getAuthenticatedUser();\n if (user !== null) {\n const response = await this.authenticatedHttpClient\n .get(`${this.config.LMS_BASE_URL}/api/user/v1/accounts/${user.username}`);\n this.setAuthenticatedUser({ ...user, ...camelCaseObject(response.data) });\n }\n }\n\n /**\n * Adds authentication defaults and interceptors to an HTTP client instance.\n *\n * @param {HttpClient} newHttpClient\n * @param {Object} config\n * @param {string} [config.REFRESH_ACCESS_TOKEN_ENDPOINT]\n * @param {string} [config.ACCESS_TOKEN_COOKIE_NAME]\n * @param {string} [config.CSRF_TOKEN_API_PATH]\n * @returns {HttpClient} A configured Axios HTTP client.\n */\n addAuthenticationToHttpClient(newHttpClient) {\n const httpClient = Object.create(newHttpClient);\n // Set withCredentials to true. Enables cross-site Access-Control requests\n // to be made using cookies, authorization headers or TLS client\n // certificates. More on MDN:\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials\n httpClient.defaults.withCredentials = true;\n\n // Axios interceptors\n\n // The JWT access token interceptor attempts to refresh the user's jwt token\n // before any request unless the isPublic flag is set on the request config.\n const refreshAccessTokenInterceptor = createJwtTokenProviderInterceptor({\n jwtTokenService: this.jwtTokenService,\n shouldSkip: axiosRequestConfig => axiosRequestConfig.isPublic,\n });\n // The CSRF token intercepter fetches and caches a csrf token for any post,\n // put, patch, or delete request. That token is then added to the request\n // headers.\n const attachCsrfTokenInterceptor = createCsrfTokenProviderInterceptor({\n csrfTokenService: this.csrfTokenService,\n CSRF_TOKEN_API_PATH: this.config.CSRF_TOKEN_API_PATH,\n shouldSkip: (axiosRequestConfig) => {\n const { method, isCsrfExempt } = axiosRequestConfig;\n const CSRF_PROTECTED_METHODS = ['post', 'put', 'patch', 'delete'];\n return isCsrfExempt || !CSRF_PROTECTED_METHODS.includes(method);\n },\n });\n\n const processAxiosRequestErrorInterceptor = createProcessAxiosRequestErrorInterceptor({\n loggingService: this.loggingService,\n });\n\n // Request interceptors: Axios runs the interceptors in reverse order from\n // how they are listed. After fetching csrf tokens no longer require jwt\n // authentication, it won't matter which happens first. This change is\n // coming soon in edx-platform. Nov. 2019\n httpClient.interceptors.request.use(attachCsrfTokenInterceptor);\n httpClient.interceptors.request.use(refreshAccessTokenInterceptor);\n\n // Response interceptor: moves axios response error data into the error\n // object at error.customAttributes\n httpClient.interceptors.response.use(\n response => response,\n processAxiosRequestErrorInterceptor,\n );\n\n return httpClient;\n }\n}\n\nexport default AxiosJwtAuthService;\n"],"mappings":";;;;+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,CAAA,SAAAC,CAAA,EAAAD,CAAA,OAAAE,CAAA,GAAAC,MAAA,CAAAC,SAAA,EAAAC,CAAA,GAAAH,CAAA,CAAAI,cAAA,EAAAC,CAAA,GAAAJ,MAAA,CAAAK,cAAA,cAAAP,CAAA,EAAAD,CAAA,EAAAE,CAAA,IAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,CAAAO,KAAA,KAAAC,CAAA,wBAAAC,MAAA,GAAAA,MA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dist/auth/AxiosJwtTokenService.js b/dist/auth/AxiosJwtTokenService.js new file mode 100644 index 000000000..90f3c0de6 --- /dev/null +++ b/dist/auth/AxiosJwtTokenService.js @@ -0,0 +1,200 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +import Cookies from 'universal-cookie'; +import jwtDecode from 'jwt-decode'; +import axios from 'axios'; +import { logFrontendAuthError, processAxiosErrorAndThrow } from './utils'; +import createRetryInterceptor from './interceptors/createRetryInterceptor'; +var AxiosJwtTokenService = /*#__PURE__*/function () { + function AxiosJwtTokenService(loggingService, tokenCookieName, tokenRefreshEndpoint) { + _classCallCheck(this, AxiosJwtTokenService); + this.loggingService = loggingService; + this.tokenCookieName = tokenCookieName; + this.tokenRefreshEndpoint = tokenRefreshEndpoint; + this.httpClient = axios.create(); + // Set withCredentials to true. Enables cross-site Access-Control requests + // to be made using cookies, authorization headers or TLS client + // certificates. More on MDN: + // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials + this.httpClient.defaults.withCredentials = true; + // Add retries to this axios instance + this.httpClient.interceptors.response.use(function (response) { + return response; + }, createRetryInterceptor({ + httpClient: this.httpClient + })); + this.cookies = new Cookies(); + this.refreshRequestPromises = {}; + } + return _createClass(AxiosJwtTokenService, [{ + key: "getHttpClient", + value: function getHttpClient() { + return this.httpClient; + } + }, { + key: "decodeJwtCookie", + value: function decodeJwtCookie() { + var cookieValue = this.cookies.get(this.tokenCookieName); + if (cookieValue) { + try { + return jwtDecode(cookieValue); + } catch (e) { + var error = Object.create(e); + error.message = 'Error decoding JWT token'; + error.customAttributes = { + cookieValue: cookieValue + }; + throw error; + } + } + return null; + } + }, { + key: "refresh", + value: function refresh() { + var _this = this; + var responseServerEpochSeconds = 0; + if (this.refreshRequestPromises[this.tokenCookieName] === undefined) { + var makeRefreshRequest = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var axiosResponse, userIsUnauthenticated, _decodedJwtToken, browserEpochSeconds, browserDriftSeconds, decodedJwtToken, error; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.prev = 1; + _context.next = 4; + return _this.httpClient.post(_this.tokenRefreshEndpoint); + case 4: + axiosResponse = _context.sent; + // eslint-disable-next-line max-len + if (axiosResponse.data && axiosResponse.data.response_epoch_seconds) { + responseServerEpochSeconds = axiosResponse.data.response_epoch_seconds; + } + _context.next = 11; + break; + case 8: + _context.prev = 8; + _context.t0 = _context["catch"](1); + processAxiosErrorAndThrow(_context.t0); + case 11: + _context.next = 21; + break; + case 13: + _context.prev = 13; + _context.t1 = _context["catch"](0); + userIsUnauthenticated = _context.t1.response && _context.t1.response.status === 401; + if (!userIsUnauthenticated) { + _context.next = 20; + break; + } + // Clean up the cookie if it exists to eliminate any situation + // where the cookie is not expired but the jwt is expired. + _this.cookies.remove(_this.tokenCookieName); + _decodedJwtToken = null; + return _context.abrupt("return", _decodedJwtToken); + case 20: + throw _context.t1; + case 21: + browserEpochSeconds = Date.now() / 1000; + browserDriftSeconds = responseServerEpochSeconds > 0 ? Math.abs(browserEpochSeconds - responseServerEpochSeconds) : null; + decodedJwtToken = _this.decodeJwtCookie(); + if (decodedJwtToken) { + _context.next = 28; + break; + } + // This is an unexpected case. The refresh endpoint should set the + // cookie that is needed. + // For more details, see: + // docs/decisions/0005-token-null-after-successful-refresh.rst + error = new Error('Access token is still null after successful refresh.'); + error.customAttributes = { + axiosResponse: axiosResponse, + browserDriftSeconds: browserDriftSeconds, + browserEpochSeconds: browserEpochSeconds + }; + throw error; + case 28: + return _context.abrupt("return", decodedJwtToken); + case 29: + case "end": + return _context.stop(); + } + }, _callee, null, [[0, 13], [1, 8]]); + })); + return function makeRefreshRequest() { + return _ref.apply(this, arguments); + }; + }(); + this.refreshRequestPromises[this.tokenCookieName] = makeRefreshRequest()["finally"](function () { + delete _this.refreshRequestPromises[_this.tokenCookieName]; + }); + } + return this.refreshRequestPromises[this.tokenCookieName]; + } + }, { + key: "getJwtToken", + value: function () { + var _getJwtToken = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var forceRefresh, + decodedJwtToken, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + forceRefresh = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : false; + _context2.prev = 1; + decodedJwtToken = this.decodeJwtCookie(this.tokenCookieName); + if (!(!AxiosJwtTokenService.isTokenExpired(decodedJwtToken) && !forceRefresh)) { + _context2.next = 5; + break; + } + return _context2.abrupt("return", decodedJwtToken); + case 5: + _context2.next = 10; + break; + case 7: + _context2.prev = 7; + _context2.t0 = _context2["catch"](1); + // Log unexpected error and continue with attempt to refresh it. + // TODO: Fix these. They're still using loggingService as a singleton. + logFrontendAuthError(this.loggingService, _context2.t0); + case 10: + _context2.prev = 10; + _context2.next = 13; + return this.refresh(); + case 13: + return _context2.abrupt("return", _context2.sent); + case 16: + _context2.prev = 16; + _context2.t1 = _context2["catch"](10); + // TODO: Fix these. They're still using loggingService as a singleton. + logFrontendAuthError(this.loggingService, _context2.t1); + throw _context2.t1; + case 20: + case "end": + return _context2.stop(); + } + }, _callee2, this, [[1, 7], [10, 16]]); + })); + function getJwtToken() { + return _getJwtToken.apply(this, arguments); + } + return getJwtToken; + }() + }], [{ + key: "isTokenExpired", + value: function isTokenExpired(token) { + return !token || token.exp < Date.now() / 1000; + } + }]); +}(); +export { AxiosJwtTokenService as default }; +//# sourceMappingURL=AxiosJwtTokenService.js.map \ No newline at end of file diff --git a/dist/auth/AxiosJwtTokenService.js.map b/dist/auth/AxiosJwtTokenService.js.map new file mode 100644 index 000000000..010a99028 --- /dev/null +++ b/dist/auth/AxiosJwtTokenService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AxiosJwtTokenService.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","_classCallCheck","_defineProperties","_toPropertyKey","key","_createClass","_toPrimitive","toPrimitive","String","Number","Cookies","jwtDecode","axios","logFrontendAuthError","processAxiosErrorAndThrow","createRetryInterceptor","AxiosJwtTokenService","loggingService","tokenCookieName","tokenRefreshEndpoint","httpClient","defaults","withCredentials","interceptors","response","use","cookies","refreshRequestPromises","getHttpClient","decodeJwtCookie","cookieValue","get","error","message","customAttributes","refresh","_this","responseServerEpochSeconds","undefined","makeRefreshRequest","_ref","_callee","axiosResponse","userIsUnauthenticated","_decodedJwtToken","browserEpochSeconds","browserDriftSeconds","decodedJwtToken","_callee$","_context","post","data","response_epoch_seconds","t0","t1","status","remove","Date","now","Math","abs","_getJwtToken","_callee2","forceRefresh","_args2","_callee2$","_context2","isTokenExpired","getJwtToken","token","exp","default"],"sources":["../../src/auth/AxiosJwtTokenService.js"],"sourcesContent":["import Cookies from 'universal-cookie';\nimport jwtDecode from 'jwt-decode';\nimport axios from 'axios';\nimport { logFrontendAuthError, processAxiosErrorAndThrow } from './utils';\nimport createRetryInterceptor from './interceptors/createRetryInterceptor';\n\nexport default class AxiosJwtTokenService {\n static isTokenExpired(token) {\n return !token || token.exp < Date.now() / 1000;\n }\n\n constructor(loggingService, tokenCookieName, tokenRefreshEndpoint) {\n this.loggingService = loggingService;\n this.tokenCookieName = tokenCookieName;\n this.tokenRefreshEndpoint = tokenRefreshEndpoint;\n\n this.httpClient = axios.create();\n // Set withCredentials to true. Enables cross-site Access-Control requests\n // to be made using cookies, authorization headers or TLS client\n // certificates. More on MDN:\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials\n this.httpClient.defaults.withCredentials = true;\n // Add retries to this axios instance\n this.httpClient.interceptors.response.use(\n response => response,\n createRetryInterceptor({ httpClient: this.httpClient }),\n );\n\n this.cookies = new Cookies();\n this.refreshRequestPromises = {};\n }\n\n getHttpClient() {\n return this.httpClient;\n }\n\n decodeJwtCookie() {\n const cookieValue = this.cookies.get(this.tokenCookieName);\n\n if (cookieValue) {\n try {\n return jwtDecode(cookieValue);\n } catch (e) {\n const error = Object.create(e);\n error.message = 'Error decoding JWT token';\n error.customAttributes = { cookieValue };\n throw error;\n }\n }\n\n return null;\n }\n\n refresh() {\n let responseServerEpochSeconds = 0;\n\n if (this.refreshRequestPromises[this.tokenCookieName] === undefined) {\n const makeRefreshRequest = async () => {\n let axiosResponse;\n try {\n try {\n axiosResponse = await this.httpClient.post(this.tokenRefreshEndpoint);\n // eslint-disable-next-line max-len\n if (axiosResponse.data && axiosResponse.data.response_epoch_seconds) {\n responseServerEpochSeconds = axiosResponse.data.response_epoch_seconds;\n }\n } catch (error) {\n processAxiosErrorAndThrow(error);\n }\n } catch (error) {\n const userIsUnauthenticated = error.response && error.response.status === 401;\n if (userIsUnauthenticated) {\n // Clean up the cookie if it exists to eliminate any situation\n // where the cookie is not expired but the jwt is expired.\n this.cookies.remove(this.tokenCookieName);\n const decodedJwtToken = null;\n return decodedJwtToken;\n }\n\n // TODO: Network timeouts and other problems will end up in\n // this block of code. We could add logic for retrying token\n // refreshes if we wanted to.\n throw error;\n }\n\n const browserEpochSeconds = Date.now() / 1000;\n const browserDriftSeconds = responseServerEpochSeconds > 0\n ? Math.abs(browserEpochSeconds - responseServerEpochSeconds)\n : null;\n\n const decodedJwtToken = this.decodeJwtCookie();\n\n if (!decodedJwtToken) {\n // This is an unexpected case. The refresh endpoint should set the\n // cookie that is needed.\n // For more details, see:\n // docs/decisions/0005-token-null-after-successful-refresh.rst\n const error = new Error('Access token is still null after successful refresh.');\n error.customAttributes = { axiosResponse, browserDriftSeconds, browserEpochSeconds };\n throw error;\n }\n\n return decodedJwtToken;\n };\n\n this.refreshRequestPromises[this.tokenCookieName] = makeRefreshRequest().finally(() => {\n delete this.refreshRequestPromises[this.tokenCookieName];\n });\n }\n\n return this.refreshRequestPromises[this.tokenCookieName];\n }\n\n async getJwtToken(forceRefresh = false) {\n try {\n const decodedJwtToken = this.decodeJwtCookie(this.tokenCookieName);\n if (!AxiosJwtTokenService.isTokenExpired(decodedJwtToken) && !forceRefresh) {\n return decodedJwtToken;\n }\n } catch (e) {\n // Log unexpected error and continue with attempt to refresh it.\n // TODO: Fix these. They're still using loggingService as a singleton.\n logFrontendAuthError(this.loggingService, e);\n }\n\n try {\n return await this.refresh();\n } catch (e) {\n // TODO: Fix these. They're still using loggingService as a singleton.\n logFrontendAuthError(this.loggingService, e);\n throw e;\n }\n }\n}\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,CAAA,SAAAC,CAAA,EAAAD,CAAA,OAAAE,CAAA,GAAAC,MAAA,CAAAC,SAAA,EAAAC,CAAA,GAAAH,CAAA,CAAAI,cAAA,EAAAC,CAAA,GAAAJ,MAAA,CAAAK,cAAA,cAAAP,CAAA,EAAAD,CAAA,EAAAE,CAAA,IAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,CAAAO,KAAA,KAAAC,CAAA,wBAAAC,MAAA,GAAAA,MAAA,OAAAC,CAAA,GAAAF,CAAA,CAAAG,QAAA,kBAAAC,CAAA,GAAAJ,CAAA,CAAAK,aAAA,uBAAAC,CAAA,GAAAN,CAAA,CAAAO,WAAA,8BAAAC,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAC,MAAA,CAAAK,cAAA,CAAAP,CAAA,EAAAD,CAAA,IAAAS,KAAA,EAAAP,CAAA,EAAAiB,UAAA,MAAAC,YAAA,MAAAC,QAAA,SAAApB,CAAA,CAAAD,CAAA,WAAAkB,MAAA,mBAAAjB,CAAA,IAAAiB,MAAA,YAAAA,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAD,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C,CAAC,GAAG,IAAI;IAChD;EAAC;AAAA;AAAA,SAHkB1C,oBAAoB,IAAAuD,OAAA","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/LocalForageCache.js b/dist/auth/LocalForageCache.js new file mode 100644 index 000000000..b6521d431 --- /dev/null +++ b/dist/auth/LocalForageCache.js @@ -0,0 +1,116 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/* eslint-disable no-underscore-dangle */ +import localforage from 'localforage'; +import memoryDriver from 'localforage-memoryStorageDriver'; +import { setupCache, defaultKeyGenerator, defaultHeaderInterpreter, buildStorage } from 'axios-cache-interceptor'; +import axios from 'axios'; + +/** + * Async function to configure localforage and setup the cache + * + * @returns {Promise} A promise that, when resolved, returns an axios instance configured to + * use localforage as a cache. + */ +export default function configureCache() { + return _configureCache.apply(this, arguments); +} +function _configureCache() { + _configureCache = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var forageStore, forageStoreAdapter; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return localforage.defineDriver(memoryDriver); + case 2: + // Create `localforage` instance + forageStore = localforage.createInstance({ + // List of drivers used + driver: [localforage.INDEXEDDB, localforage.LOCALSTORAGE, memoryDriver._driver], + name: 'edx-cache' + }); + forageStoreAdapter = buildStorage({ + find: function find(key) { + return _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var result; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return forageStore.getItem("axios-cache:".concat(key)); + case 2: + result = _context.sent; + return _context.abrupt("return", JSON.parse(result)); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + }))(); + }, + set: function set(key, value) { + return _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return forageStore.setItem("axios-cache:".concat(key), JSON.stringify(value)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + }))(); + }, + remove: function remove(key) { + return _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return forageStore.removeItem("axios-cache:".concat(key)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3); + }))(); + } + }); // only GET methods are cached by default + return _context4.abrupt("return", setupCache( + // axios instance + axios.create(), { + ttl: 5 * 60 * 1000, + // default maxAge of 5 minutes + // The storage to save the cache data. There are more available by default. + // + // https://axios-cache-interceptor.js.org/#/pages/storages + storage: forageStoreAdapter, + // The mechanism to generate a unique key for each request. + // + // https://axios-cache-interceptor.js.org/#/pages/request-id + generateKey: defaultKeyGenerator, + // The mechanism to interpret headers (when cache.interpretHeader is true). + // + // https://axios-cache-interceptor.js.org/#/pages/global-configuration?id=headerinterpreter + headerInterpreter: defaultHeaderInterpreter, + // The function that will receive debug information. + // NOTE: For this to work, you need to enable development mode. + // + // https://axios-cache-interceptor.js.org/#/pages/development-mode + // https://axios-cache-interceptor.js.org/#/pages/global-configuration?id=debug + // eslint-disable-next-line no-console + debug: console.log + })); + case 5: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _configureCache.apply(this, arguments); +} +//# sourceMappingURL=LocalForageCache.js.map \ No newline at end of file diff --git a/dist/auth/LocalForageCache.js.map b/dist/auth/LocalForageCache.js.map new file mode 100644 index 000000000..abc7a1a84 --- /dev/null +++ b/dist/auth/LocalForageCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"LocalForageCache.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","localforage","memoryDriver","setupCache","defaultKeyGenerator","defaultHeaderInterpreter","buildStorage","axios","configureCache","_configureCache","_callee4","forageStore","forageStoreAdapter","_callee4$","_context4","defineDriver","createInstance","driver","INDEXEDDB","LOCALSTORAGE","_driver","find","key","_callee","result","_callee$","_context","getItem","concat","JSON","parse","set","_callee2","_callee2$","_context2","setItem","stringify","remove","_callee3","_callee3$","_context3","removeItem","ttl","storage","generateKey","headerInterpreter","debug","console","log"],"sources":["../../src/auth/LocalForageCache.js"],"sourcesContent":["/* eslint-disable no-underscore-dangle */\nimport localforage from 'localforage';\nimport memoryDriver from 'localforage-memoryStorageDriver';\nimport {\n setupCache,\n defaultKeyGenerator,\n defaultHeaderInterpreter,\n buildStorage,\n} from 'axios-cache-interceptor';\nimport axios from 'axios';\n\n/**\n * Async function to configure localforage and setup the cache\n *\n * @returns {Promise} A promise that, when resolved, returns an axios instance configured to\n * use localforage as a cache.\n */\nexport default async function configureCache() {\n // Register the imported `memoryDriver` to `localforage`\n await localforage.defineDriver(memoryDriver);\n\n // Create `localforage` instance\n const forageStore = localforage.createInstance({\n // List of drivers used\n driver: [\n localforage.INDEXEDDB,\n localforage.LOCALSTORAGE,\n memoryDriver._driver,\n ],\n name: 'edx-cache',\n });\n\n const forageStoreAdapter = buildStorage({\n async find(key) {\n const result = await forageStore.getItem(`axios-cache:${key}`);\n return JSON.parse(result);\n },\n\n async set(key, value) {\n await forageStore.setItem(`axios-cache:${key}`, JSON.stringify(value));\n },\n\n async remove(key) {\n await forageStore.removeItem(`axios-cache:${key}`);\n },\n });\n\n // only GET methods are cached by default\n return setupCache(\n // axios instance\n axios.create(),\n {\n ttl: 5 * 60 * 1000, // default maxAge of 5 minutes\n // The storage to save the cache data. There are more available by default.\n //\n // https://axios-cache-interceptor.js.org/#/pages/storages\n storage: forageStoreAdapter,\n\n // The mechanism to generate a unique key for each request.\n //\n // https://axios-cache-interceptor.js.org/#/pages/request-id\n generateKey: defaultKeyGenerator,\n\n // The mechanism to interpret headers (when cache.interpretHeader is true).\n //\n // https://axios-cache-interceptor.js.org/#/pages/global-configuration?id=headerinterpreter\n headerInterpreter: defaultHeaderInterpreter,\n\n // The function that will receive debug information.\n // NOTE: For this to work, you need to enable development mode.\n //\n // https://axios-cache-interceptor.js.org/#/pages/development-mode\n // https://axios-cache-interceptor.js.org/#/pages/global-configuration?id=debug\n // eslint-disable-next-line no-console\n debug: console.log,\n },\n );\n}\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,CAAA,SAAAC,CAAA,EAAAD,CAAA,OAAAE,CAAA,GAAAC,MAAA,CAAAC,SAAA,EAAAC,CAAA,G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ACA;YACA;YACAgC,WAAW,EAAExC,mBAAmB;YAEhC;YACA;YACA;YACAyC,iBAAiB,EAAExC,wBAAwB;YAE3C;YACA;YACA;YACA;YACA;YACA;YACAyC,KAAK,EAAEC,OAAO,CAACC;UACjB,CACF,CAAC;QAAA;QAAA;UAAA,OAAAlC,SAAA,CAAA1B,IAAA;MAAA;IAAA,GAAAsB,QAAA;EAAA,CACF;EAAA,OAAAD,eAAA,CAAAX,KAAA,OAAAD,SAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/MockAuthService.js b/dist/auth/MockAuthService.js new file mode 100644 index 000000000..988648c85 --- /dev/null +++ b/dist/auth/MockAuthService.js @@ -0,0 +1,294 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +import axios from 'axios'; +import PropTypes from 'prop-types'; +import { ensureDefinedConfig } from '../utils'; +var userPropTypes = PropTypes.shape({ + userId: PropTypes.string.isRequired, + username: PropTypes.string.isRequired, + roles: PropTypes.arrayOf(PropTypes.string), + administrator: PropTypes["boolean"] +}); +var optionsPropTypes = { + config: PropTypes.shape({ + BASE_URL: PropTypes.string.isRequired, + LMS_BASE_URL: PropTypes.string.isRequired, + LOGIN_URL: PropTypes.string.isRequired, + LOGOUT_URL: PropTypes.string.isRequired, + REFRESH_ACCESS_TOKEN_ENDPOINT: PropTypes.string.isRequired, + ACCESS_TOKEN_COOKIE_NAME: PropTypes.string.isRequired, + CSRF_TOKEN_API_PATH: PropTypes.string.isRequired + }).isRequired, + loggingService: PropTypes.shape({ + logError: PropTypes.func.isRequired, + logInfo: PropTypes.func.isRequired + }).isRequired, + // The absence of authenticatedUser means the user is anonymous. + authenticatedUser: userPropTypes, + // Must be at least a valid user, but may have other fields. + hydratedAuthenticatedUser: userPropTypes +}; + +/** + * The MockAuthService class mocks authenticated user-fetching logic and allows for manually + * setting user data. It is compatible with axios-mock-adapter to wrap its HttpClients so that + * they can be mocked for testing. + * + * It wraps all methods of the service with Jest mock functions (jest.fn()). This allows test code + * to assert expectations on all functions of the service while preserving sensible behaviors. For + * instance, the login/logout methods related to redirecting maintain their real behavior. + * + * This service is NOT suitable for use in an application itself - only tests. It depends on Jest, + * which should only be a dev dependency of your project. You don't want to pull the entire suite + * of test dependencies into your application at runtime, probably even in your dev server. + * + * In a test where you would like to mock out API requests - perhaps from a redux-thunk function - + * you could do the following to set up a MockAuthService for your test: + * + * ``` + * import { getConfig, mergeConfig } from '@edx/frontend-platform'; + * import { configure, MockAuthService } from '@edx/frontend-platform/auth'; + * import MockAdapter from 'axios-mock-adapter'; + * + * const mockLoggingService = { + * logInfo: jest.fn(), + * logError: jest.fn(), + * }; + * mergeConfig({ + * authenticatedUser: { + * userId: 'abc123', + * username: 'Mock User', + * roles: [], + * administrator: false, + * }, + * }); + * configure(MockAuthService, { config: getConfig(), loggingService: mockLoggingService }); + * const mockAdapter = new MockAdapter(getAuthenticatedHttpClient()); + * // Mock calls for your tests. This configuration can be done in any sort of test setup. + * mockAdapter.onGet(...); + * ``` + * + * Also see the `initializeMockApp` function which also automatically uses mock services for + * Logging and Analytics. + * + * @implements {AuthService} + * @memberof module:Auth + */ +var MockAuthService = /*#__PURE__*/function () { + /** + * @param {Object} options + * @param {Object} options.config + * @param {string} options.config.BASE_URL + * @param {string} options.config.LMS_BASE_URL + * @param {string} options.config.LOGIN_URL + * @param {string} options.config.LOGOUT_URL + * @param {string} options.config.REFRESH_ACCESS_TOKEN_ENDPOINT + * @param {string} options.config.ACCESS_TOKEN_COOKIE_NAME + * @param {string} options.config.CSRF_TOKEN_API_PATH + * @param {Object} options.config.hydratedAuthenticatedUser + * @param {Object} options.config.authenticatedUser + * @param {Object} options.loggingService requires logError and logInfo methods + */ + function MockAuthService(options) { + var _this = this; + _classCallCheck(this, MockAuthService); + /** + * A Jest mock function (jest.fn()) + * + * Gets the authenticated HTTP client instance, which is an axios client wrapped in + * MockAdapter from axios-mock-adapter. + * + * @returns {HttpClient} An HttpClient wrapped in MockAdapter. + */ + _defineProperty(this, "getAuthenticatedHttpClient", jest.fn(function () { + return _this.authenticatedHttpClient; + })); + /** + * A Jest mock function (jest.fn()) + * + * Gets the unauthenticated HTTP client instance, which is an axios client wrapped in + * MockAdapter from axios-mock-adapter. + * + * @returns {HttpClient} An HttpClient wrapped in MockAdapter. + */ + _defineProperty(this, "getHttpClient", jest.fn(function () { + return _this.httpClient; + })); + /** + * A Jest mock function (jest.fn()) + * + * Builds a URL to the login page with a post-login redirect URL attached as a query parameter. + * + * ``` + * const url = getLoginRedirectUrl('http://localhost/mypage'); + * console.log(url); // http://localhost/login?next=http%3A%2F%2Flocalhost%2Fmypage + * ``` + * + * @param {string} redirectUrl The URL the user should be redirected to after logging in. + */ + _defineProperty(this, "getLoginRedirectUrl", jest.fn(function () { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.config.BASE_URL; + return "".concat(_this.config.LOGIN_URL, "?next=").concat(encodeURIComponent(redirectUrl)); + })); + /** + * A Jest mock function (jest.fn()) + * + * Redirects the user to the logout page in the real implementation. Is a no-op here. + * + * @param {string} redirectUrl The URL the user should be redirected to after logging in. + */ + _defineProperty(this, "redirectToLogin", jest.fn(function () { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.config.BASE_URL; + // Do nothing after getting the URL - this preserves the calls properly, but doesn't redirect. + _this.getLoginRedirectUrl(redirectUrl); + })); + /** + * A Jest mock function (jest.fn()) + * + * Builds a URL to the logout page with a post-logout redirect URL attached as a query parameter. + * + * ``` + * const url = getLogoutRedirectUrl('http://localhost/mypage'); + * console.log(url); // http://localhost/logout?next=http%3A%2F%2Flocalhost%2Fmypage + * ``` + * + * @param {string} redirectUrl The URL the user should be redirected to after logging out. + */ + _defineProperty(this, "getLogoutRedirectUrl", jest.fn(function () { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.config.BASE_URL; + return "".concat(_this.config.LOGOUT_URL, "?redirect_url=").concat(encodeURIComponent(redirectUrl)); + })); + /** + * A Jest mock function (jest.fn()) + * + * Redirects the user to the logout page in the real implementation. Is a no-op here. + * + * @param {string} redirectUrl The URL the user should be redirected to after logging out. + */ + _defineProperty(this, "redirectToLogout", jest.fn(function () { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.config.BASE_URL; + // Do nothing after getting the URL - this preserves the calls properly, but doesn't redirect. + _this.getLogoutRedirectUrl(redirectUrl); + })); + /** + * A Jest mock function (jest.fn()) + * + * If it exists, returns the user data representing the currently authenticated user. If the + * user is anonymous, returns null. + * + * @returns {UserData|null} + */ + _defineProperty(this, "getAuthenticatedUser", jest.fn(function () { + return _this.authenticatedUser; + })); + /** + * A Jest mock function (jest.fn()) + * + * Sets the authenticated user to the provided value. + * + * @param {UserData} authUser + */ + _defineProperty(this, "setAuthenticatedUser", jest.fn(function (authUser) { + _this.authenticatedUser = authUser; + })); + /** + * A Jest mock function (jest.fn()) + * + * Returns the current authenticated user details, as supplied in the `authenticatedUser` field + * of the config options. Resolves to null if the user is unauthenticated / the config option + * has not been set. + * + * @returns {UserData|null} Resolves to the user's access token if they are + * logged in. + */ + _defineProperty(this, "fetchAuthenticatedUser", jest.fn(function () { + return _this.getAuthenticatedUser(); + })); + /** + * A Jest mock function (jest.fn()) + * + * Ensures a user is authenticated. It will redirect to login when not authenticated. + * + * @param {string} [redirectUrl=config.BASE_URL] to return user after login when not + * authenticated. + * @returns {UserData|null} Resolves to the user's access token if they are + * logged in. + */ + _defineProperty(this, "ensureAuthenticatedUser", jest.fn(function () { + var redirectUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.config.BASE_URL; + _this.fetchAuthenticatedUser(); + if (_this.getAuthenticatedUser() === null) { + // The user is not authenticated, send them to the login page. + _this.redirectToLogin(redirectUrl); + } + return _this.getAuthenticatedUser(); + })); + /** + * A Jest mock function (jest.fn()) + * + * Adds the user data supplied in the `hydratedAuthenticatedUser` config option into the object + * returned by `getAuthenticatedUser`. This emulates the behavior of a real auth service which + * would make a request to fetch this data prior to merging it in. + * + * ``` + * console.log(authenticatedUser); // Will be sparse and only contain basic information. + * await hydrateAuthenticatedUser() + * const authenticatedUser = getAuthenticatedUser(); + * console.log(authenticatedUser); // Will contain additional user information + * ``` + * + * @returns {Promise} + */ + _defineProperty(this, "hydrateAuthenticatedUser", jest.fn(function () { + var user = _this.getAuthenticatedUser(); + if (user !== null) { + _this.setAuthenticatedUser(_objectSpread(_objectSpread({}, user), _this.hydratedAuthenticatedUser)); + } + })); + this.authenticatedHttpClient = null; + this.httpClient = null; + ensureDefinedConfig(options, 'AuthService'); + PropTypes.checkPropTypes(optionsPropTypes, options, 'options', 'AuthService'); + this.config = options.config; + this.loggingService = options.loggingService; + + // Mock user + this.authenticatedUser = this.config.authenticatedUser ? this.config.authenticatedUser : null; + this.hydratedAuthenticatedUser = this.config.hydratedAuthenticatedUser ? this.config.hydratedAuthenticatedUser : {}; + this.authenticatedHttpClient = axios.create(); + this.httpClient = axios.create(); + } + + /** + * A Jest mock function (jest.fn()) + * + * Applies middleware to the axios instances in this service. + * + * @param {Array} middleware Middleware to apply. + */ + return _createClass(MockAuthService, [{ + key: "applyMiddleware", + value: function applyMiddleware() { + var middleware = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var clients = [this.authenticatedHttpClient, this.httpClient, this.cachedAuthenticatedHttpClient, this.cachedHttpClient]; + try { + middleware.forEach(function (middlewareFn) { + clients.forEach(function (client) { + return client && middlewareFn(client); + }); + }); + } catch (error) { + throw new Error("Failed to apply middleware: ".concat(error.message, ".")); + } + } + }]); +}(); +export default MockAuthService; +//# sourceMappingURL=MockAuthService.js.map \ No newline at end of file diff --git a/dist/auth/MockAuthService.js.map b/dist/auth/MockAuthService.js.map new file mode 100644 index 000000000..5dcb7e146 --- /dev/null +++ b/dist/auth/MockAuthService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MockAuthService.js","names":["axios","PropTypes","ensureDefinedConfig","userPropTypes","shape","userId","string","isRequired","username","roles","arrayOf","administrator","optionsPropTypes","config","BASE_URL","LMS_BASE_URL","LOGIN_URL","LOGOUT_URL","REFRESH_ACCESS_TOKEN_ENDPOINT","ACCESS_TOKEN_COOKIE_NAME","CSRF_TOKEN_API_PATH","loggingService","logError","func","logInfo","authenticatedUser","hydratedAuthenticatedUser","MockAuthService","options","_this","_classCallCheck","_defineProperty","jest","fn","authenticatedHttpClient","httpClient","redirectUrl","arguments","length","undefined","concat","encodeURIComponent","getLoginRedirectUrl","getLogoutRedirectUrl","authUser","getAuthenticatedUser","fetchAuthenticatedUser","redirectToLogin","user","setAuthenticatedUser","_objectSpread","checkPropTypes","create","_createClass","key","value","applyMiddleware","middleware","clients","cachedAuthenticatedHttpClient","cachedHttpClient","forEach","middlewareFn","client","error","Error","message"],"sources":["../../src/auth/MockAuthService.js"],"sourcesContent":["import axios from 'axios';\nimport PropTypes from 'prop-types';\nimport { ensureDefinedConfig } from '../utils';\n\nconst userPropTypes = PropTypes.shape({\n userId: PropTypes.string.isRequired,\n username: PropTypes.string.isRequired,\n roles: PropTypes.arrayOf(PropTypes.string),\n administrator: PropTypes.boolean,\n});\n\nconst optionsPropTypes = {\n config: PropTypes.shape({\n BASE_URL: PropTypes.string.isRequired,\n LMS_BASE_URL: PropTypes.string.isRequired,\n LOGIN_URL: PropTypes.string.isRequired,\n LOGOUT_URL: PropTypes.string.isRequired,\n REFRESH_ACCESS_TOKEN_ENDPOINT: PropTypes.string.isRequired,\n ACCESS_TOKEN_COOKIE_NAME: PropTypes.string.isRequired,\n CSRF_TOKEN_API_PATH: PropTypes.string.isRequired,\n }).isRequired,\n loggingService: PropTypes.shape({\n logError: PropTypes.func.isRequired,\n logInfo: PropTypes.func.isRequired,\n }).isRequired,\n // The absence of authenticatedUser means the user is anonymous.\n authenticatedUser: userPropTypes,\n // Must be at least a valid user, but may have other fields.\n hydratedAuthenticatedUser: userPropTypes,\n};\n\n/**\n * The MockAuthService class mocks authenticated user-fetching logic and allows for manually\n * setting user data. It is compatible with axios-mock-adapter to wrap its HttpClients so that\n * they can be mocked for testing.\n *\n * It wraps all methods of the service with Jest mock functions (jest.fn()). This allows test code\n * to assert expectations on all functions of the service while preserving sensible behaviors. For\n * instance, the login/logout methods related to redirecting maintain their real behavior.\n *\n * This service is NOT suitable for use in an application itself - only tests. It depends on Jest,\n * which should only be a dev dependency of your project. You don't want to pull the entire suite\n * of test dependencies into your application at runtime, probably even in your dev server.\n *\n * In a test where you would like to mock out API requests - perhaps from a redux-thunk function -\n * you could do the following to set up a MockAuthService for your test:\n *\n * ```\n * import { getConfig, mergeConfig } from '@edx/frontend-platform';\n * import { configure, MockAuthService } from '@edx/frontend-platform/auth';\n * import MockAdapter from 'axios-mock-adapter';\n *\n * const mockLoggingService = {\n * logInfo: jest.fn(),\n * logError: jest.fn(),\n * };\n * mergeConfig({\n * authenticatedUser: {\n * userId: 'abc123',\n * username: 'Mock User',\n * roles: [],\n * administrator: false,\n * },\n * });\n * configure(MockAuthService, { config: getConfig(), loggingService: mockLoggingService });\n * const mockAdapter = new MockAdapter(getAuthenticatedHttpClient());\n * // Mock calls for your tests. This configuration can be done in any sort of test setup.\n * mockAdapter.onGet(...);\n * ```\n *\n * Also see the `initializeMockApp` function which also automatically uses mock services for\n * Logging and Analytics.\n *\n * @implements {AuthService}\n * @memberof module:Auth\n */\nclass MockAuthService {\n /**\n * @param {Object} options\n * @param {Object} options.config\n * @param {string} options.config.BASE_URL\n * @param {string} options.config.LMS_BASE_URL\n * @param {string} options.config.LOGIN_URL\n * @param {string} options.config.LOGOUT_URL\n * @param {string} options.config.REFRESH_ACCESS_TOKEN_ENDPOINT\n * @param {string} options.config.ACCESS_TOKEN_COOKIE_NAME\n * @param {string} options.config.CSRF_TOKEN_API_PATH\n * @param {Object} options.config.hydratedAuthenticatedUser\n * @param {Object} options.config.authenticatedUser\n * @param {Object} options.loggingService requires logError and logInfo methods\n */\n constructor(options) {\n this.authenticatedHttpClient = null;\n this.httpClient = null;\n\n ensureDefinedConfig(options, 'AuthService');\n PropTypes.checkPropTypes(optionsPropTypes, options, 'options', 'AuthService');\n\n this.config = options.config;\n this.loggingService = options.loggingService;\n\n // Mock user\n this.authenticatedUser = this.config.authenticatedUser ? this.config.authenticatedUser : null;\n this.hydratedAuthenticatedUser = this.config.hydratedAuthenticatedUser\n ? this.config.hydratedAuthenticatedUser\n : {};\n\n this.authenticatedHttpClient = axios.create();\n this.httpClient = axios.create();\n }\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Applies middleware to the axios instances in this service.\n *\n * @param {Array} middleware Middleware to apply.\n */\n applyMiddleware(middleware = []) {\n const clients = [\n this.authenticatedHttpClient, this.httpClient,\n this.cachedAuthenticatedHttpClient, this.cachedHttpClient,\n ];\n try {\n (middleware).forEach((middlewareFn) => {\n clients.forEach((client) => client && middlewareFn(client));\n });\n } catch (error) {\n throw new Error(`Failed to apply middleware: ${error.message}.`);\n }\n }\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Gets the authenticated HTTP client instance, which is an axios client wrapped in\n * MockAdapter from axios-mock-adapter.\n *\n * @returns {HttpClient} An HttpClient wrapped in MockAdapter.\n */\n getAuthenticatedHttpClient = jest.fn(() => this.authenticatedHttpClient);\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Gets the unauthenticated HTTP client instance, which is an axios client wrapped in\n * MockAdapter from axios-mock-adapter.\n *\n * @returns {HttpClient} An HttpClient wrapped in MockAdapter.\n */\n getHttpClient = jest.fn(() => this.httpClient);\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Builds a URL to the login page with a post-login redirect URL attached as a query parameter.\n *\n * ```\n * const url = getLoginRedirectUrl('http://localhost/mypage');\n * console.log(url); // http://localhost/login?next=http%3A%2F%2Flocalhost%2Fmypage\n * ```\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging in.\n */\n getLoginRedirectUrl = jest.fn(\n (redirectUrl = this.config.BASE_URL) => `${this.config.LOGIN_URL}?next=${encodeURIComponent(redirectUrl)}`,\n );\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Redirects the user to the logout page in the real implementation. Is a no-op here.\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging in.\n */\n redirectToLogin = jest.fn((redirectUrl = this.config.BASE_URL) => {\n // Do nothing after getting the URL - this preserves the calls properly, but doesn't redirect.\n this.getLoginRedirectUrl(redirectUrl);\n });\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Builds a URL to the logout page with a post-logout redirect URL attached as a query parameter.\n *\n * ```\n * const url = getLogoutRedirectUrl('http://localhost/mypage');\n * console.log(url); // http://localhost/logout?next=http%3A%2F%2Flocalhost%2Fmypage\n * ```\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging out.\n */\n getLogoutRedirectUrl = jest.fn((redirectUrl = this.config.BASE_URL) => `${this.config.LOGOUT_URL}?redirect_url=${encodeURIComponent(redirectUrl)}`);\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Redirects the user to the logout page in the real implementation. Is a no-op here.\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging out.\n */\n redirectToLogout = jest.fn((redirectUrl = this.config.BASE_URL) => {\n // Do nothing after getting the URL - this preserves the calls properly, but doesn't redirect.\n this.getLogoutRedirectUrl(redirectUrl);\n });\n\n /**\n * A Jest mock function (jest.fn())\n *\n * If it exists, returns the user data representing the currently authenticated user. If the\n * user is anonymous, returns null.\n *\n * @returns {UserData|null}\n */\n getAuthenticatedUser = jest.fn(() => this.authenticatedUser);\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Sets the authenticated user to the provided value.\n *\n * @param {UserData} authUser\n */\n setAuthenticatedUser = jest.fn((authUser) => {\n this.authenticatedUser = authUser;\n });\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Returns the current authenticated user details, as supplied in the `authenticatedUser` field\n * of the config options. Resolves to null if the user is unauthenticated / the config option\n * has not been set.\n *\n * @returns {UserData|null} Resolves to the user's access token if they are\n * logged in.\n */\n fetchAuthenticatedUser = jest.fn(() => this.getAuthenticatedUser());\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Ensures a user is authenticated. It will redirect to login when not authenticated.\n *\n * @param {string} [redirectUrl=config.BASE_URL] to return user after login when not\n * authenticated.\n * @returns {UserData|null} Resolves to the user's access token if they are\n * logged in.\n */\n ensureAuthenticatedUser = jest.fn((redirectUrl = this.config.BASE_URL) => {\n this.fetchAuthenticatedUser();\n\n if (this.getAuthenticatedUser() === null) {\n // The user is not authenticated, send them to the login page.\n this.redirectToLogin(redirectUrl);\n }\n\n return this.getAuthenticatedUser();\n });\n\n /**\n * A Jest mock function (jest.fn())\n *\n * Adds the user data supplied in the `hydratedAuthenticatedUser` config option into the object\n * returned by `getAuthenticatedUser`. This emulates the behavior of a real auth service which\n * would make a request to fetch this data prior to merging it in.\n *\n * ```\n * console.log(authenticatedUser); // Will be sparse and only contain basic information.\n * await hydrateAuthenticatedUser()\n * const authenticatedUser = getAuthenticatedUser();\n * console.log(authenticatedUser); // Will contain additional user information\n * ```\n *\n * @returns {Promise}\n */\n hydrateAuthenticatedUser = jest.fn(() => {\n const user = this.getAuthenticatedUser();\n if (user !== null) {\n this.setAuthenticatedUser({ ...user, ...this.hydratedAuthenticatedUser });\n }\n });\n}\n\nexport default MockAuthService;\n"],"mappings":";;;;;;;;;AAAA,OAAOA,KAAK,MAAM,OAAO;AACzB,OAAOC,SAAS,MAAM,YAAY;AAClC,SAASC,mBAAmB,QAAQ,UAAU;AAE9C,IAAMC,aAAa,GAAGF,SAAS,CAACG,KAAK,CAAC;EACpCC,MAAM,EAAEJ,SAAS,CAACK,MAAM,CAACC,UAAU;EACnCC,QAAQ,EAAEP,SAAS,CAACK,MAAM,CAACC,UAAU;EACrCE,KAAK,EAAER,SAAS,CAACS,OAAO,CAACT,SAAS,CAACK,MAAM,CAAC;EAC1CK,aAAa,EAAEV,SAAS;AAC1B,CAAC,CAAC;AAEF,IAAMW,gBAAgB,GAAG;EACvBC,MAAM,EAAEZ,SAAS,CAACG,KAAK,CAAC;IACtBU,QAAQ,EAAEb,SAAS,CAACK,MAAM,CAACC,UAAU;IACrCQ,YAAY,EAAEd,SAAS,CAACK,MAAM,CAACC,UAAU;IACzCS,SAAS,EAAEf,SAAS,CAACK,MAAM,CAACC,UAAU;IACtCU,UAAU,EAAEhB,SAAS,CAACK,MAAM,CAACC,UAAU;IACvCW,6BAA6B,EAAEjB,SAAS,CAACK,MAAM,CAACC,UAAU;IAC1DY,wBAAwB,EAAElB,SAAS,CAACK,MAAM,CAACC,UAAU;IACrDa,mBAAmB,EAAEnB,SAAS,CAACK,MAAM,CAACC;EACxC,CAAC,CAAC,CAACA,UAAU;EACbc,cAAc,EAAEpB,SAAS,CAACG,KAAK,CAAC;IAC9BkB,QAAQ,EAAErB,SAAS,CAACsB,IAAI,CAAChB,UAAU;IACnCiB,OAAO,EAAEvB,SAAS,CAACsB,IAAI,CAAChB;EAC1B,CAAC,CAAC,CAACA,UAAU;EACb;EACAkB,iBAAiB,EAAEtB,aAAa;EAChC;EACAuB,yBAAyB,EAAEvB;AAC7B,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA5CA,IA6CMwB,eAAe;EACnB;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACE,SAAAA,gBAAYC,OAAO,EAAE;IAAA,IAAAC,KAAA;IAAAC,eAAA,OAAAH,eAAA;IAyCrB;AACF;AACA;AACA;AACA;AACA;AACA;AACA;IAPEI,eAAA,qCAQ6BC,IAAI,CAACC,EAAE,CAAC;MAAA,OAAMJ,KAAI,CAACK,uBAAuB;IAAA,EAAC;IAExE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;IAPEH,eAAA,wBAQgBC,IAAI,CAACC,EAAE,CAAC;MAAA,OAAMJ,KAAI,CAACM,UAAU;IAAA,EAAC;IAE9C;AACF;AACA;AAC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,CAACG,OAAO,CAAC,UAACE,MAAM;YAAA,OAAKA,MAAM,IAAID,YAAY,CAACC,MAAM,CAAC;UAAA,EAAC;QAC7D,CAAC,CAAC;MACJ,CAAC,CAAC,OAAOC,KAAK,EAAE;QACd,MAAM,IAAIC,KAAK,gCAAAzB,MAAA,CAAgCwB,KAAK,CAACE,OAAO,MAAG,CAAC;MAClE;IACF;EAAC;AAAA;AA0JH,eAAevC,eAAe","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/index.js b/dist/auth/index.js new file mode 100644 index 000000000..72571b207 --- /dev/null +++ b/dist/auth/index.js @@ -0,0 +1,4 @@ +export { AUTHENTICATED_USER_TOPIC, AUTHENTICATED_USER_CHANGED, configure, getAuthenticatedHttpClient, getAuthService, getHttpClient, getLoginRedirectUrl, redirectToLogin, getLogoutRedirectUrl, redirectToLogout, getAuthenticatedUser, setAuthenticatedUser, fetchAuthenticatedUser, ensureAuthenticatedUser, hydrateAuthenticatedUser } from './interface'; +export { default as AxiosJwtAuthService } from './AxiosJwtAuthService'; +export { default as MockAuthService } from './MockAuthService'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/auth/index.js.map b/dist/auth/index.js.map new file mode 100644 index 000000000..d8d49410b --- /dev/null +++ b/dist/auth/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["AUTHENTICATED_USER_TOPIC","AUTHENTICATED_USER_CHANGED","configure","getAuthenticatedHttpClient","getAuthService","getHttpClient","getLoginRedirectUrl","redirectToLogin","getLogoutRedirectUrl","redirectToLogout","getAuthenticatedUser","setAuthenticatedUser","fetchAuthenticatedUser","ensureAuthenticatedUser","hydrateAuthenticatedUser","default","AxiosJwtAuthService","MockAuthService"],"sources":["../../src/auth/index.js"],"sourcesContent":["export {\n AUTHENTICATED_USER_TOPIC,\n AUTHENTICATED_USER_CHANGED,\n configure,\n getAuthenticatedHttpClient,\n getAuthService,\n getHttpClient,\n getLoginRedirectUrl,\n redirectToLogin,\n getLogoutRedirectUrl,\n redirectToLogout,\n getAuthenticatedUser,\n setAuthenticatedUser,\n fetchAuthenticatedUser,\n ensureAuthenticatedUser,\n hydrateAuthenticatedUser,\n} from './interface';\nexport { default as AxiosJwtAuthService } from './AxiosJwtAuthService';\nexport { default as MockAuthService } from './MockAuthService';\n"],"mappings":"AAAA,SACEA,wBAAwB,EACxBC,0BAA0B,EAC1BC,SAAS,EACTC,0BAA0B,EAC1BC,cAAc,EACdC,aAAa,EACbC,mBAAmB,EACnBC,eAAe,EACfC,oBAAoB,EACpBC,gBAAgB,EAChBC,oBAAoB,EACpBC,oBAAoB,EACpBC,sBAAsB,EACtBC,uBAAuB,EACvBC,wBAAwB,QACnB,aAAa;AACpB,SAASC,OAAO,IAAIC,mBAAmB,QAAQ,uBAAuB;AACtE,SAASD,OAAO,IAAIE,eAAe,QAAQ,mBAAmB","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/interceptors/createCsrfTokenProviderInterceptor.js b/dist/auth/interceptors/createCsrfTokenProviderInterceptor.js new file mode 100644 index 000000000..422a0b51b --- /dev/null +++ b/dist/auth/interceptors/createCsrfTokenProviderInterceptor.js @@ -0,0 +1,57 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var createCsrfTokenProviderInterceptor = function createCsrfTokenProviderInterceptor(options) { + var csrfTokenService = options.csrfTokenService, + CSRF_TOKEN_API_PATH = options.CSRF_TOKEN_API_PATH, + shouldSkip = options.shouldSkip; + + // Creating the interceptor inside this closure to + // maintain reference to the options supplied. + var interceptor = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(axiosRequestConfig) { + var url, csrfToken, requestError, CSRF_HEADER_NAME; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!shouldSkip(axiosRequestConfig)) { + _context.next = 2; + break; + } + return _context.abrupt("return", axiosRequestConfig); + case 2: + url = axiosRequestConfig.url; + _context.prev = 3; + _context.next = 6; + return csrfTokenService.getCsrfToken(url, CSRF_TOKEN_API_PATH); + case 6: + csrfToken = _context.sent; + _context.next = 15; + break; + case 9: + _context.prev = 9; + _context.t0 = _context["catch"](3); + requestError = Object.create(_context.t0); + requestError.message = "[getCsrfToken] ".concat(requestError.message); + // Important: return the original axios request config + requestError.config = axiosRequestConfig; + return _context.abrupt("return", Promise.reject(requestError)); + case 15: + CSRF_HEADER_NAME = 'X-CSRFToken'; // eslint-disable-next-line no-param-reassign + axiosRequestConfig.headers[CSRF_HEADER_NAME] = csrfToken; + return _context.abrupt("return", axiosRequestConfig); + case 18: + case "end": + return _context.stop(); + } + }, _callee, null, [[3, 9]]); + })); + return function interceptor(_x) { + return _ref.apply(this, arguments); + }; + }(); + return interceptor; +}; +export default createCsrfTokenProviderInterceptor; +//# sourceMappingURL=createCsrfTokenProviderInterceptor.js.map \ No newline at end of file diff --git a/dist/auth/interceptors/createCsrfTokenProviderInterceptor.js.map b/dist/auth/interceptors/createCsrfTokenProviderInterceptor.js.map new file mode 100644 index 000000000..cd618224f --- /dev/null +++ b/dist/auth/interceptors/createCsrfTokenProviderInterceptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"createCsrfTokenProviderInterceptor.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","createCsrfTokenProviderInterceptor","options","csrfTokenService","CSRF_TOKEN_API_PATH","shouldSkip","interceptor","_ref","_callee","axiosRequestConfig","url","csrfToken","requestError","CSRF_HEADER_NAME","_callee$","_context","getCsrfToken","t0","message","concat","config","reject","headers","_x"],"sources":["../../../src/auth/interceptors/createCsrfTokenProviderInterceptor.js"],"sourcesContent":["const createCsrfTokenProviderInterceptor = (options) => {\n const { csrfTokenService, CSRF_TOKEN_API_PATH, shouldSkip } = options;\n\n // Creating the interceptor inside this closure to\n // maintain reference to the options supplied.\n const interceptor = async (axiosRequestConfig) => {\n if (shouldSkip(axiosRequestConfig)) {\n return axiosRequestConfig;\n }\n const { url } = axiosRequestConfig;\n let csrfToken;\n\n // Important: the job of this interceptor is to get a csrf token and update\n // the original request configuration. Errors thrown getting the csrf token\n // should contain the original request config. This allows other interceptors\n // (namely our retry request interceptor below) to access the original request\n // and handle it appropriately\n try {\n csrfToken = await csrfTokenService.getCsrfToken(url, CSRF_TOKEN_API_PATH);\n } catch (error) {\n const requestError = Object.create(error);\n requestError.message = `[getCsrfToken] ${requestError.message}`;\n // Important: return the original axios request config\n requestError.config = axiosRequestConfig;\n return Promise.reject(requestError);\n }\n\n const CSRF_HEADER_NAME = 'X-CSRFToken';\n // eslint-disable-next-line no-param-reassign\n axiosRequestConfig.headers[CSRF_HEADER_NAME] = csrfToken;\n return axiosRequestConfig;\n };\n\n return interceptor;\n};\n\nexport default createCsrfTokenProviderInterceptor;\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,CAAA,SAAAC,CAAA,EAAAD,CAAA,OAAAE,CAAA,GAAAC,MAAA,CAAAC,SAAA,EAAAC,CAAA,GAAAH,CAAA,CAAAI,cAAA,EAAAC,CAAA,GAAAJ,MAAA,CAAAK,cAAA,cAAAP,CAAA,EAAAD,CAAA,EAAAE,CAAA,IAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,CAAAO,KAAA,KAAAC,CAAA,wBAAAC,MAAA,GAAAA,MAAA,OAAAC,CAAA,GAAAF,CAAA,CAAAG,QAAA,kBAAAC,CAAA,GAAAJ,CAAA,CAAAK,aAAA,uBAAAC,CAAA,GAAAN,CAAA,CAAAO,WAAA,8BAAAC,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAC,MAAA,CAAAK,cAAA,CAAAP,CAAA,EAAAD,CAAA,IAAAS,KAAA,EAAAP,CAAA,EAAAiB,UAAA,MAAAC,YAAA,MAAAC,QAAA,SAAApB,CAAA,CAAAD,CAAA,WAAAkB,MAAA,mBAAAjB,CAAA,IAAAiB,MAAA,YAAAA,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,gBAAAoB,KAAArB,CAAA,EAAAD,CAAA,EAAAE,CAAA,EAAAG,CAAA,QAAAK,CAAA,GAAAV,CAAA,IAAAA,CAAA,CAAAI,SAAA,YAAAmB,SAAA,GAAAvB,CAAA,GAAAuB,SAAA,EAAAX,CAAA,GAAAT,MAAA,CAAAqB,MAAA,CAAAd,CAAA,CAAAN,SAAA,GAAAU,CAAA,OAAAW,OAAA,C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ACM,OAAO,qBAAAC,MAAA,CAAqBP,YAAY,CAACM,OAAO,CAAE;YAC/D;YACAN,YAAY,CAACQ,MAAM,GAAGX,kBAAkB;YAAC,OAAAM,QAAA,CAAA5D,MAAA,WAClC0B,OAAO,CAACwC,MAAM,CAACT,YAAY,CAAC;UAAA;YAG/BC,gBAAgB,GAAG,aAAa,EACtC;YACAJ,kBAAkB,CAACa,OAAO,CAACT,gBAAgB,CAAC,GAAGF,SAAS;YAAC,OAAAI,QAAA,CAAA5D,MAAA,WAClDsD,kBAAkB;UAAA;UAAA;YAAA,OAAAM,QAAA,CAAA3B,IAAA;QAAA;MAAA,GAAAoB,OAAA;IAAA,CAC1B;IAAA,gBA1BKF,WAAWA,CAAAiB,EAAA;MAAA,OAAAhB,IAAA,CAAAT,KAAA,OAAAD,SAAA;IAAA;EAAA,GA0BhB;EAED,OAAOS,WAAW;AACpB,CAAC;AAED,eAAeL,kCAAkC","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/interceptors/createJwtTokenProviderInterceptor.js b/dist/auth/interceptors/createJwtTokenProviderInterceptor.js new file mode 100644 index 000000000..3f76d13fd --- /dev/null +++ b/dist/auth/interceptors/createJwtTokenProviderInterceptor.js @@ -0,0 +1,55 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var createJwtTokenProviderInterceptor = function createJwtTokenProviderInterceptor(options) { + var jwtTokenService = options.jwtTokenService, + shouldSkip = options.shouldSkip; + + // Creating the interceptor inside this closure to + // maintain reference to the options supplied. + var interceptor = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(axiosRequestConfig) { + var requestError; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!shouldSkip(axiosRequestConfig)) { + _context.next = 2; + break; + } + return _context.abrupt("return", axiosRequestConfig); + case 2: + _context.prev = 2; + _context.next = 5; + return jwtTokenService.getJwtToken(); + case 5: + _context.next = 13; + break; + case 7: + _context.prev = 7; + _context.t0 = _context["catch"](2); + requestError = Object.create(_context.t0); + requestError.message = "[getJwtToken] ".concat(requestError.message); + // Important: return the original axios request config + requestError.config = axiosRequestConfig; + return _context.abrupt("return", Promise.reject(requestError)); + case 13: + // Add the proper headers to tell the server to look for the jwt cookie + // eslint-disable-next-line no-param-reassign + axiosRequestConfig.headers['USE-JWT-COOKIE'] = true; + return _context.abrupt("return", axiosRequestConfig); + case 15: + case "end": + return _context.stop(); + } + }, _callee, null, [[2, 7]]); + })); + return function interceptor(_x) { + return _ref.apply(this, arguments); + }; + }(); + return interceptor; +}; +export default createJwtTokenProviderInterceptor; +//# sourceMappingURL=createJwtTokenProviderInterceptor.js.map \ No newline at end of file diff --git a/dist/auth/interceptors/createJwtTokenProviderInterceptor.js.map b/dist/auth/interceptors/createJwtTokenProviderInterceptor.js.map new file mode 100644 index 000000000..28236c036 --- /dev/null +++ b/dist/auth/interceptors/createJwtTokenProviderInterceptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"createJwtTokenProviderInterceptor.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","createJwtTokenProviderInterceptor","options","jwtTokenService","shouldSkip","interceptor","_ref","_callee","axiosRequestConfig","requestError","_callee$","_context","getJwtToken","t0","message","concat","config","reject","headers","_x"],"sources":["../../../src/auth/interceptors/createJwtTokenProviderInterceptor.js"],"sourcesContent":["const createJwtTokenProviderInterceptor = (options) => {\n const {\n jwtTokenService,\n shouldSkip,\n } = options;\n\n // Creating the interceptor inside this closure to\n // maintain reference to the options supplied.\n const interceptor = async (axiosRequestConfig) => {\n if (shouldSkip(axiosRequestConfig)) {\n return axiosRequestConfig;\n }\n\n // Important: the job of this interceptor is to refresh a jwt token and update\n // the original request configuration. Errors thrown from fetching the jwt\n // should contain the original request config. This allows other interceptors\n // (namely our retry request interceptor below) to access the original request\n // and handle it appropriately\n try {\n await jwtTokenService.getJwtToken();\n } catch (error) {\n const requestError = Object.create(error);\n requestError.message = `[getJwtToken] ${requestError.message}`;\n // Important: return the original axios request config\n requestError.config = axiosRequestConfig;\n return Promise.reject(requestError);\n }\n\n // Add the proper headers to tell the server to look for the jwt cookie\n // eslint-disable-next-line no-param-reassign\n axiosRequestConfig.headers['USE-JWT-COOKIE'] = true;\n return axiosRequestConfig;\n };\n\n return interceptor;\n};\n\nexport default createJwtTokenProviderInterceptor;\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WA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,CAAAR,KAAA,OAAAD,SAAA;IAAA;EAAA,GAwBhB;EAED,OAAOQ,WAAW;AACpB,CAAC;AAED,eAAeJ,iCAAiC","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js b/dist/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js new file mode 100644 index 000000000..cbb8d374a --- /dev/null +++ b/dist/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js @@ -0,0 +1,36 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +import { processAxiosError } from '../utils'; +var createProcessAxiosRequestErrorInterceptor = function createProcessAxiosRequestErrorInterceptor(options) { + var loggingService = options.loggingService; + + // Creating the interceptor inside this closure to + // maintain reference to the options supplied. + var interceptor = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(error) { + var processedError, httpErrorStatus; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + processedError = processAxiosError(error); + httpErrorStatus = processedError.customAttributes.httpErrorStatus; + if (httpErrorStatus === 401 || httpErrorStatus === 403) { + loggingService.logInfo(processedError.message, processedError.customAttributes); + } + return _context.abrupt("return", Promise.reject(processedError)); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function interceptor(_x) { + return _ref.apply(this, arguments); + }; + }(); + return interceptor; +}; +export default createProcessAxiosRequestErrorInterceptor; +//# sourceMappingURL=createProcessAxiosRequestErrorInterceptor.js.map \ No newline at end of file diff --git a/dist/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js.map b/dist/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js.map new file mode 100644 index 000000000..fd39906f9 --- /dev/null +++ b/dist/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"createProcessAxiosRequestErrorInterceptor.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","processAxiosError","createProcessAxiosRequestErrorInterceptor","options","loggingService","interceptor","_ref","_callee","error","processedError","httpErrorStatus","_callee$","_context","customAttributes","logInfo","message","reject","_x"],"sources":["../../../src/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js"],"sourcesContent":["import { processAxiosError } from '../utils';\n\nconst createProcessAxiosRequestErrorInterceptor = (options) => {\n const { loggingService } = options;\n\n // Creating the interceptor inside this closure to\n // maintain reference to the options supplied.\n const interceptor = async (error) => {\n const processedError = processAxiosError(error);\n const { httpErrorStatus } = processedError.customAttributes;\n if (httpErrorStatus === 401 || httpErrorStatus === 403) {\n loggingService.logInfo(processedError.message, processedError.customAttributes);\n }\n return Promise.reject(processedError);\n };\n\n return interceptor;\n};\n\nexport default createProcessAxiosRequestErrorInterceptor;\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,CAAA,SAAAC,CAAA,EAAAD,CAAA,OAAAE,CAAA,GAAAC,MAAA,CAAAC,SAAA,EAAAC,CAAA,GAAAH,CAAA,CAAAI,cAAA,EAAAC,CAAA,GAAAJ,MAAA,CAAAK,cAAA,cAAAP,CAAA,EAAAD,CAAA,EAAAE,CAAA,IAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,CAAAO,KAAA,KAAAC,CAAA,wBAAAC,MAAA,GAAAA,MAAA,OAAAC,CAAA,GAAAF,CAAA,CAAAG,QAAA,kBAAAC,CAAA,GAAAJ,CAAA,CAAAK,aAAA,uBAAAC,CAAA,GAAAN,CAAA,CAAAO,WAAA,8BAAAC,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAC,MAAA,CAAAK,cAAA,CAAAP,CAAA,EAAAD,CAAA,IAAAS,KAAA,EAAAP,CAAA,EAAAiB,UAAA,MAAAC,YAAA,MAAAC,QAAA,SAAApB,CAAA,CAAAD,CAAA,WAAAkB,MAAA,mBAAAjB,CAAA,IAAAiB,MAAA,YAAAA,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,gBAAAoB,KAAArB,CAAA,EAAAD,CAAA,EAAAE,CAAA,EAAAG,CAAA,QAAAK,CAAA,GAAAV,CAAA,IAAAA,CAAA,CAAAI,SAAA,YAAAmB,SAAA,GAAAvB,CAAA,GAAAuB,SAAA,EAAAX,CAAA,GAAAT,MAAA,CAAAqB,MAAA,CAAAd,CAAA,CAAAN,SAAA,GAAAU,CAAA,OAAAW,OAA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ors/createRetryInterceptor.js new file mode 100644 index 000000000..873972a2c --- /dev/null +++ b/dist/auth/interceptors/createRetryInterceptor.js @@ -0,0 +1,108 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +import axios from 'axios'; + +// This default algorithm is a recreation of what is documented here +// https://cloud.google.com/storage/docs/exponential-backoff +var defaultGetBackoffMilliseconds = function defaultGetBackoffMilliseconds(nthRetry) { + var maximumBackoffMilliseconds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16000; + // Retry at exponential intervals (2, 4, 8, 16...) + var exponentialBackoffSeconds = Math.pow(2, nthRetry); + // Add some randomness to avoid sending retries from separate requests all at once + var randomFractionOfASecond = Math.random(); + var backoffSeconds = exponentialBackoffSeconds + randomFractionOfASecond; + var backoffMilliseconds = Math.round(backoffSeconds * 1000); + return Math.min(backoffMilliseconds, maximumBackoffMilliseconds); +}; +var createRetryInterceptor = function createRetryInterceptor() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var _options$httpClient = options.httpClient, + httpClient = _options$httpClient === void 0 ? axios.create() : _options$httpClient, + _options$getBackoffMi = options.getBackoffMilliseconds, + getBackoffMilliseconds = _options$getBackoffMi === void 0 ? defaultGetBackoffMilliseconds : _options$getBackoffMi, + _options$shouldRetry = options.shouldRetry, + shouldRetry = _options$shouldRetry === void 0 ? function (error) { + var isRequestError = !error.response && error.config; + return isRequestError; + } : _options$shouldRetry, + _options$defaultMaxRe = options.defaultMaxRetries, + defaultMaxRetries = _options$defaultMaxRe === void 0 ? 2 : _options$defaultMaxRe; + var interceptor = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(error) { + var config, _config$maxRetries, maxRetries, _retryRequest; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + config = error.config; // If no config exists there was some other error setting up the request + if (config) { + _context2.next = 3; + break; + } + return _context2.abrupt("return", Promise.reject(error)); + case 3: + if (shouldRetry(error)) { + _context2.next = 5; + break; + } + return _context2.abrupt("return", Promise.reject(error)); + case 5: + _config$maxRetries = config.maxRetries, maxRetries = _config$maxRetries === void 0 ? defaultMaxRetries : _config$maxRetries; + _retryRequest = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(nthRetry) { + var retryResponse, backoffDelay; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(nthRetry > maxRetries)) { + _context.next = 2; + break; + } + return _context.abrupt("return", Promise.reject(error)); + case 2: + _context.prev = 2; + backoffDelay = getBackoffMilliseconds(nthRetry); // Delay (wrapped in a promise so we can await the setTimeout) + _context.next = 6; + return new Promise(function (resolve) { + setTimeout(resolve, backoffDelay); + }); + case 6: + _context.next = 8; + return httpClient.request(config); + case 8: + retryResponse = _context.sent; + _context.next = 14; + break; + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](2); + return _context.abrupt("return", _retryRequest(nthRetry + 1)); + case 14: + return _context.abrupt("return", retryResponse); + case 15: + case "end": + return _context.stop(); + } + }, _callee, null, [[2, 11]]); + })); + return function retryRequest(_x2) { + return _ref2.apply(this, arguments); + }; + }(); + return _context2.abrupt("return", _retryRequest(1)); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function interceptor(_x) { + return _ref.apply(this, arguments); + }; + }(); + return interceptor; +}; +export default createRetryInterceptor; +export { defaultGetBackoffMilliseconds }; +//# sourceMappingURL=createRetryInterceptor.js.map \ No newline at end of file diff --git a/dist/auth/interceptors/createRetryInterceptor.js.map b/dist/auth/interceptors/createRetryInterceptor.js.map new file mode 100644 index 000000000..c74f44215 --- /dev/null +++ b/dist/auth/interceptors/createRetryInterceptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"createRetryInterceptor.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","axios","defaultGetBackoffMilliseconds","nthRetry","maximumBackoffMilliseconds","undefined","exponentialBackoffSeconds","Math","pow","randomFractionOfASecond","random","backoffSeconds","backoffMilliseconds","round","min","createRetryInterceptor","options","_options$httpClient","httpClient","_options$getBackoffMi","getBackoffMilliseconds","_options$shouldRetry","shouldRetry","error","isRequestError","response","config","_options$defaultMaxRe","defaultMaxRetries","interceptor","_ref","_callee2","_config$maxRetries","maxRetries","_retryRequest","_callee2$","_context2","reject","retryRequest","_ref2","_callee","retryResponse","backoffDelay","_callee$","_context","setTimeout","request","t0","_x2","_x"],"sources":["../../../src/auth/interceptors/createRetryInterceptor.js"],"sourcesContent":["import axios from 'axios';\n\n// This default algorithm is a recreation of what is documented here\n// https://cloud.google.com/storage/docs/exponential-backoff\nconst defaultGetBackoffMilliseconds = (nthRetry, maximumBackoffMilliseconds = 16000) => {\n // Retry at exponential intervals (2, 4, 8, 16...)\n const exponentialBackoffSeconds = 2 ** nthRetry;\n // Add some randomness to avoid sending retries from separate requests all at once\n const randomFractionOfASecond = Math.random();\n const backoffSeconds = exponentialBackoffSeconds + randomFractionOfASecond;\n const backoffMilliseconds = Math.round(backoffSeconds * 1000);\n return Math.min(backoffMilliseconds, maximumBackoffMilliseconds);\n};\n\nconst createRetryInterceptor = (options = {}) => {\n const {\n httpClient = axios.create(),\n getBackoffMilliseconds = defaultGetBackoffMilliseconds,\n // By default only retry outbound request failures (not responses)\n shouldRetry = (error) => {\n const isRequestError = !error.response && error.config;\n return isRequestError;\n },\n // A per-request maxRetries can be specified in request config.\n defaultMaxRetries = 2,\n } = options;\n\n const interceptor = async (error) => {\n const { config } = error;\n\n // If no config exists there was some other error setting up the request\n if (!config) {\n return Promise.reject(error);\n }\n\n if (!shouldRetry(error)) {\n return Promise.reject(error);\n }\n\n const {\n maxRetries = defaultMaxRetries,\n } = config;\n\n const retryRequest = async (nthRetry) => {\n if (nthRetry > maxRetries) {\n // Reject with the original error\n return Promise.reject(error);\n }\n\n let retryResponse;\n\n try {\n const backoffDelay = getBackoffMilliseconds(nthRetry);\n // Delay (wrapped in a promise so we can await the setTimeout)\n await new Promise(resolve => { setTimeout(resolve, backoffDelay); });\n // Make retry request\n retryResponse = await httpClient.request(config);\n } catch (e) {\n return retryRequest(nthRetry + 1);\n }\n\n return retryResponse;\n };\n\n return retryRequest(1);\n };\n\n return interceptor;\n};\n\nexport default createRetryInterceptor;\nexport { defaultGetBackoffMilliseconds };\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,C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BAAsB,CAACjB,QAAQ,CAAC,EACrD;sBAAAyC,QAAA,CAAAtF,IAAA;sBAAA,OACM,IAAIuB,OAAO,CAAC,UAAAtC,OAAO,EAAI;wBAAEsG,UAAU,CAACtG,OAAO,EAAEmG,YAAY,CAAC;sBAAE,CAAC,CAAC;oBAAA;sBAAAE,QAAA,CAAAtF,IAAA;sBAAA,OAE9C4D,UAAU,CAAC4B,OAAO,CAACpB,MAAM,CAAC;oBAAA;sBAAhDe,aAAa,GAAAG,QAAA,CAAA5F,IAAA;sBAAA4F,QAAA,CAAAtF,IAAA;sBAAA;oBAAA;sBAAAsF,QAAA,CAAA3D,IAAA;sBAAA2D,QAAA,CAAAG,EAAA,GAAAH,QAAA;sBAAA,OAAAA,QAAA,CAAAzF,MAAA,WAENmF,aAAY,CAACnC,QAAQ,GAAG,CAAC,CAAC;oBAAA;sBAAA,OAAAyC,QAAA,CAAAzF,MAAA,WAG5BsF,aAAa;oBAAA;oBAAA;sBAAA,OAAAG,QAAA,CAAAxD,IAAA;kBAAA;gBAAA,GAAAoD,OAAA;cAAA,CACrB;cAAA,gBAnBKF,YAAYA,CAAAU,GAAA;gBAAA,OAAAT,KAAA,CAAAzC,KAAA,OAAAD,SAAA;cAAA;YAAA;YAAA,OAAAuC,SAAA,CAAAjF,MAAA,WAqBXmF,aAAY,CAAC,CAAC,CAAC;UAAA;UAAA;YAAA,OAAAF,SAAA,CAAAhD,IAAA;QAAA;MAAA,GAAA2C,QAAA;IAAA,CACvB;IAAA,gBAtCKF,WAAWA,CAAAoB,EAAA;MAAA,OAAAnB,IAAA,CAAAhC,KAAA,OAAAD,SAAA;IAAA;EAAA,GAsChB;EAED,OAAOgC,WAAW;AACpB,CAAC;AAED,eAAed,sBAAsB;AACrC,SAASb,6BAA6B","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/interface.js b/dist/auth/interface.js new file mode 100644 index 000000000..b13e4f0ed --- /dev/null +++ b/dist/auth/interface.js @@ -0,0 +1,359 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/** + * #### Import members from **@edx/frontend-platform/auth** + * + * Simplifies the process of making authenticated API requests to backend edX services by providing + * common authN/authZ client code that enables the login/logout flow and handles ensuring the + * presence of a valid [JWT cookie](https://github.com/openedx/edx-platform/blob/master/openedx/core/djangoapps/oauth_dispatch/docs/decisions/0009-jwt-in-session-cookie.rst). + * + * The `initialize` function performs much of the auth configuration for you. If, however, you're + * not using the `initialize` function, an authenticated API client can be created via: + * + * ``` + * import { + * configure, + * fetchAuthenticatedUser, + * getAuthenticatedHttpClient + * } from '@edx/frontend-platform/auth'; + * import { getConfig } from '@edx/frontend-platform'; + * import { getLoggingService } from '@edx/frontend-platform/logging'; + * + * configure({ + * loggingService: getLoggingService(), + * config: getConfig(), + * }); + * + * const authenticatedUser = await fetchAuthenticatedUser(); // validates and decodes JWT token + * const authenticatedHttpClient = getAuthenticatedHttpClient(); + * const response = await getAuthenticatedHttpClient().get(`https://example.com/api/user/data/${authenticatedUser.username}`); // fetching from an authenticated API using user data + * ``` + * + * As shown in this example, auth depends on the configuration document and logging. + * + * NOTE: The documentation for AxiosJwtAuthService is nearly the same as that for the top-level + * auth interface, except that it contains some Axios-specific details. + * + * @module Auth + */ +import PropTypes from 'prop-types'; +import { publish } from '../pubSub'; + +/** + * @constant + * @private + */ +export var AUTHENTICATED_USER_TOPIC = 'AUTHENTICATED_USER'; + +/** + * Published when the authenticated user data changes. This can happen when the authentication + * service determines that the user is authenticated or anonymous, as well as when we fetch + * additional user account data if the `hydrateAuthenticatedUser` flag has been set in the + * `initialize` function. + * + * @event + * @see {@link module:Initialization~initialize} + */ +export var AUTHENTICATED_USER_CHANGED = "".concat(AUTHENTICATED_USER_TOPIC, ".CHANGED"); +var optionsShape = { + config: PropTypes.shape({ + BASE_URL: PropTypes.string.isRequired, + LMS_BASE_URL: PropTypes.string.isRequired, + LOGIN_URL: PropTypes.string.isRequired, + LOGOUT_URL: PropTypes.string.isRequired, + REFRESH_ACCESS_TOKEN_ENDPOINT: PropTypes.string.isRequired, + ACCESS_TOKEN_COOKIE_NAME: PropTypes.string.isRequired, + CSRF_TOKEN_API_PATH: PropTypes.string.isRequired + }).isRequired, + loggingService: PropTypes.shape({ + logError: PropTypes.func.isRequired, + logInfo: PropTypes.func.isRequired + }).isRequired +}; +var serviceShape = { + getAuthenticatedHttpClient: PropTypes.func.isRequired, + getHttpClient: PropTypes.func.isRequired, + getLoginRedirectUrl: PropTypes.func.isRequired, + redirectToLogin: PropTypes.func.isRequired, + getLogoutRedirectUrl: PropTypes.func.isRequired, + redirectToLogout: PropTypes.func.isRequired, + getAuthenticatedUser: PropTypes.func.isRequired, + setAuthenticatedUser: PropTypes.func.isRequired, + fetchAuthenticatedUser: PropTypes.func.isRequired, + ensureAuthenticatedUser: PropTypes.func.isRequired, + hydrateAuthenticatedUser: PropTypes.func.isRequired +}; +var service; + +/** + * + * @param {class} AuthService + * @param {*} options + * @returns {AuthService} + */ +export function configure(AuthService, options) { + PropTypes.checkPropTypes(optionsShape, options, 'property', 'Auth'); + service = new AuthService(options); + PropTypes.checkPropTypes(serviceShape, service, 'property', 'AuthService'); + return service; +} + +/** + * + * + * @returns {AuthService} + */ +export function getAuthService() { + if (!service) { + throw Error('You must first configure the auth service.'); + } + return service; +} + +/** + * + */ +export function resetAuthService() { + service = null; +} + +/** + * Gets the authenticated HTTP client for the service. + * + * @param {Object} [options] Optional options for how to configure the authenticated HTTP client + * @param {boolean} [options.useCache] Whether to use front end caching for all requests made with the returned client + * + * @returns {HttpClient} + */ +export function getAuthenticatedHttpClient() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return service.getAuthenticatedHttpClient(options); +} + +/** + * Gets the unauthenticated HTTP client for the service. + * + * @param {Object} [options] Optional options for how to configure the authenticated HTTP client + * @param {boolean} [options.useCache] Whether to use front end caching for all requests made with the returned client + * + * @returns {HttpClient} + */ +export function getHttpClient() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return service.getHttpClient(options); +} + +/** + * Builds a URL to the login page with a post-login redirect URL attached as a query parameter. + * + * ``` + * const url = getLoginRedirectUrl('http://localhost/mypage'); + * console.log(url); // http://localhost/login?next=http%3A%2F%2Flocalhost%2Fmypage + * ``` + * + * @param {string} redirectUrl The URL the user should be redirected to after logging in. + */ +export function getLoginRedirectUrl(redirectUrl) { + return service.getLoginRedirectUrl(redirectUrl); +} + +/** + * Redirects the user to the login page. + * + * @param {string} redirectUrl The URL the user should be redirected to after logging in. + */ +export function redirectToLogin(redirectUrl) { + return service.redirectToLogin(redirectUrl); +} + +/** + * Builds a URL to the logout page with a post-logout redirect URL attached as a query parameter. + * + * ``` + * const url = getLogoutRedirectUrl('http://localhost/mypage'); + * console.log(url); // http://localhost/logout?redirect_url=http%3A%2F%2Flocalhost%2Fmypage + * ``` + * + * @param {string} redirectUrl The URL the user should be redirected to after logging out. + */ +export function getLogoutRedirectUrl(redirectUrl) { + return service.getLogoutRedirectUrl(redirectUrl); +} + +/** + * Redirects the user to the logout page. + * + * @param {string} redirectUrl The URL the user should be redirected to after logging out. + */ +export function redirectToLogout(redirectUrl) { + return service.redirectToLogout(redirectUrl); +} + +/** + * If it exists, returns the user data representing the currently authenticated user. If the + * user is anonymous, returns null. + * + * @returns {UserData|null} + */ +export function getAuthenticatedUser() { + return service.getAuthenticatedUser(); +} + +/** + * Sets the authenticated user to the provided value. + * + * @param {UserData} authUser + * @emits AUTHENTICATED_USER_CHANGED + */ +export function setAuthenticatedUser(authUser) { + service.setAuthenticatedUser(authUser); + publish(AUTHENTICATED_USER_CHANGED); +} + +/** + * Reads the authenticated user's access token. Resolves to null if the user is + * unauthenticated. + * + * @returns {Promise|Promise} Resolves to the user's access token if they are + * logged in. + */ +export function fetchAuthenticatedUser() { + return _fetchAuthenticatedUser.apply(this, arguments); +} + +/** + * Ensures a user is authenticated. It will redirect to login when not + * authenticated. + * + * @param {string} [redirectUrl=config.BASE_URL] to return user after login when not + * authenticated. + * @returns {Promise} + */ +function _fetchAuthenticatedUser() { + _fetchAuthenticatedUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var options, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + options = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + return _context.abrupt("return", service.fetchAuthenticatedUser(options)); + case 2: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _fetchAuthenticatedUser.apply(this, arguments); +} +export function ensureAuthenticatedUser(_x) { + return _ensureAuthenticatedUser.apply(this, arguments); +} + +/** + * Fetches additional user account information for the authenticated user and merges it into the + * existing authenticatedUser object, available via getAuthenticatedUser(). + * + * ``` + * console.log(authenticatedUser); // Will be sparse and only contain basic information. + * await hydrateAuthenticatedUser() + * const authenticatedUser = getAuthenticatedUser(); + * console.log(authenticatedUser); // Will contain additional user information + * ``` + * + * @emits AUTHENTICATED_USER_CHANGED + */ +function _ensureAuthenticatedUser() { + _ensureAuthenticatedUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(redirectUrl) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", service.ensureAuthenticatedUser(redirectUrl)); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _ensureAuthenticatedUser.apply(this, arguments); +} +export function hydrateAuthenticatedUser() { + return _hydrateAuthenticatedUser.apply(this, arguments); +} + +/** + * @name AuthService + * @interface + * @memberof module:Auth + * @property {function} getAuthenticatedHttpClient + * @property {function} getHttpClient + * @property {function} getLoginRedirectUrl + * @property {function} redirectToLogin + * @property {function} getLogoutRedirectUrl + * @property {function} redirectToLogout + * @property {function} getAuthenticatedUser + * @property {function} setAuthenticatedUser + * @property {function} fetchAuthenticatedUser + * @property {function} ensureAuthenticatedUser + * @property {function} hydrateAuthenticatedUser + */ + +/** + * A configured axios client. See axios docs for more + * info https://github.com/axios/axios. All the functions + * below accept isPublic and isCsrfExempt in the request + * config options. Setting these to true will prevent this + * client from attempting to refresh the jwt access token + * or a csrf token respectively. + * + * ``` + * // A public endpoint (no jwt token refresh) + * apiClient.get('/path/to/endpoint', { isPublic: true }); + * ``` + * + * ``` + * // A csrf exempt endpoint + * apiClient.post('/path/to/endpoint', { data }, { isCsrfExempt: true }); + * ``` + * + * @name HttpClient + * @interface + * @memberof module:Auth + * @property {function} get + * @property {function} head + * @property {function} options + * @property {function} delete (csrf protected) + * @property {function} post (csrf protected) + * @property {function} put (csrf protected) + * @property {function} patch (csrf protected) + */ + +/** + * @name UserData + * @interface + * @memberof module:Auth + * @property {string} userId + * @property {string} username + * @property {Array} roles + * @property {boolean} administrator + */ +function _hydrateAuthenticatedUser() { + _hydrateAuthenticatedUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return service.hydrateAuthenticatedUser(); + case 2: + publish(AUTHENTICATED_USER_CHANGED); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _hydrateAuthenticatedUser.apply(this, arguments); +} +//# sourceMappingURL=interface.js.map \ No newline at end of file diff --git a/dist/auth/interface.js.map b/dist/auth/interface.js.map new file mode 100644 index 000000000..17ba2b6bb --- /dev/null +++ b/dist/auth/interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interface.js","names":["_regeneratorRuntime","e","t","r","Object","prototype","n","hasOwnProperty","o","defineProperty","value","i","Symbol","a","iterator","c","asyncIterator","u","toStringTag","define","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","call","h","l","f","s","y","GeneratorFunction","GeneratorFunctionPrototype","p","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","_typeof","resolve","__await","then","callInvokeWithMethodAndArg","Error","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","length","displayName","isGeneratorFunction","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","_catch","delegateYield","asyncGeneratorStep","_asyncToGenerator","arguments","apply","_next","_throw","PropTypes","publish","AUTHENTICATED_USER_TOPIC","AUTHENTICATED_USER_CHANGED","concat","optionsShape","config","shape","BASE_URL","string","isRequired","LMS_BASE_URL","LOGIN_URL","LOGOUT_URL","REFRESH_ACCESS_TOKEN_ENDPOINT","ACCESS_TOKEN_COOKIE_NAME","CSRF_TOKEN_API_PATH","loggingService","logError","func","logInfo","serviceShape","getAuthenticatedHttpClient","getHttpClient","getLoginRedirectUrl","redirectToLogin","getLogoutRedirectUrl","redirectToLogout","getAuthenticatedUser","setAuthenticatedUser","fetchAuthenticatedUser","ensureAuthenticatedUser","hydrateAuthenticatedUser","service","configure","AuthService","options","checkPropTypes","getAuthService","resetAuthService","undefined","redirectUrl","authUser","_fetchAuthenticatedUser","_callee","_args","_callee$","_context","_x","_ensureAuthenticatedUser","_callee2","_callee2$","_context2","_hydrateAuthenticatedUser","_callee3","_callee3$","_context3"],"sources":["../../src/auth/interface.js"],"sourcesContent":["/**\n * #### Import members from **@edx/frontend-platform/auth**\n *\n * Simplifies the process of making authenticated API requests to backend edX services by providing\n * common authN/authZ client code that enables the login/logout flow and handles ensuring the\n * presence of a valid [JWT cookie](https://github.com/openedx/edx-platform/blob/master/openedx/core/djangoapps/oauth_dispatch/docs/decisions/0009-jwt-in-session-cookie.rst).\n *\n * The `initialize` function performs much of the auth configuration for you. If, however, you're\n * not using the `initialize` function, an authenticated API client can be created via:\n *\n * ```\n * import {\n * configure,\n * fetchAuthenticatedUser,\n * getAuthenticatedHttpClient\n * } from '@edx/frontend-platform/auth';\n * import { getConfig } from '@edx/frontend-platform';\n * import { getLoggingService } from '@edx/frontend-platform/logging';\n *\n * configure({\n * loggingService: getLoggingService(),\n * config: getConfig(),\n * });\n *\n * const authenticatedUser = await fetchAuthenticatedUser(); // validates and decodes JWT token\n * const authenticatedHttpClient = getAuthenticatedHttpClient();\n * const response = await getAuthenticatedHttpClient().get(`https://example.com/api/user/data/${authenticatedUser.username}`); // fetching from an authenticated API using user data\n * ```\n *\n * As shown in this example, auth depends on the configuration document and logging.\n *\n * NOTE: The documentation for AxiosJwtAuthService is nearly the same as that for the top-level\n * auth interface, except that it contains some Axios-specific details.\n *\n * @module Auth\n */\nimport PropTypes from 'prop-types';\nimport { publish } from '../pubSub';\n\n/**\n * @constant\n * @private\n */\nexport const AUTHENTICATED_USER_TOPIC = 'AUTHENTICATED_USER';\n\n/**\n * Published when the authenticated user data changes. This can happen when the authentication\n * service determines that the user is authenticated or anonymous, as well as when we fetch\n * additional user account data if the `hydrateAuthenticatedUser` flag has been set in the\n * `initialize` function.\n *\n * @event\n * @see {@link module:Initialization~initialize}\n */\nexport const AUTHENTICATED_USER_CHANGED = `${AUTHENTICATED_USER_TOPIC}.CHANGED`;\n\nconst optionsShape = {\n config: PropTypes.shape({\n BASE_URL: PropTypes.string.isRequired,\n LMS_BASE_URL: PropTypes.string.isRequired,\n LOGIN_URL: PropTypes.string.isRequired,\n LOGOUT_URL: PropTypes.string.isRequired,\n REFRESH_ACCESS_TOKEN_ENDPOINT: PropTypes.string.isRequired,\n ACCESS_TOKEN_COOKIE_NAME: PropTypes.string.isRequired,\n CSRF_TOKEN_API_PATH: PropTypes.string.isRequired,\n }).isRequired,\n loggingService: PropTypes.shape({\n logError: PropTypes.func.isRequired,\n logInfo: PropTypes.func.isRequired,\n }).isRequired,\n};\n\nconst serviceShape = {\n getAuthenticatedHttpClient: PropTypes.func.isRequired,\n getHttpClient: PropTypes.func.isRequired,\n getLoginRedirectUrl: PropTypes.func.isRequired,\n redirectToLogin: PropTypes.func.isRequired,\n getLogoutRedirectUrl: PropTypes.func.isRequired,\n redirectToLogout: PropTypes.func.isRequired,\n getAuthenticatedUser: PropTypes.func.isRequired,\n setAuthenticatedUser: PropTypes.func.isRequired,\n fetchAuthenticatedUser: PropTypes.func.isRequired,\n ensureAuthenticatedUser: PropTypes.func.isRequired,\n hydrateAuthenticatedUser: PropTypes.func.isRequired,\n};\n\nlet service;\n\n/**\n *\n * @param {class} AuthService\n * @param {*} options\n * @returns {AuthService}\n */\nexport function configure(AuthService, options) {\n PropTypes.checkPropTypes(optionsShape, options, 'property', 'Auth');\n service = new AuthService(options);\n PropTypes.checkPropTypes(serviceShape, service, 'property', 'AuthService');\n return service;\n}\n\n/**\n *\n *\n * @returns {AuthService}\n */\nexport function getAuthService() {\n if (!service) {\n throw Error('You must first configure the auth service.');\n }\n\n return service;\n}\n\n/**\n *\n */\nexport function resetAuthService() {\n service = null;\n}\n\n/**\n * Gets the authenticated HTTP client for the service.\n *\n * @param {Object} [options] Optional options for how to configure the authenticated HTTP client\n * @param {boolean} [options.useCache] Whether to use front end caching for all requests made with the returned client\n *\n * @returns {HttpClient}\n */\nexport function getAuthenticatedHttpClient(options = {}) {\n return service.getAuthenticatedHttpClient(options);\n}\n\n/**\n * Gets the unauthenticated HTTP client for the service.\n *\n * @param {Object} [options] Optional options for how to configure the authenticated HTTP client\n * @param {boolean} [options.useCache] Whether to use front end caching for all requests made with the returned client\n *\n * @returns {HttpClient}\n */\nexport function getHttpClient(options = {}) {\n return service.getHttpClient(options);\n}\n\n/**\n * Builds a URL to the login page with a post-login redirect URL attached as a query parameter.\n *\n * ```\n * const url = getLoginRedirectUrl('http://localhost/mypage');\n * console.log(url); // http://localhost/login?next=http%3A%2F%2Flocalhost%2Fmypage\n * ```\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging in.\n */\nexport function getLoginRedirectUrl(redirectUrl) {\n return service.getLoginRedirectUrl(redirectUrl);\n}\n\n/**\n * Redirects the user to the login page.\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging in.\n */\nexport function redirectToLogin(redirectUrl) {\n return service.redirectToLogin(redirectUrl);\n}\n\n/**\n * Builds a URL to the logout page with a post-logout redirect URL attached as a query parameter.\n *\n * ```\n * const url = getLogoutRedirectUrl('http://localhost/mypage');\n * console.log(url); // http://localhost/logout?redirect_url=http%3A%2F%2Flocalhost%2Fmypage\n * ```\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging out.\n */\nexport function getLogoutRedirectUrl(redirectUrl) {\n return service.getLogoutRedirectUrl(redirectUrl);\n}\n\n/**\n * Redirects the user to the logout page.\n *\n * @param {string} redirectUrl The URL the user should be redirected to after logging out.\n */\nexport function redirectToLogout(redirectUrl) {\n return service.redirectToLogout(redirectUrl);\n}\n\n/**\n * If it exists, returns the user data representing the currently authenticated user. If the\n * user is anonymous, returns null.\n *\n * @returns {UserData|null}\n */\nexport function getAuthenticatedUser() {\n return service.getAuthenticatedUser();\n}\n\n/**\n * Sets the authenticated user to the provided value.\n *\n * @param {UserData} authUser\n * @emits AUTHENTICATED_USER_CHANGED\n */\nexport function setAuthenticatedUser(authUser) {\n service.setAuthenticatedUser(authUser);\n publish(AUTHENTICATED_USER_CHANGED);\n}\n\n/**\n * Reads the authenticated user's access token. Resolves to null if the user is\n * unauthenticated.\n *\n * @returns {Promise|Promise} Resolves to the user's access token if they are\n * logged in.\n */\nexport async function fetchAuthenticatedUser(options = {}) {\n return service.fetchAuthenticatedUser(options);\n}\n\n/**\n * Ensures a user is authenticated. It will redirect to login when not\n * authenticated.\n *\n * @param {string} [redirectUrl=config.BASE_URL] to return user after login when not\n * authenticated.\n * @returns {Promise}\n */\nexport async function ensureAuthenticatedUser(redirectUrl) {\n return service.ensureAuthenticatedUser(redirectUrl);\n}\n\n/**\n * Fetches additional user account information for the authenticated user and merges it into the\n * existing authenticatedUser object, available via getAuthenticatedUser().\n *\n * ```\n * console.log(authenticatedUser); // Will be sparse and only contain basic information.\n * await hydrateAuthenticatedUser()\n * const authenticatedUser = getAuthenticatedUser();\n * console.log(authenticatedUser); // Will contain additional user information\n * ```\n *\n * @emits AUTHENTICATED_USER_CHANGED\n */\nexport async function hydrateAuthenticatedUser() {\n await service.hydrateAuthenticatedUser();\n publish(AUTHENTICATED_USER_CHANGED);\n}\n\n/**\n * @name AuthService\n * @interface\n * @memberof module:Auth\n * @property {function} getAuthenticatedHttpClient\n * @property {function} getHttpClient\n * @property {function} getLoginRedirectUrl\n * @property {function} redirectToLogin\n * @property {function} getLogoutRedirectUrl\n * @property {function} redirectToLogout\n * @property {function} getAuthenticatedUser\n * @property {function} setAuthenticatedUser\n * @property {function} fetchAuthenticatedUser\n * @property {function} ensureAuthenticatedUser\n * @property {function} hydrateAuthenticatedUser\n */\n\n/**\n * A configured axios client. See axios docs for more\n * info https://github.com/axios/axios. All the functions\n * below accept isPublic and isCsrfExempt in the request\n * config options. Setting these to true will prevent this\n * client from attempting to refresh the jwt access token\n * or a csrf token respectively.\n *\n * ```\n * // A public endpoint (no jwt token refresh)\n * apiClient.get('/path/to/endpoint', { isPublic: true });\n * ```\n *\n * ```\n * // A csrf exempt endpoint\n * apiClient.post('/path/to/endpoint', { data }, { isCsrfExempt: true });\n * ```\n *\n * @name HttpClient\n * @interface\n * @memberof module:Auth\n * @property {function} get\n * @property {function} head\n * @property {function} options\n * @property {function} delete (csrf protected)\n * @property {function} post (csrf protected)\n * @property {function} put (csrf protected)\n * @property {function} patch (csrf protected)\n */\n\n/**\n * @name UserData\n * @interface\n * @memberof module:Auth\n * @property {string} userId\n * @property {string} username\n * @property {Array} roles\n * @property {boolean} administrator\n */\n"],"mappings":";+CACA,qJAAAA,mBAAA,YAAAA,oBAAA,WAAAC,CAAA,SAAAC,CAAA,EAAAD,CAAA,OAAAE,CAAA,GAAAC,MAAA,CAAAC,SAAA,EAAAC,CAAA,GAAAH,CAAA,CAAAI,cAAA,EAAAC,CAAA,GAAAJ,MAAA,CAAAK,cAAA,cAAAP,CAAA,EAAAD,CAAA,EAAAE,CAAA,IAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,CAAAO,KAAA,KAAAC,CAAA,wBAAAC,MAAA,GAAAA,MAAA,OAAAC,CAAA,GAAAF,CAAA,CAAAG,QAAA,kBAAAC,CAAA,GAAAJ,CAAA,CAAAK,aAAA,uBAAAC,CAAA,GAAAN,CAAA,CAAAO,WAAA,8BAAAC,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAC,MAAA,CAAAK,cAAA,CAAAP,CAAA,EAAAD,CAAA,IAAAS,KAAA,EAAAP,CAAA,EAAAiB,UAAA,MAAAC,YAAA,MAAAC,QAAA,SAAApB,CAAA,CAAAD,CAAA,WAAAkB,MAAA,mBAAAjB,CAAA,IAAAiB,MAAA,YAAAA,OAAAjB,CAAA,EAAAD,CAAA,EAAAE,CAAA,WAAAD,CAAA,CAAAD,CAAA,IAAAE,CAAA,gBAAAoB,KAAArB,CAAA,EAAAD,CAAA,EAAAE,CAAA,EAAAG,CAAA,QAAAK,CAAA,GAAAV,CAAA,IAAAA,CAAA,CAAAI,SAAA,YAAAmB,SAAA,GAAAvB,CAAA,GAAAuB,SAAA,EAAAX,CAAA,GAAAT,MAAA,CAAAqB,MAAA,CAAAd,CAAA,CAAAN,SAAA,GAAAU,CAAA,OAAAW,OAAA,CAAApB,CAAA,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AA,GAAAoE,SAAA,CAAA/F,IAAA;QAAA;UAAA,OAAA+F,SAAA,CAAAlG,MAAA,WAChD+E,OAAO,CAACF,uBAAuB,CAACU,WAAW,CAAC;QAAA;QAAA;UAAA,OAAAW,SAAA,CAAAjE,IAAA;MAAA;IAAA,GAAA+D,QAAA;EAAA,CACpD;EAAA,OAAAD,wBAAA,CAAApD,KAAA,OAAAD,SAAA;AAAA;AAeD,gBAAsBoC,wBAAwBA,CAAA;EAAA,OAAAqB,yBAAA,CAAAxD,KAAA,OAAAD,SAAA;AAAA;;AAK9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AARA,SAAAyD,0BAAA;EAAAA,yBAAA,GAAA1D,iBAAA,cAAAxG,mBAAA,GAAAoF,IAAA,CApDO,SAAA+E,SAAA;IAAA,OAAAnK,mBAAA,GAAAuB,IAAA,UAAA6I,UAAAC,SAAA;MAAA,kBAAAA,SAAA,CAAAxE,IAAA,GAAAwE,SAAA,CAAAnG,IAAA;QAAA;UAAAmG,SAAA,CAAAnG,IAAA;UAAA,OACC4E,OAAO,CAACD,wBAAwB,CAAC,CAAC;QAAA;UACxC/B,OAAO,CAACE,0BAA0B,CAAC;QAAC;QAAA;UAAA,OAAAqD,SAAA,CAAArE,IAAA;MAAA;IAAA,GAAAmE,QAAA;EAAA,CACrC;EAAA,OAAAD,yBAAA,CAAAxD,KAAA,OAAAD,SAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/dist/auth/utils.js b/dist/auth/utils.js new file mode 100644 index 000000000..2094efbed --- /dev/null +++ b/dist/auth/utils.js @@ -0,0 +1,101 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +// Lifted from here: https://regexr.com/3ok5o +var urlRegex = /([a-z]{1,2}tps?):\/\/((?:(?!(?:\/|#|\?|&)).)+)(?:(\/(?:(?:(?:(?!(?:#|\?|&)).)+\/))?))?(?:((?:(?!(?:\.|$|\?|#)).)+))?(?:(\.(?:(?!(?:\?|$|#)).)+))?(?:(\?(?:(?!(?:$|#)).)+))?(?:(#.+))?/; +var getUrlParts = function getUrlParts(url) { + var found = url.match(urlRegex); + try { + var _found = _slicedToArray(found, 8), + fullUrl = _found[0], + protocol = _found[1], + domain = _found[2], + path = _found[3], + endFilename = _found[4], + endFileExtension = _found[5], + query = _found[6], + hash = _found[7]; + return { + fullUrl: fullUrl, + protocol: protocol, + domain: domain, + path: path, + endFilename: endFilename, + endFileExtension: endFileExtension, + query: query, + hash: hash + }; + } catch (e) { + throw new Error("Could not find url parts from ".concat(url, ".")); + } +}; +var logFrontendAuthError = function logFrontendAuthError(loggingService, error) { + var prefixedMessageError = Object.create(error); + prefixedMessageError.message = "[frontend-auth] ".concat(error.message); + loggingService.logError(prefixedMessageError, prefixedMessageError.customAttributes); +}; +var processAxiosError = function processAxiosError(axiosErrorObject) { + var error = Object.create(axiosErrorObject); + var request = error.request, + response = error.response, + config = error.config; + if (!config) { + error.customAttributes = _objectSpread(_objectSpread({}, error.customAttributes), {}, { + httpErrorType: 'unknown-api-request-error' + }); + return error; + } + var httpErrorRequestUrl = config.url, + httpErrorRequestMethod = config.method; + /* istanbul ignore else: difficult to enter the request-only error case in a unit test */ + if (response) { + var status = response.status, + data = response.data; + var stringifiedData = JSON.stringify(data) || '(empty response)'; + var responseIsHTML = stringifiedData.includes(''); + // Don't include data if it is just an HTML document, like a 500 error page. + /* istanbul ignore next */ + var httpErrorResponseData = responseIsHTML ? '' : stringifiedData; + error.customAttributes = _objectSpread(_objectSpread({}, error.customAttributes), {}, { + httpErrorType: 'api-response-error', + httpErrorStatus: status, + httpErrorResponseData: httpErrorResponseData, + httpErrorRequestUrl: httpErrorRequestUrl, + httpErrorRequestMethod: httpErrorRequestMethod + }); + error.message = "Axios Error (Response): ".concat(status, " - See custom attributes for details."); + } else if (request) { + error.customAttributes = _objectSpread(_objectSpread({}, error.customAttributes), {}, { + httpErrorType: 'api-request-error', + httpErrorMessage: error.message, + httpErrorRequestUrl: httpErrorRequestUrl, + httpErrorRequestMethod: httpErrorRequestMethod + }); + // This case occurs most likely because of intermittent internet connection issues + // but it also, though less often, catches CORS or server configuration problems. + error.message = 'Axios Error (Request): (Possible local connectivity issue.) See custom attributes for details.'; + } else { + error.customAttributes = _objectSpread(_objectSpread({}, error.customAttributes), {}, { + httpErrorType: 'api-request-config-error', + httpErrorMessage: error.message, + httpErrorRequestUrl: httpErrorRequestUrl, + httpErrorRequestMethod: httpErrorRequestMethod + }); + error.message = 'Axios Error (Config): See custom attributes for details.'; + } + return error; +}; +var processAxiosErrorAndThrow = function processAxiosErrorAndThrow(axiosErrorObject) { + throw processAxiosError(axiosErrorObject); +}; +export { getUrlParts, logFrontendAuthError, processAxiosError, processAxiosErrorAndThrow }; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/dist/auth/utils.js.map b/dist/auth/utils.js.map new file mode 100644 index 000000000..7dbdeb147 --- /dev/null +++ b/dist/auth/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","names":["urlRegex","getUrlParts","url","found","match","_found","_slicedToArray","fullUrl","protocol","domain","path","endFilename","endFileExtension","query","hash","e","Error","concat","logFrontendAuthError","loggingService","error","prefixedMessageError","Object","create","message","logError","customAttributes","processAxiosError","axiosErrorObject","request","response","config","_objectSpread","httpErrorType","httpErrorRequestUrl","httpErrorRequestMethod","method","status","data","stringifiedData","JSON","stringify","responseIsHTML","includes","httpErrorResponseData","httpErrorStatus","httpErrorMessage","processAxiosErrorAndThrow"],"sources":["../../src/auth/utils.js"],"sourcesContent":["// Lifted from here: https://regexr.com/3ok5o\nconst urlRegex = /([a-z]{1,2}tps?):\\/\\/((?:(?!(?:\\/|#|\\?|&)).)+)(?:(\\/(?:(?:(?:(?!(?:#|\\?|&)).)+\\/))?))?(?:((?:(?!(?:\\.|$|\\?|#)).)+))?(?:(\\.(?:(?!(?:\\?|$|#)).)+))?(?:(\\?(?:(?!(?:$|#)).)+))?(?:(#.+))?/;\nconst getUrlParts = (url) => {\n const found = url.match(urlRegex);\n try {\n const [\n fullUrl,\n protocol,\n domain,\n path,\n endFilename,\n endFileExtension,\n query,\n hash,\n ] = found;\n\n return {\n fullUrl,\n protocol,\n domain,\n path,\n endFilename,\n endFileExtension,\n query,\n hash,\n };\n } catch (e) {\n throw new Error(`Could not find url parts from ${url}.`);\n }\n};\n\nconst logFrontendAuthError = (loggingService, error) => {\n const prefixedMessageError = Object.create(error);\n prefixedMessageError.message = `[frontend-auth] ${error.message}`;\n loggingService.logError(prefixedMessageError, prefixedMessageError.customAttributes);\n};\n\nconst processAxiosError = (axiosErrorObject) => {\n const error = Object.create(axiosErrorObject);\n const { request, response, config } = error;\n\n if (!config) {\n error.customAttributes = {\n ...error.customAttributes,\n httpErrorType: 'unknown-api-request-error',\n };\n return error;\n }\n\n const {\n url: httpErrorRequestUrl,\n method: httpErrorRequestMethod,\n } = config;\n /* istanbul ignore else: difficult to enter the request-only error case in a unit test */\n if (response) {\n const { status, data } = response;\n const stringifiedData = JSON.stringify(data) || '(empty response)';\n const responseIsHTML = stringifiedData.includes('');\n // Don't include data if it is just an HTML document, like a 500 error page.\n /* istanbul ignore next */\n const httpErrorResponseData = responseIsHTML ? '' : stringifiedData;\n error.customAttributes = {\n ...error.customAttributes,\n httpErrorType: 'api-response-error',\n httpErrorStatus: status,\n httpErrorResponseData,\n httpErrorRequestUrl,\n httpErrorRequestMethod,\n };\n error.message = `Axios Error (Response): ${status} - See custom attributes for details.`;\n } else if (request) {\n error.customAttributes = {\n ...error.customAttributes,\n httpErrorType: 'api-request-error',\n httpErrorMessage: error.message,\n httpErrorRequestUrl,\n httpErrorRequestMethod,\n };\n // This case occurs most likely because of intermittent internet connection issues\n // but it also, though less often, catches CORS or server configuration problems.\n error.message = 'Axios Error (Request): (Possible local connectivity issue.) See custom attributes for details.';\n } else {\n error.customAttributes = {\n ...error.customAttributes,\n httpErrorType: 'api-request-config-error',\n httpErrorMessage: error.message,\n httpErrorRequestUrl,\n httpErrorRequestMethod,\n };\n error.message = 'Axios Error (Config): See custom attributes for details.';\n }\n\n return error;\n};\n\nconst processAxiosErrorAndThrow = (axiosErrorObject) => {\n throw processAxiosError(axiosErrorObject);\n};\n\nexport {\n getUrlParts,\n logFrontendAuthError,\n processAxiosError,\n processAxiosErrorAndThrow,\n};\n"],"mappings":";;;;;;;;;;;;AAAA;AACA,IAAMA,QAAQ,GAAG,uLAAuL;AACxM,IAAMC,WAAW,GAAG,SAAdA,WAAWA,CAAIC,GAAG,EAAK;EAC3B,IAAMC,KAAK,GAAGD,GAAG,CAACE,KAAK,CAACJ,QAAQ,CAAC;EACjC,IAAI;IACF,IAAAK,MAAA,GAAAC,cAAA,CASIH,KAAK;MARPI,OAAO,GAAAF,MAAA;MACPG,QAAQ,GAAAH,MAAA;MACRI,MAAM,GAAAJ,MAAA;MACNK,IAAI,GAAAL,MAAA;M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sB,EACvB;IACDf,KAAK,CAACI,OAAO,GAAG,0DAA0D;EAC5E;EAEA,OAAOJ,KAAK;AACd,CAAC;AAED,IAAM2B,yBAAyB,GAAG,SAA5BA,yBAAyBA,CAAInB,gBAAgB,EAAK;EACtD,MAAMD,iBAAiB,CAACC,gBAAgB,CAAC;AAC3C,CAAC;AAED,SACE3B,WAAW,EACXiB,oBAAoB,EACpBS,iBAAiB,EACjBoB,yBAAyB","ignoreList":[]} \ No newline at end of file diff --git a/dist/config.js b/dist/config.js new file mode 100644 index 000000000..af3967263 --- /dev/null +++ b/dist/config.js @@ -0,0 +1,328 @@ +/** + * #### Import members from **@edx/frontend-platform** + * + * The configuration module provides utilities for working with an application's configuration + * document (ConfigDocument). Configuration variables can be supplied to the + * application in four different ways. They are applied in the following order: + * + * - Build-time Configuration + * - Environment Variables + * - JavaScript File + * - Runtime Configuration + * + * Last one in wins. Variables with the same name defined via the later methods will override any + * defined using an earlier method. i.e., if a variable is defined in Runtime Configuration, that + * will override the same variable defined in either Build-time Configuration method (environment + * variables or JS file). Configuration defined in a JS file will override environment variables. + * + * ##### Build-time Configuration + * + * Build-time configuration methods add config variables into the app when it is built by webpack. + * This saves the app an API call and means it has all the information it needs to initialize right + * away. There are two methods of supplying build-time configuration: environment variables and a + * JavaScript file. + * + * ###### Environment Variables + * + * A set list of required config variables can be supplied as + * command-line environment variables during the build process. + * + * As a simple example, these are supplied on the command-line before invoking `npm run build`: + * + * ``` + * LMS_BASE_URL=http://localhost:18000 npm run build + * ``` + * + * Note that additional variables _cannot_ be supplied via this method without using the `config` + * initialization handler. The app won't pick them up and they'll appear `undefined`. + * + * This configuration method is being deprecated in favor of JavaScript File Configuration. + * + * ###### JavaScript File Configuration + * + * Configuration variables can be supplied in an optional file named env.config.js. This file must + * export either an Object containing configuration variables or a function. The function must + * return an Object containing configuration variables or, alternately, a promise which resolves to + * an Object. + * + * Using a function or async function allows the configuration to be resolved at runtime (because + * the function will be executed at runtime). This is not common, and the capability is included + * for the sake of flexibility. + * + * JavaScript File Configuration is well-suited to extensibility use cases or component overrides, + * in that the configuration file can depend on any installed JavaScript module. It is also the + * preferred way of doing build-time configuration if runtime configuration isn't used by your + * deployment of the platform. + * + * Exporting a config object: + * ``` + * const config = { + * LMS_BASE_URL: 'http://localhost:18000' + * }; + * + * export default config; + * ``` + * + * Exporting a function that returns an object: + * ``` + * function getConfig() { + * return { + * LMS_BASE_URL: 'http://localhost:18000' + * }; + * } + * ``` + * + * Exporting a function that returns a promise that resolves to an object: + * ``` + * function getAsyncConfig() { + * return new Promise((resolve, reject) => { + * resolve({ + * LMS_BASE_URL: 'http://localhost:18000' + * }); + * }); + * } + * + * export default getAsyncConfig; + * ``` + * + * ##### Runtime Configuration + * + * Configuration variables can also be supplied using the "runtime configuration" method, taking + * advantage of the Micro-frontend Config API in edx-platform. More information on this API can be + * found in the ADR which introduced it: + * + * https://github.com/openedx/edx-platform/blob/master/lms/djangoapps/mfe_config_api/docs/decisions/0001-mfe-config-api.rst + * + * The runtime configuration method can be enabled by supplying a MFE_CONFIG_API_URL via one of the other + * two configuration methods above. + * + * Runtime configuration is particularly useful if you need to supply different configurations to + * a single deployment of a micro-frontend, for instance. It is also a perfectly valid alternative + * to build-time configuration, though it introduces an additional API call to edx-platform on MFE + * initialization. + * + * ##### Initialization Config Handler + * + * The configuration document can be extended by + * applications at run-time using a `config` initialization handler. Please see the Initialization + * documentation for more information on handlers and initialization phases. + * + * ``` + * initialize({ + * handlers: { + * config: () => { + * mergeConfig({ + * CUSTOM_VARIABLE: 'custom value', + * LMS_BASE_URL: 'http://localhost:18001' // You can override variables, but this is uncommon. + * }, 'App config override handler'); + * }, + * }, + * }); + * ``` + * + * @module Config + */ + +import { APP_CONFIG_INITIALIZED, CONFIG_CHANGED } from './constants'; +import { publish, subscribe } from './pubSub'; +import { ensureDefinedConfig } from './utils'; +function extractRegex(envVar) { + // Convert the environment variable string to a regex, while guarding + // against a non-string and an empty/whitespace-only string. + if (typeof envVar === 'string' && envVar.trim() !== '') { + return new RegExp(envVar); + } + return undefined; +} +var ENVIRONMENT = process.env.NODE_ENV; +var config = { + ACCESS_TOKEN_COOKIE_NAME: process.env.ACCESS_TOKEN_COOKIE_NAME, + ACCOUNT_PROFILE_URL: process.env.ACCOUNT_PROFILE_URL, + ACCOUNT_SETTINGS_URL: process.env.ACCOUNT_SETTINGS_URL, + BASE_URL: process.env.BASE_URL, + PUBLIC_PATH: process.env.PUBLIC_PATH || '/', + CREDENTIALS_BASE_URL: process.env.CREDENTIALS_BASE_URL, + CSRF_TOKEN_API_PATH: process.env.CSRF_TOKEN_API_PATH, + DISCOVERY_API_BASE_URL: process.env.DISCOVERY_API_BASE_URL, + PUBLISHER_BASE_URL: process.env.PUBLISHER_BASE_URL, + ECOMMERCE_BASE_URL: process.env.ECOMMERCE_BASE_URL, + ENVIRONMENT: ENVIRONMENT, + IGNORED_ERROR_REGEX: extractRegex(process.env.IGNORED_ERROR_REGEX), + LANGUAGE_PREFERENCE_COOKIE_NAME: process.env.LANGUAGE_PREFERENCE_COOKIE_NAME, + LEARNING_BASE_URL: process.env.LEARNING_BASE_URL, + LMS_BASE_URL: process.env.LMS_BASE_URL, + LOGIN_URL: process.env.LOGIN_URL, + LOGOUT_URL: process.env.LOGOUT_URL, + STUDIO_BASE_URL: process.env.STUDIO_BASE_URL, + MARKETING_SITE_BASE_URL: process.env.MARKETING_SITE_BASE_URL, + ORDER_HISTORY_URL: process.env.ORDER_HISTORY_URL, + REFRESH_ACCESS_TOKEN_ENDPOINT: process.env.REFRESH_ACCESS_TOKEN_ENDPOINT, + SECURE_COOKIES: ENVIRONMENT !== 'development', + SEGMENT_KEY: process.env.SEGMENT_KEY, + SITE_NAME: process.env.SITE_NAME, + USER_INFO_COOKIE_NAME: process.env.USER_INFO_COOKIE_NAME, + LOGO_URL: process.env.LOGO_URL, + LOGO_TRADEMARK_URL: process.env.LOGO_TRADEMARK_URL, + LOGO_WHITE_URL: process.env.LOGO_WHITE_URL, + FAVICON_URL: process.env.FAVICON_URL, + MFE_CONFIG_API_URL: process.env.MFE_CONFIG_API_URL, + APP_ID: process.env.APP_ID, + SUPPORT_URL: process.env.SUPPORT_URL, + PARAGON_THEME_URLS: JSON.parse(process.env.PARAGON_THEME_URLS) || {} +}; + +/** + * Getter for the application configuration document. This is synchronous and merely returns a + * reference to an existing object, and is thus safe to call as often as desired. + * + * Example: + * + * ``` + * import { getConfig } from '@edx/frontend-platform'; + * + * const { + * LMS_BASE_URL, + * } = getConfig(); + * ``` + * + * @returns {ConfigDocument} + */ +export function getConfig() { + return config; +} + +/** + * Replaces the existing ConfigDocument. This is not commonly used, but can be helpful for tests. + * + * The supplied config document will be tested with `ensureDefinedConfig` to ensure it does not + * have any `undefined` keys. + * + * Example: + * + * ``` + * import { setConfig } from '@edx/frontend-platform'; + * + * setConfig({ + * LMS_BASE_URL, // This is overriding the ENTIRE document - this is not merged in! + * }); + * ``` + * + * @param {ConfigDocument} newConfig + */ +export function setConfig(newConfig) { + ensureDefinedConfig(config, 'config'); + config = newConfig; + publish(CONFIG_CHANGED); +} + +/** + * Merges additional configuration values into the ConfigDocument returned by `getConfig`. Will + * override any values that exist with the same keys. + * + * ``` + * mergeConfig({ + * NEW_KEY: 'new value', + * OTHER_NEW_KEY: 'other new value', + * }); + * + * If any of the key values are `undefined`, an error will be logged to 'warn'. + * + * @param {Object} newConfig + */ +export function mergeConfig(newConfig) { + ensureDefinedConfig(newConfig, 'ProcessEnvConfigService'); + config = Object.assign(config, newConfig); + publish(CONFIG_CHANGED); +} + +/** + * A method allowing application code to indicate that particular ConfigDocument keys are required + * for them to function. This is useful for diagnosing development/deployment issues, primarily, + * by surfacing misconfigurations early. For instance, if the build process fails to supply an + * environment variable on the command-line, it's possible that one of the `process.env` variables + * will be undefined. Should be used in conjunction with `mergeConfig` for custom `ConfigDocument` + * properties. Requester is for informational/error reporting purposes only. + * + * ``` + * ensureConfig(['LMS_BASE_URL', 'LOGIN_URL'], 'MySpecialComponent'); + * + * // Will log a warning with: + * // "App configuration error: LOGIN_URL is required by MySpecialComponent." + * // if LOGIN_URL is undefined, for example. + * ``` + * + * *NOTE*: `ensureConfig` waits until `APP_CONFIG_INITIALIZED` is published to verify the existence + * of the specified properties. This means that this function is compatible with custom `config` + * phase handlers responsible for loading additional configuration data in the initialization + * sequence. + * + * @param {Array} keys + * @param {string} [requester='unspecified application code'] + */ +export function ensureConfig(keys) { + var requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'unspecified application code'; + subscribe(APP_CONFIG_INITIALIZED, function () { + keys.forEach(function (key) { + if (config[key] === undefined) { + // eslint-disable-next-line no-console + console.warn("App configuration error: ".concat(key, " is required by ").concat(requester, ".")); + } + }); + }); +} + +/** + * An object describing the current application configuration. + * + * In its most basic form, the initialization process loads this document via `process.env` + * variables. There are other ways to add configuration variables to the ConfigDocument as + * documented above (JavaScript File Configuration, Runtime Configuration, and the Initialization + * Config Handler) + * + * ``` + * { + * BASE_URL: process.env.BASE_URL, + * // ... other vars + * } + * ``` + * + * When using Webpack (i.e., normal usage), the build process is responsible for supplying these + * variables via command-line environment variables. That means they must be supplied at build + * time. + * + * @name ConfigDocument + * @memberof module:Config + * @property {string} ACCESS_TOKEN_COOKIE_NAME + * @property {string} ACCOUNT_PROFILE_URL + * @property {string} ACCOUNT_SETTINGS_URL + * @property {string} BASE_URL The URL of the current application. + * @property {string} CREDENTIALS_BASE_URL + * @property {string} CSRF_TOKEN_API_PATH + * @property {string} DISCOVERY_API_BASE_URL + * @property {string} PUBLISHER_BASE_URL + * @property {string} ECOMMERCE_BASE_URL + * @property {string} ENVIRONMENT This is one of: development, production, or test. + * @property {string} IGNORED_ERROR_REGEX + * @property {string} LANGUAGE_PREFERENCE_COOKIE_NAME + * @property {string} LEARNING_BASE_URL + * @property {string} LMS_BASE_URL + * @property {string} LOGIN_URL + * @property {string} LOGOUT_URL + * @property {string} STUDIO_BASE_URL + * @property {string} MARKETING_SITE_BASE_URL + * @property {string} ORDER_HISTORY_URL + * @property {string} REFRESH_ACCESS_TOKEN_ENDPOINT + * @property {boolean} SECURE_COOKIES + * @property {string} SEGMENT_KEY + * @property {string} SITE_NAME + * @property {string} USER_INFO_COOKIE_NAME + * @property {string} LOGO_URL + * @property {string} LOGO_TRADEMARK_URL + * @property {string} LOGO_WHITE_URL + * @property {string} FAVICON_URL + * @property {string} MFE_CONFIG_API_URL + * @property {string} APP_ID + * @property {string} SUPPORT_URL + * @property {string} PARAGON_THEME_URLS + */ +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/dist/config.js.map b/dist/config.js.map new file mode 100644 index 000000000..c0d564881 --- /dev/null +++ b/dist/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","names":["APP_CONFIG_INITIALIZED","CONFIG_CHANGED","publish","subscribe","ensureDefinedConfig","extractRegex","envVar","trim","RegExp","undefined","ENVIRONMENT","process","env","NODE_ENV","config","ACCESS_TOKEN_COOKIE_NAME","ACCOUNT_PROFILE_URL","ACCOUNT_SETTINGS_URL","BASE_URL","PUBLIC_PATH","CREDENTIALS_BASE_URL","CSRF_TOKEN_API_PATH","DISCOVERY_API_BASE_URL","PUBLISHER_BASE_URL","ECOMMERCE_BASE_URL","IGNORED_ERROR_REGEX","LANGUAGE_PREFERENCE_COOKIE_NAME","LEARNING_BASE_URL","LMS_BASE_URL","LOGIN_URL","LOGOUT_URL","STUDIO_BASE_URL","MARKETING_SITE_BASE_URL","ORDER_HISTORY_URL","REFRESH_ACCESS_TOKEN_ENDPOINT","SECURE_COOKIES","SEGMENT_KEY","SITE_NAME","USER_INFO_COOKIE_NAME","LOGO_URL","LOGO_TRADEMARK_URL","LOGO_WHITE_URL","FAVICON_URL","MFE_CONFIG_API_URL","APP_ID","SUPPORT_URL","PARAGON_THEME_URLS","JSON","parse","getConfig","setConfig","newConfig","mergeConfig","Object","assign","ensureConfig","keys","requester","arguments","length","forEach","key","console","warn","concat"],"sources":["../src/config.js"],"sourcesContent":["/**\n * #### Import members from **@edx/frontend-platform**\n *\n * The configuration module provides utilities for working with an application's configuration\n * document (ConfigDocument). Configuration variables can be supplied to the\n * application in four different ways. They are applied in the following order:\n *\n * - Build-time Configuration\n * - Environment Variables\n * - JavaScript File\n * - Runtime Configuration\n *\n * Last one in wins. Variables with the same name defined via the later methods will override any\n * defined using an earlier method. i.e., if a variable is defined in Runtime Configuration, that\n * will override the same variable defined in either Build-time Configuration method (environment\n * variables or JS file). Configuration defined in a JS file will override environment variables.\n *\n * ##### Build-time Configuration\n *\n * Build-time configuration methods add config variables into the app when it is built by webpack.\n * This saves the app an API call and means it has all the information it needs to initialize right\n * away. There are two methods of supplying build-time configuration: environment variables and a\n * JavaScript file.\n *\n * ###### Environment Variables\n *\n * A set list of required config variables can be supplied as\n * command-line environment variables during the build process.\n *\n * As a simple example, these are supplied on the command-line before invoking `npm run build`:\n *\n * ```\n * LMS_BASE_URL=http://localhost:18000 npm run build\n * ```\n *\n * Note that additional variables _cannot_ be supplied via this method without using the `config`\n * initialization handler. The app won't pick them up and they'll appear `undefined`.\n *\n * This configuration method is being deprecated in favor of JavaScript File Configuration.\n *\n * ###### JavaScript File Configuration\n *\n * Configuration variables can be supplied in an optional file named env.config.js. This file must\n * export either an Object containing configuration variables or a function. The function must\n * return an Object containing configuration variables or, alternately, a promise which resolves to\n * an Object.\n *\n * Using a function or async function allows the configuration to be resolved at runtime (because\n * the function will be executed at runtime). This is not common, and the capability is included\n * for the sake of flexibility.\n *\n * JavaScript File Configuration is well-suited to extensibility use cases or component overrides,\n * in that the configuration file can depend on any installed JavaScript module. It is also the\n * preferred way of doing build-time configuration if runtime configuration isn't used by your\n * deployment of the platform.\n *\n * Exporting a config object:\n * ```\n * const config = {\n * LMS_BASE_URL: 'http://localhost:18000'\n * };\n *\n * export default config;\n * ```\n *\n * Exporting a function that returns an object:\n * ```\n * function getConfig() {\n * return {\n * LMS_BASE_URL: 'http://localhost:18000'\n * };\n * }\n * ```\n *\n * Exporting a function that returns a promise that resolves to an object:\n * ```\n * function getAsyncConfig() {\n * return new Promise((resolve, reject) => {\n * resolve({\n * LMS_BASE_URL: 'http://localhost:18000'\n * });\n * });\n * }\n *\n * export default getAsyncConfig;\n * ```\n *\n * ##### Runtime Configuration\n *\n * Configuration variables can also be supplied using the \"runtime configuration\" method, taking\n * advantage of the Micro-frontend Config API in edx-platform. More information on this API can be\n * found in the ADR which introduced it:\n *\n * https://github.com/openedx/edx-platform/blob/master/lms/djangoapps/mfe_config_api/docs/decisions/0001-mfe-config-api.rst\n *\n * The runtime configuration method can be enabled by supplying a MFE_CONFIG_API_URL via one of the other\n * two configuration methods above.\n *\n * Runtime configuration is particularly useful if you need to supply different configurations to\n * a single deployment of a micro-frontend, for instance. It is also a perfectly valid alternative\n * to build-time configuration, though it introduces an additional API call to edx-platform on MFE\n * initialization.\n *\n * ##### Initialization Config Handler\n *\n * The configuration document can be extended by\n * applications at run-time using a `config` initialization handler. Please see the Initialization\n * documentation for more information on handlers and initialization phases.\n *\n * ```\n * initialize({\n * handlers: {\n * config: () => {\n * mergeConfig({\n * CUSTOM_VARIABLE: 'custom value',\n * LMS_BASE_URL: 'http://localhost:18001' // You can override variables, but this is uncommon.\n * }, 'App config override handler');\n * },\n * },\n * });\n * ```\n *\n * @module Config\n */\n\nimport { APP_CONFIG_INITIALIZED, CONFIG_CHANGED } from './constants';\n\nimport { publish, subscribe } from './pubSub';\nimport { ensureDefinedConfig } from './utils';\n\nfunction extractRegex(envVar) {\n // Convert the environment variable string to a regex, while guarding\n // against a non-string and an empty/whitespace-only string.\n if (typeof envVar === 'string' && envVar.trim() !== '') {\n return new RegExp(envVar);\n }\n return undefined;\n}\n\nconst ENVIRONMENT = process.env.NODE_ENV;\nlet config = {\n ACCESS_TOKEN_COOKIE_NAME: process.env.ACCESS_TOKEN_COOKIE_NAME,\n ACCOUNT_PROFILE_URL: process.env.ACCOUNT_PROFILE_URL,\n ACCOUNT_SETTINGS_URL: process.env.ACCOUNT_SETTINGS_URL,\n BASE_URL: process.env.BASE_URL,\n PUBLIC_PATH: process.env.PUBLIC_PATH || '/',\n CREDENTIALS_BASE_URL: process.env.CREDENTIALS_BASE_URL,\n CSRF_TOKEN_API_PATH: process.env.CSRF_TOKEN_API_PATH,\n DISCOVERY_API_BASE_URL: process.env.DISCOVERY_API_BASE_URL,\n PUBLISHER_BASE_URL: process.env.PUBLISHER_BASE_URL,\n ECOMMERCE_BASE_URL: process.env.ECOMMERCE_BASE_URL,\n ENVIRONMENT,\n IGNORED_ERROR_REGEX: extractRegex(process.env.IGNORED_ERROR_REGEX),\n LANGUAGE_PREFERENCE_COOKIE_NAME: process.env.LANGUAGE_PREFERENCE_COOKIE_NAME,\n LEARNING_BASE_URL: process.env.LEARNING_BASE_URL,\n LMS_BASE_URL: process.env.LMS_BASE_URL,\n LOGIN_URL: process.env.LOGIN_URL,\n LOGOUT_URL: process.env.LOGOUT_URL,\n STUDIO_BASE_URL: process.env.STUDIO_BASE_URL,\n MARKETING_SITE_BASE_URL: process.env.MARKETING_SITE_BASE_URL,\n ORDER_HISTORY_URL: process.env.ORDER_HISTORY_URL,\n REFRESH_ACCESS_TOKEN_ENDPOINT: process.env.REFRESH_ACCESS_TOKEN_ENDPOINT,\n SECURE_COOKIES: ENVIRONMENT !== 'development',\n SEGMENT_KEY: process.env.SEGMENT_KEY,\n SITE_NAME: process.env.SITE_NAME,\n USER_INFO_COOKIE_NAME: process.env.USER_INFO_COOKIE_NAME,\n LOGO_URL: process.env.LOGO_URL,\n LOGO_TRADEMARK_URL: process.env.LOGO_TRADEMARK_URL,\n LOGO_WHITE_URL: process.env.LOGO_WHITE_URL,\n FAVICON_URL: process.env.FAVICON_URL,\n MFE_CONFIG_API_URL: process.env.MFE_CONFIG_API_URL,\n APP_ID: process.env.APP_ID,\n SUPPORT_URL: process.env.SUPPORT_URL,\n PARAGON_THEME_URLS: JSON.parse(process.env.PARAGON_THEME_URLS) || {},\n};\n\n/**\n * Getter for the application configuration document. This is synchronous and merely returns a\n * reference to an existing object, and is thus safe to call as often as desired.\n *\n * Example:\n *\n * ```\n * import { getConfig } from '@edx/frontend-platform';\n *\n * const {\n * LMS_BASE_URL,\n * } = getConfig();\n * ```\n *\n * @returns {ConfigDocument}\n */\nexport function getConfig() {\n return config;\n}\n\n/**\n * Replaces the existing ConfigDocument. This is not commonly used, but can be helpful for tests.\n *\n * The supplied config document will be tested with `ensureDefinedConfig` to ensure it does not\n * have any `undefined` keys.\n *\n * Example:\n *\n * ```\n * import { setConfig } from '@edx/frontend-platform';\n *\n * setConfig({\n * LMS_BASE_URL, // This is overriding the ENTIRE document - this is not merged in!\n * });\n * ```\n *\n * @param {ConfigDocument} newConfig\n */\nexport function setConfig(newConfig) {\n ensureDefinedConfig(config, 'config');\n config = newConfig;\n publish(CONFIG_CHANGED);\n}\n\n/**\n * Merges additional configuration values into the ConfigDocument returned by `getConfig`. Will\n * override any values that exist with the same keys.\n *\n * ```\n * mergeConfig({\n * NEW_KEY: 'new value',\n * OTHER_NEW_KEY: 'other new value',\n * });\n *\n * If any of the key values are `undefined`, an error will be logged to 'warn'.\n *\n * @param {Object} newConfig\n */\nexport function mergeConfig(newConfig) {\n ensureDefinedConfig(newConfig, 'ProcessEnvConfigService');\n config = Object.assign(config, newConfig);\n publish(CONFIG_CHANGED);\n}\n\n/**\n * A method allowing application code to indicate that particular ConfigDocument keys are required\n * for them to function. This is useful for diagnosing development/deployment issues, primarily,\n * by surfacing misconfigurations early. For instance, if the build process fails to supply an\n * environment variable on the command-line, it's possible that one of the `process.env` variables\n * will be undefined. Should be used in conjunction with `mergeConfig` for custom `ConfigDocument`\n * properties. Requester is for informational/error reporting purposes only.\n *\n * ```\n * ensureConfig(['LMS_BASE_URL', 'LOGIN_URL'], 'MySpecialComponent');\n *\n * // Will log a warning with:\n * // \"App configuration error: LOGIN_URL is required by MySpecialComponent.\"\n * // if LOGIN_URL is undefined, for example.\n * ```\n *\n * *NOTE*: `ensureConfig` waits until `APP_CONFIG_INITIALIZED` is published to verify the existence\n * of the specified properties. This means that this function is compatible with custom `config`\n * phase handlers responsible for loading additional configuration data in the initialization\n * sequence.\n *\n * @param {Array} keys\n * @param {string} [requester='unspecified application code']\n */\nexport function ensureConfig(keys, requester = 'unspecified application code') {\n subscribe(APP_CONFIG_INITIALIZED, () => {\n keys.forEach((key) => {\n if (config[key] === undefined) {\n // eslint-disable-next-line no-console\n console.warn(`App configuration error: ${key} is required by ${requester}.`);\n }\n });\n });\n}\n\n/**\n * An object describing the current application configuration.\n *\n * In its most basic form, the initialization process loads this document via `process.env`\n * variables. There are other ways to add configuration variables to the ConfigDocument as\n * documented above (JavaScript File Configuration, Runtime Configuration, and the Initialization\n * Config Handler)\n *\n * ```\n * {\n * BASE_URL: process.env.BASE_URL,\n * // ... other vars\n * }\n * ```\n *\n * When using Webpack (i.e., normal usage), the build process is responsible for supplying these\n * variables via command-line environment variables. That means they must be supplied at build\n * time.\n *\n * @name ConfigDocument\n * @memberof module:Config\n * @property {string} ACCESS_TOKEN_COOKIE_NAME\n * @property {string} ACCOUNT_PROFILE_URL\n * @property {string} ACCOUNT_SETTINGS_URL\n * @property {string} BASE_URL The URL of the current application.\n * @property {string} CREDENTIALS_BASE_URL\n * @property {string} CSRF_TOKEN_API_PATH\n * @property {string} DISCOVERY_API_BASE_URL\n * @property {string} PUBLISHER_BASE_URL\n * @property {string} ECOMMERCE_BASE_URL\n * @property {string} ENVIRONMENT This is one of: development, production, or test.\n * @property {string} IGNORED_ERROR_REGEX\n * @property {string} LANGUAGE_PREFERENCE_COOKIE_NAME\n * @property {string} LEARNING_BASE_URL\n * @property {string} LMS_BASE_URL\n * @property {string} LOGIN_URL\n * @property {string} LOGOUT_URL\n * @property {string} STUDIO_BASE_URL\n * @property {string} MARKETING_SITE_BASE_URL\n * @property {string} ORDER_HISTORY_URL\n * @property {string} REFRESH_ACCESS_TOKEN_ENDPOINT\n * @property {boolean} SECURE_COOKIES\n * @property {string} SEGMENT_KEY\n * @property {string} SITE_NAME\n * @property {string} USER_INFO_COOKIE_NAME\n * @property {string} LOGO_URL\n * @property {string} LOGO_TRADEMARK_URL\n * @property {string} LOGO_WHITE_URL\n * @property {string} FAVICON_URL\n * @property {string} MFE_CONFIG_API_URL\n * @property {string} APP_ID\n * @property {string} SUPPORT_URL\n * @property {string} PARAGON_THEME_URLS\n */\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,sBAAsB,EAAEC,cAAc,QAAQ,aAAa;AAEpE,SAASC,OAAO,EAAEC,SAAS,QAAQ,UAAU;AAC7C,SAASC,mBAAmB,QAAQ,SAAS;AAE7C,SAASC,YAAYA,CAACC,MAAM,EAAE;EAC5B;EACA;EACA,IAAI,OAAOA,MAAM,KAAK,QAAQ,IAAIA,MAAM,CAACC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;IACtD,OAAO,IAAIC,MAAM,CAACF,MAAM,CAAC;EAC3B;EACA,OAAOG,SAAS;AAClB;AAEA,IAAMC,WAAW,GAAGC,OAAO,CAACC,GAAG,CAACC,QAAQ;AACxC,IAAIC,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ACC,MAAM,CAACxC,MAAM,EAAEqC,SAAS,CAAC;EACzCjD,OAAO,CAACD,cAAc,CAAC;AACzB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASsD,YAAYA,CAACC,IAAI,EAA8C;EAAA,IAA5CC,SAAS,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAjD,SAAA,GAAAiD,SAAA,MAAG,8BAA8B;EAC3EvD,SAAS,CAACH,sBAAsB,EAAE,YAAM;IACtCwD,IAAI,CAACI,OAAO,CAAC,UAACC,GAAG,EAAK;MACpB,IAAI/C,MAAM,CAAC+C,GAAG,CAAC,KAAKpD,SAAS,EAAE;QAC7B;QACAqD,OAAO,CAACC,IAAI,6BAAAC,MAAA,CAA6BH,GAAG,sBAAAG,MAAA,CAAmBP,SAAS,MAAG,CAAC;MAC9E;IACF,CAAC,CAAC;EACJ,CAAC,CAAC;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]} \ No newline at end of file diff --git a/dist/constants.js b/dist/constants.js new file mode 100644 index 000000000..71d23040d --- /dev/null +++ b/dist/constants.js @@ -0,0 +1,65 @@ +/** @constant */ +export var APP_TOPIC = 'APP'; +export var APP_PUBSUB_INITIALIZED = "".concat(APP_TOPIC, ".PUBSUB_INITIALIZED"); + +/** + * Event published when the application initialization sequence has finished loading any dynamic + * configuration setup in a custom config handler. + * + * @event + */ +export var APP_CONFIG_INITIALIZED = "".concat(APP_TOPIC, ".CONFIG_INITIALIZED"); + +/** + * Event published when the application initialization sequence has finished determining the user's + * authentication state, creating an authenticated API client, and executing auth handlers. + * + * @event + */ +export var APP_AUTH_INITIALIZED = "".concat(APP_TOPIC, ".AUTH_INITIALIZED"); + +/** + * Event published when the application initialization sequence has finished initializing + * internationalization and executing any i18n handlers. + * + * @event + */ +export var APP_I18N_INITIALIZED = "".concat(APP_TOPIC, ".I18N_INITIALIZED"); + +/** + * Event published when the application initialization sequence has finished initializing the + * logging service and executing any logging handlers. + * + * @event + */ +export var APP_LOGGING_INITIALIZED = "".concat(APP_TOPIC, ".LOGGING_INITIALIZED"); + +/** + * Event published when the application initialization sequence has finished initializing the + * analytics service and executing any analytics handlers. + * + * @event + */ +export var APP_ANALYTICS_INITIALIZED = "".concat(APP_TOPIC, ".ANALYTICS_INITIALIZED"); + +/** + * Event published when the application initialization sequence has finished. Applications should + * subscribe to this event and start rendering the UI when it has fired. + * + * @event + */ +export var APP_READY = "".concat(APP_TOPIC, ".READY"); + +/** + * Event published when the application initialization sequence has aborted. This is frequently + * used to show an error page when an initialization error has occurred. + * + * @see {@link module:React~ErrorPage} + * @event + */ +export var APP_INIT_ERROR = "".concat(APP_TOPIC, ".INIT_ERROR"); + +/** @constant */ +export var CONFIG_TOPIC = 'CONFIG'; +export var CONFIG_CHANGED = "".concat(CONFIG_TOPIC, ".CHANGED"); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/dist/constants.js.map b/dist/constants.js.map new file mode 100644 index 000000000..630735411 --- /dev/null +++ b/dist/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","names":["APP_TOPIC","APP_PUBSUB_INITIALIZED","concat","APP_CONFIG_INITIALIZED","APP_AUTH_INITIALIZED","APP_I18N_INITIALIZED","APP_LOGGING_INITIALIZED","APP_ANALYTICS_INITIALIZED","APP_READY","APP_INIT_ERROR","CONFIG_TOPIC","CONFIG_CHANGED"],"sources":["../src/constants.js"],"sourcesContent":["/** @constant */\nexport const APP_TOPIC = 'APP';\n\nexport const APP_PUBSUB_INITIALIZED = `${APP_TOPIC}.PUBSUB_INITIALIZED`;\n\n/**\n * Event published when the application initialization sequence has finished loading any dynamic\n * configuration setup in a custom config handler.\n *\n * @event\n */\nexport const APP_CONFIG_INITIALIZED = `${APP_TOPIC}.CONFIG_INITIALIZED`;\n\n/**\n * Event published when the application initialization sequence has finished determining the user's\n * authentication state, creating an authenticated API client, and executing auth handlers.\n *\n * @event\n */\nexport const APP_AUTH_INITIALIZED = `${APP_TOPIC}.AUTH_INITIALIZED`;\n\n/**\n * Event published when the application initialization sequence has finished initializing\n * internationalization and executing any i18n handlers.\n *\n * @event\n */\nexport const APP_I18N_INITIALIZED = `${APP_TOPIC}.I18N_INITIALIZED`;\n\n/**\n * Event published when the application initialization sequence has finished initializing the\n * logging service and executing any logging handlers.\n *\n * @event\n */\nexport const APP_LOGGING_INITIALIZED = `${APP_TOPIC}.LOGGING_INITIALIZED`;\n\n/**\n * Event published when the application initialization sequence has finished initializing the\n * analytics service and executing any analytics handlers.\n *\n * @event\n */\nexport const APP_ANALYTICS_INITIALIZED = `${APP_TOPIC}.ANALYTICS_INITIALIZED`;\n\n/**\n * Event published when the application initialization sequence has finished. Applications should\n * subscribe to this event and start rendering the UI when it has fired.\n *\n * @event\n */\nexport const APP_READY = `${APP_TOPIC}.READY`;\n\n/**\n * Event published when the application initialization sequence has aborted. This is frequently\n * used to show an error page when an initialization error has occurred.\n *\n * @see {@link module:React~ErrorPage}\n * @event\n */\nexport const APP_INIT_ERROR = `${APP_TOPIC}.INIT_ERROR`;\n\n/** @constant */\nexport const CONFIG_TOPIC = 'CONFIG';\n\nexport const CONFIG_CHANGED = `${CONFIG_TOPIC}.CHANGED`;\n"],"mappings":"AAAA;AACA,OAAO,IAAMA,SAAS,GAAG,KAAK;AAE9B,OAAO,IAAMC,sBAAsB,MAAAC,MAAA,CAAMF,SAAS,wBAAqB;;AAEvE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMG,sBAAsB,MAAAD,MAAA,CAAMF,SAAS,wBAAqB;;AAEvE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMI,oBAAoB,MAAAF,MAAA,CAAMF,SAAS,sBAAmB;;AAEnE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMK,oBAAoB,MAAAH,MAAA,CAAMF,SAAS,sBAAmB;;AAEnE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMM,uBAAuB,MAAAJ,MAAA,CAAMF,SAAS,yBAAsB;;AAEzE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMO,yBAAyB,MAAAL,MAAA,CAAMF,SAAS,2BAAwB;;AAE7E;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMQ,SAAS,MAAAN,MAAA,CAAMF,SAAS,WAAQ;;AAE7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMS,cAAc,MAAAP,MAAA,CAAMF,SAAS,gBAAa;;AAEvD;AACA,OAAO,IAAMU,YAAY,GAAG,QAAQ;AAEpC,OAAO,IAAMC,cAAc,MAAAT,MAAA,CAAMQ,YAAY,aAAU","ignoreList":[]} \ No newline at end of file diff --git a/dist/i18n/countries.js b/dist/i18n/countries.js new file mode 100644 index 000000000..c9388a9c2 --- /dev/null +++ b/dist/i18n/countries.js @@ -0,0 +1,83 @@ +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +/* eslint-disable import/extensions */ +import COUNTRIES, { langs as countryLangs } from 'i18n-iso-countries'; +import arLocale from 'i18n-iso-countries/langs/ar.json'; +import enLocale from 'i18n-iso-countries/langs/en.json'; +import esLocale from 'i18n-iso-countries/langs/es.json'; +import frLocale from 'i18n-iso-countries/langs/fr.json'; +import zhLocale from 'i18n-iso-countries/langs/zh.json'; +import caLocale from 'i18n-iso-countries/langs/ca.json'; +import heLocale from 'i18n-iso-countries/langs/he.json'; +import idLocale from 'i18n-iso-countries/langs/id.json'; +import koLocale from 'i18n-iso-countries/langs/ko.json'; +import plLocale from 'i18n-iso-countries/langs/pl.json'; +import ptLocale from 'i18n-iso-countries/langs/pt.json'; +import ruLocale from 'i18n-iso-countries/langs/ru.json'; +import ukLocale from 'i18n-iso-countries/langs/uk.json'; +import { getPrimaryLanguageSubtag } from './lib'; + +/* + * COUNTRY LISTS + * + * Lists of country names localized in supported languages. + * + * TODO: When we start dynamically loading translations only for the current locale, change this. + */ + +COUNTRIES.registerLocale(arLocale); +COUNTRIES.registerLocale(enLocale); +COUNTRIES.registerLocale(esLocale); +COUNTRIES.registerLocale(frLocale); +COUNTRIES.registerLocale(zhLocale); +COUNTRIES.registerLocale(caLocale); +COUNTRIES.registerLocale(heLocale); +COUNTRIES.registerLocale(idLocale); +COUNTRIES.registerLocale(koLocale); +COUNTRIES.registerLocale(plLocale); +COUNTRIES.registerLocale(ptLocale); +COUNTRIES.registerLocale(ruLocale); +// COUNTRIES.registerLocale(thLocale); // Doesn't exist in lib. +COUNTRIES.registerLocale(ukLocale); + +/** + * Provides a lookup table of country IDs to country names for the current locale. + * + * @memberof module:I18n + */ +export function getCountryMessages(locale) { + var primaryLanguageSubtag = getPrimaryLanguageSubtag(locale); + var languageCode = countryLangs().includes(primaryLanguageSubtag) ? primaryLanguageSubtag : 'en'; + return COUNTRIES.getNames(languageCode); +} + +/** + * Provides a list of countries represented as objects of the following shape: + * + * { + * key, // The ID of the country + * name // The localized name of the country + * } + * + * TODO: ARCH-878: The list should be sorted alphabetically in the current locale. + * This is useful for populating dropdowns. + * + * @memberof module:I18n + */ +export function getCountryList(locale) { + var countryMessages = getCountryMessages(locale); + return Object.entries(countryMessages).map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + code = _ref2[0], + name = _ref2[1]; + return { + code: code, + name: name + }; + }); +} +//# sourceMappingURL=countries.js.map \ No newline at end of file diff --git a/dist/i18n/countries.js.map b/dist/i18n/countries.js.map new file mode 100644 index 000000000..24a5a239a --- /dev/null +++ b/dist/i18n/countries.js.map @@ -0,0 +1 @@ +{"version":3,"file":"countries.js","names":["COUNTRIES","langs","countryLangs","arLocale","enLocale","esLocale","frLocale","zhLocale","caLocale","heLocale","idLocale","koLocale","plLocale","ptLocale","ruLocale","ukLocale","getPrimaryLanguageSubtag","registerLocale","getCountryMessages","locale","primaryLanguageSubtag","languageCode","includes","getNames","getCountryList","countryMessages","Object","entries","map","_ref","_ref2","_slicedToArray","code","name"],"sources":["../../src/i18n/countries.js"],"sourcesContent":["/* eslint-disable import/extensions */\nimport COUNTRIES, { langs as countryLangs } from 'i18n-iso-countries';\n\nimport arLocale from 'i18n-iso-countries/langs/ar.json';\nimport enLocale from 'i18n-iso-countries/langs/en.json';\nimport esLocale from 'i18n-iso-countries/langs/es.json';\nimport frLocale from 'i18n-iso-countries/langs/fr.json';\nimport zhLocale from 'i18n-iso-countries/langs/zh.json';\nimport caLocale from 'i18n-iso-countries/langs/ca.json';\nimport heLocale from 'i18n-iso-countries/langs/he.json';\nimport idLocale from 'i18n-iso-countries/langs/id.json';\nimport koLocale from 'i18n-iso-countries/langs/ko.json';\nimport plLocale from 'i18n-iso-countries/langs/pl.json';\nimport ptLocale from 'i18n-iso-countries/langs/pt.json';\nimport ruLocale from 'i18n-iso-countries/langs/ru.json';\nimport ukLocale from 'i18n-iso-countries/langs/uk.json';\n\nimport { getPrimaryLanguageSubtag } from './lib';\n\n/*\n * COUNTRY LISTS\n *\n * Lists of country names localized in supported languages.\n *\n * TODO: When we start dynamically loading translations only for the current locale, change this.\n */\n\nCOUNTRIES.registerLocale(arLocale);\nCOUNTRIES.registerLocale(enLocale);\nCOUNTRIES.registerLocale(esLocale);\nCOUNTRIES.registerLocale(frLocale);\nCOUNTRIES.registerLocale(zhLocale);\nCOUNTRIES.registerLocale(caLocale);\nCOUNTRIES.registerLocale(heLocale);\nCOUNTRIES.registerLocale(idLocale);\nCOUNTRIES.registerLocale(koLocale);\nCOUNTRIES.registerLocale(plLocale);\nCOUNTRIES.registerLocale(ptLocale);\nCOUNTRIES.registerLocale(ruLocale);\n// COUNTRIES.registerLocale(thLocale); // Doesn't exist in lib.\nCOUNTRIES.registerLocale(ukLocale);\n\n/**\n * Provides a lookup table of country IDs to country names for the current locale.\n *\n * @memberof module:I18n\n */\nexport function getCountryMessages(locale) {\n const primaryLanguageSubtag = getPrimaryLanguageSubtag(locale);\n const languageCode = countryLangs().includes(primaryLanguageSubtag) ? primaryLanguageSubtag : 'en';\n\n return COUNTRIES.getNames(languageCode);\n}\n\n/**\n * Provides a list of countries represented as objects of the following shape:\n *\n * {\n * key, // The ID of the country\n * name // The localized name of the country\n * }\n *\n * TODO: ARCH-878: The list should be sorted alphabetically in the current locale.\n * This is useful for populating dropdowns.\n *\n * @memberof module:I18n\n */\nexport function getCountryList(locale) {\n const countryMessages = getCountryMessages(locale);\n return Object.entries(countryMessages).map(([code, name]) => ({ code, name }));\n}\n"],"mappings":";;;;;;AAAA;AACA,OAAOA,SAAS,IAAIC,KAAK,IAAIC,YAAY,QAAQ,oBAAoB;AAErE,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AACvD,OAAOC,QAAQ,MAAM,kCAAkC;AAEvD,SAASC,wBAAwB,QAAQ,OAAO;;AAEhD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEAhB,SAAS,CAACiB,cAAc,CAACd,QAAQ,CAAC;AAClCH,SAAS,CAACiB,cAAc,CAACb,QAAQ,CAAC;AAClCJ,SAAS,CAACiB,cAAc,CAACZ,QAAQ,CAAC;AAClCL,SAAS,CAACiB,cAAc,CAACX,QAAQ,CAAC;AAClCN,SAAS,CAACiB,cAAc,CAACV,QAAQ,CAAC;AAClCP,SAAS,CAACiB,cAAc,CAACT,QAAQ,CAAC;AAClCR,SAAS,CAACiB,cAAc,CAACR,QAAQ,CAAC;AAClCT,SAAS,CAACiB,cAAc,CAACP,QAAQ,CAAC;AAClCV,SAAS,CAACiB,cAAc,CAACN,QAAQ,CAAC;AAClCX,SAAS,CAACiB,cAAc,CAACL,QAAQ,CAAC;AAClCZ,SAAS,CAACiB,cAAc,CAACJ,QAAQ,CAAC;AAClCb,SAAS,CAACiB,cAAc,CAACH,QAAQ,CAAC;AAClC;AACAd,SAAS,CAACiB,cAAc,CAACF,QAAQ,CAAC;;AAElC;AACA;AACA;AACA;AACA;AACA,OAAO,SAASG,kBAAkBA,CAACC,MAAM,EAAE;EACzC,IAAMC,qBAAqB,GAAGJ,wBAAwB,CAACG,MAAM,CAAC;EAC9D,IAAME,YAAY,GAAGnB,YAAY,CAAC,CAAC,CAACoB,QAAQ,CAACF,qBAAqB,CAAC,GAAGA,qBAAqB,GAAG,IAAI;EAElG,OAAOpB,SAAS,CAACuB,QAAQ,CAACF,YAAY,CAAC;AACzC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASG,cAAcA,CAACL,MAAM,EAAE;EACrC,IAAMM,eAAe,GAAGP,kBAAkB,CAACC,MAAM,CAAC;EAClD,OAAOO,MAAM,CAACC,OAAO,CAACF,eAAe,CAAC,CAACG,GAAG,CAAC,UAAAC,IAAA;IAAA,IAAAC,KAAA,GAAAC,cAAA,CAAAF,IAAA;MAAEG,IAAI,GAAAF,KAAA;MAAEG,IAAI,GAAAH,KAAA;IAAA,OAAO;MAAEE,IAAI,EAAJA,IAAI;MAAEC,IAAI,EAAJA;IAAK,CAAC;EAAA,CAAC,CAAC;AAChF","ignoreList":[]} \ No newline at end of file diff --git a/dist/i18n/index.js b/dist/i18n/index.js new file mode 100644 index 000000000..8daec8009 --- /dev/null +++ b/dist/i18n/index.js @@ -0,0 +1,91 @@ +/** + * #### Import members from **@edx/frontend-platform/i18n** + * The i18n module relies on react-intl and re-exports all of that package's exports. + * + * For each locale we want to support, react-intl needs 1) the locale-data, which includes + * information about how to format numbers, handle plurals, etc., and 2) the translations, as an + * object holding message id / translated string pairs. A locale string and the messages object are + * passed into the IntlProvider element that wraps your element hierarchy. + * + * Note that react-intl has no way of checking if the translations you give it actually have + * anything to do with the locale you pass it; it will happily use whatever messages object you pass + * in. However, if the locale data for the locale you passed into the IntlProvider was not + * correctly installed with addLocaleData, all of your translations will fall back to the default + * (in our case English), *even if you gave IntlProvider the correct messages object for that + * locale*. + * + * Messages are provided to this module via the configure() function below. + * + * + * @module Internationalization + * @see {@link https://github.com/openedx/frontend-platform/blob/master/docs/how_tos/i18n.rst} + * @see {@link https://formatjs.io/docs/react-intl/components/ Intl} for components exported from this module. + * + */ + +/** + * @name createIntl + * @kind function + * @see {@link https://formatjs.io/docs/react-intl/api#createIntl Intl} + */ + +/** + * @name FormattedDate + * @kind class + * @see {@link https://formatjs.io/docs/react-intl/components/#formatteddate Intl} + */ + +/** + * @name FormattedTime + * @kind class + * @see {@link https://formatjs.io/docs/react-intl/components/#formattedtime Intl} + */ + +/** + * @name FormattedRelativeTime + * @kind class + * @see {@link https://formatjs.io/docs/react-intl/components/#formattedrelativetime Intl} + */ + +/** + * @name FormattedNumber + * @kind class + * @see {@link https://formatjs.io/docs/react-intl/components/#formattednumber Intl} + */ + +/** + * @name FormattedPlural + * @kind class + * @see {@link https://formatjs.io/docs/react-intl/components/#formattedplural Intl} + */ + +/** + * @name FormattedMessage + * @kind class + * @see {@link https://formatjs.io/docs/react-intl/components/#formattedmessage Intl} + */ + +/** + * @name IntlProvider + * @kind class + * @see {@link https://formatjs.io/docs/react-intl/components/#intlprovider Intl} + */ + +/** + * @name defineMessages + * @kind function + * @see {@link https://formatjs.io/docs/react-intl/api#definemessagesdefinemessage Intl} + */ + +/** + * @name useIntl + * @kind function + * @see {@link https://formatjs.io/docs/react-intl/api#useIntl Intl} + */ + +export { createIntl, FormattedDate, FormattedTime, FormattedRelativeTime, FormattedNumber, FormattedPlural, FormattedMessage, defineMessages, IntlProvider, useIntl } from 'react-intl'; +export { intlShape, configure, getPrimaryLanguageSubtag, getLocale, getMessages, isRtl, handleRtl, mergeMessages, LOCALE_CHANGED, LOCALE_TOPIC } from './lib'; +export { default as injectIntl } from './injectIntlWithShim'; +export { getCountryList, getCountryMessages } from './countries'; +export { getLanguageList, getLanguageMessages } from './languages'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/i18n/index.js.map b/dist/i18n/index.js.map new file mode 100644 index 000000000..3d87cf949 --- /dev/null +++ b/dist/i18n/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["createIntl","FormattedDate","FormattedTime","FormattedRelativeTime","FormattedNumber","FormattedPlural","FormattedMessage","defineMessages","IntlProvider","useIntl","intlShape","configure","getPrimaryLanguageSubtag","getLocale","getMessages","isRtl","handleRtl","mergeMessages","LOCALE_CHANGED","LOCALE_TOPIC","default","injectIntl","getCountryList","getCountryMessages","getLanguageList","getLanguageMessages"],"sources":["../../src/i18n/index.js"],"sourcesContent":["/**\n * #### Import members from **@edx/frontend-platform/i18n**\n * The i18n module relies on react-intl and re-exports all of that package's exports.\n *\n * For each locale we want to support, react-intl needs 1) the locale-data, which includes\n * information about how to format numbers, handle plurals, etc., and 2) the translations, as an\n * object holding message id / translated string pairs. A locale string and the messages object are\n * passed into the IntlProvider element that wraps your element hierarchy.\n *\n * Note that react-intl has no way of checking if the translations you give it actually have\n * anything to do with the locale you pass it; it will happily use whatever messages object you pass\n * in. However, if the locale data for the locale you passed into the IntlProvider was not\n * correctly installed with addLocaleData, all of your translations will fall back to the default\n * (in our case English), *even if you gave IntlProvider the correct messages object for that\n * locale*.\n *\n * Messages are provided to this module via the configure() function below.\n *\n *\n * @module Internationalization\n * @see {@link https://github.com/openedx/frontend-platform/blob/master/docs/how_tos/i18n.rst}\n * @see {@link https://formatjs.io/docs/react-intl/components/ Intl} for components exported from this module.\n *\n */\n\n/**\n * @name createIntl\n * @kind function\n * @see {@link https://formatjs.io/docs/react-intl/api#createIntl Intl}\n */\n\n/**\n * @name FormattedDate\n * @kind class\n * @see {@link https://formatjs.io/docs/react-intl/components/#formatteddate Intl}\n */\n\n/**\n * @name FormattedTime\n * @kind class\n * @see {@link https://formatjs.io/docs/react-intl/components/#formattedtime Intl}\n */\n\n/**\n * @name FormattedRelativeTime\n * @kind class\n * @see {@link https://formatjs.io/docs/react-intl/components/#formattedrelativetime Intl}\n */\n\n/**\n * @name FormattedNumber\n * @kind class\n * @see {@link https://formatjs.io/docs/react-intl/components/#formattednumber Intl}\n */\n\n/**\n * @name FormattedPlural\n * @kind class\n * @see {@link https://formatjs.io/docs/react-intl/components/#formattedplural Intl}\n */\n\n/**\n * @name FormattedMessage\n * @kind class\n * @see {@link https://formatjs.io/docs/react-intl/components/#formattedmessage Intl}\n */\n\n/**\n * @name IntlProvider\n * @kind class\n * @see {@link https://formatjs.io/docs/react-intl/components/#intlprovider Intl}\n */\n\n/**\n * @name defineMessages\n * @kind function\n * @see {@link https://formatjs.io/docs/react-intl/api#definemessagesdefinemessage Intl}\n */\n\n/**\n * @name useIntl\n * @kind function\n * @see {@link https://formatjs.io/docs/react-intl/api#useIntl Intl}\n */\n\nexport {\n createIntl,\n FormattedDate,\n FormattedTime,\n FormattedRelativeTime,\n FormattedNumber,\n FormattedPlural,\n FormattedMessage,\n defineMessages,\n IntlProvider,\n useIntl,\n} from 'react-intl';\n\nexport {\n intlShape,\n configure,\n getPrimaryLanguageSubtag,\n getLocale,\n getMessages,\n isRtl,\n handleRtl,\n mergeMessages,\n LOCALE_CHANGED,\n LOCALE_TOPIC,\n} from './lib';\n\nexport {\n default as injectIntl,\n} from './injectIntlWithShim';\n\nexport {\n getCountryList,\n getCountryMessages,\n} from './countries';\n\nexport {\n getLanguageList,\n getLanguageMessages,\n} from './languages';\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,SACEA,UAAU,EACVC,aAAa,EACbC,aAAa,EACbC,qBAAqB,EACrBC,eAAe,EACfC,eAAe,EACfC,gBAAgB,EAChBC,cAAc,EACdC,YAAY,EACZC,OAAO,QACF,YAAY;AAEnB,SACEC,SAAS,EACTC,SAAS,EACTC,wBAAwB,EACxBC,SAAS,EACTC,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,aAAa,EACbC,cAAc,EACdC,YAAY,QACP,OAAO;AAEd,SACEC,OAAO,IAAIC,UAAU,QAChB,sBAAsB;AAE7B,SACEC,cAAc,EACdC,kBAAkB,QACb,aAAa;AAEpB,SACEC,eAAe,EACfC,mBAAmB,QACd,aAAa","ignoreList":[]} \ No newline at end of file diff --git a/dist/i18n/injectIntlWithShim.js b/dist/i18n/injectIntlWithShim.js new file mode 100644 index 000000000..f05f09332 --- /dev/null +++ b/dist/i18n/injectIntlWithShim.js @@ -0,0 +1,69 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +import React from 'react'; +import { injectIntl } from 'react-intl'; +import { getLoggingService, intlShape } from './lib'; + +/** + * This function wraps react-intl's injectIntl function in order to add error logging to the intl + * property's formatMessage function. + * + * @memberof I18n + */ +var injectIntlWithShim = function injectIntlWithShim(WrappedComponent) { + var ShimmedIntlComponent = /*#__PURE__*/function (_React$Component) { + function ShimmedIntlComponent(props) { + var _this; + _classCallCheck(this, ShimmedIntlComponent); + _this = _callSuper(this, ShimmedIntlComponent, [props]); + _this.shimmedIntl = Object.create(_this.props.intl, { + formatMessage: { + value: function value(definition) { + var _this$props$intl; + if (definition === undefined || definition.id === undefined) { + var error = new Error('i18n error: An undefined message was supplied to intl.formatMessage.'); + if (process.env.NODE_ENV !== 'production') { + console.error(error); // eslint-disable-line no-console + return '!!! Missing message supplied to intl.formatMessage !!!'; + } + getLoggingService().logError(error); + return ''; // Fail silently in production + } + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + return (_this$props$intl = _this.props.intl).formatMessage.apply(_this$props$intl, [definition].concat(args)); + } + } + }); + return _this; + } + _inherits(ShimmedIntlComponent, _React$Component); + return _createClass(ShimmedIntlComponent, [{ + key: "render", + value: function render() { + return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, this.props, { + intl: this.shimmedIntl + })); + } + }]); + }(React.Component); + ShimmedIntlComponent.propTypes = { + intl: intlShape.isRequired + }; + return injectIntl(ShimmedIntlComponent); +}; +export default injectIntlWithShim; +//# sourceMappingURL=injectIntlWithShim.js.map \ No newline at end of file diff --git a/dist/i18n/injectIntlWithShim.js.map b/dist/i18n/injectIntlWithShim.js.map new file mode 100644 index 000000000..236d72e85 --- /dev/null +++ b/dist/i18n/injectIntlWithShim.js.map @@ -0,0 +1 @@ +{"version":3,"file":"injectIntlWithShim.js","names":["React","injectIntl","getLoggingService","intlShape","injectIntlWithShim","WrappedComponent","ShimmedIntlComponent","_React$Component","props","_this","_classCallCheck","_callSuper","shimmedIntl","Object","create","intl","formatMessage","value","definition","_this$props$intl","undefined","id","error","Error","process","env","NODE_ENV","console","logError","_len","arguments","length","args","Array","_key","apply","concat","_inherits","_createClass","key","render","createElement","_extends","Component","propTypes","isRequired"],"sources":["../../src/i18n/injectIntlWithShim.jsx"],"sourcesContent":["import React from 'react';\nimport { injectIntl } from 'react-intl';\nimport { getLoggingService, intlShape } from './lib';\n\n/**\n * This function wraps react-intl's injectIntl function in order to add error logging to the intl\n * property's formatMessage function.\n *\n * @memberof I18n\n */\nconst injectIntlWithShim = (WrappedComponent) => {\n class ShimmedIntlComponent extends React.Component {\n constructor(props) {\n super(props);\n this.shimmedIntl = Object.create(this.props.intl, {\n formatMessage: {\n value: (definition, ...args) => {\n if (definition === undefined || definition.id === undefined) {\n const error = new Error('i18n error: An undefined message was supplied to intl.formatMessage.');\n if (process.env.NODE_ENV !== 'production') {\n console.error(error); // eslint-disable-line no-console\n return '!!! Missing message supplied to intl.formatMessage !!!';\n }\n getLoggingService().logError(error);\n return ''; // Fail silently in production\n }\n return this.props.intl.formatMessage(definition, ...args);\n },\n },\n });\n }\n\n render() {\n return ;\n }\n }\n\n ShimmedIntlComponent.propTypes = {\n intl: intlShape.isRequired,\n };\n\n return injectIntl(ShimmedIntlComponent);\n};\n\nexport default injectIntlWithShim;\n"],"mappings":";;;;;;;;;;;;;;AAAA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,UAAU,QAAQ,YAAY;AACvC,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,OAAO;;AAEpD;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,kBAAkB,GAAG,SAArBA,kBAAkBA,CAAIC,gBAAgB,EAAK;EAAA,IACzCC,oBAAoB,0BAAAC,gBAAA;IACxB,SAAAD,qBAAYE,KAAK,EAAE;MAAA,IAAAC,KAAA;MAAAC,eAAA,OAAAJ,oBAAA;MACjBG,KAAA,GAAAE,UAAA,OAAAL,oBAAA,GAAME,KAAK;MACXC,KAAA,CAAKG,WAAW,GAAGC,MAAM,CAACC,MAAM,CAACL,KAAA,CAAKD,KAAK,CAACO,IAAI,EAAE;QAChDC,aAAa,EAAE;UACbC,KAAK,EAAE,SAAPA,KAAKA,CAAGC,UAAU,EAAc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AClB,CAAC;EAED,OAAO5C,UAAU,CAACK,oBAAoB,CAAC;AACzC,CAAC;AAED,eAAeF,kBAAkB","ignoreList":[]} \ No newline at end of file diff --git a/dist/i18n/languages.js b/dist/i18n/languages.js new file mode 100644 index 000000000..413f39ddf --- /dev/null +++ b/dist/i18n/languages.js @@ -0,0 +1,89 @@ +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +/* eslint-disable import/extensions */ +import LANGUAGES, { langs as languageLangs } from '@cospired/i18n-iso-languages'; + +// import arLocale from '@cospired/i18n-iso-languages/langs/ar.json'; +import enLocale from '@cospired/i18n-iso-languages/langs/en.json'; +import esLocale from '@cospired/i18n-iso-languages/langs/es.json'; +import frLocale from '@cospired/i18n-iso-languages/langs/fr.json'; +// import zhLocale from '@cospired/i18n-iso-languages/langs/zh.json'; +// import caLocale from '@cospired/i18n-iso-languages/langs/ca.json'; +// import heLocale from '@cospired/i18n-iso-languages/langs/he.json'; +// import idLocale from '@cospired/i18n-iso-languages/langs/id.json'; +// import koLocale from '@cospired/i18n-iso-languages/langs/ko.json'; +import plLocale from '@cospired/i18n-iso-languages/langs/pl.json'; +import ptLocale from '@cospired/i18n-iso-languages/langs/pt.json'; +// import ruLocale from '@cospired/i18n-iso-languages/langs/ru.json'; +// import thLocale from '@cospired/i18n-iso-languages/langs/th.json'; +// import ukLocale from '@cospired/i18n-iso-languages/langs/uk.json'; + +import { getPrimaryLanguageSubtag } from './lib'; + +/* + * LANGUAGE LISTS + * + * Lists of language names localized in supported languages. + * + * TODO: When we start dynamically loading translations only for the current locale, change this. + * TODO: Also note that a bunch of languages are missing here. They're present but commented out + * for reference. That's because they're not implemented in this library. If you read this and it's + * been a while, go check and see if that's changed! + */ + +// LANGUAGES.registerLocale(arLocale); +LANGUAGES.registerLocale(enLocale); +LANGUAGES.registerLocale(esLocale); +LANGUAGES.registerLocale(frLocale); +// LANGUAGES.registerLocale(zhLocale); +// LANGUAGES.registerLocale(caLocale); +// LANGUAGES.registerLocale(heLocale); +// LANGUAGES.registerLocale(idLocale); +// LANGUAGES.registerLocale(koLocale); +LANGUAGES.registerLocale(plLocale); +LANGUAGES.registerLocale(ptLocale); +// LANGUAGES.registerLocale(ruLocale); +// LANGUAGES.registerLocale(thLocale); +// LANGUAGES.registerLocale(ukLocale); + +/** + * Provides a lookup table of language IDs to language names for the current locale. + * + * @memberof I18n + */ +export var getLanguageMessages = function getLanguageMessages(locale) { + var primaryLanguageSubtag = getPrimaryLanguageSubtag(locale); + var languageCode = languageLangs().includes(primaryLanguageSubtag) ? primaryLanguageSubtag : 'en'; + return LANGUAGES.getNames(languageCode); +}; + +/** + * Provides a list of languages represented as objects of the following shape: + * + * { + * key, // The ID of the language + * name // The localized name of the language + * } + * + * TODO: ARCH-878: The list should be sorted alphabetically in the current locale. + * This is useful for populating dropdowns. + * + * @memberof I18n + */ +export var getLanguageList = function getLanguageList(locale) { + var languageMessages = getLanguageMessages(locale); + return Object.entries(languageMessages).map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + code = _ref2[0], + name = _ref2[1]; + return { + code: code, + name: name + }; + }); +}; +//# sourceMappingURL=languages.js.map \ No newline at end of file diff --git a/dist/i18n/languages.js.map b/dist/i18n/languages.js.map new file mode 100644 index 000000000..ab0a9e745 --- /dev/null +++ b/dist/i18n/languages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"languages.js","names":["LANGUAGES","langs","languageLangs","enLocale","esLocale","frLocale","plLocale","ptLocale","getPrimaryLanguageSubtag","registerLocale","getLanguageMessages","locale","primaryLanguageSubtag","languageCode","includes","getNames","getLanguageList","languageMessages","Object","entries","map","_ref","_ref2","_slicedToArray","code","name"],"sources":["../../src/i18n/languages.js"],"sourcesContent":["/* eslint-disable import/extensions */\nimport LANGUAGES, { langs as languageLangs } from '@cospired/i18n-iso-languages';\n\n// import arLocale from '@cospired/i18n-iso-languages/langs/ar.json';\nimport enLocale from '@cospired/i18n-iso-languages/langs/en.json';\nimport esLocale from '@cospired/i18n-iso-languages/langs/es.json';\nimport frLocale from '@cospired/i18n-iso-languages/langs/fr.json';\n// import zhLocale from '@cospired/i18n-iso-languages/langs/zh.json';\n// import caLocale from '@cospired/i18n-iso-languages/langs/ca.json';\n// import heLocale from '@cospired/i18n-iso-languages/langs/he.json';\n// import idLocale from '@cospired/i18n-iso-languages/langs/id.json';\n// import koLocale from '@cospired/i18n-iso-languages/langs/ko.json';\nimport plLocale from '@cospired/i18n-iso-languages/langs/pl.json';\nimport ptLocale from '@cospired/i18n-iso-languages/langs/pt.json';\n// import ruLocale from '@cospired/i18n-iso-languages/langs/ru.json';\n// import thLocale from '@cospired/i18n-iso-languages/langs/th.json';\n// import ukLocale from '@cospired/i18n-iso-languages/langs/uk.json';\n\nimport { getPrimaryLanguageSubtag } from './lib';\n\n/*\n * LANGUAGE LISTS\n *\n * Lists of language names localized in supported languages.\n *\n * TODO: When we start dynamically loading translations only for the current locale, change this.\n * TODO: Also note that a bunch of languages are missing here. They're present but commented out\n * for reference. That's because they're not implemented in this library. If you read this and it's\n * been a while, go check and see if that's changed!\n */\n\n// LANGUAGES.registerLocale(arLocale);\nLANGUAGES.registerLocale(enLocale);\nLANGUAGES.registerLocale(esLocale);\nLANGUAGES.registerLocale(frLocale);\n// LANGUAGES.registerLocale(zhLocale);\n// LANGUAGES.registerLocale(caLocale);\n// LANGUAGES.registerLocale(heLocale);\n// LANGUAGES.registerLocale(idLocale);\n// LANGUAGES.registerLocale(koLocale);\nLANGUAGES.registerLocale(plLocale);\nLANGUAGES.registerLocale(ptLocale);\n// LANGUAGES.registerLocale(ruLocale);\n// LANGUAGES.registerLocale(thLocale);\n// LANGUAGES.registerLocale(ukLocale);\n\n/**\n * Provides a lookup table of language IDs to language names for the current locale.\n *\n * @memberof I18n\n */\nexport const getLanguageMessages = (locale) => {\n const primaryLanguageSubtag = getPrimaryLanguageSubtag(locale);\n const languageCode = languageLangs().includes(primaryLanguageSubtag) ? primaryLanguageSubtag : 'en';\n\n return LANGUAGES.getNames(languageCode);\n};\n\n/**\n * Provides a list of languages represented as objects of the following shape:\n *\n * {\n * key, // The ID of the language\n * name // The localized name of the language\n * }\n *\n * TODO: ARCH-878: The list should be sorted alphabetically in the current locale.\n * This is useful for populating dropdowns.\n *\n * @memberof I18n\n */\nexport const getLanguageList = (locale) => {\n const languageMessages = getLanguageMessages(locale);\n return Object.entries(languageMessages).map(([code, name]) => ({ code, name }));\n};\n"],"mappings":";;;;;;AAAA;AACA,OAAOA,SAAS,IAAIC,KAAK,IAAIC,aAAa,QAAQ,8BAA8B;;AAEhF;AACA,OAAOC,QAAQ,MAAM,4CAA4C;AACjE,OAAOC,QAAQ,MAAM,4CAA4C;AACjE,OAAOC,Q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AJA;IAAK,CAAC;EAAA,CAAC,CAAC;AACjF,CAAC","ignoreList":[]} \ No newline at end of file diff --git a/dist/i18n/lib.js b/dist/i18n/lib.js new file mode 100644 index 000000000..926738193 --- /dev/null +++ b/dist/i18n/lib.js @@ -0,0 +1,307 @@ +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +import PropTypes from 'prop-types'; +import Cookies from 'universal-cookie'; +import merge from 'lodash.merge'; +import '@formatjs/intl-pluralrules/polyfill'; +import '@formatjs/intl-pluralrules/locale-data/ar'; +import '@formatjs/intl-pluralrules/locale-data/en'; +import '@formatjs/intl-pluralrules/locale-data/es'; +import '@formatjs/intl-pluralrules/locale-data/fr'; +import '@formatjs/intl-pluralrules/locale-data/zh'; +import '@formatjs/intl-pluralrules/locale-data/ca'; +import '@formatjs/intl-pluralrules/locale-data/he'; +import '@formatjs/intl-pluralrules/locale-data/id'; +import '@formatjs/intl-pluralrules/locale-data/ko'; +import '@formatjs/intl-pluralrules/locale-data/pl'; +import '@formatjs/intl-pluralrules/locale-data/pt'; +import '@formatjs/intl-pluralrules/locale-data/ru'; +import '@formatjs/intl-pluralrules/locale-data/th'; +import '@formatjs/intl-pluralrules/locale-data/uk'; +import '@formatjs/intl-relativetimeformat/polyfill'; +import '@formatjs/intl-relativetimeformat/locale-data/ar'; +import '@formatjs/intl-relativetimeformat/locale-data/en'; +import '@formatjs/intl-relativetimeformat/locale-data/es'; +import '@formatjs/intl-relativetimeformat/locale-data/fr'; +import '@formatjs/intl-relativetimeformat/locale-data/zh'; +import '@formatjs/intl-relativetimeformat/locale-data/ca'; +import '@formatjs/intl-relativetimeformat/locale-data/he'; +import '@formatjs/intl-relativetimeformat/locale-data/id'; +import '@formatjs/intl-relativetimeformat/locale-data/ko'; +import '@formatjs/intl-relativetimeformat/locale-data/pl'; +import '@formatjs/intl-relativetimeformat/locale-data/pt'; +import '@formatjs/intl-relativetimeformat/locale-data/ru'; +import '@formatjs/intl-relativetimeformat/locale-data/th'; +import '@formatjs/intl-relativetimeformat/locale-data/uk'; +var cookies = new Cookies(); +var supportedLocales = ['ar', +// Arabic +// NOTE: 'en' is not included in this list intentionally, since it's the fallback. +'es-419', +// Spanish, Latin American +'fa', +// Farsi +'fa-ir', +// Farsi, Iran +'fr', +// French +'zh-cn', +// Chinese, Simplified +'ca', +// Catalan +'he', +// Hebrew +'id', +// Indonesian +'ko-kr', +// Korean (Korea) +'pl', +// Polish +'pt-br', +// Portuguese (Brazil) +'ru', +// Russian +'th', +// Thai +'uk' // Ukrainian +]; +var rtlLocales = ['ar', +// Arabic +'he', +// Hebrew +'fa', +// Farsi (not currently supported) +'fa-ir', +// Farsi Iran +'ur' // Urdu (not currently supported) +]; +var config = null; +var loggingService = null; +var messages = null; + +/** + * @memberof module:Internationalization + * + * Prior versions of react-intl (our primary implementation of the i18n service) included a + * PropTypes-based 'shape' for its `intl` object. This has since been removed. For legacy + * compatibility, we include an `intlShape` export that is set to PropTypes.object. Usage of this + * export is deprecated. + * + * @deprecated + */ +export var intlShape = PropTypes.object; + +/** + * + * @ignore + * @returns {LoggingService} + */ +export var getLoggingService = function getLoggingService() { + return loggingService; +}; + +/** + * @memberof module:Internationalization + */ +export var LOCALE_TOPIC = 'LOCALE'; + +/** + * @memberof module:Internationalization + */ +export var LOCALE_CHANGED = "".concat(LOCALE_TOPIC, ".CHANGED"); + +/** + * + * @memberof module:Internationalization + * @returns {Cookies} + */ +export function getCookies() { + return cookies; +} + +/** + * Some of our dependencies function on primary language subtags, rather than full locales. + * This function strips a locale down to that first subtag. Depending on the code, this + * may be 2 or more characters. + * + * @param {string} code + * @memberof module:Internationalization + */ +export function getPrimaryLanguageSubtag(code) { + return code.split('-')[0]; +} + +/** + * Finds the closest supported locale to the one provided. This is done in three steps: + * + * 1. Returning the locale itself if its exact language code is supported. + * 2. Returning the primary language subtag of the language code if it is supported (ar for ar-eg, + * for instance). + * 3. Returning 'en' if neither of the above produce a supported locale. + * + * @param {string} locale + * @returns {string} + * @memberof module:Internationalization + */ +export function findSupportedLocale(locale) { + if (messages[locale] !== undefined) { + return locale; + } + if (messages[getPrimaryLanguageSubtag(locale)] !== undefined) { + return getPrimaryLanguageSubtag(locale); + } + return 'en'; +} + +/** + * Get the locale from the cookie or, failing that, the browser setting. + * Gracefully fall back to a more general primary language subtag or to English (en) + * if we don't support that language. + * + * @param {string} locale If a locale is provided, returns the closest supported locale. Optional. + * @throws An error if i18n has not yet been configured. + * @returns {string} + * @memberof module:Internationalization + */ +export function getLocale(locale) { + if (messages === null) { + throw new Error('getLocale called before configuring i18n. Call configure with messages first.'); + } + // 1. Explicit application request + if (locale !== undefined) { + return findSupportedLocale(locale); + } + // 2. User setting in cookie + var cookieLangPref = cookies.get(config.LANGUAGE_PREFERENCE_COOKIE_NAME); + if (cookieLangPref) { + return findSupportedLocale(cookieLangPref.toLowerCase()); + } + // 3. Browser language (default) + // Note that some browers prefer upper case for the region part of the locale, while others don't. + // Thus the toLowerCase, for consistency. + // https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language + return findSupportedLocale(globalThis.navigator.language.toLowerCase()); +} + +/** + * Returns messages for the provided locale, or the user's preferred locale if no argument is + * provided. + * + * @param {string} [locale=getLocale()] + * @memberof module:Internationalization + */ +export function getMessages() { + var locale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getLocale(); + return messages[locale]; +} + +/** + * Determines if the provided locale is a right-to-left language. + * + * @param {string} locale + * @memberof module:Internationalization + */ +export function isRtl(locale) { + return rtlLocales.includes(locale); +} + +/** + * Handles applying the RTL stylesheet and "dir=rtl" attribute to the html tag if the current locale + * is a RTL language. + * + * @memberof module:Internationalization + */ +export function handleRtl() { + if (isRtl(getLocale())) { + globalThis.document.getElementsByTagName('html')[0].setAttribute('dir', 'rtl'); + } else { + globalThis.document.getElementsByTagName('html')[0].setAttribute('dir', 'ltr'); + } +} +var messagesShape = { + ar: PropTypes.objectOf(PropTypes.string), + // Arabic + en: PropTypes.objectOf(PropTypes.string), + 'es-419': PropTypes.objectOf(PropTypes.string), + // Spanish, Latin American + fr: PropTypes.objectOf(PropTypes.string), + // French + 'zh-cn': PropTypes.objectOf(PropTypes.string), + // Chinese, Simplified + ca: PropTypes.objectOf(PropTypes.string), + // Catalan + he: PropTypes.objectOf(PropTypes.string), + // Hebrew + id: PropTypes.objectOf(PropTypes.string), + // Indonesian + 'ko-kr': PropTypes.objectOf(PropTypes.string), + // Korean (Korea) + pl: PropTypes.objectOf(PropTypes.string), + // Polish + 'pt-br': PropTypes.objectOf(PropTypes.string), + // Portuguese (Brazil) + ru: PropTypes.objectOf(PropTypes.string), + // Russian + th: PropTypes.objectOf(PropTypes.string), + // Thai + uk: PropTypes.objectOf(PropTypes.string) // Ukrainian +}; +var optionsShape = { + config: PropTypes.object.isRequired, + loggingService: PropTypes.shape({ + logError: PropTypes.func.isRequired + }).isRequired, + messages: PropTypes.oneOfType([PropTypes.shape(messagesShape), PropTypes.arrayOf(PropTypes.shape(messagesShape))]).isRequired +}; + +/** + * + * + * @param {Object} newMessages + * @returns {Object} + * @memberof module:Internationalization + */ +export function mergeMessages(newMessages) { + var msgs = Array.isArray(newMessages) ? merge.apply(void 0, [{}].concat(_toConsumableArray(newMessages))) : newMessages; + messages = merge(messages, msgs); + return messages; +} + +/** + * Configures the i18n library with messages for your application. + * + * Logs a warning if it detects a locale it doesn't expect (as defined by the supportedLocales list + * above), or if an expected locale is not provided. + * + * @param {Object} options + * @param {LoggingService} options.loggingService + * @param {Object} options.config + * @param {Object} options.messages + * @memberof module:Internationalization + */ +export function configure(options) { + PropTypes.checkPropTypes(optionsShape, options, 'property', 'i18n'); + // eslint-disable-next-line prefer-destructuring + loggingService = options.loggingService; + // eslint-disable-next-line prefer-destructuring + config = options.config; + messages = Array.isArray(options.messages) ? merge.apply(void 0, [{}].concat(_toConsumableArray(options.messages))) : options.messages; + if (config.ENVIRONMENT !== 'production') { + Object.keys(messages).forEach(function (key) { + if (supportedLocales.indexOf(key) < 0) { + console.warn("Unexpected locale: ".concat(key)); // eslint-disable-line no-console + } + }); + supportedLocales.forEach(function (key) { + if (messages[key] === undefined) { + console.warn("Missing locale: ".concat(key)); // eslint-disable-line no-console + } + }); + } + handleRtl(); +} +//# sourceMappingURL=lib.js.map \ No newline at end of file diff --git a/dist/i18n/lib.js.map b/dist/i18n/lib.js.map new file mode 100644 index 000000000..07e0c0b37 --- /dev/null +++ b/dist/i18n/lib.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lib.js","names":["PropTypes","Cookies","merge","cookies","supportedLocales","rtlLocales","config","loggingService","messages","intlShape","object","getLoggingService","LOCALE_TOPIC","LOCALE_CHANGED","concat","getCookies","getPrimaryLanguageSubtag","code","split","findSupportedLocale","locale","undefined","getLocale","Error","cookieLangPref","get","LANGUAGE_PREFERENCE_COOKIE_NAME","toLowerCase","globalThis","navigator","language","getMessages","arguments","length","isRtl","includes","handleRtl","document","getElementsByTagName","setAttribute","messagesShape","ar","objectOf","string","en","fr","ca","he","id","pl","ru","th","uk","optionsShape","isRequired","shape","logError","func","oneOfType","arrayOf","mergeMessages","newMessages","msgs","Array","isArray","apply","_toConsumableArray","configure","options","checkPropTypes","ENVIRONMENT","Object","keys","forEach","key","indexOf","console","warn"],"sources":["../../src/i18n/lib.js"],"sourcesContent":["import PropTypes from 'prop-types';\nimport Cookies from 'universal-cookie';\nimport merge from 'lodash.merge';\n\nimport '@formatjs/intl-pluralrules/polyfill';\nimport '@formatjs/intl-pluralrules/locale-data/ar';\nimport '@formatjs/intl-pluralrules/locale-data/en';\nimport '@formatjs/intl-pluralrules/locale-data/es';\nimport '@formatjs/intl-pluralrules/locale-data/fr';\nimport '@formatjs/intl-pluralrules/locale-data/zh';\nimport '@formatjs/intl-pluralrules/locale-data/ca';\nimport '@formatjs/intl-pluralrules/locale-data/he';\nimport '@formatjs/intl-pluralrules/locale-data/id';\nimport '@formatjs/intl-pluralrules/locale-data/ko';\nimport '@formatjs/intl-pluralrules/locale-data/pl';\nimport '@formatjs/intl-pluralrules/locale-data/pt';\nimport '@formatjs/intl-pluralrules/locale-data/ru';\nimport '@formatjs/intl-pluralrules/locale-data/th';\nimport '@formatjs/intl-pluralrules/locale-data/uk';\n\nimport '@formatjs/intl-relativetimeformat/polyfill';\nimport '@formatjs/intl-relativetimeformat/locale-data/ar';\nimport '@formatjs/intl-relativetimeformat/locale-data/en';\nimport '@formatjs/intl-relativetimeformat/locale-data/es';\nimport '@formatjs/intl-relativetimeformat/locale-data/fr';\nimport '@formatjs/intl-relativetimeformat/locale-data/zh';\nimport '@formatjs/intl-relativetimeformat/locale-data/ca';\nimport '@formatjs/intl-relativetimeformat/locale-data/he';\nimport '@formatjs/intl-relativetimeformat/locale-data/id';\nimport '@formatjs/intl-relativetimeformat/locale-data/ko';\nimport '@formatjs/intl-relativetimeformat/locale-data/pl';\nimport '@formatjs/intl-relativetimeformat/locale-data/pt';\nimport '@formatjs/intl-relativetimeformat/locale-data/ru';\nimport '@formatjs/intl-relativetimeformat/locale-data/th';\nimport '@formatjs/intl-relativetimeformat/locale-data/uk';\n\nconst cookies = new Cookies();\nconst supportedLocales = [\n 'ar', // Arabic\n // NOTE: 'en' is not included in this list intentionally, since it's the fallback.\n 'es-419', // Spanish, Latin American\n 'fa', // Farsi\n 'fa-ir', // Farsi, Iran\n 'fr', // French\n 'zh-cn', // Chinese, Simplified\n 'ca', // Catalan\n 'he', // Hebrew\n 'id', // Indonesian\n 'ko-kr', // Korean (Korea)\n 'pl', // Polish\n 'pt-br', // Portuguese (Brazil)\n 'ru', // Russian\n 'th', // Thai\n 'uk', // Ukrainian\n];\nconst rtlLocales = [\n 'ar', // Arabic\n 'he', // Hebrew\n 'fa', // Farsi (not currently supported)\n 'fa-ir', // Farsi Iran\n 'ur', // Urdu (not currently supported)\n];\n\nlet config = null;\nlet loggingService = null;\nlet messages = null;\n\n/**\n * @memberof module:Internationalization\n *\n * Prior versions of react-intl (our primary implementation of the i18n service) included a\n * PropTypes-based 'shape' for its `intl` object. This has since been removed. For legacy\n * compatibility, we include an `intlShape` export that is set to PropTypes.object. Usage of this\n * export is deprecated.\n *\n * @deprecated\n */\nexport const intlShape = PropTypes.object;\n\n/**\n *\n * @ignore\n * @returns {LoggingService}\n */\nexport const getLoggingService = () => loggingService;\n\n/**\n * @memberof module:Internationalization\n */\nexport const LOCALE_TOPIC = 'LOCALE';\n\n/**\n * @memberof module:Internationalization\n */\nexport const LOCALE_CHANGED = `${LOCALE_TOPIC}.CHANGED`;\n\n/**\n *\n * @memberof module:Internationalization\n * @returns {Cookies}\n */\nexport function getCookies() {\n return cookies;\n}\n\n/**\n * Some of our dependencies function on primary language subtags, rather than full locales.\n * This function strips a locale down to that first subtag. Depending on the code, this\n * may be 2 or more characters.\n *\n * @param {string} code\n * @memberof module:Internationalization\n */\nexport function getPrimaryLanguageSubtag(code) {\n return code.split('-')[0];\n}\n\n/**\n * Finds the closest supported locale to the one provided. This is done in three steps:\n *\n * 1. Returning the locale itself if its exact language code is supported.\n * 2. Returning the primary language subtag of the language code if it is supported (ar for ar-eg,\n * for instance).\n * 3. Returning 'en' if neither of the above produce a supported locale.\n *\n * @param {string} locale\n * @returns {string}\n * @memberof module:Internationalization\n */\nexport function findSupportedLocale(locale) {\n if (messages[locale] !== undefined) {\n return locale;\n }\n\n if (messages[getPrimaryLanguageSubtag(locale)] !== undefined) {\n return getPrimaryLanguageSubtag(locale);\n }\n\n return 'en';\n}\n\n/**\n * Get the locale from the cookie or, failing that, the browser setting.\n * Gracefully fall back to a more general primary language subtag or to English (en)\n * if we don't support that language.\n *\n * @param {string} locale If a locale is provided, returns the closest supported locale. Optional.\n * @throws An error if i18n has not yet been configured.\n * @returns {string}\n * @memberof module:Internationalization\n */\nexport function getLocale(locale) {\n if (messages === null) {\n throw new Error('getLocale called before configuring i18n. Call configure with messages first.');\n }\n // 1. Explicit application request\n if (locale !== undefined) {\n return findSupportedLocale(locale);\n }\n // 2. User setting in cookie\n const cookieLangPref = cookies\n .get(config.LANGUAGE_PREFERENCE_COOKIE_NAME);\n if (cookieLangPref) {\n return findSupportedLocale(cookieLangPref.toLowerCase());\n }\n // 3. Browser language (default)\n // Note that some browers prefer upper case for the region part of the locale, while others don't.\n // Thus the toLowerCase, for consistency.\n // https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language\n return findSupportedLocale(globalThis.navigator.language.toLowerCase());\n}\n\n/**\n * Returns messages for the provided locale, or the user's preferred locale if no argument is\n * provided.\n *\n * @param {string} [locale=getLocale()]\n * @memberof module:Internationalization\n */\nexport function getMessages(locale = getLocale()) {\n return messages[locale];\n}\n\n/**\n * Determines if the provided locale is a right-to-left language.\n *\n * @param {string} locale\n * @memberof module:Internationalization\n */\nexport function isRtl(locale) {\n return rtlLocales.includes(locale);\n}\n\n/**\n * Handles applying the RTL stylesheet and \"dir=rtl\" attribute to the html tag if the current locale\n * is a RTL language.\n *\n * @memberof module:Internationalization\n */\nexport function handleRtl() {\n if (isRtl(getLocale())) {\n globalThis.document.getElementsByTagName('html')[0].setAttribute('dir', 'rtl');\n } else {\n globalThis.document.getElementsByTagName('html')[0].setAttribute('dir', 'ltr');\n }\n}\n\nconst messagesShape = {\n ar: PropTypes.objectOf(PropTypes.string), // Arabic\n en: PropTypes.objectOf(PropTypes.string),\n 'es-419': PropTypes.objectOf(PropTypes.string), // Spanish, Latin American\n fr: PropTypes.objectOf(PropTypes.string), // French\n 'zh-cn': PropTypes.objectOf(PropTypes.string), // Chinese, Simplified\n ca: PropTypes.objectOf(PropTypes.string), // Catalan\n he: PropTypes.objectOf(PropTypes.string), // Hebrew\n id: PropTypes.objectOf(PropTypes.string), // Indonesian\n 'ko-kr': PropTypes.objectOf(PropTypes.string), // Korean (Korea)\n pl: PropTypes.objectOf(PropTypes.string), // Polish\n 'pt-br': PropTypes.objectOf(PropTypes.string), // Portuguese (Brazil)\n ru: PropTypes.objectOf(PropTypes.string), // Russian\n th: PropTypes.objectOf(PropTypes.string), // Thai\n uk: PropTypes.objectOf(PropTypes.string), // Ukrainian\n};\n\nconst optionsShape = {\n config: PropTypes.object.isRequired,\n loggingService: PropTypes.shape({\n logError: PropTypes.func.isRequired,\n }).isRequired,\n messages: PropTypes.oneOfType([\n PropTypes.shape(messagesShape),\n PropTypes.arrayOf(PropTypes.shape(messagesShape)),\n ]).isRequired,\n};\n\n/**\n *\n *\n * @param {Object} newMessages\n * @returns {Object}\n * @memberof module:Internationalization\n */\nexport function mergeMessages(newMessages) {\n const msgs = Array.isArray(newMessages) ? merge({}, ...newMessages) : newMessages;\n messages = merge(messages, msgs);\n\n return messages;\n}\n\n/**\n * Configures the i18n library with messages for your application.\n *\n * Logs a warning if it detects a locale it doesn't expect (as defined by the supportedLocales list\n * above), or if an expected locale is not provided.\n *\n * @param {Object} options\n * @param {LoggingService} options.loggingService\n * @param {Object} options.config\n * @param {Object} options.messages\n * @memberof module:Internationalization\n */\nexport function configure(options) {\n PropTypes.checkPropTypes(optionsShape, options, 'property', 'i18n');\n // eslint-disable-next-line prefer-destructuring\n loggingService = options.loggingService;\n // eslint-disable-next-line prefer-destructuring\n config = options.config;\n messages = Array.isArray(options.messages) ? merge({}, ...options.messages) : options.messages;\n\n if (config.ENVIRONMENT !== 'production') {\n Object.keys(messages).forEach((key) => {\n if (supportedLocales.indexOf(key) < 0) {\n console.warn(`Unexpected locale: ${key}`); // eslint-disable-line no-console\n }\n });\n\n supportedLocales.forEach((key) => {\n if (messages[key] === undefined) {\n console.warn(`Missing locale: ${key}`); // eslint-disable-line no-console\n }\n });\n }\n\n handleRtl();\n}\n"],"mappings":";;;;;;AAAA,OAAOA,SAAS,MAAM,YAAY;AAClC,OAAOC,OAAO,MAAM,kBAAkB;AACtC,OAAOC,KAAK,MAAM,cAAc;AAEhC,OAAO,qCAAqC;AAC5C,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAClD,OAAO,2CAA2C;AAElD,OAAO,4CAA4C;AACnD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AACzD,OAAO,kDAAkD;AAEzD,IAAMC,OAAO,GAAG,IAAIF,OAAO,CAAC,CAAC;AAC7B,IAAMG,gBAAgB,GAAG,CACvB,IAAI;AAAE;AACN;AACA,QAAQ;AAAE;AACV,IAAI;AAAE;AACN,OAAO;AAAE;AACT,IAAI;AAAE;AACN,OAAO;AAAE;AACT,IAAI;AAAE;AACN,IAAI;AAAE;A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GN,KAAK,CAAA+D,KAAA,UAAC,CAAC,CAAC,EAAAnD,MAAA,CAAAoD,kBAAA,CAAKE,OAAO,CAAC5D,QAAQ,GAAC,GAAG4D,OAAO,CAAC5D,QAAQ;EAE9F,IAAIF,MAAM,CAACgE,WAAW,KAAK,YAAY,EAAE;IACvCC,MAAM,CAACC,IAAI,CAAChE,QAAQ,CAAC,CAACiE,OAAO,CAAC,UAACC,GAAG,EAAK;MACrC,IAAItE,gBAAgB,CAACuE,OAAO,CAACD,GAAG,CAAC,GAAG,CAAC,EAAE;QACrCE,OAAO,CAACC,IAAI,uBAAA/D,MAAA,CAAuB4D,GAAG,CAAE,CAAC,CAAC,CAAC;MAC7C;IACF,CAAC,CAAC;IAEFtE,gBAAgB,CAACqE,OAAO,CAAC,UAACC,GAAG,EAAK;MAChC,IAAIlE,QAAQ,CAACkE,GAAG,CAAC,KAAKrD,SAAS,EAAE;QAC/BuD,OAAO,CAACC,IAAI,oBAAA/D,MAAA,CAAoB4D,GAAG,CAAE,CAAC,CAAC,CAAC;MAC1C;IACF,CAAC,CAAC;EACJ;EAEAtC,SAAS,CAAC,CAAC;AACb","ignoreList":[]} \ No newline at end of file diff --git a/dist/i18n/scripts/README.md b/dist/i18n/scripts/README.md new file mode 100644 index 000000000..0a3fa7bb6 --- /dev/null +++ b/dist/i18n/scripts/README.md @@ -0,0 +1,29 @@ +# i18n/scripts + +This directory contains the `transifex-utils.js` and `intl-imports.js` files which are shared across all micro-frontends. + +The package.json of `frontend-platform` includes the following sections: + +``` + "bin": { + "intl-imports.js": "i18n/scripts/intl-imports.js" + "transifex-utils.js": "i18n/scripts/transifex-utils.js" + }, +``` + +This config block causes boths scripts to be copied to the following path when `frontend-platform` is installed as a +dependency of a micro-frontend: + +``` +/node_modules/.bin/intl-imports.js +/node_modules/.bin/transifex-utils.js +``` + +All micro-frontends have a `Makefile` with a line that loads the scripts from the above path: + +``` +intl_imports = ./node_modules/.bin/intl-imports.js +transifex_utils = ./node_modules/.bin/transifex-utils.js +``` + +So if you delete either of the files or the `scripts` directory, you'll break all micro-frontend builds. Happy coding! diff --git a/dist/i18n/scripts/intl-imports.js b/dist/i18n/scripts/intl-imports.js new file mode 100755 index 000000000..52ab6828d --- /dev/null +++ b/dist/i18n/scripts/intl-imports.js @@ -0,0 +1,177 @@ +#!/usr/bin/env node +var scriptHelpDocument = "\nNAME\n intl-imports.js \u2014 Script to generate the src/i18n/index.js file that exports messages from all the languages for Micro-frontends.\n\nSYNOPSIS\n intl-imports.js [DIRECTORY ...]\n\nDESCRIPTION\n This script is intended to run after 'atlas' has pulled the files.\n \n This expects to run inside a Micro-frontend root directory with the following structure:\n \n frontend-app-learning $ tree src/i18n/\n src/i18n/\n \u251C\u2500\u2500 index.js\n \u2514\u2500\u2500 messages\n \u251C\u2500\u2500 frontend-app-example\n \u2502 \u251C\u2500\u2500 ar.json\n \u2502 \u251C\u2500\u2500 es_419.json\n \u2502 \u2514\u2500\u2500 zh_CN.json\n \u251C\u2500\u2500 frontend-component-footer\n \u2502 \u251C\u2500\u2500 ar.json\n \u2502 \u251C\u2500\u2500 es_419.json\n \u2502 \u2514\u2500\u2500 zh_CN.json\n \u2514\u2500\u2500 frontend-component-header (empty directory)\n \n \n \n With the structure above it's expected to run with the following command in Makefile:\n \n \n $ node_modules/.bin/intl-imports.js frontend-component-footer frontend-component-header frontend-app-example\n \n \n It will generate two type of files:\n \n - Main src/i18n/index.js which overrides the Micro-frontend provided with a sample output of:\n \n \"\"\"\n import messagesFromFrontendComponentFooter from './messages/frontend-component-footer';\n // Skipped import due to missing './messages/frontend-component-footer/index.js' likely due to empty translations.\n import messagesFromFrontendAppExample from './messages/frontend-app-example';\n \n export default [\n messagesFromFrontendComponentFooter,\n messagesFromFrontendAppExample,\n ];\n \"\"\"\n \n - Each sub-directory has src/i18n/messages/frontend-component-header/index.js which is imported by the main file.:\n \n \"\"\"\n import messagesOfArLanguage from './ar.json';\n import messagesOfDeLanguage from './de.json';\n import messagesOfEs419Language from './es_419.json';\n export default {\n 'ar': messagesOfArLanguage,\n 'de': messagesOfDeLanguage,\n 'es-419': messagesOfEs419Language,\n };\n \"\"\"\n"; +var fs = require('fs'); +var path = require('path'); +var camelCase = require('lodash.camelcase'); +var loggingPrefix = path.basename("".concat(__filename)); // the name of this JS file + +// Header note for generated src/i18n/index.js file +var filesCodeGeneratorNoticeHeader = "// This file is generated by the openedx/frontend-platform's \"intl-import.js\" script.\n//\n// Refer to the i18n documents in https://docs.openedx.org/en/latest/developers/references/i18n.html to update\n// the file and use the Micro-frontend i18n pattern in new repositories.\n//\n"; + +/** + * Create frontend-app-example/index.js file with proper imports. + * + * @param directory - a directory name containing .json files from Transifex e.g. "frontend-app-example". + * @param log - Mockable process.stdout.write + * @param writeFileSync - Mockable fs.writeFileSync + * @param i18nDir - Path to `src/i18n` directory + * + * @return object - An object containing directory name and whether its "index.js" file was successfully written. + */ +function generateSubdirectoryMessageFile(_ref) { + var directory = _ref.directory, + log = _ref.log, + writeFileSync = _ref.writeFileSync, + i18nDir = _ref.i18nDir; + var importLines = []; + var messagesLines = []; + var counter = { + nonEmptyLanguages: 0 + }; + var messagesDir = "".concat(i18nDir, "/messages"); // The directory of Micro-frontend i18n messages + + try { + var files = fs.readdirSync("".concat(messagesDir, "/").concat(directory), { + withFileTypes: true + }); + files.sort(); // Sorting ensures a consistent generated `index.js` order of imports cross-platforms. + + var jsonFiles = files.filter(function (file) { + return file.isFile() && file.name.endsWith('.json'); + }); + if (!jsonFiles.length) { + log("".concat(loggingPrefix, ": Not creating '").concat(directory, "/index.js' because no .json translation files were found.\n")); + return { + directory: directory, + isWritten: false + }; + } + jsonFiles.forEach(function (file) { + var filename = file.name; + // Gets `fr_CA` from `fr_CA.json` + var languageCode = filename.replace(/\.json$/, ''); + // React-friendly language code fr_CA --> fr-ca + var reactIntlLanguageCode = languageCode.toLowerCase().replace(/_/g, '-'); + // camelCase variable name + var messagesCamelCaseVar = camelCase("messages_Of_".concat(languageCode, "_Language")); + var filePath = "".concat(messagesDir, "/").concat(directory, "/").concat(filename); + try { + var entries = JSON.parse(fs.readFileSync(filePath, { + encoding: 'utf8' + })); + if (!Object.keys(entries).length) { + importLines.push("// Note: Skipped empty '".concat(filename, "' messages file.")); + return; // Skip the language + } + } catch (e) { + importLines.push("// Error: unable to parse '".concat(filename, "' messages file.")); + log("".concat(loggingPrefix, ": NOTICE: Skipping '").concat(directory, "/").concat(filename, "' due to error: ").concat(e, ".\n")); + return; // Skip the language + } + counter.nonEmptyLanguages += 1; + importLines.push("import ".concat(messagesCamelCaseVar, " from './").concat(filename, "';")); + messagesLines.splice(1, 0, " '".concat(reactIntlLanguageCode, "': ").concat(messagesCamelCaseVar, ",")); + }); + if (counter.nonEmptyLanguages) { + // See the help message above for sample output. + var messagesFileContent = [filesCodeGeneratorNoticeHeader, importLines.join('\n'), '\nexport default {', messagesLines.join('\n'), '};\n'].join('\n'); + writeFileSync("".concat(messagesDir, "/").concat(directory, "/index.js"), messagesFileContent); + return { + directory: directory, + isWritten: true + }; + } + log("".concat(loggingPrefix, ": Skipping '").concat(directory, "' because no languages were found.\n")); + } catch (e) { + log("".concat(loggingPrefix, ": NOTICE: Skipping '").concat(directory, "' due to error: ").concat(e, ".\n")); + } + return { + directory: directory, + isWritten: false + }; +} + +/** + * Create main `src/i18n/index.js` messages import file. + * + * + * @param processedDirectories - List of directories with a boolean flag whether its "index.js" file is written + * The format is "[\{ directory: "frontend-component-example", isWritten: false \}, ...]" + * @param log - Mockable process.stdout.write + * @param writeFileSync - Mockable fs.writeFileSync + * @param i18nDir` - Path to `src/i18n` directory + */ +function generateMainMessagesFile(_ref2) { + var processedDirectories = _ref2.processedDirectories, + log = _ref2.log, + writeFileSync = _ref2.writeFileSync, + i18nDir = _ref2.i18nDir; + var importLines = []; + var exportLines = []; + processedDirectories.forEach(function (processedDirectory) { + var directory = processedDirectory.directory, + isWritten = processedDirectory.isWritten; + if (isWritten) { + var moduleCamelCaseVariableName = camelCase("messages_from_".concat(directory)); + importLines.push("import ".concat(moduleCamelCaseVariableName, " from './messages/").concat(directory, "';")); + exportLines.push(" ".concat(moduleCamelCaseVariableName, ",")); + } else { + var skipMessage = "Skipped import due to missing '".concat(directory, "/index.js' likely due to empty translations."); + importLines.push("// ".concat(skipMessage, ".")); + log("".concat(loggingPrefix, ": ").concat(skipMessage, "\n")); + } + }); + + // See the help message above for sample output. + var indexFileContent = [filesCodeGeneratorNoticeHeader, importLines.join('\n'), '\nexport default [', exportLines.join('\n'), '];\n'].join('\n'); + writeFileSync("".concat(i18nDir, "/index.js"), indexFileContent); +} + +/* + * Main function of the file. + */ +function main(_ref3) { + var directories = _ref3.directories, + log = _ref3.log, + writeFileSync = _ref3.writeFileSync, + pwd = _ref3.pwd; + var i18nDir = "".concat(pwd, "/src/i18n"); // The Micro-frontend i18n root directory + + if (directories.includes('--help') || directories.includes('-h')) { + log(scriptHelpDocument); + } else if (!directories.length) { + log(scriptHelpDocument); + log("".concat(loggingPrefix, ": Error: A list of directories is required.\n")); + } else if (!fs.existsSync(i18nDir) || !fs.lstatSync(i18nDir).isDirectory()) { + log(scriptHelpDocument); + log("".concat(loggingPrefix, ": Error: src/i18n directory was not found.\n")); + } else { + var processedDirectories = directories.map(function (directory) { + return generateSubdirectoryMessageFile({ + directory: directory, + log: log, + writeFileSync: writeFileSync, + i18nDir: i18nDir + }); + }); + generateMainMessagesFile({ + processedDirectories: processedDirectories, + log: log, + writeFileSync: writeFileSync, + i18nDir: i18nDir + }); + } +} +if (require.main === module) { + // Run the main() function if called from the command line. + main({ + directories: process.argv.slice(2), + log: function log(text) { + return process.stdout.write(text); + }, + writeFileSync: fs.writeFileSync, + pwd: process.env.PWD + }); +} +module.exports.main = main; // Allow tests to use the main function. +//# sourceMappingURL=intl-imports.js.map \ No newline at end of file diff --git a/dist/i18n/scripts/intl-imports.js.map b/dist/i18n/scripts/intl-imports.js.map new file mode 100644 index 000000000..5a26b76ab --- /dev/null +++ b/dist/i18n/scripts/intl-imports.js.map @@ -0,0 +1 @@ +{"version":3,"file":"intl-imports.js","names":["scriptHelpDocument","fs","require","path","camelCase","loggingPrefix","basename","concat","__filename","filesCodeGeneratorNoticeHeader","generateSubdirectoryMessageFile","_ref","directory","log","writeFileSync","i18nDir","importLines","messagesLines","counter","nonEmptyLanguages","messagesDir","files","readdirSync","withFileTypes","sort","jsonFiles","filter","file","isFile","name","endsWith","length","isWritten","forEach","filename","languageCode","replace","reactIntlLanguageCode","toLowerCase","messagesCamelCaseVar","filePath","entries","JSON","parse","readFileSync","encoding","Object","keys","push","e","splice","messagesFileContent","join","generateMainMessagesFile","_ref2","processedDirectories","exportLines","processedDirectory","moduleCamelCaseVariableName","skipMessage","indexFileContent","main","_ref3","directories","pwd","includes","existsSync","lstatSync","isDirectory","map","module","process","argv","slice","text","stdout","write","env","PWD","exports"],"sources":["../../../src/i18n/scripts/intl-imports.js"],"sourcesContent":["#!/usr/bin/env node\n\nconst scriptHelpDocument = `\nNAME\n intl-imports.js — Script to generate the src/i18n/index.js file that exports messages from all the languages for Micro-frontends.\n\nSYNOPSIS\n intl-imports.js [DIRECTORY ...]\n\nDESCRIPTION\n This script is intended to run after 'atlas' has pulled the files.\n \n This expects to run inside a Micro-frontend root directory with the following structure:\n \n frontend-app-learning $ tree src/i18n/\n src/i18n/\n ├── index.js\n └── messages\n ├── frontend-app-example\n │ ├── ar.json\n │ ├── es_419.json\n │ └── zh_CN.json\n ├── frontend-component-footer\n │ ├── ar.json\n │ ├── es_419.json\n │ └── zh_CN.json\n └── frontend-component-header (empty directory)\n \n \n \n With the structure above it's expected to run with the following command in Makefile:\n \n \n $ node_modules/.bin/intl-imports.js frontend-component-footer frontend-component-header frontend-app-example\n \n \n It will generate two type of files:\n \n - Main src/i18n/index.js which overrides the Micro-frontend provided with a sample output of:\n \n \"\"\"\n import messagesFromFrontendComponentFooter from './messages/frontend-component-footer';\n // Skipped import due to missing './messages/frontend-component-footer/index.js' likely due to empty translations.\n import messagesFromFrontendAppExample from './messages/frontend-app-example';\n \n export default [\n messagesFromFrontendComponentFooter,\n messagesFromFrontendAppExample,\n ];\n \"\"\"\n \n - Each sub-directory has src/i18n/messages/frontend-component-header/index.js which is imported by the main file.:\n \n \"\"\"\n import messagesOfArLanguage from './ar.json';\n import messagesOfDeLanguage from './de.json';\n import messagesOfEs419Language from './es_419.json';\n export default {\n 'ar': messagesOfArLanguage,\n 'de': messagesOfDeLanguage,\n 'es-419': messagesOfEs419Language,\n };\n \"\"\"\n`;\n\nconst fs = require('fs');\nconst path = require('path');\nconst camelCase = require('lodash.camelcase');\n\nconst loggingPrefix = path.basename(`${__filename}`); // the name of this JS file\n\n// Header note for generated src/i18n/index.js file\nconst filesCodeGeneratorNoticeHeader = `// This file is generated by the openedx/frontend-platform's \"intl-import.js\" script.\n//\n// Refer to the i18n documents in https://docs.openedx.org/en/latest/developers/references/i18n.html to update\n// the file and use the Micro-frontend i18n pattern in new repositories.\n//\n`;\n\n/**\n * Create frontend-app-example/index.js file with proper imports.\n *\n * @param directory - a directory name containing .json files from Transifex e.g. \"frontend-app-example\".\n * @param log - Mockable process.stdout.write\n * @param writeFileSync - Mockable fs.writeFileSync\n * @param i18nDir - Path to `src/i18n` directory\n *\n * @return object - An object containing directory name and whether its \"index.js\" file was successfully written.\n */\nfunction generateSubdirectoryMessageFile({\n directory,\n log,\n writeFileSync,\n i18nDir,\n}) {\n const importLines = [];\n const messagesLines = [];\n const counter = { nonEmptyLanguages: 0 };\n const messagesDir = `${i18nDir}/messages`; // The directory of Micro-frontend i18n messages\n\n try {\n const files = fs.readdirSync(`${messagesDir}/${directory}`, { withFileTypes: true });\n files.sort(); // Sorting ensures a consistent generated `index.js` order of imports cross-platforms.\n\n const jsonFiles = files.filter(file => file.isFile() && file.name.endsWith('.json'));\n\n if (!jsonFiles.length) {\n log(`${loggingPrefix}: Not creating '${directory}/index.js' because no .json translation files were found.\\n`);\n return {\n directory,\n isWritten: false,\n };\n }\n\n jsonFiles.forEach((file) => {\n const filename = file.name;\n // Gets `fr_CA` from `fr_CA.json`\n const languageCode = filename.replace(/\\.json$/, '');\n // React-friendly language code fr_CA --> fr-ca\n const reactIntlLanguageCode = languageCode.toLowerCase().replace(/_/g, '-');\n // camelCase variable name\n const messagesCamelCaseVar = camelCase(`messages_Of_${languageCode}_Language`);\n const filePath = `${messagesDir}/${directory}/${filename}`;\n\n try {\n const entries = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf8' }));\n\n if (!Object.keys(entries).length) {\n importLines.push(`// Note: Skipped empty '${filename}' messages file.`);\n return; // Skip the language\n }\n } catch (e) {\n importLines.push(`// Error: unable to parse '${filename}' messages file.`);\n log(`${loggingPrefix}: NOTICE: Skipping '${directory}/${filename}' due to error: ${e}.\\n`);\n return; // Skip the language\n }\n\n counter.nonEmptyLanguages += 1;\n importLines.push(`import ${messagesCamelCaseVar} from './${filename}';`);\n messagesLines.splice(1, 0, ` '${reactIntlLanguageCode}': ${messagesCamelCaseVar},`);\n });\n\n if (counter.nonEmptyLanguages) {\n // See the help message above for sample output.\n const messagesFileContent = [\n filesCodeGeneratorNoticeHeader,\n importLines.join('\\n'),\n '\\nexport default {',\n messagesLines.join('\\n'),\n '};\\n',\n ].join('\\n');\n\n writeFileSync(`${messagesDir}/${directory}/index.js`, messagesFileContent);\n return {\n directory,\n isWritten: true,\n };\n }\n log(`${loggingPrefix}: Skipping '${directory}' because no languages were found.\\n`);\n } catch (e) {\n log(`${loggingPrefix}: NOTICE: Skipping '${directory}' due to error: ${e}.\\n`);\n }\n\n return {\n directory,\n isWritten: false,\n };\n}\n\n/**\n * Create main `src/i18n/index.js` messages import file.\n *\n *\n * @param processedDirectories - List of directories with a boolean flag whether its \"index.js\" file is written\n * The format is \"[\\{ directory: \"frontend-component-example\", isWritten: false \\}, ...]\"\n * @param log - Mockable process.stdout.write\n * @param writeFileSync - Mockable fs.writeFileSync\n * @param i18nDir` - Path to `src/i18n` directory\n */\nfunction generateMainMessagesFile({\n processedDirectories,\n log,\n writeFileSync,\n i18nDir,\n}) {\n const importLines = [];\n const exportLines = [];\n\n processedDirectories.forEach(processedDirectory => {\n const { directory, isWritten } = processedDirectory;\n if (isWritten) {\n const moduleCamelCaseVariableName = camelCase(`messages_from_${directory}`);\n importLines.push(`import ${moduleCamelCaseVariableName} from './messages/${directory}';`);\n exportLines.push(` ${moduleCamelCaseVariableName},`);\n } else {\n const skipMessage = `Skipped import due to missing '${directory}/index.js' likely due to empty translations.`;\n importLines.push(`// ${skipMessage}.`);\n log(`${loggingPrefix}: ${skipMessage}\\n`);\n }\n });\n\n // See the help message above for sample output.\n const indexFileContent = [\n filesCodeGeneratorNoticeHeader,\n importLines.join('\\n'),\n '\\nexport default [',\n exportLines.join('\\n'),\n '];\\n',\n ].join('\\n');\n\n writeFileSync(`${i18nDir}/index.js`, indexFileContent);\n}\n\n/*\n * Main function of the file.\n */\nfunction main({\n directories,\n log,\n writeFileSync,\n pwd,\n}) {\n const i18nDir = `${pwd}/src/i18n`; // The Micro-frontend i18n root directory\n\n if (directories.includes('--help') || directories.includes('-h')) {\n log(scriptHelpDocument);\n } else if (!directories.length) {\n log(scriptHelpDocument);\n log(`${loggingPrefix}: Error: A list of directories is required.\\n`);\n } else if (!fs.existsSync(i18nDir) || !fs.lstatSync(i18nDir).isDirectory()) {\n log(scriptHelpDocument);\n log(`${loggingPrefix}: Error: src/i18n directory was not found.\\n`);\n } else {\n const processedDirectories = directories.map(directory => generateSubdirectoryMessageFile({\n directory,\n log,\n writeFileSync,\n i18nDir,\n }));\n generateMainMessagesFile({\n processedDirectories,\n log,\n writeFileSync,\n i18nDir,\n });\n }\n}\n\nif (require.main === module) {\n // Run the main() function if called from the command line.\n main({\n directories: process.argv.slice(2),\n log: text => process.stdout.write(text),\n writeFileSync: fs.writeFileSync,\n pwd: process.env.PWD,\n });\n}\n\nmodule.exports.main = main; // Allow tests to use the main function.\n"],"mappings":"AAAA;AAEA,IAAMA,kBAAkB,suEA6DvB;AAED,IAAMC,EAAE,GAAGC,OAAO,CAAC,IA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G,EAAEO,OAAO,CAACM,GAAG,CAACC;EACnB,CAAC,CAAC;AACJ;AAEAR,MAAM,CAACS,OAAO,CAAClB,IAAI,GAAGA,IAAI,CAAC,CAAC","ignoreList":[]} \ No newline at end of file diff --git a/dist/i18n/scripts/transifex-utils.js b/dist/i18n/scripts/transifex-utils.js new file mode 100755 index 000000000..9b1fe9951 --- /dev/null +++ b/dist/i18n/scripts/transifex-utils.js @@ -0,0 +1,72 @@ +#!/usr/bin/env node +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +var fs = require('fs'); +var glob = require('glob'); +var path = require('path'); + +/* + * See the Makefile for how the required hash file is downloaded from Transifex. + */ + +/* + * Expected input: a directory, possibly containing subdirectories, with .json files. Each .json + * file is an array of translation triplets (id, description, defaultMessage). + * + * + */ +function gatherJson(dir) { + var ret = []; + var files = glob.sync("".concat(dir, "/**/*.json")); + files.forEach(function (filename) { + var messages = JSON.parse(fs.readFileSync(filename)); + ret.push.apply(ret, _toConsumableArray(messages)); + }); + return ret; +} + +// the hash file returns ids whose periods are "escaped" (sort of), like this: +// "key": "profile\\.sociallinks\\.social\\.links" +// so our regular messageIds won't match them out of the box +function escapeDots(messageId) { + return messageId.replace(/\./g, '\\.'); +} +var jsonDir = process.argv[2]; +var messageObjects = gatherJson(jsonDir); +if (messageObjects.length === 0) { + process.exitCode = 1; + throw new Error('Found no messages'); +} +if (process.argv[3] === '--comments') { + // prepare to handle the translator notes + var loggingPrefix = path.basename("".concat(__filename)); // the name of this JS file + var bashScriptsPath = process.argv[4] && process.argv[4] === '--v3-scripts-path' ? './node_modules/@edx/reactifex/bash_scripts' : './node_modules/reactifex/bash_scripts'; + var hashFile = "".concat(bashScriptsPath, "/hashmap.json"); + process.stdout.write("".concat(loggingPrefix, ": reading hash file ").concat(hashFile, "\n")); + var messageInfo = JSON.parse(fs.readFileSync(hashFile)); + var outputFile = "".concat(bashScriptsPath, "/hashed_data.txt"); + process.stdout.write("".concat(loggingPrefix, ": writing to output file ").concat(outputFile, "\n")); + fs.writeFileSync(outputFile, ''); + messageObjects.forEach(function (message) { + var transifexFormatId = escapeDots(message.id); + var info = messageInfo.find(function (mi) { + return mi.key === transifexFormatId; + }); + if (info) { + fs.appendFileSync(outputFile, "".concat(info.string_hash, "|").concat(message.description, "\n")); + } else { + process.stdout.write("".concat(loggingPrefix, ": string ").concat(message.id, " does not yet exist on transifex!\n")); + } + }); +} else { + var output = {}; + messageObjects.forEach(function (message) { + output[message.id] = message.defaultMessage; + }); + fs.writeFileSync(process.argv[3], JSON.stringify(output, null, 2)); +} +//# sourceMappingURL=transifex-utils.js.map \ No newline at end of file diff --git a/dist/i18n/scripts/transifex-utils.js.map b/dist/i18n/scripts/transifex-utils.js.map new file mode 100644 index 000000000..4ff345902 --- /dev/null +++ b/dist/i18n/scripts/transifex-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transifex-utils.js","names":["_toConsumableArray","r","_arrayWithoutHoles","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","TypeError","a","_arrayLikeToArray","t","toString","call","slice","constructor","name","Array","from","test","Symbol","iterator","isArray","length","e","n","fs","require","glob","path","gatherJson","dir","ret","files","sync","concat","forEach","filename","messages","JSON","parse","readFileSync","push","apply","escapeDots","messageId","replace","jsonDir","process","argv","messageObjects","exitCode","Error","loggingPrefix","basename","__filename","bashScriptsPath","hashFile","stdout","write","messageInfo","outputFile","writeFileSync","message","transifexFormatId","id","info","find","mi","key","appendFileSync","string_hash","description","output","defaultMessage","stringify"],"sources":["../../../src/i18n/scripts/transifex-utils.js"],"sourcesContent":["#!/usr/bin/env node\n\nconst fs = require('fs');\nconst glob = require('glob');\nconst path = require('path');\n\n/*\n * See the Makefile for how the required hash file is downloaded from Transifex.\n */\n\n/*\n * Expected input: a directory, possibly containing subdirectories, with .json files. Each .json\n * file is an array of translation triplets (id, description, defaultMessage).\n *\n *\n */\nfunction gatherJson(dir) {\n const ret = [];\n const files = glob.sync(`${dir}/**/*.json`);\n\n files.forEach((filename) => {\n const messages = JSON.parse(fs.readFileSync(filename));\n ret.push(...messages);\n });\n return ret;\n}\n\n// the hash file returns ids whose periods are \"escaped\" (sort of), like this:\n// \"key\": \"profile\\\\.sociallinks\\\\.social\\\\.links\"\n// so our regular messageIds won't match them out of the box\nfunction escapeDots(messageId) {\n return messageId.replace(/\\./g, '\\\\.');\n}\n\nconst jsonDir = process.argv[2];\nconst messageObjects = gatherJson(jsonDir);\n\nif (messageObjects.length === 0) {\n process.exitCode = 1;\n throw new Error('Found no messages');\n}\n\nif (process.argv[3] === '--comments') { // prepare to handle the translator notes\n const loggingPrefix = path.basename(`${__filename}`); // the name of this JS file\n const bashScriptsPath = (\n process.argv[4] && process.argv[4] === '--v3-scripts-path'\n ? './node_modules/@edx/reactifex/bash_scripts'\n : './node_modules/reactifex/bash_scripts');\n\n const hashFile = `${bashScriptsPath}/hashmap.json`;\n process.stdout.write(`${loggingPrefix}: reading hash file ${hashFile}\\n`);\n const messageInfo = JSON.parse(fs.readFileSync(hashFile));\n\n const outputFile = `${bashScriptsPath}/hashed_data.txt`;\n process.stdout.write(`${loggingPrefix}: writing to output file ${outputFile}\\n`);\n fs.writeFileSync(outputFile, '');\n\n messageObjects.forEach((message) => {\n const transifexFormatId = escapeDots(message.id);\n\n const info = messageInfo.find(mi => mi.key === transifexFormatId);\n if (info) {\n fs.appendFileSync(outputFile, `${info.string_hash}|${message.description}\\n`);\n } else {\n process.stdout.write(`${loggingPrefix}: string ${message.id} does not yet exist on transifex!\\n`);\n }\n });\n} else {\n const output = {};\n\n messageObjects.forEach((message) => {\n output[message.id] = message.defaultMessage;\n });\n fs.writeFileSync(process.argv[3], JSON.stringify(output, null, 2));\n}\n"],"mappings":"AAAA;AAAmB,SAAAA,mBAAAC,CAAA,WAAAC,kBAAA,CAAAD,CAAA,KAAAE,gBAAA,CAAAF,CAAA,KAAAG,2BAAA,CAAAH,CAAA,KAAAI,kBAAA;AAAA,SAAAA,mBAAA,cAAAC,SAAA;AAAA,SAAAF,4BAAAH,CAAA,EAAAM,CAAA,QAAAN,CAAA,2BAAAA,CAAA,SAAAO,iBAAA,CAAAP,CAAA,EAAAM,CAAA,OAAAE,CAAA,MAAAC,QAAA,CAAAC,IAAA,CAAAV,CAAA,EAAAW,KAAA,6BAAAH,CAAA,IAAAR,CAAA,CAAAY,WAAA,KAAAJ,CAAA,GAAAR,CAAA,CAAAY,WAAA,CAAAC,IAAA,aAAAL,CAAA,cAAAA,CAAA,GAAAM,KAAA,CAAAC,IAAA,CAAAf,CAAA,oBAAAQ,CAAA,+CAAAQ,IAAA,CAAAR,CAAA,IAAAD,iBAAA,CAAAP,CAAA,EAAAM,CAAA;AAAA,SAAAJ,iBAAAF,CAAA,8BAAAiB,MAAA,YAAAjB,CAAA,CAAAiB,MAAA,CAAAC,QAAA,aAAAlB,CAAA,uBAAAc,KAAA,CAAAC,IAAA,CAAAf,CAAA;AAAA,SAAAC,mBAAAD,CAAA,QAAAc,KAAA,CAAAK,OAAA,CAAAnB,CAAA,UAAAO,iBAAA,CAAAP,CAA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,CAACK,WAAW,OAAApC,MAAA,CAAI4B,OAAO,CAACS,WAAW,OAAI,CAAC;IAC/E,CAAC,MAAM;MACLxB,OAAO,CAACU,MAAM,CAACC,KAAK,IAAAxB,MAAA,CAAIkB,aAAa,eAAAlB,MAAA,CAAY4B,OAAO,CAACE,EAAE,wCAAqC,CAAC;IACnG;EACF,CAAC,CAAC;AACJ,CAAC,MAAM;EACL,IAAMQ,MAAM,GAAG,CAAC,CAAC;EAEjBvB,cAAc,CAACd,OAAO,CAAC,UAAC2B,OAAO,EAAK;IAClCU,MAAM,CAACV,OAAO,CAACE,EAAE,CAAC,GAAGF,OAAO,CAACW,cAAc;EAC7C,CAAC,CAAC;EACFhD,EAAE,CAACoC,aAAa,CAACd,OAAO,CAACC,IAAI,CAAC,CAAC,CAAC,EAAEV,IAAI,CAACoC,SAAS,CAACF,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACpE","ignoreList":[]} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 000000000..b34ca6f92 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,7 @@ +export { modifyObjectKeys, camelCaseObject, snakeCaseObject, convertKeyNames, getQueryParameters, ensureDefinedConfig, parseURL, getPath } from './utils'; +export { APP_TOPIC, APP_PUBSUB_INITIALIZED, APP_CONFIG_INITIALIZED, APP_AUTH_INITIALIZED, APP_I18N_INITIALIZED, APP_LOGGING_INITIALIZED, APP_ANALYTICS_INITIALIZED, APP_READY, APP_INIT_ERROR, CONFIG_TOPIC, CONFIG_CHANGED } from './constants'; +export { initialize, history, initError, auth } from './initialize'; +export { publish, subscribe, unsubscribe } from './pubSub'; +export { getConfig, setConfig, mergeConfig, ensureConfig } from './config'; +export { initializeMockApp, mockMessages } from './testing'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map new file mode 100644 index 000000000..6333f5b47 --- /dev/null +++ b/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["modifyObjectKeys","camelCaseObject","snakeCaseObject","convertKeyNames","getQueryParameters","ensureDefinedConfig","parseURL","getPath","APP_TOPIC","APP_PUBSUB_INITIALIZED","APP_CONFIG_INITIALIZED","APP_AUTH_INITIALIZED","APP_I18N_INITIALIZED","APP_LOGGING_INITIALIZED","APP_ANALYTICS_INITIALIZED","APP_READY","APP_INIT_ERROR","CONFIG_TOPIC","CONFIG_CHANGED","initialize","history","initError","auth","publish","subscribe","unsubscribe","getConfig","setConfig","mergeConfig","ensureConfig","initializeMockApp","mockMessages"],"sources":["../src/index.js"],"sourcesContent":["export {\n modifyObjectKeys,\n camelCaseObject,\n snakeCaseObject,\n convertKeyNames,\n getQueryParameters,\n ensureDefinedConfig,\n parseURL,\n getPath,\n} from './utils';\nexport {\n APP_TOPIC,\n APP_PUBSUB_INITIALIZED,\n APP_CONFIG_INITIALIZED,\n APP_AUTH_INITIALIZED,\n APP_I18N_INITIALIZED,\n APP_LOGGING_INITIALIZED,\n APP_ANALYTICS_INITIALIZED,\n APP_READY,\n APP_INIT_ERROR,\n CONFIG_TOPIC,\n CONFIG_CHANGED,\n} from './constants';\nexport {\n initialize,\n history,\n initError,\n auth,\n} from './initialize';\nexport {\n publish,\n subscribe,\n unsubscribe,\n} from './pubSub';\nexport {\n getConfig,\n setConfig,\n mergeConfig,\n ensureConfig,\n} from './config';\nexport {\n initializeMockApp,\n mockMessages,\n} from './testing';\n"],"mappings":"AAAA,SACEA,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,kBAAkB,EAClBC,mBAAmB,EACnBC,QAAQ,EACRC,OAAO,QACF,SAAS;AAChB,SACEC,SAAS,EACTC,sBAAsB,EACtBC,sBAAsB,EACtBC,oBAAoB,EACpBC,oBAAoB,EACpBC,uBAAuB,EACvBC,yBAAyB,EACzBC,SAAS,EACTC,cAAc,EACdC,YAAY,EACZC,cAAc,QACT,aAAa;AACpB,SACEC,UAAU,EACVC,OAAO,EACPC,SAAS,EACTC,IAAI,QACC,cAAc;AACrB,SACEC,OAAO,EACPC,SAAS,EACTC,WAAW,QACN,UAAU;AACjB,SACEC,SAAS,EACTC,SAAS,EACTC,WAAW,EACXC,YAAY,QACP,UAAU;AACjB,SACEC,iBAAiB,EACjBC,YAAY,QACP,WAAW","ignoreList":[]} \ No newline at end of file diff --git a/dist/initialize.js b/dist/initialize.js new file mode 100644 index 000000000..3425c8529 --- /dev/null +++ b/dist/initialize.js @@ -0,0 +1,494 @@ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/** + * #### Import members from **@edx/frontend-platform** + * + * The initialization module provides a function for managing an application's initialization + * lifecycle. It also provides constants and default handler implementations. + * + * ``` + * import { + * initialize, + * APP_INIT_ERROR, + * APP_READY, + * subscribe, + * } from '@edx/frontend-platform'; + * import { AppProvider, ErrorPage, PageWrap } from '@edx/frontend-platform/react'; + * import React from 'react'; + * import ReactDOM from 'react-dom'; + * import { Routes, Route } from 'react-router-dom'; + * + * subscribe(APP_READY, () => { + * ReactDOM.render( + * + *
+ *
+ * + * } /> + * + *
+ *