fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

788
node_modules/@wordpress/eslint-plugin/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,788 @@
## Gutenberg
Copyright 2016-2024 by the contributors
**License for Contributions (on and after April 15, 2021)**
All code contributed to the Gutenberg project is dual-licensed,
and released under both of the following licenses:
the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License or (at your option) any later version (the “GPL”)
and the Mozilla Public License, Version 2.0 (the “MPL”).
**Project License**
The Gutenberg project license is not affected by the License for Contributions (as
discussed in the [Dual License section](#dual-license) below). The Gutenberg project
continues to be free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License or (at your option) any
later version (the “GPL”).
This program incorporates work covered by the following copyright and
permission notices:
b2 is (c) 2001, 2002 Michel Valdrighi - m@tidakada.com -
http://tidakada.com
Wherever third party code has been used, credit has been given in the code's
comments.
b2 is released under the GPL
and
WordPress - Web publishing software
Copyright 2003-2010 by the contributors
WordPress is released under the GPL
### Dual License
**We are currently in the process of changing Gutenbergs software license from
GPL to a dual license: GPL and MPL.**
**This process involves two independent steps (1) obtaining permission for dual
licensing from contributors of already contributed Gutenberg code and (2)
dual licensing of all contributions to Gutenberg that are made on or after
April 15, 2021.**
**For part (1): Were reaching out to everyone who has contributed code, prior
to April 15, 2021, and asking that they agree to dual license their
contribution to the project. We expect this process to be completed by
mid-year, 2021.**
**For part (2): We have changed the license for contributed code to this
repository to make clear that all contributions on or after April 15, 2021
will be made under the dual-license.**
**When we have received all necessary rights and permissions to dual license
the pre-April 15, 2021 code of the Gutenberg project (Part 1 above), you will
have the option to use and distribute all of the Gutenberg project under
either the GPL or MPL license. At this time we will change the “Project
License” to the following:**
The Gutenberg project is free software; you can redistribute it and/or modify
it under the terms of either of the following licenses:
1. the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License or (at your option) any later version (the
“GPL”) OR
2. the Mozilla Public License Version 2.0 (the “MPL”).
---
## Full Text of Referenced Licenses
1. [GNU General Public License, Version 2](#gnu-general-public-license-version-2)
2. [Mozilla Public License, Version 2.0](#mozilla-public-license-version-20)
## GNU General Public License, Version 2
### GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
### Preamble
The licenses for most software are designed to take away your freedom
to share and change it. By contrast, the GNU General Public License is
intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
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
this service 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.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on,
we want its recipients to know that what they have is not the
original, so that any problems introduced by others will not reflect
on the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at
all.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
**0.** This License applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License. The
"Program", below, refers to any such program or work, and a "work
based on the Program" means either the Program or any derivative work
under copyright law: that is to say, a work containing the Program or
a portion of it, either verbatim or with modifications and/or
translated into another language. (Hereinafter, translation is
included without limitation in the term "modification".) Each licensee
is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the Program
(independent of having been made by running the Program). Whether that
is true depends on what the Program does.
**1.** You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a
fee.
**2.** You may modify your copy or copies of the Program or any
portion of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
**a)** You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
**b)** You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any part
thereof, to be licensed as a whole at no charge to all third parties
under the terms of this License.
**c)** If the modified program normally reads commands interactively
when run, you must cause it, when started running for such interactive
use in the most ordinary way, to print or display an announcement
including an appropriate copyright notice and a notice that there is
no warranty (or else, saying that you provide a warranty) and that
users may redistribute the program under these conditions, and telling
the user how to view a copy of this License. (Exception: if the
Program itself is interactive but does not normally print such an
announcement, your work based on the Program is not required to print
an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
**3.** You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
**a)** Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections 1
and 2 above on a medium customarily used for software interchange; or,
**b)** Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your cost of
physically performing source distribution, a complete machine-readable
copy of the corresponding source code, to be distributed under the
terms of Sections 1 and 2 above on a medium customarily used for
software interchange; or,
**c)** Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is allowed
only for noncommercial distribution and only if you received the
program in object code or executable form with such an offer, in
accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
**4.** You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt otherwise
to copy, modify, sublicense or distribute the Program is void, and
will automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
**5.** You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
**6.** Each time you redistribute the Program (or any work based on
the Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
**7.** If, as a consequence of a court judgment or allegation of
patent infringement or for any other reason (not limited to patent
issues), 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 distribute so as to satisfy simultaneously your
obligations under this License and any other pertinent obligations,
then as a consequence you may not distribute the Program at all. For
example, if a patent license would not permit royalty-free
redistribution of the Program by all those who receive copies directly
or indirectly through you, then the only way you could satisfy both it
and this License would be to refrain entirely from distribution of the
Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
**8.** If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
**9.** The Free Software Foundation may publish revised and/or new
versions of the 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 a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Program does not specify a
version number of this License, you may choose any version ever
published by the Free Software Foundation.
**10.** If you wish to incorporate parts of the Program into other
free programs whose distribution conditions are different, write to
the author to ask for permission. For software which is copyrighted by
the Free Software Foundation, write to the Free Software Foundation;
we sometimes make exceptions for this. Our decision will be guided by
the two goals of preserving the free status of all derivatives of our
free software and of promoting the sharing and reuse of software
generally.
**NO WARRANTY**
**11.** BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
**12.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE 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.
### 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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Also add information on how to contact you by electronic and paper
mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'. This is free software, and you are welcome
to redistribute it under certain conditions; type `show c'
for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, the
commands you use may be called something other than \`show w' and
\`show c'; they could even be mouse-clicks or menu items--whatever
suits your program.
You should also get your employer (if you work as a programmer) or
your school, if any, to sign a "copyright disclaimer" for the program,
if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written
by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library,
you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
[GNU Lesser General Public
License](http://www.gnu.org/licenses/lgpl.html) instead of this
License.
---
## Mozilla Public License, Version 2.0
### 1. Definitions
**1.1. “Contributor”**
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
**1.2. “Contributor Version”**
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
**1.3. “Contribution”**
means Covered Software of a particular Contributor.
**1.4. “Covered Software”**
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
**1.5. “Incompatible With Secondary Licenses”**
means
- **(a)** that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
- **(b)** that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
**1.6. “Executable Form”**
means any form of the work other than Source Code Form.
**1.7. “Larger Work”**
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
**1.8. “License”**
means this document.
**1.9. “Licensable”**
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
**1.10. “Modifications”**
means any of the following:
- **(a)** any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
- **(b)** any new file in Source Code Form that contains any Covered
Software.
**1.11. “Patent Claims” of a Contributor**
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
**1.12. “Secondary License”**
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
**1.13. “Source Code Form”**
means the form of the work preferred for making modifications.
**1.14. “You” (or “Your”)**
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, “control” means **(a)** the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or **(b)** ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
### 2. License Grants and Conditions
#### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
- **(a)** under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
- **(b)** under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
#### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
#### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
- **(a)** for any code that a Contributor has removed from Covered Software;
or
- **(b)** for infringements caused by: **(i)** Your and any other third party's
modifications of Covered Software, or **(ii)** the combination of its
Contributions with other software (except as part of its Contributor
Version); or
- **(c)** under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
#### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
#### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
#### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
#### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
### 3. Responsibilities
#### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
#### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
- **(a)** such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
- **(b)** You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
#### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
#### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
#### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
### 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: **(a)** comply with
the terms of this License to the maximum extent possible; and **(b)**
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
### 5. Termination
**5.1.** The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated **(a)** provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and **(b)** on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
**5.2.** If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
**5.3.** In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
### 6. Disclaimer of Warranty
> Covered Software is provided under this License on an “as is”
> basis, without warranty of any kind, either expressed, implied, or
> statutory, including, without limitation, warranties that the
> Covered Software is free of defects, merchantable, fit for a
> particular purpose or non-infringing. The entire risk as to the
> quality and performance of the Covered Software is with You.
> Should any Covered Software prove defective in any respect, You
> (not any Contributor) assume the cost of any necessary servicing,
> repair, or correction. This disclaimer of warranty constitutes an
> essential part of this License. No use of any Covered Software is
> authorized under this License except under this disclaimer.
### 7. Limitation of Liability
> Under no circumstances and under no legal theory, whether tort
> (including negligence), contract, or otherwise, shall any
> Contributor, or anyone who distributes Covered Software as
> permitted above, be liable to You for any direct, indirect,
> special, incidental, or consequential damages of any character
> including, without limitation, damages for lost profits, loss of
> goodwill, work stoppage, computer failure or malfunction, or any
> and all other commercial damages or losses, even if such party
> shall have been informed of the possibility of such damages. This
> limitation of liability shall not apply to liability for death or
> personal injury resulting from such party's negligence to the
> extent applicable law prohibits such limitation. Some
> jurisdictions do not allow the exclusion or limitation of
> incidental or consequential damages, so this exclusion and
> limitation may not apply to You.
### 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
### 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
### 10. Versions of the License
#### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
#### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
#### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
#### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

108
node_modules/@wordpress/eslint-plugin/README.md generated vendored Normal file
View File

@@ -0,0 +1,108 @@
# ESLint Plugin
[ESLint](https://eslint.org/) plugin including configurations and custom rules for WordPress development.
## Installation
Install the module
```bash
npm install @wordpress/eslint-plugin --save-dev
```
**Note**: This package requires `node` 14.0.0 or later, and `npm` 6.14.4 or later. It is not compatible with older versions.
## Usage
To opt-in to the default configuration, extend your own project's `.eslintrc` file:
```json
{
"extends": [ "plugin:@wordpress/eslint-plugin/recommended" ]
}
```
Refer to the [ESLint documentation on Shareable Configs](http://eslint.org/docs/developer-guide/shareable-configs) for more information.
The `recommended` preset will include rules governing an ES2015+ environment, and includes rules from the [`eslint-plugin-jsdoc`](https://github.com/gajus/eslint-plugin-jsdoc), [`eslint-plugin-jsx-a11y`](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y), [`eslint-plugin-react`](https://github.com/yannickcr/eslint-plugin-react), and other similar plugins.
This preset offers an optional integration with the [`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier) package that runs [Prettier](https://prettier.io) code formatter and reports differences as individual ESLint issues. You can activate it by installing the [`prettier`](https://www.npmjs.com/package/prettier) package separately with:
```bash
npm install prettier --save-dev
```
Finally, this ruleset also includes an optional integration with the [`@typescript-eslint/eslint-plugin`](https://github.com/typescript-eslint/typescript-eslint) package that enables ESLint to support [TypeScript](https://www.typescriptlang.org) language. You can activate it by installing the [`typescript`](https://www.npmjs.com/package/typescript) package separately with:
```bash
npm install typescript --save-dev
```
There is also `recommended-with-formatting` ruleset for projects that want to ensure that [Prettier](https://prettier.io) and [TypeScript](https://www.typescriptlang.org) integration is never activated. This preset has the native ESLint code formatting rules enabled instead.
### Rulesets
Alternatively, you can opt-in to only the more granular rulesets offered by the plugin. These include:
- `custom` custom rules for WordPress development.
- `es5` rules for legacy ES5 environments.
- `esnext` rules for ES2015+ environments.
- `i18n` rules for internationalization.
- `jsdoc` rules for JSDoc comments.
- `jsx-a11y` rules for accessibility in JSX.
- `react` rules for React components.
- `test-e2e` rules for end-to-end tests written in Puppeteer.
- `test-unit` rules for unit tests written in Jest.
- `test-playwright` rules for end-to-end tests written in Playwright.
For example, if your project does not use React, you could consider extending including only the ESNext rules in your project using the following `extends` definition:
```json
{
"extends": [ "plugin:@wordpress/eslint-plugin/esnext" ]
}
```
These rules can be used additively, so you could extend both `esnext` and `custom` rulesets, but omit the `react` and `jsx-a11y` configurations.
The granular rulesets will not define any environment globals. As such, if they are required for your project, you will need to define them yourself.
### Rules
| Rule | Description | Recommended |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------- |
| [data-no-store-string-literals](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/data-no-store-string-literals.md) | Discourage passing string literals to reference data stores | |
| [dependency-group](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/dependency-group.md) | Enforce dependencies docblocks formatting | ✓ |
| [is-gutenberg-plugin](docs/rules/is-gutenberg-plugin.md) | Governs the use of the `process.env.IS_GUTENBERG_PLUGIN` constant | ✓ |
| [no-base-control-with-label-without-id](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/no-base-control-with-label-without-id.md) | Disallow the usage of BaseControl component with a label prop set but omitting the id property | ✓ |
| [no-unguarded-get-range-at](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/no-unguarded-get-range-at.md) | Disallow the usage of unguarded `getRangeAt` calls | ✓ |
| [no-unsafe-wp-apis](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/no-unsafe-wp-apis.md) | Disallow the usage of unsafe APIs from `@wordpress/*` packages | ✓ |
| [no-unused-vars-before-return](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/no-unused-vars-before-return.md) | Disallow assigning variable values if unused before a return | ✓ |
| [react-no-unsafe-timeout](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/react-no-unsafe-timeout.md) | Disallow unsafe `setTimeout` in component | |
| [valid-sprintf](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/valid-sprintf.md) | Enforce valid sprintf usage | ✓ |
| [i18n-ellipsis](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-ellipsis.md) | Disallow using three dots in translatable strings | ✓ |
| [i18n-no-collapsible-whitespace](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-no-collapsible-whitespace.md) | Disallow collapsible whitespace in translatable strings | ✓ |
| [i18n-no-placeholders-only](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-no-placeholders-only.md) | Prevent using only placeholders in translatable strings | ✓ |
| [i18n-no-variables](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-no-variables.md) | Enforce string literals as translation function arguments | ✓ |
| [i18n-text-domain](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-text-domain.md) | Enforce passing valid text domains | ✓ |
| [i18n-translator-comments](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-translator-comments.md) | Enforce adding translator comments | ✓ |
| [i18n-no-flanking-whitespace](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-no-flanking-whitespace.md) | Disallow leading or trailing whitespace in translatable strings | |
| [i18n-hyphenated-range](https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/docs/rules/i18n-hyphenated-range.md) | Disallow hyphenated numerical ranges in translatable strings | |
### Legacy
If you are using WordPress' `.jshintrc` JSHint configuration and you would like to take the first step to migrate to an ESLint equivalent it is also possible to define your own project's `.eslintrc` file as:
```json
{
"extends": [ "plugin:@wordpress/eslint-plugin/jshint" ]
}
```
## Contributing to this package
This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to [npm](https://www.npmjs.com/) and used by [WordPress](https://make.wordpress.org/core/) as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main [contributor guide](https://github.com/WordPress/gutenberg/tree/HEAD/CONTRIBUTING.md).
<br /><br /><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>

View File

@@ -0,0 +1,32 @@
module.exports = {
plugins: [ '@wordpress' ],
rules: {
'@wordpress/no-unused-vars-before-return': 'error',
'@wordpress/no-base-control-with-label-without-id': 'error',
'@wordpress/no-unguarded-get-range-at': 'error',
'@wordpress/no-global-active-element': 'error',
'@wordpress/no-global-get-selection': 'error',
'@wordpress/no-unsafe-wp-apis': 'error',
},
overrides: [
{
files: [ '*.native.js' ],
rules: {
'@wordpress/no-base-control-with-label-without-id': 'off',
'@wordpress/i18n-no-flanking-whitespace': 'error',
'@wordpress/i18n-hyphenated-range': 'error',
},
},
{
files: [
'*.test.js',
'**/test/*.js',
'packages/e2e-test-utils/**/*.js',
],
rules: {
'@wordpress/no-global-active-element': 'off',
'@wordpress/no-global-get-selection': 'off',
},
},
],
};

89
node_modules/@wordpress/eslint-plugin/configs/es5.js generated vendored Normal file
View File

@@ -0,0 +1,89 @@
module.exports = {
extends: [ require.resolve( './jsdoc.js' ) ],
rules: {
'array-bracket-spacing': [ 'error', 'always' ],
'array-callback-return': 'error',
'brace-style': [ 'error', '1tbs' ],
camelcase: [
'error',
{
properties: 'never',
},
],
'comma-dangle': [ 'error', 'always-multiline' ],
'comma-spacing': 'error',
'comma-style': [ 'error', 'last' ],
curly: [ 'error', 'all' ],
'dot-notation': 'error',
'eol-last': 'error',
eqeqeq: 'error',
'func-call-spacing': 'error',
indent: [ 'error', 'tab', { SwitchCase: 1 } ],
'key-spacing': 'error',
'keyword-spacing': 'error',
'linebreak-style': [ 'error', 'unix' ],
'no-alert': 'error',
'no-bitwise': 'error',
'no-caller': 'error',
'no-cond-assign': [ 'error', 'except-parens' ],
'no-console': 'error',
'no-debugger': 'error',
'no-dupe-args': 'error',
'no-dupe-keys': 'error',
'no-duplicate-case': 'error',
'no-else-return': 'error',
'no-eval': 'error',
'no-extra-semi': 'error',
'no-fallthrough': 'error',
'no-irregular-whitespace': 'error',
'no-lonely-if': 'error',
'no-multi-str': 'error',
'no-mixed-operators': 'error',
'no-mixed-spaces-and-tabs': 'error',
'no-multiple-empty-lines': [ 'error', { max: 1 } ],
'no-multi-spaces': 'error',
'no-nested-ternary': 'error',
'no-redeclare': 'error',
'no-shadow': 'error',
'no-trailing-spaces': 'error',
'no-undef': 'error',
'no-undef-init': 'error',
'no-unreachable': 'error',
'no-unsafe-negation': 'error',
'no-unused-expressions': 'error',
'no-unused-vars': [ 'error', { ignoreRestSiblings: true } ],
'no-useless-return': 'error',
'no-whitespace-before-property': 'error',
'no-with': 'error',
'object-curly-spacing': [ 'error', 'always' ],
'one-var-declaration-per-line': [ 'error', 'initializations' ],
'operator-linebreak': 'error',
'padded-blocks': [ 'error', 'never' ],
'quote-props': [ 'error', 'as-needed' ],
quotes: [ 'error', 'single', { avoidEscape: true } ],
semi: 'error',
'semi-spacing': 'error',
'space-before-blocks': [ 'error', 'always' ],
'space-before-function-paren': [
'error',
{
anonymous: 'never',
named: 'never',
asyncArrow: 'always',
},
],
'space-in-parens': [ 'error', 'always' ],
'space-infix-ops': 'error',
'space-unary-ops': [
'error',
{
overrides: {
'!': true,
},
},
],
'valid-typeof': 'error',
'vars-on-top': 'error',
'wrap-iife': 'error',
},
};

View File

@@ -0,0 +1,68 @@
/**
* External dependencies
*/
const { cosmiconfigSync } = require( 'cosmiconfig' );
const config = {
parser: '@babel/eslint-parser',
parserOptions: {
sourceType: 'module',
},
env: {
es6: true,
},
extends: [ require.resolve( './es5.js' ) ],
rules: {
// Disable ES5-specific (extended from ES5)
'vars-on-top': 'off',
// Enable ESNext-specific.
'arrow-parens': [ 'error', 'always' ],
'arrow-spacing': 'error',
'computed-property-spacing': [ 'error', 'always' ],
'constructor-super': 'error',
'no-const-assign': 'error',
'no-dupe-class-members': 'error',
'no-duplicate-imports': 'error',
'no-useless-computed-key': 'error',
'no-useless-constructor': 'error',
'no-var': 'error',
'object-shorthand': 'error',
'prefer-const': [
'error',
{
destructuring: 'all',
},
],
quotes: [
'error',
'single',
{ allowTemplateLiterals: true, avoidEscape: true },
],
'space-unary-ops': [
'error',
{
overrides: {
'!': true,
yield: true,
},
},
],
'template-curly-spacing': [ 'error', 'always' ],
},
};
// It won't recognize the `babel.config.json` file used in the project until the upstream bug in `cosmiconfig` is fixed:
// https://github.com/davidtheclark/cosmiconfig/issues/246.
const result = cosmiconfigSync( 'babel' ).search();
if ( ! result || ! result.filepath ) {
config.parserOptions = {
...config.parserOptions,
requireConfigFile: false,
babelOptions: {
presets: [ require.resolve( '@wordpress/babel-preset-default' ) ],
},
};
}
module.exports = config;

12
node_modules/@wordpress/eslint-plugin/configs/i18n.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
module.exports = {
plugins: [ '@wordpress' ],
rules: {
'@wordpress/valid-sprintf': 'error',
'@wordpress/i18n-translator-comments': 'error',
'@wordpress/i18n-text-domain': 'error',
'@wordpress/i18n-no-collapsible-whitespace': 'error',
'@wordpress/i18n-no-placeholders-only': 'error',
'@wordpress/i18n-no-variables': 'error',
'@wordpress/i18n-ellipsis': 'error',
},
};

View File

@@ -0,0 +1 @@
module.exports = require( 'requireindex' )( __dirname );

153
node_modules/@wordpress/eslint-plugin/configs/jsdoc.js generated vendored Normal file
View File

@@ -0,0 +1,153 @@
/**
* External dependencies
*/
const globals = require( 'globals' );
/**
* The temporary list of types defined in Gutenberg which are allowed to avoid
* ESLint warnings. It should be removed once importing is going to be implemented
* in the tool which generates public APIs from JSDoc comments. Related issue to
* fix the root cause `@wordpress/docgen`:
* https://github.com/WordPress/gutenberg/issues/18045.
*/
const temporaryWordPressInternalTypes = [
'WPBlockChildren',
'WPBlockNode',
'WPBlockSelection',
'WPBlockSerializationOptions',
'WPBlock',
'WPBlockPattern',
'WPBlockType',
'WPBlockTypeIcon',
'WPBlockTypeIconRender',
'WPBlockTypeIconDescriptor',
'WPIcon',
// These two should be removed once we use the TS types from "react".
'Component',
'Element',
];
/**
* The temporary list of external types used in Gutenberg which are allowed
* to avoid ESLint warnings. It's similar to `wordpressInternalTypes` and it
* should be removed once the related issues is fixed:
* https://github.com/WordPress/gutenberg/issues/18045
*/
const temporaryExternalTypes = [ 'DOMHighResTimeStamp', 'espree' ];
/**
* Helpful utilities that are globally defined and known to the TypeScript compiler.
*
* @see http://www.typescriptlang.org/docs/handbook/utility-types.html
*/
const typescriptUtilityTypes = [
'ArrayLike',
'Exclude',
'Extract',
'InstanceType',
'Iterable',
'IterableIterator',
'NonNullable',
'Omit',
'Parameters',
'Partial',
'Pick',
'PromiseLike',
'Readonly',
'ReadonlyArray',
'ReadonlyMap',
'ReadonlySet',
'Record',
'Required',
'ReturnType',
'ThisType',
'unknown',
'never',
'NodeJS',
'AsyncIterableIterator',
'NodeRequire',
'true',
'false',
];
module.exports = {
extends: [ 'plugin:jsdoc/recommended' ],
settings: {
jsdoc: {
preferredTypes: {
object: 'Object',
},
tagNamePreference: {
returns: 'return',
yields: 'yield',
},
},
},
rules: {
'jsdoc/no-defaults': 'off',
'jsdoc/no-undefined-types': [
'error',
{
definedTypes: [
// Required to reference browser types because we don't have the `browser` environment enabled for the project.
// Here we filter out all browser globals that don't begin with an uppercase letter because those
// generally refer to window-level event listeners and are not a valid type to reference (e.g. `onclick`).
...Object.keys( globals.browser ).filter( ( k ) =>
/^[A-Z]/.test( k )
),
...typescriptUtilityTypes,
...temporaryWordPressInternalTypes,
...temporaryExternalTypes,
'void',
'JSX',
],
},
],
'jsdoc/require-jsdoc': 'off',
'jsdoc/require-param-description': 'off',
'jsdoc/require-returns': 'off',
'jsdoc/require-yields': 'off',
'jsdoc/tag-lines': [
1,
'any',
{
startLines: null,
endLines: 0,
applyToEndTag: false,
},
],
'jsdoc/no-multi-asterisks': [
'error',
{ preventAtMiddleLines: false },
],
'jsdoc/check-access': 'error',
'jsdoc/check-alignment': 'error',
'jsdoc/check-line-alignment': [
'error',
'always',
{
tags: [ 'param', 'arg', 'argument', 'property', 'prop' ],
preserveMainDescriptionPostDelimiter: true,
},
],
'jsdoc/check-param-names': 'error',
'jsdoc/check-property-names': 'error',
'jsdoc/check-tag-names': 'error',
'jsdoc/check-types': 'error',
'jsdoc/check-values': 'off',
'jsdoc/empty-tags': 'error',
'jsdoc/implements-on-classes': 'error',
'jsdoc/require-param': 'error',
'jsdoc/require-param-name': 'error',
'jsdoc/require-param-type': 'error',
'jsdoc/require-property': 'error',
'jsdoc/require-property-description': 'error',
'jsdoc/require-property-name': 'error',
'jsdoc/require-property-type': 'error',
'jsdoc/require-returns-check': 'error',
'jsdoc/require-returns-description': 'error',
'jsdoc/require-returns-type': 'error',
'jsdoc/valid-types': 'error',
},
};

View File

@@ -0,0 +1,17 @@
module.exports = {
rules: {
curly: 'error',
eqeqeq: 'error',
'no-caller': 'error',
'no-cond-assign': [ 'error', 'except-parens' ],
'no-eq-null': 'error',
'no-irregular-whitespace': 'error',
'no-trailing-spaces': 'error',
'no-undef': 'error',
'no-unused-expressions': 'error',
'no-unused-vars': [ 'error', { ignoreRestSiblings: true } ],
'one-var': [ 'error', 'always' ],
quotes: [ 'error', 'single' ],
'wrap-iife': [ 'error', 'any' ],
},
};

View File

@@ -0,0 +1,16 @@
module.exports = {
extends: [ 'plugin:jsx-a11y/recommended' ],
plugins: [ 'jsx-a11y' ],
rules: {
'jsx-a11y/label-has-associated-control': [
'error',
{
assert: 'htmlFor',
},
],
'jsx-a11y/media-has-caption': 'off',
'jsx-a11y/no-noninteractive-tabindex': 'off',
'jsx-a11y/role-has-required-aria-props': 'off',
'jsx-quotes': 'error',
},
};

45
node_modules/@wordpress/eslint-plugin/configs/react.js generated vendored Normal file
View File

@@ -0,0 +1,45 @@
module.exports = {
extends: [ 'plugin:react/recommended' ],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
settings: {
react: {
version: 'detect',
},
},
plugins: [ '@wordpress', 'react', 'react-hooks' ],
rules: {
'@wordpress/no-unused-vars-before-return': [
'error',
{
excludePattern: '^use',
},
],
'react/display-name': 'off',
'react/jsx-curly-spacing': [
'error',
{
when: 'always',
children: true,
},
],
'react/jsx-equals-spacing': 'error',
'react/jsx-indent': [ 'error', 'tab' ],
'react/jsx-indent-props': [ 'error', 'tab' ],
'react/jsx-key': 'error',
'react/jsx-tag-spacing': 'error',
'react/no-children-prop': 'off',
'react/prop-types': 'off',
'react/react-in-jsx-scope': 'off',
'react-hooks/exhaustive-deps': [
'warn',
{
additionalHooks: '^(useSelect|useSuspenseSelect)$',
},
],
'react-hooks/rules-of-hooks': 'error',
},
};

View File

@@ -0,0 +1,44 @@
// Exclude bundled WordPress packages from the list.
const wpPackagesRegExp = '^@wordpress/(?!(icons|interface|style-engine))';
const config = {
extends: [
require.resolve( './jsx-a11y.js' ),
require.resolve( './custom.js' ),
require.resolve( './react.js' ),
require.resolve( './esnext.js' ),
require.resolve( './i18n.js' ),
],
plugins: [ 'import' ],
env: {
node: true,
},
globals: {
window: true,
document: true,
SCRIPT_DEBUG: 'readonly',
wp: 'readonly',
},
settings: {
'import/internal-regex': wpPackagesRegExp,
'import/extensions': [ '.js', '.jsx' ],
},
rules: {
'import/no-extraneous-dependencies': [
'error',
{
peerDependencies: true,
},
],
'import/no-unresolved': [
'error',
{
ignore: [ wpPackagesRegExp ],
},
],
'import/default': 'warn',
'import/named': 'warn',
},
};
module.exports = config;

View File

@@ -0,0 +1,68 @@
/**
* External dependencies
*/
const { cosmiconfigSync } = require( 'cosmiconfig' );
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const { isPackageInstalled } = require( '../utils' );
const config = {
extends: [ require.resolve( './recommended-with-formatting.js' ) ],
};
if ( isPackageInstalled( 'prettier' ) ) {
config.extends.push( 'plugin:prettier/recommended' );
const { config: localPrettierConfig } =
cosmiconfigSync( 'prettier' ).search() || {};
const defaultPrettierConfig = require( '@wordpress/prettier-config' );
const prettierConfig = { ...defaultPrettierConfig, ...localPrettierConfig };
config.rules = {
'prettier/prettier': [ 'error', prettierConfig ],
// Prettier _disables_ this rule, but we want it!
// See https://github.com/prettier/eslint-config-prettier?tab=readme-ov-file#curly
// > This rule requires certain options.
// > …
// > If you like this rule, it can be used just fine with Prettier as long as you dont use the "multi-line" or "multi-or-nest" option.
curly: [ 'error', 'all' ],
};
}
if ( isPackageInstalled( 'typescript' ) ) {
config.settings = {
'import/resolver': {
node: {
extensions: [ '.js', '.jsx', '.ts', '.tsx' ],
},
},
};
config.extends.push( 'plugin:@typescript-eslint/eslint-recommended' );
config.ignorePatterns = [ '**/*.d.ts' ];
config.plugins = [ '@typescript-eslint' ];
config.overrides = [
{
files: [ '**/*.ts', '**/*.tsx' ],
parser: '@typescript-eslint/parser',
rules: {
'no-duplicate-imports': 'off',
'import/no-duplicates': 'error',
// Don't require redundant JSDoc types in TypeScript files.
'jsdoc/require-param-type': 'off',
'jsdoc/require-returns-type': 'off',
// Handled by TS itself.
'no-unused-vars': 'off',
// no-shadow doesn't work correctly in TS, so let's use a TS-dedicated version instead.
'no-shadow': 'off',
'@typescript-eslint/no-shadow': 'error',
},
},
];
}
module.exports = config;

View File

@@ -0,0 +1,11 @@
module.exports = {
extends: [ 'plugin:jest/recommended' ],
env: {
browser: true,
},
globals: {
browser: 'readonly',
page: 'readonly',
wp: 'readonly',
},
};

View File

@@ -0,0 +1,3 @@
module.exports = {
extends: [ 'plugin:playwright/recommended' ],
};

View File

@@ -0,0 +1,9 @@
module.exports = {
extends: [ 'plugin:jest/recommended' ],
rules: {
'jest/expect-expect': [
'error',
{ assertFunctionNames: [ 'expect', 'measurePerformance' ] },
],
},
};

4
node_modules/@wordpress/eslint-plugin/index.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
module.exports = {
configs: require( './configs' ),
rules: require( './rules' ),
};

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 David Clark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,581 @@
# cosmiconfig
[![Build Status](https://img.shields.io/travis/davidtheclark/cosmiconfig/main.svg?label=unix%20build)](https://travis-ci.org/davidtheclark/cosmiconfig) [![Build status](https://img.shields.io/appveyor/ci/davidtheclark/cosmiconfig/main.svg?label=windows%20build)](https://ci.appveyor.com/project/davidtheclark/cosmiconfig/branch/main)
[![codecov](https://codecov.io/gh/davidtheclark/cosmiconfig/branch/main/graph/badge.svg)](https://codecov.io/gh/davidtheclark/cosmiconfig)
Cosmiconfig searches for and loads configuration for your program.
It features smart defaults based on conventional expectations in the JavaScript ecosystem.
But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load.
By default, Cosmiconfig will start where you tell it to start and search up the directory tree for the following:
- a `package.json` property
- a JSON or YAML, extensionless "rc file"
- an "rc file" with the extensions `.json`, `.yaml`, `.yml`, `.js`, or `.cjs`
- any of the above two inside a `.config` subdirectory
- a `.config.js` or `.config.cjs` CommonJS module
For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:
- a `myapp` property in `package.json`
- a `.myapprc` file in JSON or YAML format
- a `.myapprc.json`, `.myapprc.yaml`, `.myapprc.yml`, `.myapprc.js`, or `.myapprc.cjs` file
- a `myapprc`, `myapprc.json`, `myapprc.yaml`, `myapprc.yml`, `myapprc.js` or `myapprc.cjs` file inside a `.config` subdirectory`
- a `myapp.config.js` or `myapp.config.cjs` CommonJS module exporting an object
Cosmiconfig continues to search up the directory tree, checking each of these places in each directory, until it finds some acceptable configuration (or hits the home directory).
## Table of contents
- [Installation](#installation)
- [Usage](#usage)
- [Result](#result)
- [Asynchronous API](#asynchronous-api)
- [cosmiconfig()](#cosmiconfig-1)
- [explorer.search()](#explorersearch)
- [explorer.load()](#explorerload)
- [explorer.clearLoadCache()](#explorerclearloadcache)
- [explorer.clearSearchCache()](#explorerclearsearchcache)
- [explorer.clearCaches()](#explorerclearcaches)
- [Synchronous API](#synchronous-api)
- [cosmiconfigSync()](#cosmiconfigsync)
- [explorerSync.search()](#explorersyncsearch)
- [explorerSync.load()](#explorersyncload)
- [explorerSync.clearLoadCache()](#explorersyncclearloadcache)
- [explorerSync.clearSearchCache()](#explorersyncclearsearchcache)
- [explorerSync.clearCaches()](#explorersyncclearcaches)
- [cosmiconfigOptions](#cosmiconfigoptions)
- [searchPlaces](#searchplaces)
- [loaders](#loaders)
- [packageProp](#packageprop)
- [stopDir](#stopdir)
- [cache](#cache)
- [transform](#transform)
- [ignoreEmptySearchPlaces](#ignoreemptysearchplaces)
- [Caching](#caching)
- [Differences from rc](#differences-from-rc)
- [Contributing & Development](#contributing--development)
## Installation
```
npm install cosmiconfig
```
Tested in Node 10+.
## Usage
Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file.
```js
const { cosmiconfig, cosmiconfigSync } = require('cosmiconfig');
// ...
const explorer = cosmiconfig(moduleName);
// Search for a configuration by walking up directories.
// See documentation for search, below.
explorer.search()
.then((result) => {
// result.config is the parsed configuration object.
// result.filepath is the path to the config file that was found.
// result.isEmpty is true if there was nothing to parse in the config file.
})
.catch((error) => {
// Do something constructive.
});
// Load a configuration directly when you know where it should be.
// The result object is the same as for search.
// See documentation for load, below.
explorer.load(pathToConfig).then(..);
// You can also search and load synchronously.
const explorerSync = cosmiconfigSync(moduleName);
const searchedFor = explorerSync.search();
const loaded = explorerSync.load(pathToConfig);
```
## Result
The result object you get from `search` or `load` has the following properties:
- **config:** The parsed configuration object. `undefined` if the file is empty.
- **filepath:** The path to the configuration file that was found.
- **isEmpty:** `true` if the configuration file is empty. This property will not be present if the configuration file is not empty.
## Asynchronous API
### cosmiconfig()
```js
const { cosmiconfig } = require('cosmiconfig');
const explorer = cosmiconfig(moduleName[, cosmiconfigOptions])
```
Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
#### moduleName
Type: `string`. **Required.**
Your module name. This is used to create the default [`searchPlaces`] and [`packageProp`].
If your [`searchPlaces`] value will include files, as it does by default (e.g. `${moduleName}rc`), your `moduleName` must consist of characters allowed in filenames. That means you should not copy scoped package names, such as `@my-org/my-package`, directly into `moduleName`.
**[`cosmiconfigOptions`] are documented below.**
You may not need them, and should first read about the functions you'll use.
### explorer.search()
```js
explorer.search([searchFrom]).then(result => {..})
```
Searches for a configuration file. Returns a Promise that resolves with a [result] or with `null`, if no configuration file is found.
You can do the same thing synchronously with [`explorerSync.search()`].
Let's say your module name is `goldengrahams` so you initialized with `const explorer = cosmiconfig('goldengrahams');`.
Here's how your default [`search()`] will work:
- Starting from `process.cwd()` (or some other directory defined by the `searchFrom` argument to [`search()`]), look for configuration objects in the following places:
1. A `goldengrahams` property in a `package.json` file.
2. A `.goldengrahamsrc` file with JSON or YAML syntax.
3. A `.goldengrahamsrc.json`, `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, `.goldengrahamsrc.js`, or `.goldengrahamsrc.cjs` file.
4. A `goldengrahamsrc`, `goldengrahamsrc.json`, `goldengrahamsrc.yaml`, `goldengrahamsrc.yml`, `goldengrahamsrc.js`, or `goldengrahamsrc.cjs` file in the `.config` subdirectory.
5. A `goldengrahams.config.js` or `goldengrahams.config.cjs` CommonJS module exporting the object.
- If none of those searches reveal a configuration object, move up one directory level and try again.
So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory.
- Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option [`stopDir`]).
- If at any point a parsable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`explorerSync.search()`], the [result] is returned).
- If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`explorerSync.search()`], `null` is returned).
- If a configuration object is found *but is malformed* (causing a parsing error), the [`search()`] Promise rejects with that error (so you should `.catch()` it). (Or, with [`explorerSync.search()`], the error is thrown.)
**If you know exactly where your configuration file should be, you can use [`load()`], instead.**
**The search process is highly customizable.**
Use the cosmiconfig options [`searchPlaces`] and [`loaders`] to precisely define where you want to look for configurations and how you want to load them.
#### searchFrom
Type: `string`.
Default: `process.cwd()`.
A filename.
[`search()`] will start its search here.
If the value is a directory, that's where the search starts.
If it's a file, the search starts in that file's directory.
### explorer.load()
```js
explorer.load(loadPath).then(result => {..})
```
Loads a configuration file. Returns a Promise that resolves with a [result] or rejects with an error (if the file does not exist or cannot be loaded).
Use `load` if you already know where the configuration file is and you just need to load it.
```js
explorer.load('load/this/file.json'); // Tries to load load/this/file.json.
```
If you load a `package.json` file, the result will be derived from whatever property is specified as your [`packageProp`].
You can do the same thing synchronously with [`explorerSync.load()`].
### explorer.clearLoadCache()
Clears the cache used in [`load()`].
### explorer.clearSearchCache()
Clears the cache used in [`search()`].
### explorer.clearCaches()
Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
## Synchronous API
### cosmiconfigSync()
```js
const { cosmiconfigSync } = require('cosmiconfig');
const explorerSync = cosmiconfigSync(moduleName[, cosmiconfigOptions])
```
Creates a *synchronous* cosmiconfig instance ("explorerSync") configured according to the arguments, and initializes its caches.
See [`cosmiconfig()`].
### explorerSync.search()
```js
const result = explorerSync.search([searchFrom]);
```
Synchronous version of [`explorer.search()`].
Returns a [result] or `null`.
### explorerSync.load()
```js
const result = explorerSync.load(loadPath);
```
Synchronous version of [`explorer.load()`].
Returns a [result].
### explorerSync.clearLoadCache()
Clears the cache used in [`load()`].
### explorerSync.clearSearchCache()
Clears the cache used in [`search()`].
### explorerSync.clearCaches()
Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
## cosmiconfigOptions
Type: `Object`.
Possible options are documented below.
### searchPlaces
Type: `Array<string>`.
Default: See below.
An array of places that [`search()`] will check in each directory as it moves up the directory tree.
Each place is relative to the directory being searched, and the places are checked in the specified order.
**Default `searchPlaces`:**
```js
[
'package.json',
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`.${moduleName}rc.cjs`,
`.config/${moduleName}rc`,
`.config/${moduleName}rc.json`,
`.config/${moduleName}rc.yaml`,
`.config/${moduleName}rc.yml`,
`.config/${moduleName}rc.js`,
`.config/${moduleName}rc.cjs`,
`${moduleName}.config.js`,
`${moduleName}.config.cjs`,
]
```
Create your own array to search more, fewer, or altogether different places.
Every item in `searchPlaces` needs to have a loader in [`loaders`] that corresponds to its extension.
(Common extensions are covered by default loaders.)
Read more about [`loaders`] below.
`package.json` is a special value: When it is included in `searchPlaces`, Cosmiconfig will always parse it as JSON and load a property within it, not the whole file.
That property is defined with the [`packageProp`] option, and defaults to your module name.
Examples, with a module named `porgy`:
```js
// Disallow extensions on rc files:
[
'package.json',
'.porgyrc',
'porgy.config.js'
]
// ESLint searches for configuration in these places:
[
'.eslintrc.js',
'.eslintrc.yaml',
'.eslintrc.yml',
'.eslintrc.json',
'.eslintrc',
'package.json'
]
// Babel looks in fewer places:
[
'package.json',
'.babelrc'
]
// Maybe you want to look for a wide variety of JS flavors:
[
'porgy.config.js',
'porgy.config.mjs',
'porgy.config.ts',
'porgy.config.coffee'
]
// ^^ You will need to designate custom loaders to tell
// Cosmiconfig how to handle these special JS flavors.
// Look within a .config/ subdirectory of every searched directory:
[
'package.json',
'.porgyrc',
'.config/.porgyrc',
'.porgyrc.json',
'.config/.porgyrc.json'
]
```
### loaders
Type: `Object`.
Default: See below.
An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions.
Cosmiconfig exposes its default loaders on a named export `defaultLoaders`.
**Default `loaders`:**
```js
const { defaultLoaders } = require('cosmiconfig');
console.log(Object.entries(defaultLoaders))
// [
// [ '.cjs', [Function: loadJs] ],
// [ '.js', [Function: loadJs] ],
// [ '.json', [Function: loadJson] ],
// [ '.yaml', [Function: loadYaml] ],
// [ '.yml', [Function: loadYaml] ],
// [ 'noExt', [Function: loadYaml] ]
// ]
```
(YAML is a superset of JSON; which means YAML parsers can parse JSON; which is how extensionless files can be either YAML *or* JSON with only one parser.)
**If you provide a `loaders` object, your object will be *merged* with the defaults.**
So you can override one or two without having to override them all.
**Keys in `loaders`** are extensions (starting with a period), or `noExt` to specify the loader for files *without* extensions, like `.myapprc`.
**Values in `loaders`** are a loader function (described below) whose values are loader functions.
**The most common use case for custom loaders value is to load extensionless `rc` files as strict JSON**, instead of JSON *or* YAML (the default).
To accomplish that, provide the following `loaders` value:
```js
{
noExt: defaultLoaders['.json']
}
```
If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function or use one from NPM if it exists.
**Third-party loaders:**
- [cosmiconfig-typescript-loader](https://github.com/codex-/cosmiconfig-typescript-loader)
**Use cases for custom loader function:**
- Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML.
- Allow ES2015 modules from `.mjs` configuration files.
- Parse JS files with Babel before deriving the configuration.
**Custom loader functions** have the following signature:
```js
// Sync
(filepath: string, content: string) => Object | null
// Async
(filepath: string, content: string) => Object | null | Promise<Object | null>
```
Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content.
Do whatever you need to, and return either a configuration object or `null` (or, for async-only loaders, a Promise that resolves with one of those).
`null` indicates that no real configuration was found and the search should continue.
A few things to note:
- If you use a custom loader, be aware of whether it's sync or async: you cannot use async customer loaders with the sync API ([`cosmiconfigSync()`]).
- **Special JS syntax can also be handled by using a `require` hook**, because `defaultLoaders['.js']` just uses `require`.
Whether you use custom loaders or a `require` hook is up to you.
Examples:
```js
// Allow JSON5 syntax:
{
'.json': json5Loader
}
// Allow a special configuration syntax of your own creation:
{
'.special': specialLoader
}
// Allow many flavors of JS, using custom loaders:
{
'.mjs': esmLoader,
'.ts': typeScriptLoader,
'.coffee': coffeeScriptLoader
}
// Allow many flavors of JS but rely on require hooks:
{
'.mjs': defaultLoaders['.js'],
'.ts': defaultLoaders['.js'],
'.coffee': defaultLoaders['.js']
}
```
### packageProp
Type: `string | Array<string>`.
Default: `` `${moduleName}` ``.
Name of the property in `package.json` to look for.
Use a period-delimited string or an array of strings to describe a path to nested properties.
For example, the value `'configs.myPackage'` or `['configs', 'myPackage']` will get you the `"myPackage"` value in a `package.json` like this:
```json
{
"configs": {
"myPackage": {..}
}
}
```
If nested property names within the path include periods, you need to use an array of strings. For example, the value `['configs', 'foo.bar', 'baz']` will get you the `"baz"` value in a `package.json` like this:
```json
{
"configs": {
"foo.bar": {
"baz": {..}
}
}
}
```
If a string includes period but corresponds to a top-level property name, it will not be interpreted as a period-delimited path. For example, the value `'one.two'` will get you the `"three"` value in a `package.json` like this:
```json
{
"one.two": "three",
"one": {
"two": "four"
}
}
```
### stopDir
Type: `string`.
Default: Absolute path to your home directory.
Directory where the search will stop.
### cache
Type: `boolean`.
Default: `true`.
If `false`, no caches will be used.
Read more about ["Caching"](#caching) below.
### transform
Type: `(Result) => Promise<Result> | Result`.
A function that transforms the parsed configuration. Receives the [result].
If using [`search()`] or [`load()`] \(which are async), the transform function can return the transformed result or return a Promise that resolves with the transformed result.
If using `cosmiconfigSync`, [`search()`] or [`load()`], the function must be synchronous and return the transformed result.
The reason you might use this option — instead of simply applying your transform function some other way — is that *the transformed result will be cached*. If your transformation involves additional filesystem I/O or other potentially slow processing, you can use this option to avoid repeating those steps every time a given configuration is searched or loaded.
### ignoreEmptySearchPlaces
Type: `boolean`.
Default: `true`.
By default, if [`search()`] encounters an empty file (containing nothing but whitespace) in one of the [`searchPlaces`], it will ignore the empty file and move on.
If you'd like to load empty configuration files, instead, set this option to `false`.
Why might you want to load empty configuration files?
If you want to throw an error, or if an empty configuration file means something to your program.
## Caching
As of v2, cosmiconfig uses caching to reduce the need for repetitious reading of the filesystem or expensive transforms. Every new cosmiconfig instance (created with `cosmiconfig()`) has its own caches.
To avoid or work around caching, you can do the following:
- Set the `cosmiconfig` option [`cache`] to `false`.
- Use the cache-clearing methods [`clearLoadCache()`], [`clearSearchCache()`], and [`clearCaches()`].
- Create separate instances of cosmiconfig (separate "explorers").
## Differences from [rc](https://github.com/dominictarr/rc)
[rc](https://github.com/dominictarr/rc) serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others:
- Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions.
- Built-in support for JSON, YAML, and CommonJS formats.
- Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically.
- Options.
- Asynchronous by default (though can be run synchronously).
## Contributing & Development
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
And please do participate!
[result]: #result
[`load()`]: #explorerload
[`search()`]: #explorersearch
[`clearloadcache()`]: #explorerclearloadcache
[`clearsearchcache()`]: #explorerclearsearchcache
[`cosmiconfig()`]: #cosmiconfig
[`cosmiconfigSync()`]: #cosmiconfigsync
[`clearcaches()`]: #explorerclearcaches
[`packageprop`]: #packageprop
[`cache`]: #cache
[`stopdir`]: #stopdir
[`searchplaces`]: #searchplaces
[`loaders`]: #loaders
[`cosmiconfigoptions`]: #cosmiconfigoptions
[`explorerSync.search()`]: #explorersyncsearch
[`explorerSync.load()`]: #explorersyncload
[`explorer.search()`]: #explorersearch
[`explorer.load()`]: #explorerload

View File

@@ -0,0 +1,14 @@
import { ExplorerBase } from './ExplorerBase';
import { CosmiconfigResult, ExplorerOptions } from './types';
declare class Explorer extends ExplorerBase<ExplorerOptions> {
constructor(options: ExplorerOptions);
search(searchFrom?: string): Promise<CosmiconfigResult>;
private searchFromDirectory;
private searchDirectory;
private loadSearchPlace;
private loadFileContent;
private createCosmiconfigResult;
load(filepath: string): Promise<CosmiconfigResult>;
}
export { Explorer };
//# sourceMappingURL=Explorer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Explorer.d.ts","sourceRoot":"","sources":["../src/Explorer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAI9C,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAqB,MAAM,SAAS,CAAC;AAEhF,cAAM,QAAS,SAAQ,YAAY,CAAC,eAAe,CAAC;gBAC/B,OAAO,EAAE,eAAe;IAI9B,MAAM,CACjB,UAAU,GAAE,MAAsB,GACjC,OAAO,CAAC,iBAAiB,CAAC;YAOf,mBAAmB;YAuBnB,eAAe;YAaf,eAAe;YAYf,eAAe;YAef,uBAAuB;IAUxB,IAAI,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;CAyBhE;AAED,OAAO,EAAE,QAAQ,EAAE,CAAC"}

View File

@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Explorer = void 0;
var _path = _interopRequireDefault(require("path"));
var _ExplorerBase = require("./ExplorerBase");
var _readFile = require("./readFile");
var _cacheWrapper = require("./cacheWrapper");
var _getDirectory = require("./getDirectory");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Explorer extends _ExplorerBase.ExplorerBase {
constructor(options) {
super(options);
}
async search(searchFrom = process.cwd()) {
const startDirectory = await (0, _getDirectory.getDirectory)(searchFrom);
const result = await this.searchFromDirectory(startDirectory);
return result;
}
async searchFromDirectory(dir) {
const absoluteDir = _path.default.resolve(process.cwd(), dir);
const run = async () => {
const result = await this.searchDirectory(absoluteDir);
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectory(nextDir);
}
const transformResult = await this.config.transform(result);
return transformResult;
};
if (this.searchCache) {
return (0, _cacheWrapper.cacheWrapper)(this.searchCache, absoluteDir, run);
}
return run();
}
async searchDirectory(dir) {
for await (const place of this.config.searchPlaces) {
const placeResult = await this.loadSearchPlace(dir, place);
if (this.shouldSearchStopWithResult(placeResult) === true) {
return placeResult;
}
} // config not found
return null;
}
async loadSearchPlace(dir, place) {
const filepath = _path.default.join(dir, place);
const fileContents = await (0, _readFile.readFile)(filepath);
const result = await this.createCosmiconfigResult(filepath, fileContents);
return result;
}
async loadFileContent(filepath, content) {
if (content === null) {
return null;
}
if (content.trim() === '') {
return undefined;
}
const loader = this.getLoaderEntryForFile(filepath);
const loaderResult = await loader(filepath, content);
return loaderResult;
}
async createCosmiconfigResult(filepath, content) {
const fileContent = await this.loadFileContent(filepath, content);
const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
return result;
}
async load(filepath) {
this.validateFilePath(filepath);
const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
const runLoad = async () => {
const fileContents = await (0, _readFile.readFile)(absoluteFilePath, {
throwNotFound: true
});
const result = await this.createCosmiconfigResult(absoluteFilePath, fileContents);
const transformResult = await this.config.transform(result);
return transformResult;
};
if (this.loadCache) {
return (0, _cacheWrapper.cacheWrapper)(this.loadCache, absoluteFilePath, runLoad);
}
return runLoad();
}
}
exports.Explorer = Explorer;
//# sourceMappingURL=Explorer.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import { CosmiconfigResult, ExplorerOptions, ExplorerOptionsSync, Cache, LoadedFileContent } from './types';
import { Loader } from './index';
declare class ExplorerBase<T extends ExplorerOptions | ExplorerOptionsSync> {
protected readonly loadCache?: Cache;
protected readonly searchCache?: Cache;
protected readonly config: T;
constructor(options: T);
clearLoadCache(): void;
clearSearchCache(): void;
clearCaches(): void;
private validateConfig;
protected shouldSearchStopWithResult(result: CosmiconfigResult): boolean;
protected nextDirectoryToSearch(currentDir: string, currentResult: CosmiconfigResult): string | null;
private loadPackageProp;
protected getLoaderEntryForFile(filepath: string): Loader;
protected loadedContentToCosmiconfigResult(filepath: string, loadedContent: LoadedFileContent): CosmiconfigResult;
protected validateFilePath(filepath: string): void;
}
declare function getExtensionDescription(filepath: string): string;
export { ExplorerBase, getExtensionDescription };
//# sourceMappingURL=ExplorerBase.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExplorerBase.d.ts","sourceRoot":"","sources":["../src/ExplorerBase.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACnB,KAAK,EACL,iBAAiB,EAClB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,cAAM,YAAY,CAAC,CAAC,SAAS,eAAe,GAAG,mBAAmB;IAChE,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC;IACrC,SAAS,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC;IACvC,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;gBAEV,OAAO,EAAE,CAAC;IAUtB,cAAc,IAAI,IAAI;IAMtB,gBAAgB,IAAI,IAAI;IAMxB,WAAW,IAAI,IAAI;IAK1B,OAAO,CAAC,cAAc;IAwBtB,SAAS,CAAC,0BAA0B,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO;IAMxE,SAAS,CAAC,qBAAqB,CAC7B,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,iBAAiB,GAC/B,MAAM,GAAG,IAAI;IAWhB,OAAO,CAAC,eAAe;IASvB,SAAS,CAAC,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM;IAmBzD,SAAS,CAAC,gCAAgC,CACxC,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,iBAAiB,GAC/B,iBAAiB;IAUpB,SAAS,CAAC,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;CAKnD;AAMD,iBAAS,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGzD;AAED,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAE,CAAC"}

View File

@@ -0,0 +1,142 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ExplorerBase = void 0;
exports.getExtensionDescription = getExtensionDescription;
var _path = _interopRequireDefault(require("path"));
var _loaders = require("./loaders");
var _getPropertyByPath = require("./getPropertyByPath");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class ExplorerBase {
constructor(options) {
if (options.cache === true) {
this.loadCache = new Map();
this.searchCache = new Map();
}
this.config = options;
this.validateConfig();
}
clearLoadCache() {
if (this.loadCache) {
this.loadCache.clear();
}
}
clearSearchCache() {
if (this.searchCache) {
this.searchCache.clear();
}
}
clearCaches() {
this.clearLoadCache();
this.clearSearchCache();
}
validateConfig() {
const config = this.config;
config.searchPlaces.forEach(place => {
const loaderKey = _path.default.extname(place) || 'noExt';
const loader = config.loaders[loaderKey];
if (!loader) {
throw new Error(`No loader specified for ${getExtensionDescription(place)}, so searchPlaces item "${place}" is invalid`);
}
if (typeof loader !== 'function') {
throw new Error(`loader for ${getExtensionDescription(place)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
}
});
}
shouldSearchStopWithResult(result) {
if (result === null) return false;
if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
return true;
}
nextDirectoryToSearch(currentDir, currentResult) {
if (this.shouldSearchStopWithResult(currentResult)) {
return null;
}
const nextDir = nextDirUp(currentDir);
if (nextDir === currentDir || currentDir === this.config.stopDir) {
return null;
}
return nextDir;
}
loadPackageProp(filepath, content) {
const parsedContent = _loaders.loaders.loadJson(filepath, content);
const packagePropValue = (0, _getPropertyByPath.getPropertyByPath)(parsedContent, this.config.packageProp);
return packagePropValue || null;
}
getLoaderEntryForFile(filepath) {
if (_path.default.basename(filepath) === 'package.json') {
const loader = this.loadPackageProp.bind(this);
return loader;
}
const loaderKey = _path.default.extname(filepath) || 'noExt';
const loader = this.config.loaders[loaderKey];
if (!loader) {
throw new Error(`No loader specified for ${getExtensionDescription(filepath)}`);
}
return loader;
}
loadedContentToCosmiconfigResult(filepath, loadedContent) {
if (loadedContent === null) {
return null;
}
if (loadedContent === undefined) {
return {
filepath,
config: undefined,
isEmpty: true
};
}
return {
config: loadedContent,
filepath
};
}
validateFilePath(filepath) {
if (!filepath) {
throw new Error('load must pass a non-empty string');
}
}
}
exports.ExplorerBase = ExplorerBase;
function nextDirUp(dir) {
return _path.default.dirname(dir);
}
function getExtensionDescription(filepath) {
const ext = _path.default.extname(filepath);
return ext ? `extension "${ext}"` : 'files without extensions';
}
//# sourceMappingURL=ExplorerBase.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,14 @@
import { ExplorerBase } from './ExplorerBase';
import { CosmiconfigResult, ExplorerOptionsSync } from './types';
declare class ExplorerSync extends ExplorerBase<ExplorerOptionsSync> {
constructor(options: ExplorerOptionsSync);
searchSync(searchFrom?: string): CosmiconfigResult;
private searchFromDirectorySync;
private searchDirectorySync;
private loadSearchPlaceSync;
private loadFileContentSync;
private createCosmiconfigResultSync;
loadSync(filepath: string): CosmiconfigResult;
}
export { ExplorerSync };
//# sourceMappingURL=ExplorerSync.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExplorerSync.d.ts","sourceRoot":"","sources":["../src/ExplorerSync.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAI9C,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EAEpB,MAAM,SAAS,CAAC;AAEjB,cAAM,YAAa,SAAQ,YAAY,CAAC,mBAAmB,CAAC;gBACvC,OAAO,EAAE,mBAAmB;IAIxC,UAAU,CAAC,UAAU,GAAE,MAAsB,GAAG,iBAAiB;IAOxE,OAAO,CAAC,uBAAuB;IAuB/B,OAAO,CAAC,mBAAmB;IAa3B,OAAO,CAAC,mBAAmB;IAS3B,OAAO,CAAC,mBAAmB;IAgB3B,OAAO,CAAC,2BAA2B;IAU5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB;CAsBrD;AAED,OAAO,EAAE,YAAY,EAAE,CAAC"}

View File

@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ExplorerSync = void 0;
var _path = _interopRequireDefault(require("path"));
var _ExplorerBase = require("./ExplorerBase");
var _readFile = require("./readFile");
var _cacheWrapper = require("./cacheWrapper");
var _getDirectory = require("./getDirectory");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class ExplorerSync extends _ExplorerBase.ExplorerBase {
constructor(options) {
super(options);
}
searchSync(searchFrom = process.cwd()) {
const startDirectory = (0, _getDirectory.getDirectorySync)(searchFrom);
const result = this.searchFromDirectorySync(startDirectory);
return result;
}
searchFromDirectorySync(dir) {
const absoluteDir = _path.default.resolve(process.cwd(), dir);
const run = () => {
const result = this.searchDirectorySync(absoluteDir);
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectorySync(nextDir);
}
const transformResult = this.config.transform(result);
return transformResult;
};
if (this.searchCache) {
return (0, _cacheWrapper.cacheWrapperSync)(this.searchCache, absoluteDir, run);
}
return run();
}
searchDirectorySync(dir) {
for (const place of this.config.searchPlaces) {
const placeResult = this.loadSearchPlaceSync(dir, place);
if (this.shouldSearchStopWithResult(placeResult) === true) {
return placeResult;
}
} // config not found
return null;
}
loadSearchPlaceSync(dir, place) {
const filepath = _path.default.join(dir, place);
const content = (0, _readFile.readFileSync)(filepath);
const result = this.createCosmiconfigResultSync(filepath, content);
return result;
}
loadFileContentSync(filepath, content) {
if (content === null) {
return null;
}
if (content.trim() === '') {
return undefined;
}
const loader = this.getLoaderEntryForFile(filepath);
const loaderResult = loader(filepath, content);
return loaderResult;
}
createCosmiconfigResultSync(filepath, content) {
const fileContent = this.loadFileContentSync(filepath, content);
const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
return result;
}
loadSync(filepath) {
this.validateFilePath(filepath);
const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
const runLoadSync = () => {
const content = (0, _readFile.readFileSync)(absoluteFilePath, {
throwNotFound: true
});
const cosmiconfigResult = this.createCosmiconfigResultSync(absoluteFilePath, content);
const transformResult = this.config.transform(cosmiconfigResult);
return transformResult;
};
if (this.loadCache) {
return (0, _cacheWrapper.cacheWrapperSync)(this.loadCache, absoluteFilePath, runLoadSync);
}
return runLoadSync();
}
}
exports.ExplorerSync = ExplorerSync;
//# sourceMappingURL=ExplorerSync.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
import { Cache, CosmiconfigResult } from './types';
declare function cacheWrapper(cache: Cache, key: string, fn: () => Promise<CosmiconfigResult>): Promise<CosmiconfigResult>;
declare function cacheWrapperSync(cache: Cache, key: string, fn: () => CosmiconfigResult): CosmiconfigResult;
export { cacheWrapper, cacheWrapperSync };
//# sourceMappingURL=cacheWrapper.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cacheWrapper.d.ts","sourceRoot":"","sources":["../src/cacheWrapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEnD,iBAAe,YAAY,CACzB,KAAK,EAAE,KAAK,EACZ,GAAG,EAAE,MAAM,EACX,EAAE,EAAE,MAAM,OAAO,CAAC,iBAAiB,CAAC,GACnC,OAAO,CAAC,iBAAiB,CAAC,CAS5B;AAED,iBAAS,gBAAgB,CACvB,KAAK,EAAE,KAAK,EACZ,GAAG,EAAE,MAAM,EACX,EAAE,EAAE,MAAM,iBAAiB,GAC1B,iBAAiB,CASnB;AAED,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,CAAC"}

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cacheWrapper = cacheWrapper;
exports.cacheWrapperSync = cacheWrapperSync;
async function cacheWrapper(cache, key, fn) {
const cached = cache.get(key);
if (cached !== undefined) {
return cached;
}
const result = await fn();
cache.set(key, result);
return result;
}
function cacheWrapperSync(cache, key, fn) {
const cached = cache.get(key);
if (cached !== undefined) {
return cached;
}
const result = fn();
cache.set(key, result);
return result;
}
//# sourceMappingURL=cacheWrapper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/cacheWrapper.ts"],"names":["cacheWrapper","cache","key","fn","cached","get","undefined","result","set","cacheWrapperSync"],"mappings":";;;;;;;;AAEA,eAAeA,YAAf,CACEC,KADF,EAEEC,GAFF,EAGEC,EAHF,EAI8B;AAC5B,QAAMC,MAAM,GAAGH,KAAK,CAACI,GAAN,CAAUH,GAAV,CAAf;;AACA,MAAIE,MAAM,KAAKE,SAAf,EAA0B;AACxB,WAAOF,MAAP;AACD;;AAED,QAAMG,MAAM,GAAG,MAAMJ,EAAE,EAAvB;AACAF,EAAAA,KAAK,CAACO,GAAN,CAAUN,GAAV,EAAeK,MAAf;AACA,SAAOA,MAAP;AACD;;AAED,SAASE,gBAAT,CACER,KADF,EAEEC,GAFF,EAGEC,EAHF,EAIqB;AACnB,QAAMC,MAAM,GAAGH,KAAK,CAACI,GAAN,CAAUH,GAAV,CAAf;;AACA,MAAIE,MAAM,KAAKE,SAAf,EAA0B;AACxB,WAAOF,MAAP;AACD;;AAED,QAAMG,MAAM,GAAGJ,EAAE,EAAjB;AACAF,EAAAA,KAAK,CAACO,GAAN,CAAUN,GAAV,EAAeK,MAAf;AACA,SAAOA,MAAP;AACD","sourcesContent":["import { Cache, CosmiconfigResult } from './types';\n\nasync function cacheWrapper(\n cache: Cache,\n key: string,\n fn: () => Promise<CosmiconfigResult>,\n): Promise<CosmiconfigResult> {\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n\n const result = await fn();\n cache.set(key, result);\n return result;\n}\n\nfunction cacheWrapperSync(\n cache: Cache,\n key: string,\n fn: () => CosmiconfigResult,\n): CosmiconfigResult {\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n\n const result = fn();\n cache.set(key, result);\n return result;\n}\n\nexport { cacheWrapper, cacheWrapperSync };\n"],"file":"cacheWrapper.js"}

View File

@@ -0,0 +1,4 @@
declare function getDirectory(filepath: string): Promise<string>;
declare function getDirectorySync(filepath: string): string;
export { getDirectory, getDirectorySync };
//# sourceMappingURL=getDirectory.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getDirectory.d.ts","sourceRoot":"","sources":["../src/getDirectory.ts"],"names":[],"mappings":"AAGA,iBAAe,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAU7D;AAED,iBAAS,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAUlD;AAED,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,CAAC"}

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getDirectory = getDirectory;
exports.getDirectorySync = getDirectorySync;
var _path = _interopRequireDefault(require("path"));
var _pathType = require("path-type");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
async function getDirectory(filepath) {
const filePathIsDirectory = await (0, _pathType.isDirectory)(filepath);
if (filePathIsDirectory === true) {
return filepath;
}
const directory = _path.default.dirname(filepath);
return directory;
}
function getDirectorySync(filepath) {
const filePathIsDirectory = (0, _pathType.isDirectorySync)(filepath);
if (filePathIsDirectory === true) {
return filepath;
}
const directory = _path.default.dirname(filepath);
return directory;
}
//# sourceMappingURL=getDirectory.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/getDirectory.ts"],"names":["getDirectory","filepath","filePathIsDirectory","directory","path","dirname","getDirectorySync"],"mappings":";;;;;;;;AAAA;;AACA;;;;AAEA,eAAeA,YAAf,CAA4BC,QAA5B,EAA+D;AAC7D,QAAMC,mBAAmB,GAAG,MAAM,2BAAYD,QAAZ,CAAlC;;AAEA,MAAIC,mBAAmB,KAAK,IAA5B,EAAkC;AAChC,WAAOD,QAAP;AACD;;AAED,QAAME,SAAS,GAAGC,cAAKC,OAAL,CAAaJ,QAAb,CAAlB;;AAEA,SAAOE,SAAP;AACD;;AAED,SAASG,gBAAT,CAA0BL,QAA1B,EAAoD;AAClD,QAAMC,mBAAmB,GAAG,+BAAgBD,QAAhB,CAA5B;;AAEA,MAAIC,mBAAmB,KAAK,IAA5B,EAAkC;AAChC,WAAOD,QAAP;AACD;;AAED,QAAME,SAAS,GAAGC,cAAKC,OAAL,CAAaJ,QAAb,CAAlB;;AAEA,SAAOE,SAAP;AACD","sourcesContent":["import path from 'path';\nimport { isDirectory, isDirectorySync } from 'path-type';\n\nasync function getDirectory(filepath: string): Promise<string> {\n const filePathIsDirectory = await isDirectory(filepath);\n\n if (filePathIsDirectory === true) {\n return filepath;\n }\n\n const directory = path.dirname(filepath);\n\n return directory;\n}\n\nfunction getDirectorySync(filepath: string): string {\n const filePathIsDirectory = isDirectorySync(filepath);\n\n if (filePathIsDirectory === true) {\n return filepath;\n }\n\n const directory = path.dirname(filepath);\n\n return directory;\n}\n\nexport { getDirectory, getDirectorySync };\n"],"file":"getDirectory.js"}

View File

@@ -0,0 +1,5 @@
declare function getPropertyByPath(source: {
[key: string]: unknown;
}, path: string | Array<string>): unknown;
export { getPropertyByPath };
//# sourceMappingURL=getPropertyByPath.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getPropertyByPath.d.ts","sourceRoot":"","sources":["../src/getPropertyByPath.ts"],"names":[],"mappings":"AAKA,iBAAS,iBAAiB,CACxB,MAAM,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,EAClC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAC3B,OAAO,CAgBT;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC"}

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getPropertyByPath = getPropertyByPath;
// Resolves property names or property paths defined with period-delimited
// strings or arrays of strings. Property names that are found on the source
// object are used directly (even if they include a period).
// Nested property names that include periods, within a path, are only
// understood in array paths.
function getPropertyByPath(source, path) {
if (typeof path === 'string' && Object.prototype.hasOwnProperty.call(source, path)) {
return source[path];
}
const parsedPath = typeof path === 'string' ? path.split('.') : path; // eslint-disable-next-line @typescript-eslint/no-explicit-any
return parsedPath.reduce((previous, key) => {
if (previous === undefined) {
return previous;
}
return previous[key];
}, source);
}
//# sourceMappingURL=getPropertyByPath.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/getPropertyByPath.ts"],"names":["getPropertyByPath","source","path","Object","prototype","hasOwnProperty","call","parsedPath","split","reduce","previous","key","undefined"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,SAASA,iBAAT,CACEC,MADF,EAEEC,IAFF,EAGW;AACT,MACE,OAAOA,IAAP,KAAgB,QAAhB,IACAC,MAAM,CAACC,SAAP,CAAiBC,cAAjB,CAAgCC,IAAhC,CAAqCL,MAArC,EAA6CC,IAA7C,CAFF,EAGE;AACA,WAAOD,MAAM,CAACC,IAAD,CAAb;AACD;;AAED,QAAMK,UAAU,GAAG,OAAOL,IAAP,KAAgB,QAAhB,GAA2BA,IAAI,CAACM,KAAL,CAAW,GAAX,CAA3B,GAA6CN,IAAhE,CARS,CAST;;AACA,SAAOK,UAAU,CAACE,MAAX,CAAkB,CAACC,QAAD,EAAgBC,GAAhB,KAAiC;AACxD,QAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1B,aAAOF,QAAP;AACD;;AACD,WAAOA,QAAQ,CAACC,GAAD,CAAf;AACD,GALM,EAKJV,MALI,CAAP;AAMD","sourcesContent":["// Resolves property names or property paths defined with period-delimited\n// strings or arrays of strings. Property names that are found on the source\n// object are used directly (even if they include a period).\n// Nested property names that include periods, within a path, are only\n// understood in array paths.\nfunction getPropertyByPath(\n source: { [key: string]: unknown },\n path: string | Array<string>,\n): unknown {\n if (\n typeof path === 'string' &&\n Object.prototype.hasOwnProperty.call(source, path)\n ) {\n return source[path];\n }\n\n const parsedPath = typeof path === 'string' ? path.split('.') : path;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return parsedPath.reduce((previous: any, key): unknown => {\n if (previous === undefined) {\n return previous;\n }\n return previous[key];\n }, source);\n}\n\nexport { getPropertyByPath };\n"],"file":"getPropertyByPath.js"}

View File

@@ -0,0 +1,45 @@
import { Config, CosmiconfigResult, Loaders, LoadersSync } from './types';
declare type LoaderResult = Config | null;
export declare type Loader = ((filepath: string, content: string) => Promise<LoaderResult>) | LoaderSync;
export declare type LoaderSync = (filepath: string, content: string) => LoaderResult;
export declare type Transform = ((CosmiconfigResult: CosmiconfigResult) => Promise<CosmiconfigResult>) | TransformSync;
export declare type TransformSync = (CosmiconfigResult: CosmiconfigResult) => CosmiconfigResult;
interface OptionsBase {
packageProp?: string | Array<string>;
searchPlaces?: Array<string>;
ignoreEmptySearchPlaces?: boolean;
stopDir?: string;
cache?: boolean;
}
export interface Options extends OptionsBase {
loaders?: Loaders;
transform?: Transform;
}
export interface OptionsSync extends OptionsBase {
loaders?: LoadersSync;
transform?: TransformSync;
}
declare function cosmiconfig(moduleName: string, options?: Options): {
readonly search: (searchFrom?: string) => Promise<CosmiconfigResult>;
readonly load: (filepath: string) => Promise<CosmiconfigResult>;
readonly clearLoadCache: () => void;
readonly clearSearchCache: () => void;
readonly clearCaches: () => void;
};
declare function cosmiconfigSync(moduleName: string, options?: OptionsSync): {
readonly search: (searchFrom?: string) => CosmiconfigResult;
readonly load: (filepath: string) => CosmiconfigResult;
readonly clearLoadCache: () => void;
readonly clearSearchCache: () => void;
readonly clearCaches: () => void;
};
declare const defaultLoaders: Readonly<{
readonly '.cjs': LoaderSync;
readonly '.js': LoaderSync;
readonly '.json': LoaderSync;
readonly '.yaml': LoaderSync;
readonly '.yml': LoaderSync;
readonly noExt: LoaderSync;
}>;
export { cosmiconfig, cosmiconfigSync, defaultLoaders };
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,MAAM,EACN,iBAAiB,EAGjB,OAAO,EACP,WAAW,EACZ,MAAM,SAAS,CAAC;AAEjB,aAAK,YAAY,GAAG,MAAM,GAAG,IAAI,CAAC;AAClC,oBAAY,MAAM,GACd,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC,GAC9D,UAAU,CAAC;AACf,oBAAY,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,YAAY,CAAC;AAE7E,oBAAY,SAAS,GACjB,CAAC,CAAC,iBAAiB,EAAE,iBAAiB,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC,GACtE,aAAa,CAAC;AAElB,oBAAY,aAAa,GAAG,CAC1B,iBAAiB,EAAE,iBAAiB,KACjC,iBAAiB,CAAC;AAEvB,UAAU,WAAW;IACnB,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IACrC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,OAAQ,SAAQ,WAAW;IAC1C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB;AAED,MAAM,WAAW,WAAY,SAAQ,WAAW;IAC9C,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,SAAS,CAAC,EAAE,aAAa,CAAC;CAC3B;AAGD,iBAAS,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,OAAY;;;;;;EAe7D;AAGD,iBAAS,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB;;;;;;EAerE;AAGD,QAAA,MAAM,cAAc;;;;;;;EAOT,CAAC;AAwDZ,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,CAAC"}

View File

@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cosmiconfig = cosmiconfig;
exports.cosmiconfigSync = cosmiconfigSync;
exports.defaultLoaders = void 0;
var _os = _interopRequireDefault(require("os"));
var _Explorer = require("./Explorer");
var _ExplorerSync = require("./ExplorerSync");
var _loaders = require("./loaders");
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function cosmiconfig(moduleName, options = {}) {
const normalizedOptions = normalizeOptions(moduleName, options);
const explorer = new _Explorer.Explorer(normalizedOptions);
return {
search: explorer.search.bind(explorer),
load: explorer.load.bind(explorer),
clearLoadCache: explorer.clearLoadCache.bind(explorer),
clearSearchCache: explorer.clearSearchCache.bind(explorer),
clearCaches: explorer.clearCaches.bind(explorer)
};
} // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function cosmiconfigSync(moduleName, options = {}) {
const normalizedOptions = normalizeOptions(moduleName, options);
const explorerSync = new _ExplorerSync.ExplorerSync(normalizedOptions);
return {
search: explorerSync.searchSync.bind(explorerSync),
load: explorerSync.loadSync.bind(explorerSync),
clearLoadCache: explorerSync.clearLoadCache.bind(explorerSync),
clearSearchCache: explorerSync.clearSearchCache.bind(explorerSync),
clearCaches: explorerSync.clearCaches.bind(explorerSync)
};
} // do not allow mutation of default loaders. Make sure it is set inside options
const defaultLoaders = Object.freeze({
'.cjs': _loaders.loaders.loadJs,
'.js': _loaders.loaders.loadJs,
'.json': _loaders.loaders.loadJson,
'.yaml': _loaders.loaders.loadYaml,
'.yml': _loaders.loaders.loadYaml,
noExt: _loaders.loaders.loadYaml
});
exports.defaultLoaders = defaultLoaders;
const identity = function identity(x) {
return x;
};
function normalizeOptions(moduleName, options) {
const defaults = {
packageProp: moduleName,
searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `.config/${moduleName}rc`, `.config/${moduleName}rc.json`, `.config/${moduleName}rc.yaml`, `.config/${moduleName}rc.yml`, `.config/${moduleName}rc.js`, `.config/${moduleName}rc.cjs`, `${moduleName}.config.js`, `${moduleName}.config.cjs`],
ignoreEmptySearchPlaces: true,
stopDir: _os.default.homedir(),
cache: true,
transform: identity,
loaders: defaultLoaders
};
const normalizedOptions = { ...defaults,
...options,
loaders: { ...defaults.loaders,
...options.loaders
}
};
return normalizedOptions;
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
import { LoadersSync } from './types';
declare const loaders: LoadersSync;
export { loaders };
//# sourceMappingURL=loaders.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"loaders.d.ts","sourceRoot":"","sources":["../src/loaders.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AA0CtC,QAAA,MAAM,OAAO,EAAE,WAA4C,CAAC;AAE5D,OAAO,EAAE,OAAO,EAAE,CAAC"}

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loaders = void 0;
/* eslint-disable @typescript-eslint/no-require-imports */
let importFresh;
const loadJs = function loadJs(filepath) {
if (importFresh === undefined) {
importFresh = require('import-fresh');
}
const result = importFresh(filepath);
return result;
};
let parseJson;
const loadJson = function loadJson(filepath, content) {
if (parseJson === undefined) {
parseJson = require('parse-json');
}
try {
const result = parseJson(content);
return result;
} catch (error) {
error.message = `JSON Error in ${filepath}:\n${error.message}`;
throw error;
}
};
let yaml;
const loadYaml = function loadYaml(filepath, content) {
if (yaml === undefined) {
yaml = require('yaml');
}
try {
const result = yaml.parse(content, {
prettyErrors: true
});
return result;
} catch (error) {
error.message = `YAML Error in ${filepath}:\n${error.message}`;
throw error;
}
};
const loaders = {
loadJs,
loadJson,
loadYaml
};
exports.loaders = loaders;
//# sourceMappingURL=loaders.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/loaders.ts"],"names":["importFresh","loadJs","filepath","undefined","require","result","parseJson","loadJson","content","error","message","yaml","loadYaml","parse","prettyErrors","loaders"],"mappings":";;;;;;;AAAA;AAQA,IAAIA,WAAJ;;AACA,MAAMC,MAAkB,GAAG,SAASA,MAAT,CAAgBC,QAAhB,EAA0B;AACnD,MAAIF,WAAW,KAAKG,SAApB,EAA+B;AAC7BH,IAAAA,WAAW,GAAGI,OAAO,CAAC,cAAD,CAArB;AACD;;AAED,QAAMC,MAAM,GAAGL,WAAW,CAACE,QAAD,CAA1B;AACA,SAAOG,MAAP;AACD,CAPD;;AASA,IAAIC,SAAJ;;AACA,MAAMC,QAAoB,GAAG,SAASA,QAAT,CAAkBL,QAAlB,EAA4BM,OAA5B,EAAqC;AAChE,MAAIF,SAAS,KAAKH,SAAlB,EAA6B;AAC3BG,IAAAA,SAAS,GAAGF,OAAO,CAAC,YAAD,CAAnB;AACD;;AAED,MAAI;AACF,UAAMC,MAAM,GAAGC,SAAS,CAACE,OAAD,CAAxB;AACA,WAAOH,MAAP;AACD,GAHD,CAGE,OAAOI,KAAP,EAAc;AACdA,IAAAA,KAAK,CAACC,OAAN,GAAiB,iBAAgBR,QAAS,MAAKO,KAAK,CAACC,OAAQ,EAA7D;AACA,UAAMD,KAAN;AACD;AACF,CAZD;;AAcA,IAAIE,IAAJ;;AACA,MAAMC,QAAoB,GAAG,SAASA,QAAT,CAAkBV,QAAlB,EAA4BM,OAA5B,EAAqC;AAChE,MAAIG,IAAI,KAAKR,SAAb,EAAwB;AACtBQ,IAAAA,IAAI,GAAGP,OAAO,CAAC,MAAD,CAAd;AACD;;AAED,MAAI;AACF,UAAMC,MAAM,GAAGM,IAAI,CAACE,KAAL,CAAWL,OAAX,EAAoB;AAAEM,MAAAA,YAAY,EAAE;AAAhB,KAApB,CAAf;AACA,WAAOT,MAAP;AACD,GAHD,CAGE,OAAOI,KAAP,EAAc;AACdA,IAAAA,KAAK,CAACC,OAAN,GAAiB,iBAAgBR,QAAS,MAAKO,KAAK,CAACC,OAAQ,EAA7D;AACA,UAAMD,KAAN;AACD;AACF,CAZD;;AAcA,MAAMM,OAAoB,GAAG;AAAEd,EAAAA,MAAF;AAAUM,EAAAA,QAAV;AAAoBK,EAAAA;AAApB,CAA7B","sourcesContent":["/* eslint-disable @typescript-eslint/no-require-imports */\n\nimport parseJsonType from 'parse-json';\nimport yamlType from 'yaml';\nimport importFreshType from 'import-fresh';\nimport { LoaderSync } from './index';\nimport { LoadersSync } from './types';\n\nlet importFresh: typeof importFreshType;\nconst loadJs: LoaderSync = function loadJs(filepath) {\n if (importFresh === undefined) {\n importFresh = require('import-fresh');\n }\n\n const result = importFresh(filepath);\n return result;\n};\n\nlet parseJson: typeof parseJsonType;\nconst loadJson: LoaderSync = function loadJson(filepath, content) {\n if (parseJson === undefined) {\n parseJson = require('parse-json');\n }\n\n try {\n const result = parseJson(content);\n return result;\n } catch (error) {\n error.message = `JSON Error in ${filepath}:\\n${error.message}`;\n throw error;\n }\n};\n\nlet yaml: typeof yamlType;\nconst loadYaml: LoaderSync = function loadYaml(filepath, content) {\n if (yaml === undefined) {\n yaml = require('yaml');\n }\n\n try {\n const result = yaml.parse(content, { prettyErrors: true });\n return result;\n } catch (error) {\n error.message = `YAML Error in ${filepath}:\\n${error.message}`;\n throw error;\n }\n};\n\nconst loaders: LoadersSync = { loadJs, loadJson, loadYaml };\n\nexport { loaders };\n"],"file":"loaders.js"}

View File

@@ -0,0 +1,7 @@
interface Options {
throwNotFound?: boolean;
}
declare function readFile(filepath: string, options?: Options): Promise<string | null>;
declare function readFileSync(filepath: string, options?: Options): string | null;
export { readFile, readFileSync };
//# sourceMappingURL=readFile.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"readFile.d.ts","sourceRoot":"","sources":["../src/readFile.ts"],"names":[],"mappings":"AAkBA,UAAU,OAAO;IACf,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,iBAAe,QAAQ,CACrB,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,OAAY,GACpB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAiBxB;AAED,iBAAS,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,GAAE,OAAY,GAAG,MAAM,GAAG,IAAI,CAiB5E;AAED,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC"}

View File

@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.readFile = readFile;
exports.readFileSync = readFileSync;
var _fs = _interopRequireDefault(require("fs"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
async function fsReadFileAsync(pathname, encoding) {
return new Promise((resolve, reject) => {
_fs.default.readFile(pathname, encoding, (error, contents) => {
if (error) {
reject(error);
return;
}
resolve(contents);
});
});
}
async function readFile(filepath, options = {}) {
const throwNotFound = options.throwNotFound === true;
try {
const content = await fsReadFileAsync(filepath, 'utf8');
return content;
} catch (error) {
if (throwNotFound === false && (error.code === 'ENOENT' || error.code === 'EISDIR')) {
return null;
}
throw error;
}
}
function readFileSync(filepath, options = {}) {
const throwNotFound = options.throwNotFound === true;
try {
const content = _fs.default.readFileSync(filepath, 'utf8');
return content;
} catch (error) {
if (throwNotFound === false && (error.code === 'ENOENT' || error.code === 'EISDIR')) {
return null;
}
throw error;
}
}
//# sourceMappingURL=readFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/readFile.ts"],"names":["fsReadFileAsync","pathname","encoding","Promise","resolve","reject","fs","readFile","error","contents","filepath","options","throwNotFound","content","code","readFileSync"],"mappings":";;;;;;;;AAAA;;;;AAEA,eAAeA,eAAf,CACEC,QADF,EAEEC,QAFF,EAGmB;AACjB,SAAO,IAAIC,OAAJ,CAAY,CAACC,OAAD,EAAUC,MAAV,KAA2B;AAC5CC,gBAAGC,QAAH,CAAYN,QAAZ,EAAsBC,QAAtB,EAAgC,CAACM,KAAD,EAAQC,QAAR,KAA2B;AACzD,UAAID,KAAJ,EAAW;AACTH,QAAAA,MAAM,CAACG,KAAD,CAAN;AACA;AACD;;AAEDJ,MAAAA,OAAO,CAACK,QAAD,CAAP;AACD,KAPD;AAQD,GATM,CAAP;AAUD;;AAMD,eAAeF,QAAf,CACEG,QADF,EAEEC,OAAgB,GAAG,EAFrB,EAG0B;AACxB,QAAMC,aAAa,GAAGD,OAAO,CAACC,aAAR,KAA0B,IAAhD;;AAEA,MAAI;AACF,UAAMC,OAAO,GAAG,MAAMb,eAAe,CAACU,QAAD,EAAW,MAAX,CAArC;AAEA,WAAOG,OAAP;AACD,GAJD,CAIE,OAAOL,KAAP,EAAc;AACd,QACEI,aAAa,KAAK,KAAlB,KACCJ,KAAK,CAACM,IAAN,KAAe,QAAf,IAA2BN,KAAK,CAACM,IAAN,KAAe,QAD3C,CADF,EAGE;AACA,aAAO,IAAP;AACD;;AAED,UAAMN,KAAN;AACD;AACF;;AAED,SAASO,YAAT,CAAsBL,QAAtB,EAAwCC,OAAgB,GAAG,EAA3D,EAA8E;AAC5E,QAAMC,aAAa,GAAGD,OAAO,CAACC,aAAR,KAA0B,IAAhD;;AAEA,MAAI;AACF,UAAMC,OAAO,GAAGP,YAAGS,YAAH,CAAgBL,QAAhB,EAA0B,MAA1B,CAAhB;;AAEA,WAAOG,OAAP;AACD,GAJD,CAIE,OAAOL,KAAP,EAAc;AACd,QACEI,aAAa,KAAK,KAAlB,KACCJ,KAAK,CAACM,IAAN,KAAe,QAAf,IAA2BN,KAAK,CAACM,IAAN,KAAe,QAD3C,CADF,EAGE;AACA,aAAO,IAAP;AACD;;AAED,UAAMN,KAAN;AACD;AACF","sourcesContent":["import fs from 'fs';\n\nasync function fsReadFileAsync(\n pathname: string,\n encoding: BufferEncoding,\n): Promise<string> {\n return new Promise((resolve, reject): void => {\n fs.readFile(pathname, encoding, (error, contents): void => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve(contents);\n });\n });\n}\n\ninterface Options {\n throwNotFound?: boolean;\n}\n\nasync function readFile(\n filepath: string,\n options: Options = {},\n): Promise<string | null> {\n const throwNotFound = options.throwNotFound === true;\n\n try {\n const content = await fsReadFileAsync(filepath, 'utf8');\n\n return content;\n } catch (error) {\n if (\n throwNotFound === false &&\n (error.code === 'ENOENT' || error.code === 'EISDIR')\n ) {\n return null;\n }\n\n throw error;\n }\n}\n\nfunction readFileSync(filepath: string, options: Options = {}): string | null {\n const throwNotFound = options.throwNotFound === true;\n\n try {\n const content = fs.readFileSync(filepath, 'utf8');\n\n return content;\n } catch (error) {\n if (\n throwNotFound === false &&\n (error.code === 'ENOENT' || error.code === 'EISDIR')\n ) {\n return null;\n }\n\n throw error;\n }\n}\n\nexport { readFile, readFileSync };\n"],"file":"readFile.js"}

View File

@@ -0,0 +1,20 @@
import { Loader, LoaderSync, Options, OptionsSync } from './index';
export declare type Config = any;
export declare type CosmiconfigResult = {
config: Config;
filepath: string;
isEmpty?: boolean;
} | null;
export interface ExplorerOptions extends Required<Options> {
}
export interface ExplorerOptionsSync extends Required<OptionsSync> {
}
export declare type Cache = Map<string, CosmiconfigResult>;
export declare type LoadedFileContent = Config | null | undefined;
export interface Loaders {
[key: string]: Loader;
}
export interface LoadersSync {
[key: string]: LoaderSync;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGnE,oBAAY,MAAM,GAAG,GAAG,CAAC;AAEzB,oBAAY,iBAAiB,GAAG;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,IAAI,CAAC;AAIT,MAAM,WAAW,eAAgB,SAAQ,QAAQ,CAAC,OAAO,CAAC;CAAG;AAC7D,MAAM,WAAW,mBAAoB,SAAQ,QAAQ,CAAC,WAAW,CAAC;CAAG;AAGrE,oBAAY,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;AAMnD,oBAAY,iBAAiB,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;AAE1D,MAAM,WAAW,OAAO;IACtB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,WAAW;IAC1B,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC;CAC3B"}

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[],"file":"types.js"}

View File

@@ -0,0 +1,145 @@
{
"name": "cosmiconfig",
"version": "7.1.0",
"description": "Find and load configuration from a package.json property, rc file, or CommonJS module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"clean": "del-cli --dot=true \"./dist/**/*\"",
"build": "npm run clean && npm run build:compile && npm run build:types",
"build:compile": "cross-env NODE_ENV=production babel src -d dist --verbose --extensions .js,.ts --ignore \"**/**/*.test.js\",\"**/**/*.test.ts\" --source-maps",
"build:types": "cross-env NODE_ENV=production tsc --project tsconfig.types.json",
"dev": "npm run clean && npm run build:compile -- --watch",
"lint": "eslint --ext .js,.ts . && npm run lint:md",
"lint:fix": "eslint --ext .js,.ts . --fix",
"lint:md": "remark-preset-davidtheclark",
"format": "prettier \"**/*.{js,ts,json,yml,yaml}\" --write",
"format:md": "remark-preset-davidtheclark --format",
"format:check": "prettier \"**/*.{js,ts,json,yml,yaml}\" --check",
"typescript": "tsc",
"test": "jest --coverage",
"test:watch": "jest --watch",
"check:all": "npm run test && npm run typescript && npm run lint && npm run format:check",
"prepublishOnly": "npm run check:all && npm run build"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged && npm run typescript && npm run test",
"pre-push": "npm run check:all"
}
},
"lint-staged": {
"*.{js,ts}": [
"eslint --fix",
"prettier --write"
],
"*.{json,yml,yaml}": [
"prettier --write"
],
"*.md": [
"remark-preset-davidtheclark",
"remark-preset-davidtheclark --format"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/davidtheclark/cosmiconfig.git"
},
"keywords": [
"load",
"configuration",
"config"
],
"author": "David Clark <david.dave.clark@gmail.com>",
"contributors": [
"Bogdan Chadkin <trysound@yandex.ru>",
"Suhas Karanth <sudo.suhas@gmail.com>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/davidtheclark/cosmiconfig/issues"
},
"homepage": "https://github.com/davidtheclark/cosmiconfig#readme",
"prettier": {
"trailingComma": "all",
"arrowParens": "always",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
},
"jest": {
"testEnvironment": "node",
"collectCoverageFrom": [
"src/**/*.{js,ts}"
],
"coverageReporters": [
"text",
"html",
"lcov"
],
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
"resetModules": true,
"resetMocks": true,
"restoreMocks": true
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "10"
}
}
],
"@babel/preset-typescript"
]
},
"dependencies": {
"@types/parse-json": "^4.0.0",
"import-fresh": "^3.2.1",
"parse-json": "^5.0.0",
"path-type": "^4.0.0",
"yaml": "^1.10.0"
},
"devDependencies": {
"@babel/cli": "^7.10.4",
"@babel/core": "^7.10.4",
"@babel/preset-env": "^7.10.4",
"@babel/preset-typescript": "^7.10.4",
"@types/jest": "^26.0.4",
"@types/node": "^14.0.22",
"@typescript-eslint/eslint-plugin": "^3.6.0",
"@typescript-eslint/parser": "^3.6.0",
"cross-env": "^7.0.2",
"del": "^5.1.0",
"del-cli": "^3.0.1",
"eslint": "^7.4.0",
"eslint-config-davidtheclark-node": "^0.2.2",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jest": "^23.18.0",
"eslint-plugin-node": "^11.1.0",
"husky": "^4.2.5",
"jest": "^26.1.0",
"lint-staged": "^10.2.11",
"make-dir": "^3.1.0",
"parent-module": "^2.0.0",
"prettier": "^2.0.5",
"remark-preset-davidtheclark": "^0.12.0",
"typescript": "^3.9.6"
},
"engines": {
"node": ">=10"
}
}

70
node_modules/@wordpress/eslint-plugin/package.json generated vendored Normal file
View File

@@ -0,0 +1,70 @@
{
"name": "@wordpress/eslint-plugin",
"version": "18.1.0",
"description": "ESLint plugin for WordPress development.",
"author": "The WordPress Contributors",
"license": "GPL-2.0-or-later",
"keywords": [
"wordpress",
"gutenberg",
"eslint",
"plugin"
],
"homepage": "https://github.com/WordPress/gutenberg/tree/HEAD/packages/eslint-plugin/README.md",
"repository": {
"type": "git",
"url": "https://github.com/WordPress/gutenberg.git",
"directory": "packages/eslint-plugin"
},
"bugs": {
"url": "https://github.com/WordPress/gutenberg/issues"
},
"engines": {
"node": ">=14",
"npm": ">=6.14.4"
},
"files": [
"configs",
"rules",
"utils",
"index.js"
],
"main": "index.js",
"dependencies": {
"@babel/eslint-parser": "^7.16.0",
"@typescript-eslint/eslint-plugin": "^6.4.1",
"@typescript-eslint/parser": "^6.4.1",
"@wordpress/babel-preset-default": "^7.42.0",
"@wordpress/prettier-config": "^3.15.0",
"cosmiconfig": "^7.0.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-jest": "^27.2.3",
"eslint-plugin-jsdoc": "^46.4.6",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-playwright": "^0.15.3",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-react": "^7.27.0",
"eslint-plugin-react-hooks": "^4.3.0",
"globals": "^13.12.0",
"requireindex": "^1.2.0"
},
"peerDependencies": {
"@babel/core": ">=7",
"eslint": ">=8",
"prettier": ">=3",
"typescript": ">=4"
},
"peerDependenciesMeta": {
"prettier": {
"optional": true
},
"typescript": {
"optional": true
}
},
"publishConfig": {
"access": "public"
},
"gitHead": "42f38f287506a6b3ed8ccba839b18ad066821044"
}

View File

@@ -0,0 +1,127 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../data-no-store-string-literals';
const ruleTester = new RuleTester( {
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
},
} );
const valid = [
// Callback functions.
`import { createRegistrySelector } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; createRegistrySelector(( select ) => { select(coreStore); });`,
`import { useSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; useSelect(( select ) => { select(coreStore); });`,
`import { withSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; withSelect(( select ) => { select(coreStore); });`,
`import { withDispatch } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; withDispatch(( select ) => { select(coreStore); });`,
`import { withDispatch as withDispatchAlias } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; withDispatchAlias(( select ) => { select(coreStore); });`,
// Direct function calls.
`import { useDispatch } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; useDispatch( coreStore );`,
`import { dispatch } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; dispatch( coreStore );`,
`import { useSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; useSelect( coreStore );`,
`import { select } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; select( coreStore );`,
`import { resolveSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; resolveSelect( coreStore );`,
`import { resolveSelect as resolveSelectAlias } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; resolveSelectAlias( coreStore );`,
// Object property function calls.
`import { controls } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; controls.select( coreStore );`,
`import { controls } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; controls.dispatch( coreStore );`,
`import { controls } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; controls.resolveSelect( coreStore );`,
`import { controls as controlsAlias } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; controlsAlias.resolveSelect( coreStore );`,
];
const createSuggestionTestCase = ( code, output ) => ( {
code,
errors: [
{
suggestions: [
{
desc: 'Replace literal with store definition. Import store if necessary.',
output,
},
],
},
],
} );
const invalid = [
// Callback functions.
`import { createRegistrySelector } from '@wordpress/data'; createRegistrySelector(( select ) => { select( 'core' ); });`,
`import { useSelect } from '@wordpress/data'; useSelect(( select ) => { select( 'core' ); });`,
`import { withSelect } from '@wordpress/data'; withSelect(( select ) => { select( 'core' ); });`,
`import { withDispatch } from '@wordpress/data'; withDispatch(( select ) => { select( 'core' ); });`,
`import { withDispatch as withDispatchAlias } from '@wordpress/data'; withDispatchAlias(( select ) => { select( 'core' ); });`,
// Direct function calls.
`import { useDispatch } from '@wordpress/data'; useDispatch( 'core' );`,
`import { dispatch } from '@wordpress/data'; dispatch( 'core' );`,
`import { useSelect } from '@wordpress/data'; useSelect( 'core' );`,
`import { select } from '@wordpress/data'; select( 'core' );`,
`import { resolveSelect } from '@wordpress/data'; resolveSelect( 'core' );`,
`import { resolveSelect as resolveSelectAlias } from '@wordpress/data'; resolveSelectAlias( 'core' );`,
// Object property function calls.
`import { controls } from '@wordpress/data'; controls.select( 'core' );`,
`import { controls } from '@wordpress/data'; controls.dispatch( 'core' );`,
`import { controls } from '@wordpress/data'; controls.resolveSelect( 'core' );`,
`import { controls as controlsAlias } from '@wordpress/data'; controlsAlias.resolveSelect( 'core' );`,
// Direct function calls suggestions
// Replace core with coreStore and import coreStore.
createSuggestionTestCase(
`import { select } from '@wordpress/data'; select( 'core' );`,
`import { select } from '@wordpress/data';\nimport { store as coreStore } from '@wordpress/core-data'; select( coreStore );`
),
// Replace core with coreStore. A @wordpress/core-data already exists, so it should append the import to that one.
createSuggestionTestCase(
`import { select } from '@wordpress/data'; import { something } from '@wordpress/core-data'; select( 'core' );`,
`import { select } from '@wordpress/data'; import { something,store as coreStore } from '@wordpress/core-data'; select( coreStore );`
),
// Replace core with coreStore. A @wordpress/core-data already exists, so it should append the import to that one.
// This time there is a comma after the import.
createSuggestionTestCase(
`import { select } from '@wordpress/data'; import { something, } from '@wordpress/core-data'; select( 'core' );`,
`import { select } from '@wordpress/data'; import { something,store as coreStore, } from '@wordpress/core-data'; select( coreStore );`
),
// Replace core with coreStore. Store import already exists. It shouldn't modify the import, just replace the literal with the store definition.
createSuggestionTestCase(
`import { select } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; select( 'core' );`,
`import { select } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; select( coreStore );`
),
// Replace core with coreStore. There are internal and WordPress dependencies.
// It should append the import after the last WordPress dependency import.
createSuggestionTestCase(
`import { a } from './a'; import { select } from '@wordpress/data'; import { b } from './b'; select( 'core' );`,
`import { a } from './a'; import { select } from '@wordpress/data';\nimport { store as coreStore } from '@wordpress/core-data'; import { b } from './b'; select( coreStore );`
),
// Replace block-editor with blockEditorStore.
createSuggestionTestCase(
`import { select } from '@wordpress/data'; select( 'core/block-editor' );`,
`import { select } from '@wordpress/data';\nimport { store as blockEditorStore } from '@wordpress/block-editor'; select( blockEditorStore );`
),
// Replace notices with noticesStore.
createSuggestionTestCase(
`import { select } from '@wordpress/data'; select( 'core/notices' );`,
`import { select } from '@wordpress/data';\nimport { store as noticesStore } from '@wordpress/notices'; select( noticesStore );`
),
];
const errors = [
{
message: `Do not use string literals ( 'core' ) for accessing @wordpress/data stores. Pass the store definition instead`,
},
];
ruleTester.run( 'data-no-store-string-literals', rule, {
valid: valid.map( ( code ) => ( { code } ) ),
invalid: invalid.map( ( code ) =>
typeof code === 'string' ? { code, errors } : code
),
} );

View File

@@ -0,0 +1,135 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../dependency-group';
const ruleTester = new RuleTester( {
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
},
} );
ruleTester.run( 'dependency-group', rule, {
valid: [
{
code: `
/**
* External dependencies
*/
import { camelCase } from 'change-case';
import clsx from 'clsx';;
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
/**
* Internal dependencies
*/
import edit from './edit';`,
},
{
code: `
/**
* External dependencies
*/
const { camelCase } = require( 'change-case' );
const clsx = require( 'clsx' );
/**
* WordPress dependencies
*/
const { Component } = require( '@wordpress/element' );
/**
* Internal dependencies
*/
const edit = require( './edit' );`,
},
],
invalid: [
{
code: `
import { camelCase } from 'change-case';
import clsx from 'clsx';;
/*
* wordpress dependencies.
*/
import { Component } from '@wordpress/element';
import edit from './edit';`,
errors: [
{
message:
'Expected preceding "External dependencies" comment block',
},
{
message:
'Expected preceding "WordPress dependencies" comment block',
},
{
message:
'Expected preceding "Internal dependencies" comment block',
},
],
output: `
/**
* External dependencies
*/
import { camelCase } from 'change-case';
import clsx from 'clsx';;
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
/**
* Internal dependencies
*/
import edit from './edit';`,
},
{
code: `
const { camelCase } = require( 'change-case' );
const clsx = require( 'clsx' );
/*
* wordpress dependencies.
*/
const { Component } = require( '@wordpress/element' );
const edit = require( './edit' );`,
errors: [
{
message:
'Expected preceding "External dependencies" comment block',
},
{
message:
'Expected preceding "WordPress dependencies" comment block',
},
{
message:
'Expected preceding "Internal dependencies" comment block',
},
],
output: `
/**
* External dependencies
*/
const { camelCase } = require( 'change-case' );
const clsx = require( 'clsx' );
/**
* WordPress dependencies
*/
const { Component } = require( '@wordpress/element' );
/**
* Internal dependencies
*/
const edit = require( './edit' );`,
},
],
} );

View File

@@ -0,0 +1,65 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-ellipsis';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-ellipsis', rule, {
valid: [
{
code: `__( 'Hello World…' )`,
},
{
code: `__( 'Hello' + 'World…' )`,
},
{
code: `_x( 'Hello World…', 'context' )`,
},
{
code: `_n( 'Singular…', 'Plural…', number)`,
},
{
code: `i18n.__( 'Hello World…' )`,
},
],
invalid: [
{
code: `__( 'Hello World...' )`,
output: `__( 'Hello World…' )`,
errors: [ { messageId: 'foundThreeDots' } ],
},
{
code: `__( 'Hello' + 'World...' )`,
output: `__( 'Hello' + 'World…' )`,
errors: [ { messageId: 'foundThreeDots' } ],
},
{
code: `_x( 'Hello World...', 'context' )`,
output: `_x( 'Hello World…', 'context' )`,
errors: [ { messageId: 'foundThreeDots' } ],
},
{
code: `_n( 'Singular...', 'Plural...', number)`,
output: `_n( 'Singular…', 'Plural…', number)`,
errors: [
{ messageId: 'foundThreeDots' },
{ messageId: 'foundThreeDots' },
],
},
{
code: `i18n.__( 'Hello World...' )`,
output: `i18n.__( 'Hello World…' )`,
errors: [ { messageId: 'foundThreeDots' } ],
},
],
} );

View File

@@ -0,0 +1,63 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-hyphenated-range';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-hyphenated-range', rule, {
valid: [
{
code: `__( 'Hyphenated-words are ok' )`,
},
{
code: `__( 'Hyphen - when used in this case - is ok' )`,
},
{
code: `__('en dash and em dash — are ok')`,
},
{
code: `__( 'en dash ranges work 199 or 2 98' )`,
},
{
code: `__( 'Negative numbers like -99 or -33 are ok' )`,
},
{
code: `__( 'Numbers with trailing hyphens are odd but ok like 99-' )`,
},
{
code: `__( '1 0 -1' )`,
},
],
invalid: [
{
code: `__( 'guess a number 1 - 10' )`,
output: `__( 'guess a number 1 10' )`,
errors: [ { messageId: 'foundHyphen' } ],
},
{
code: `__( 'No spaces: 00-99' )`,
output: `__( 'No spaces: 0099' )`,
errors: [ { messageId: 'foundHyphen' } ],
},
{
code: `__( 'From 0 - 2 many spaces in the range' )`,
output: `__( 'From 0 2 many spaces in the range' )`,
errors: [ { messageId: 'foundHyphen' } ],
},
{
code: `__( '1-2' + ' fixing multiple strings' )`,
output: `__( '12' + ' fixing multiple strings' )`,
errors: [ { messageId: 'foundHyphen' } ],
},
],
} );

View File

@@ -0,0 +1,60 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-no-collapsible-whitespace';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-no-collapsible-whitespace', rule, {
valid: [
{
code: `__( 'Hello World…' )`,
},
{
code: '__( `A long string ` +\n `spread over ` +\n `multiple lines.` );',
},
],
invalid: [
{
code: '__( "My double-quoted string\\nwith a newline" );',
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
{
code: "__( 'My single quoted string\\nwith a newline' );",
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
{
code: '__( `My template literal\non two lines` );',
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
{
code: "__( ' My tab-indented string.' );",
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
{
code: "__( '\tMy string with a tab escape sequence.' );",
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
{
code: "__( '\u0009My string with a unicode tab.' );",
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
{
code: '__( `A string with \r a carriage return.` );',
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
{
code: "__( 'A string with consecutive spaces. These two are after a full stop.' );",
errors: [ { messageId: 'noCollapsibleWhitespace' } ],
},
],
} );

View File

@@ -0,0 +1,76 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-no-flanking-whitespace';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-no-flanking-whitespace', rule, {
valid: [
{
code: `__( 'Hello World…' )`,
},
{
code: '__( `A long string ` +\n `spread over ` +\n `multiple lines.` );',
},
{
code: `__( 'Not concerned about \t whitespace rules')`,
},
],
invalid: [
{
code: '__( "Double quoted string with a trailing newline\\n" );',
output: `__( 'Double quoted string with a trailing newline' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: `__( ' Leading whitespace.' );`,
output: `__( 'Leading whitespace.' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: `__( 'Trailing whitespace. ' );`,
output: `__( 'Trailing whitespace.' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: `__( ' Flanking whitespace. ' );`,
output: `__( 'Flanking whitespace.' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: '__( "\tLeading tab." );',
output: `__( 'Leading tab.' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: '__( "\u0009Leading unicode tab." );',
output: `__( 'Leading unicode tab.' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: `__( "Trailing tab.\t" );`,
output: `__( 'Trailing tab.' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: `__( "\tFlanking tab.\t" );`,
output: `__( 'Flanking tab.' );`,
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
{
code: '__( ` Template literals ` )',
errors: [ { messageId: 'noFlankingWhitespace' } ],
},
],
} );

View File

@@ -0,0 +1,50 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-no-placeholders-only';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-no-placeholders-only', rule, {
valid: [
{
code: `__( 'Hello %s' )`,
},
{
code: `i18n.__( 'Hello %s' )`,
},
{
code: `__( '%d%%' )`,
},
],
invalid: [
{
code: `__( '%s' )`,
errors: [ { messageId: 'noPlaceholdersOnly' } ],
},
{
code: `__( '%s%s' )`,
errors: [ { messageId: 'noPlaceholdersOnly' } ],
},
{
code: `_x( '%1$s' )`,
errors: [ { messageId: 'noPlaceholdersOnly' } ],
},
{
code: `_n( '%s', '%s', number)`,
errors: [
{ messageId: 'noPlaceholdersOnly' },
{ messageId: 'noPlaceholdersOnly' },
],
},
],
} );

View File

@@ -0,0 +1,92 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-no-variables';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-no-variables', rule, {
valid: [
{
code: `__( 'Hello World' )`,
},
{
code: `__( 'Hello' + 'World' )`,
},
{
code: `_x( 'Hello World', 'context' )`,
},
{
code: `var number = ''; _n( 'Singular', 'Plural', number)`,
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, 'context' )`,
},
{
code: `__( 'Hello World', 'foo' )`,
},
{
code: `_x( 'Hello World', 'context', 'foo' )`,
},
{
code: `var number = ''; _n( 'Singular', 'Plural', number, 'foo' )`,
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, 'context', 'foo' )`,
},
{
code: `i18n.__( 'Hello World' )`,
},
],
invalid: [
{
code: `__(foo)`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: '__(`Hello ${foo}`)',
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `_x(foo, 'context' )`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `_x( 'Hello World', bar)`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `var number = ''; _n(foo,'Plural', number)`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `var number = ''; _n( 'Singular', bar, number)`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `var number = ''; _nx(foo, 'Plural', number, 'context' )`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `var number = ''; _nx( 'Singular', bar, number, 'context' )`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, baz)`,
errors: [ { messageId: 'invalidArgument' } ],
},
{
code: `i18n.__(foo)`,
errors: [ { messageId: 'invalidArgument' } ],
},
],
} );

View File

@@ -0,0 +1,176 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-text-domain';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-text-domain', rule, {
valid: [
{
code: `_x( 'Hello World' )`,
},
{
code: `_x( 'Hello World', 'random' )`,
},
{
code: `__( 'Hello World' )`,
options: [ { allowedTextDomain: 'default' } ],
},
{
code: `_x( 'Hello World', 'context' )`,
options: [ { allowedTextDomain: 'default' } ],
},
{
code: `var number = ''; _n( 'Singular', 'Plural', number )`,
options: [ { allowedTextDomain: 'default' } ],
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, 'context' )`,
options: [ { allowedTextDomain: 'default' } ],
},
{
code: `__( 'Hello World', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
},
{
code: `_x( 'Hello World', 'context', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
},
{
code: `var number = ''; _n( 'Singular', 'Plural', number, 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, 'context', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
},
{
code: `i18n.__( 'Hello World' )`,
options: [ { allowedTextDomain: 'default' } ],
},
],
invalid: [
{
code: `__( 'Hello World' )`,
output: `__( 'Hello World', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'missing' } ],
},
{
code: `_x( 'Hello World', 'context' )`,
output: `_x( 'Hello World', 'context', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'missing' } ],
},
{
code: `var number = ''; _n( 'Singular', 'Plural', number )`,
output: `var number = ''; _n( 'Singular', 'Plural', number, 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'missing' } ],
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, 'context' )`,
output: `var number = ''; _nx( 'Singular', 'Plural', number, 'context', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'missing' } ],
},
{
code: `__( 'Hello World', 'bar' )`,
output: `__( 'Hello World', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'invalidValue' } ],
},
{
code: `_x( 'Hello World', 'context', 'bar' )`,
output: `_x( 'Hello World', 'context', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'invalidValue' } ],
},
{
code: `var number = ''; _n( 'Singular', 'Plural', number, 'bar' )`,
output: `var number = ''; _n( 'Singular', 'Plural', number, 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'invalidValue' } ],
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, 'context', 'bar' )`,
output: `var number = ''; _nx( 'Singular', 'Plural', number, 'context', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'invalidValue' } ],
},
{
code: `var value = ''; __( 'Hello World', value )`,
errors: [ { messageId: 'invalidType' } ],
},
{
code: `var value = ''; _x( 'Hello World', 'context', value )`,
errors: [ { messageId: 'invalidType' } ],
},
{
code: `var value = ''; var number = ''; _n( 'Singular', 'Plural', number, value )`,
errors: [ { messageId: 'invalidType' } ],
},
{
code: `var value = ''; var number = ''; _nx( 'Singular', 'Plural', number, 'context', value )`,
errors: [ { messageId: 'invalidType' } ],
},
{
code: `__( 'Hello World', 'default' )`,
output: `__( 'Hello World' )`,
options: [ { allowedTextDomain: 'default' } ],
errors: [ { messageId: 'unnecessaryDefault' } ],
},
{
code: `__( 'default', 'default' )`,
output: `__( 'default' )`,
options: [ { allowedTextDomain: 'default' } ],
errors: [ { messageId: 'unnecessaryDefault' } ],
},
{
code: `_x( 'Hello World', 'context', 'default' )`,
output: `_x( 'Hello World', 'context' )`,
options: [ { allowedTextDomain: 'default' } ],
errors: [ { messageId: 'unnecessaryDefault' } ],
},
{
code: `var number = ''; _n( 'Singular', 'Plural', number, 'default' )`,
output: `var number = ''; _n( 'Singular', 'Plural', number )`,
options: [ { allowedTextDomain: 'default' } ],
errors: [ { messageId: 'unnecessaryDefault' } ],
},
{
code: `var number = ''; _nx( 'Singular', 'Plural', number, 'context', 'default' )`,
output: `var number = ''; _nx( 'Singular', 'Plural', number, 'context' )`,
options: [ { allowedTextDomain: 'default' } ],
errors: [ { messageId: 'unnecessaryDefault' } ],
},
{
code: `i18n.__( 'Hello World' )`,
output: `i18n.__( 'Hello World', 'foo' )`,
options: [ { allowedTextDomain: 'foo' } ],
errors: [ { messageId: 'missing' } ],
},
{
code: `__( 'Hello World' )`,
output: `__( 'Hello World', 'foo' )`,
options: [ { allowedTextDomain: [ 'foo' ] } ],
errors: [ { messageId: 'missing' } ],
},
{
code: `__( 'Hello World' )`,
output: `__( 'Hello World' )`,
options: [ { allowedTextDomain: [ 'foo', 'bar' ] } ],
errors: [ { messageId: 'missing' } ],
},
],
} );

View File

@@ -0,0 +1,101 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../i18n-translator-comments';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'i18n-translator-comments', rule, {
valid: [
{
code: `
// translators: %s: Color
sprintf( __( 'Color: %s' ), color );`,
},
{
code: `
sprintf(
// translators: %s: Address.
__( 'Address: %s' ),
address
);`,
},
{
code: `
// translators: %s: Color
i18n.sprintf( i18n.__( 'Color: %s' ), color );`,
},
{
code: `
sprintf(
/*
* translators: %s is the name of the city we couldn't locate.
* Replace the examples with cities related to your locale. Test that
* they match the expected location and have upcoming events before
* including them. If no cities related to your locale have events,
* then use cities related to your locale that would be recognizable
* to most users. Use only the city name itself, without any region
* or country. Use the endonym (native locale name) instead of the
* English name if possible.
*/
__( 'We couldnt locate %s. Please try another nearby city. For example: Kansas City; Springfield; Portland.' ),
templateParams.unknownCity
);`,
},
],
invalid: [
{
code: `
sprintf( __( 'Color: %s' ), color );`,
errors: [ { messageId: 'missing' } ],
},
{
code: `
sprintf(
__( 'Address: %s' ),
address
);`,
errors: [ { messageId: 'missing' } ],
},
{
code: `
// translators: %s: Name
var name = '';
sprintf( __( 'Name: %s' ), name );`,
errors: [ { messageId: 'missing' } ],
},
{
code: `
// translators: %s: Surname
console.log(
sprintf( __( 'Surname: %s' ), name )
);`,
errors: [ { messageId: 'missing' } ],
},
{
code: `
// translators: %s: Preference
console.log(
sprintf(
__( 'Preference: %s' ),
preference
)
);`,
errors: [ { messageId: 'missing' } ],
},
{
code: `
i18n.sprintf( i18n.__( 'Color: %s' ), color );`,
errors: [ { messageId: 'missing' } ],
},
],
} );

View File

@@ -0,0 +1,65 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../is-gutenberg-plugin';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
const ERROR_MESSAGE =
'The `process.env.IS_GUTENBERG_PLUGIN` constant should only be used as the condition in an if statement or ternary expression.';
ruleTester.run( 'is-gutenberg-plugin', rule, {
valid: [
{ code: `if ( process.env.IS_GUTENBERG_PLUGIN ) {}` },
{ code: `if ( ! process.env.IS_GUTENBERG_PLUGIN ) {}` },
{
// Ensure whitespace is ok.
code: `if (
process.env.
IS_GUTENBERG_PLUGIN
) {}`,
},
{ code: `const test = process.env.IS_GUTENBERG_PLUGIN ? foo : bar` },
{ code: `const test = ! process.env.IS_GUTENBERG_PLUGIN ? bar : foo` },
{
// Ensure whitespace is ok.
code: `const test = ! process.env.
IS_GUTENBERG_PLUGIN ? bar : foo`,
},
],
invalid: [
{
code: `if ( IS_GUTENBERG_PLUGIN ) {}`,
errors: [ { message: ERROR_MESSAGE } ],
},
{
code: `if ( window[ 'IS_GUTENBERG_PLUGIN' ] ) {}`,
errors: [ { message: ERROR_MESSAGE } ],
},
{
code: `if ( true ) { process.env.IS_GUTENBERG_PLUGIN === 2 }`,
errors: [ { message: ERROR_MESSAGE } ],
},
{
code: `if ( process.env.IS_GUTENBERG_PLUGIN === 2 ) {}`,
errors: [ { message: ERROR_MESSAGE } ],
},
{
code: `if ( true || process.env.IS_GUTENBERG_PLUGIN === 2 ) {}`,
errors: [ { message: ERROR_MESSAGE } ],
},
{
code: `const isFeatureActive = process.env.IS_GUTENBERG_PLUGIN;`,
errors: [ { message: ERROR_MESSAGE } ],
},
],
} );

View File

@@ -0,0 +1,84 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../no-base-control-with-label-without-id';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
ecmaFeatures: {
jsx: true,
},
},
} );
ruleTester.run( 'no-base-control-with-label-without-id', rule, {
valid: [
{
code: `
<BaseControl
label="ok"
id="my-id"
/>`,
},
{
code: `<BaseControl />`,
},
{
code: `
<BaseControl
label="ok"
id="my-id"
>
<input id="my-id" />
</BaseControl>`,
},
{
code: `
<BaseControl>
<input id="my-id" />
</BaseControl>`,
},
{
code: `
<BaseControl
id="my-id"
>
<input id="my-id" />
</BaseControl>`,
},
],
invalid: [
{
code: `
<BaseControl
label="ok"
>
<input id="my-id" />
</BaseControl>`,
errors: [
{
message:
'When using BaseControl component if a label property is passed an id property should also be passed.',
},
],
},
{
code: `
<BaseControl
label="ok"
/>`,
errors: [
{
message:
'When using BaseControl component if a label property is passed an id property should also be passed.',
},
],
},
],
} );

View File

@@ -0,0 +1,34 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../no-global-active-element';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'no-global-active-element', rule, {
valid: [
{
code: 'ownerDocument.activeElement;',
},
],
invalid: [
{
code: 'document.activeElement;',
errors: [
{
message:
'Avoid accessing the active element with a global. Use the ownerDocument property on a node ref instead.',
},
],
},
],
} );

View File

@@ -0,0 +1,34 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../no-global-get-selection';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'no-global-get-selection', rule, {
valid: [
{
code: 'defaultView.getSelection();',
},
],
invalid: [
{
code: 'window.getSelection();',
errors: [
{
message:
'Avoid accessing the selection with a global. Use the ownerDocument.defaultView property on a node ref instead.',
},
],
},
],
} );

View File

@@ -0,0 +1,29 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../no-unguarded-get-range-at';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'no-unguarded-get-range-at', rule, {
valid: [
{
code: `const selection = defaultView.getSelection(); const range = selection.rangeCount ? selection.getRangeAt( 0 ) : null;`,
},
],
invalid: [
{
code: `defaultView.getSelection().getRangeAt( 0 );`,
errors: [ { message: 'Avoid unguarded getRangeAt' } ],
},
],
} );

View File

@@ -0,0 +1,116 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../no-unsafe-wp-apis';
const ruleTester = new RuleTester( {
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
},
} );
const options = [
{ '@wordpress/package': [ '__experimentalSafe', '__unstableSafe' ] },
];
ruleTester.run( 'no-unsafe-wp-apis', rule, {
valid: [
{ code: "import _ from 'change-case';", options },
{ code: "import { camelCase } from 'change-case';", options },
{ code: "import { __experimentalFoo } from 'change-case';", options },
{ code: "import { __unstableFoo } from 'change-case';", options },
{ code: "import _, { __unstableFoo } from 'change-case';", options },
{ code: "import * as _ from 'change-case';", options },
{ code: "import _ from './x';", options },
{ code: "import { camelCase } from './x';", options },
{ code: "import { __experimentalFoo } from './x';", options },
{ code: "import { __unstableFoo } from './x';", options },
{ code: "import _, { __unstableFoo } from './x';", options },
{ code: "import * as _ from './x';", options },
{ code: "import s from '@wordpress/package';", options },
{ code: "import { feature } from '@wordpress/package';", options },
{
code: "import { __experimentalSafe } from '@wordpress/package';",
options,
},
{
code: "import { __unstableSafe } from '@wordpress/package';",
options,
},
{
code: "import { feature, __experimentalSafe } from '@wordpress/package';",
options,
},
{
code: "import s, { __experimentalSafe } from '@wordpress/package';",
options,
},
{ code: "import * as s from '@wordpress/package';", options },
],
invalid: [
{
code: "import { __experimentalUnsafe } from '@wordpress/package';",
options,
errors: [
{
message: `Usage of \`__experimentalUnsafe\` from \`@wordpress/package\` is not allowed.
See https://developer.wordpress.org/block-editor/contributors/develop/coding-guidelines/#experimental-and-unstable-apis for details.`,
type: 'ImportSpecifier',
},
],
},
{
code: "import { __experimentalSafe } from '@wordpress/unsafe';",
options,
errors: [
{
message: `Usage of \`__experimentalSafe\` from \`@wordpress/unsafe\` is not allowed.
See https://developer.wordpress.org/block-editor/contributors/develop/coding-guidelines/#experimental-and-unstable-apis for details.`,
type: 'ImportSpecifier',
},
],
},
{
code: "import { feature, __experimentalSafe } from '@wordpress/unsafe';",
options,
errors: [
{
message: `Usage of \`__experimentalSafe\` from \`@wordpress/unsafe\` is not allowed.
See https://developer.wordpress.org/block-editor/contributors/develop/coding-guidelines/#experimental-and-unstable-apis for details.`,
type: 'ImportSpecifier',
},
],
},
{
code: "import s, { __experimentalUnsafe } from '@wordpress/package';",
options,
errors: [
{
message: `Usage of \`__experimentalUnsafe\` from \`@wordpress/package\` is not allowed.
See https://developer.wordpress.org/block-editor/contributors/develop/coding-guidelines/#experimental-and-unstable-apis for details.`,
type: 'ImportSpecifier',
},
],
},
{
code: "import { __unstableFeature } from '@wordpress/package';",
options,
errors: [
{
message: `Usage of \`__unstableFeature\` from \`@wordpress/package\` is not allowed.
See https://developer.wordpress.org/block-editor/contributors/develop/coding-guidelines/#experimental-and-unstable-apis for details.`,
type: 'ImportSpecifier',
},
],
},
],
} );

View File

@@ -0,0 +1,137 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../no-unused-vars-before-return';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
ecmaFeatures: {
jsx: true,
},
},
} );
ruleTester.run( 'no-unused-vars-before-return', rule, {
valid: [
{
code: `
function example( number ) {
if ( number > 10 ) {
return number + 1;
}
const foo = doSomeCostlyOperation();
return number + foo;
}`,
},
{
code: `
function example() {
const { foo, bar } = doSomeCostlyOperation();
if ( number > 10 ) {
return number + bar + 1;
}
return number + foo;
}`,
},
{
code: `
function example() {
const foo = doSomeCostlyOperation();
if ( number > 10 ) {
return number + 1;
}
return number + foo;
}`,
options: [ { excludePattern: '^do' } ],
},
{
code: `
function MyComponent() {
const Foo = getSomeComponent();
return <Foo />;
}`,
},
],
invalid: [
{
code: `
function example( number ) {
const foo = doSomeCostlyOperation();
if ( number > 10 ) {
return number + 1;
}
return number + foo;
}`,
errors: [
{
message:
'Variables should not be assigned until just prior its first reference. An early return statement may leave this variable unused.',
},
],
},
{
code: `
function example() {
const { foo } = doSomeCostlyOperation();
if ( number > 10 ) {
return number + 1;
}
return number + foo;
}`,
errors: [
{
message:
'Variables should not be assigned until just prior its first reference. An early return statement may leave this variable unused.',
},
],
},
{
code: `
function example() {
const foo = doSomeCostlyOperation();
if ( number > 10 ) {
return number + 1;
}
return number + foo;
}`,
options: [ { excludePattern: '^run' } ],
errors: [
{
message:
'Variables should not be assigned until just prior its first reference. An early return statement may leave this variable unused.',
},
],
},
{
code: `
function example() {
const foo = doSomeCostlyOperation();
const bar = anotherCostlyOperation( foo );
if ( number > 10 ) {
return number + 1;
}
return number + foo + bar;
}`,
options: [ { excludePattern: '^do' } ],
errors: [
{
message:
'Variables should not be assigned until just prior its first reference. An early return statement may leave this variable unused.',
},
],
},
],
} );

View File

@@ -0,0 +1,85 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../react-no-unsafe-timeout';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'react-no-unsafe-timeout', rule, {
valid: [
{
code: `function getNotComponent() { setTimeout(); }`,
},
{
code: `function MyComponent( props ) { const { setTimeout } = props; ( () => { setTimeout(); } )(); }`,
},
{
code: `function MyComponent( props ) { props.setTimeout(); }`,
},
{
code: `class MyNotComponent { doAction() { setTimeout(); } }`,
},
{
code: `class MyComponent extends wp.element.Component { componentDidMount() { const { setTimeout } = this.props; setTimeout(); } }`,
},
{
code: `class MyComponent extends Component { componentDidMount() { const { setTimeout } = this.props; setTimeout(); } }`,
},
{
code: `class MyComponent extends Component { componentDidMount() { this.props.setTimeout(); } }`,
},
{
code: `class MyComponent extends Component { componentDidMount() { this.timeoutId = setTimeout(); } }`,
},
{
code: `
function MyComponent() {
useEffect( () => {
const timeoutHandle = setTimeout( () => {} );
return () => clearTimeout( timeoutHandle );
}, [] );
return null;
}`,
},
],
invalid: [
{
code: `function MyComponent() { setTimeout(); }`,
errors: [
{
message:
'setTimeout in a component must be cancelled on unmount',
},
],
},
{
code: `class MyComponent extends Component { componentDidMount() { setTimeout(); } }`,
errors: [
{
message:
'setTimeout in a component must be cancelled on unmount',
},
],
},
{
code: `class MyComponent extends wp.element.Component { componentDidMount() { setTimeout(); } }`,
errors: [
{
message:
'setTimeout in a component must be cancelled on unmount',
},
],
},
],
} );

View File

@@ -0,0 +1,131 @@
/**
* External dependencies
*/
import { RuleTester } from 'eslint';
/**
* Internal dependencies
*/
import rule from '../valid-sprintf';
const ruleTester = new RuleTester( {
parserOptions: {
ecmaVersion: 6,
},
} );
ruleTester.run( 'valid-sprintf', rule, {
valid: [
{
code: `sprintf( '%s', 'substitute' )`,
},
{
code: `sprintf( '%1$d%%', 500 )`,
},
{
code: `sprintf( __( '%s' ), 'substitute' )`,
},
{
code: `sprintf( _x( '%s' ), 'substitute' )`,
},
{
code: `sprintf( _n( '%s', '%s' ), 'substitute' )`,
},
{
code: `sprintf( _nx( '%s', '%s' ), 'substitute' )`,
},
{
code: `var getValue = () => ''; sprintf( getValue(), 'substitute' )`,
},
{
code: `var value = ''; sprintf( value, 'substitute' )`,
},
{
code: `
sprintf(
/* translators: 1: number of blocks. 2: average rating. */
_n(
'This author has %1$d block, with an average rating of %2$d.',
'This author has %1$d blocks, with an average rating of %2$d.',
authorBlockCount
),
authorBlockCount,
authorBlockRating
);`,
},
{
code: `i18n.sprintf( '%s', 'substitute' )`,
},
{
code: `i18n.sprintf( i18n.__( '%s' ), 'substitute' )`,
},
{
code: `sprintf( ...args )`,
},
{
code: `sprintf( '%1$s %2$s', 'foo', 'bar' )`,
},
{
code: `sprintf( '%(greeting)s', 'Hello' )`,
},
{
code: `sprintf( '%(greeting)s %(toWhom)s', 'Hello', 'World' )`,
},
],
invalid: [
{
code: `sprintf()`,
errors: [ { messageId: 'noFormatString' } ],
},
{
code: `sprintf( '%s' )`,
errors: [ { messageId: 'noPlaceholderArgs' } ],
},
{
code: `sprintf( 1, 'substitute' )`,
errors: [ { messageId: 'invalidFormatString' } ],
},
{
code: `sprintf( [], 'substitute' )`,
errors: [ { messageId: 'invalidFormatString' } ],
},
{
code: `sprintf( '%%', 'substitute' )`,
errors: [ { messageId: 'noPlaceholders' } ],
},
{
code: `sprintf( __( '%%' ), 'substitute' )`,
errors: [ { messageId: 'noPlaceholders' } ],
},
{
code: `sprintf( _n( '%s', '' ), 'substitute' )`,
errors: [ { messageId: 'placeholderMismatch' } ],
},
{
code: `sprintf( _n( '%s', '%s %s' ), 'substitute' )`,
errors: [ { messageId: 'placeholderMismatch' } ],
},
{
code: `
sprintf(
/* translators: 1: number of blocks. 2: average rating. */
_n(
'This author has %d block, with an average rating of %d.',
'This author has %d blocks, with an average rating of %d.',
authorBlockCount
),
authorBlockCount,
authorBlockRating
);`,
errors: [ { messageId: 'noOrderedPlaceholders' } ],
},
{
code: `i18n.sprintf()`,
errors: [ { messageId: 'noFormatString' } ],
},
{
code: `i18n.sprintf( i18n.__( '%%' ), 'substitute' )`,
errors: [ { messageId: 'noPlaceholders' } ],
},
],
} );

View File

@@ -0,0 +1,249 @@
/**
* Converts store name to variable name.
* Removes dashes and uppercases the characters after dashes and appends `Store` at the end.
*
* @param {string} storeName
* @return {string} store name as variable name
*/
function storeNameToVariableNames( storeName ) {
return (
storeName
.split( '-' )
.map( ( value, index ) =>
index === 0
? value.toLowerCase()
: value[ 0 ].toUpperCase() + value.slice( 1 ).toLowerCase()
)
.join( '' ) + 'Store'
);
}
/**
* Returns last element of an array.
*
* @param {Array} array
* @return {*} last element of the array
*/
function arrayLast( array ) {
return array[ array.length - 1 ];
}
function getReferences( context, specifiers ) {
const variables = specifiers.reduce(
( acc, specifier ) =>
acc.concat( context.getDeclaredVariables( specifier ) ),
[]
);
const references = variables.reduce(
( acc, variable ) => acc.concat( variable.references ),
[]
);
return references;
}
function collectAllNodesFromCallbackFunctions( context, node ) {
const functionSpecifiers = node.specifiers.filter(
( specifier ) =>
specifier.imported &&
[
'createRegistrySelector',
'useSelect',
'withSelect',
'withDispatch',
].includes( specifier.imported.name )
);
const functionReferences = getReferences( context, functionSpecifiers );
const functionArgumentVariables = functionReferences.reduce(
( acc, { identifier: { parent } } ) =>
parent && parent.arguments && parent.arguments.length > 0
? acc.concat(
context.getDeclaredVariables( parent.arguments[ 0 ] )
)
: acc,
[]
);
const functionArgumentReferences = functionArgumentVariables.reduce(
( acc, variable ) => acc.concat( variable.references ),
[]
);
const possibleCallExpressionNodes = functionArgumentReferences
.filter( ( reference ) => reference.identifier.parent )
.map( ( reference ) => reference.identifier.parent );
return possibleCallExpressionNodes;
}
function collectAllNodesFromDirectFunctionCalls( context, node ) {
const specifiers = node.specifiers.filter(
( specifier ) =>
specifier.imported &&
[
'useDispatch',
'dispatch',
'useSelect',
'select',
'resolveSelect',
].includes( specifier.imported.name )
);
const references = getReferences( context, specifiers );
const possibleCallExpressionNodes = references
.filter( ( reference ) => reference.identifier.parent )
.map( ( reference ) => reference.identifier.parent );
return possibleCallExpressionNodes;
}
function collectAllNodesFromObjectPropertyFunctionCalls( context, node ) {
const specifiers = node.specifiers.filter(
( specifier ) =>
specifier.imported &&
[ 'controls' ].includes( specifier.imported.name )
);
const references = getReferences( context, specifiers );
const referencesWithPropertyCalls = references.filter(
( reference ) =>
reference.identifier.parent.property &&
[ 'select', 'resolveSelect', 'dispatch' ].includes(
reference.identifier.parent.property.name
)
);
const possibleCallExpressionNodes = referencesWithPropertyCalls
.filter(
( reference ) =>
reference.identifier.parent &&
reference.identifier.parent.parent
)
.map( ( reference ) => reference.identifier.parent.parent );
return possibleCallExpressionNodes;
}
function getSuggest( context, callNode ) {
return [
{
desc: 'Replace literal with store definition. Import store if necessary.',
fix: ( fixer ) => getFixes( fixer, context, callNode ),
},
];
}
function getFixes( fixer, context, callNode ) {
const storeName = callNode.arguments[ 0 ].value;
const storeDefinitions = {
core: {
import: '@wordpress/core-data',
variable: 'coreStore',
},
};
let storeDefinition = storeDefinitions[ storeName ];
if ( ! storeDefinition && storeName.startsWith( 'core/' ) ) {
const storeNameWithoutCore = storeName.substring( 5 );
storeDefinition = {
import: `@wordpress/${ storeNameWithoutCore }`,
variable: storeNameToVariableNames( storeNameWithoutCore ),
};
}
if ( ! storeDefinition ) {
return null;
}
const { variable: variableName, import: importName } = storeDefinition;
const fixes = [
fixer.replaceText( callNode.arguments[ 0 ], variableName ),
];
const imports = context
.getAncestors()[ 0 ]
.body.filter( ( node ) => node.type === 'ImportDeclaration' );
const packageImports = imports.filter(
( node ) => node.source.value === importName
);
const packageImport =
packageImports.length > 0 ? packageImports[ 0 ] : null;
if ( packageImport ) {
const alreadyHasStore = packageImport.specifiers.some(
( specifier ) => specifier.imported.name === 'store'
);
if ( ! alreadyHasStore ) {
const lastSpecifier = arrayLast( packageImport.specifiers );
fixes.push(
fixer.insertTextAfter(
lastSpecifier,
`,store as ${ variableName }`
)
);
}
} else {
const wpImports = imports.filter( ( node ) =>
node.source.value.startsWith( '@wordpress/' )
);
const lastImport =
wpImports.length > 0
? arrayLast( wpImports )
: arrayLast( imports );
fixes.push(
fixer.insertTextAfter(
lastImport,
`\nimport { store as ${ variableName } } from '${ importName }';`
)
);
}
return fixes;
}
module.exports = {
meta: {
type: 'problem',
hasSuggestions: true,
schema: [],
messages: {
doNotUseStringLiteral: `Do not use string literals ( '{{ argument }}' ) for accessing @wordpress/data stores. Pass the store definition instead`,
},
},
create( context ) {
return {
ImportDeclaration( node ) {
if ( node.source.value !== '@wordpress/data' ) {
return;
}
const callbackFunctionNodes =
collectAllNodesFromCallbackFunctions( context, node );
const directNodes = collectAllNodesFromDirectFunctionCalls(
context,
node
);
const objectPropertyCallNodes =
collectAllNodesFromObjectPropertyFunctionCalls(
context,
node
);
const allNodes = [
...callbackFunctionNodes,
...directNodes,
...objectPropertyCallNodes,
];
allNodes
.filter(
( callNode ) =>
callNode &&
callNode.type === 'CallExpression' &&
callNode.arguments.length > 0 &&
callNode.arguments[ 0 ].type === 'Literal'
)
.forEach( ( callNode ) => {
context.report( {
node: callNode.parent,
messageId: 'doNotUseStringLiteral',
data: { argument: callNode.arguments[ 0 ].value },
suggest: getSuggest( context, callNode ),
} );
} );
},
};
},
};

View File

@@ -0,0 +1,260 @@
/** @typedef {import('estree').Comment} Comment */
/** @typedef {import('estree').Node} Node */
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'layout',
docs: {
description: 'Enforce dependencies docblocks formatting',
url: 'https://github.com/WordPress/gutenberg/blob/HEAD/packages/eslint-plugin/docs/rules/dependency-group.md',
},
schema: [],
fixable: 'code',
},
create( context ) {
const comments = context.getSourceCode().getAllComments();
/**
* Locality classification of an import, one of "External",
* "WordPress", "Internal".
*
* @typedef {string} WPPackageLocality
*/
/**
* Object describing a dependency block correction to be made.
*
* @typedef WPDependencyBlockCorrection
*
* @property {Comment} [comment] Comment node on which to replace value,
* if one can be salvaged.
* @property {string} value Expected comment node value.
*/
/**
* Given a desired locality, generates the expected comment node value
* property.
*
* @param {WPPackageLocality} locality Desired package locality.
*
* @return {string} Expected comment node value.
*/
function getCommentValue( locality ) {
return `*\n * ${ locality } dependencies\n `;
}
/**
* Given an import source string, returns the locality classification
* of the import sort.
*
* @param {string} source Import source string.
*
* @return {WPPackageLocality} Package locality.
*/
function getPackageLocality( source ) {
if ( source.startsWith( '.' ) ) {
return 'Internal';
} else if ( source.startsWith( '@wordpress/' ) ) {
return 'WordPress';
}
return 'External';
}
/**
* Returns true if the given comment node satisfies a desired locality,
* or false otherwise.
*
* @param {Comment} node Comment node to check.
* @param {WPPackageLocality} locality Desired package locality.
*
* @return {boolean} Whether comment node satisfies locality.
*/
function isLocalityDependencyBlock( node, locality ) {
const { type, value } = node;
if ( type !== 'Block' ) {
return false;
}
// Tolerances:
// - Normalize `/**` and `/*`
// - Case insensitive "Dependencies" vs. "dependencies"
// - Ending period
// - "Node" dependencies as an alias for External.
if ( locality === 'External' ) {
locality = '(External|Node)';
}
const pattern = new RegExp(
`^\\*?\\n \\* ${ locality } dependencies\\.?\\n $`,
'i'
);
return pattern.test( value );
}
/**
* Returns true if the given node occurs prior in code to a reference,
* or false otherwise.
*
* @param {Comment} node Node to test being before reference.
* @param {Node} reference Node against which to compare.
*
* @return {boolean} Whether node occurs before reference.
*/
function isBefore( node, reference ) {
if ( ! node.range || ! reference.range ) {
return false;
}
return node.range[ 0 ] < reference.range[ 0 ];
}
/**
* Tests source comments to determine whether a comment exists which
* satisfies the desired locality. If a match is found and requires no
* updates, the function returns undefined. Otherwise, it will return
* a WPDependencyBlockCorrection object describing a correction.
*
* @param {Node} node Node to test.
* @param {WPPackageLocality} locality Desired package locality.
*
* @return {WPDependencyBlockCorrection | undefined} Correction, if applicable.
*/
function getDependencyBlockCorrection( node, locality ) {
const value = getCommentValue( locality );
let comment;
for ( let i = 0; i < comments.length; i++ ) {
comment = comments[ i ];
if ( ! isBefore( comment, node ) ) {
// Exhausted options.
break;
}
if ( ! isLocalityDependencyBlock( comment, locality ) ) {
// Not usable (either not an block comment, or not one
// matching a tolerable pattern).
continue;
}
if ( comment.value === value ) {
// No change needed. (OK)
return;
}
// Found a comment needing correction.
return { comment, value };
}
return { value };
}
return {
/**
* @param {import('estree').Program} node Program node.
*/
Program( node ) {
/**
* The set of package localities which have been reported for
* the current program. Each locality is reported at most one
* time, since otherwise the fixer would insert a comment
* block for each individual import statement.
*
* @type {Set<WPPackageLocality>}
*/
const verified = new Set();
/**
* Nodes to check for violations associated with module import,
* an array of tuples of the node and its import source string.
*
* @type {Array<[Node,string]>}
*/
const candidates = [];
// Since we only care to enforce imports which occur at the
// top-level scope, match on Program and test its children,
// rather than matching the import nodes directly.
node.body.forEach( ( child ) => {
/** @type {string} */
let source;
switch ( child.type ) {
case 'ImportDeclaration':
source = /** @type {string} */ (
child.source.value
);
candidates.push( [ child, source ] );
break;
case 'VariableDeclaration':
child.declarations.forEach( ( declaration ) => {
const { init } = declaration;
if (
! init ||
init.type !== 'CallExpression' ||
/** @type {import('estree').CallExpression} */ (
init
).callee.type !== 'Identifier' ||
/** @type {import('estree').Identifier} */ (
init.callee
).name !== 'require'
) {
return;
}
const { arguments: args } = init;
if (
args.length === 1 &&
args[ 0 ].type === 'Literal' &&
typeof args[ 0 ].value === 'string'
) {
source = args[ 0 ].value;
candidates.push( [ child, source ] );
}
} );
}
} );
for ( const [ child, source ] of candidates ) {
const locality = getPackageLocality( source );
if ( verified.has( locality ) ) {
continue;
}
// Avoid verifying any other imports for the locality,
// regardless whether a correction must be made.
verified.add( locality );
// Determine whether a correction must be made.
const correction = getDependencyBlockCorrection(
child,
locality
);
if ( ! correction ) {
continue;
}
context.report( {
node: child,
message: `Expected preceding "${ locality } dependencies" comment block`,
fix( fixer ) {
const { comment, value } = correction;
const text = `/*${ value }*/`;
if ( comment && comment.range ) {
return fixer.replaceTextRange(
comment.range,
text
);
}
return fixer.insertTextBefore( child, text + '\n' );
},
} );
}
},
};
},
};

View File

@@ -0,0 +1,174 @@
/**
* Traverse up through the chain of parent AST nodes returning the first parent
* the predicate returns a truthy value for.
*
* @param {Object} sourceNode The AST node to search from.
* @param {Function} predicate A predicate invoked for each parent.
*
* @return {Object | undefined} The first encountered parent node where the predicate
* returns a truthy value.
*/
function findParent( sourceNode, predicate ) {
if ( ! sourceNode.parent ) {
return;
}
if ( predicate( sourceNode.parent ) ) {
return sourceNode.parent;
}
return findParent( sourceNode.parent, predicate );
}
/**
* Tests whether the GUTENBERG_PHASE variable is accessed via
* `process.env.GUTENBERG_PHASE`.
*
* @example
* ```js
* // good
* if ( process.env.GUTENBERG_PHASE === 2 ) {
*
* // bad
* if ( GUTENBERG_PHASE === 2 ) {
* ```
*
* @param {Object} node The GUTENBERG_PHASE identifier node.
* @param {Object} context The eslint context object.
*/
function testIsAccessedViaProcessEnv( node, context ) {
const parent = node.parent;
if (
parent &&
parent.type === 'MemberExpression' &&
context.getSource( parent ) === 'process.env.GUTENBERG_PHASE'
) {
return;
}
context.report(
node,
'The `GUTENBERG_PHASE` constant should be accessed using `process.env.GUTENBERG_PHASE`.'
);
}
/**
* Tests whether the GUTENBERG_PHASE variable is used in a strict binary
* equality expression in a comparison with a number, triggering a
* violation if not.
*
* @example
* ```js
* // good
* if ( process.env.GUTENBERG_PHASE === 2 ) {
*
* // bad
* if ( process.env.GUTENBERG_PHASE >= '2' ) {
* ```
*
* @param {Object} node The GUTENBERG_PHASE identifier node.
* @param {Object} context The eslint context object.
*/
function testIsUsedInStrictBinaryExpression( node, context ) {
const parent = findParent(
node,
( candidate ) => candidate.type === 'BinaryExpression'
);
if ( parent ) {
const comparisonNode =
node.parent.type === 'MemberExpression' ? node.parent : node;
// Test for process.env.GUTENBERG_PHASE === <number> or <number> === process.env.GUTENBERG_PHASE.
const hasCorrectOperator = [ '===', '!==' ].includes( parent.operator );
const hasCorrectOperands =
( parent.left === comparisonNode &&
typeof parent.right.value === 'number' ) ||
( parent.right === comparisonNode &&
typeof parent.left.value === 'number' );
if ( hasCorrectOperator && hasCorrectOperands ) {
return;
}
}
context.report(
node,
'The `GUTENBERG_PHASE` constant should only be used in a strict equality comparison with a primitive number.'
);
}
/**
* Tests whether the GUTENBERG_PHASE variable is used as the condition for an
* if statement, triggering a violation if not.
*
* @example
* ```js
* // good
* if ( process.env.GUTENBERG_PHASE === 2 ) {
*
* // bad
* const isFeatureActive = process.env.GUTENBERG_PHASE === 2;
* ```
*
* @param {Object} node The GUTENBERG_PHASE identifier node.
* @param {Object} context The eslint context object.
*/
function testIsUsedInIfOrTernary( node, context ) {
const conditionalParent = findParent( node, ( candidate ) =>
[ 'IfStatement', 'ConditionalExpression' ].includes( candidate.type )
);
const binaryParent = findParent(
node,
( candidate ) => candidate.type === 'BinaryExpression'
);
if (
conditionalParent &&
binaryParent &&
conditionalParent.test &&
conditionalParent.test.range[ 0 ] === binaryParent.range[ 0 ] &&
conditionalParent.test.range[ 1 ] === binaryParent.range[ 1 ]
) {
return;
}
context.report(
node,
'The `GUTENBERG_PHASE` constant should only be used as part of the condition in an if statement or ternary expression.'
);
}
module.exports = {
meta: {
type: 'problem',
schema: [],
deprecated: true,
replacedBy: '@wordpress/is-gutenberg-plugin',
},
create( context ) {
return {
Identifier( node ) {
// Bypass any identifiers with a node name different to `GUTENBERG_PHASE`.
if ( node.name !== 'GUTENBERG_PHASE' ) {
return;
}
testIsAccessedViaProcessEnv( node, context );
testIsUsedInStrictBinaryExpression( node, context );
testIsUsedInIfOrTernary( node, context );
},
Literal( node ) {
// Bypass any identifiers with a node value different to `GUTENBERG_PHASE`.
if ( node.value !== 'GUTENBERG_PHASE' ) {
return;
}
if ( node.parent && node.parent.type === 'MemberExpression' ) {
testIsAccessedViaProcessEnv( node, context );
}
},
};
},
};

View File

@@ -0,0 +1,98 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
getTextContentFromNode,
getTranslateFunctionName,
getTranslateFunctionArgs,
} = require( '../utils' );
const THREE_DOTS = '...';
const ELLIPSIS = '…';
function replaceThreeDotsWithEllipsis( string ) {
return string.replace( /\.\.\./g, ELLIPSIS );
}
// see eslint-plugin-wpcalypso.
function makeFixerFunction( arg ) {
return ( fixer ) => {
switch ( arg.type ) {
case 'TemplateLiteral':
return arg.quasis.reduce( ( fixes, quasi ) => {
if (
'TemplateElement' === quasi.type &&
quasi.value.raw.includes( THREE_DOTS )
) {
fixes.push(
fixer.replaceTextRange(
[ quasi.start, quasi.end ],
replaceThreeDotsWithEllipsis( quasi.value.raw )
)
);
}
return fixes;
}, [] );
case 'Literal':
return [
fixer.replaceText(
arg,
replaceThreeDotsWithEllipsis( arg.raw )
),
];
case 'BinaryExpression':
return [
...makeFixerFunction( arg.left )( fixer ),
...makeFixerFunction( arg.right )( fixer ),
];
}
};
}
module.exports = {
meta: {
type: 'problem',
schema: [],
messages: {
foundThreeDots: 'Use ellipsis character (…) in place of three dots',
},
fixable: 'code',
},
create( context ) {
return {
CallExpression( node ) {
const { callee, arguments: args } = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const candidates = getTranslateFunctionArgs(
functionName,
args
);
for ( const arg of candidates ) {
const argumentString = getTextContentFromNode( arg );
if (
! argumentString ||
! argumentString.includes( THREE_DOTS )
) {
continue;
}
context.report( {
node,
messageId: 'foundThreeDots',
fix: makeFixerFunction( arg ),
} );
}
},
};
},
};

View File

@@ -0,0 +1,101 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
getTextContentFromNode,
getTranslateFunctionName,
getTranslateFunctionArgs,
} = require( '../utils' );
const EN_DASH = '';
const HYPHEN_IN_RANGE = /(\d\s+-\s+\d)|(\d-\d)/g;
function replaceHyphenWithEnDash( string ) {
if ( string.match( HYPHEN_IN_RANGE ) ) {
return string.replace( '-', EN_DASH );
}
return string;
}
function makeFixerFunction( arg ) {
return ( fixer ) => {
switch ( arg.type ) {
case 'TemplateLiteral':
return arg.quasis.reduce( ( fixes, quasi ) => {
if (
'TemplateElement' === quasi.type &&
quasi.value.raw.match( HYPHEN_IN_RANGE )
) {
fixes.push(
fixer.replaceTextRange(
[ quasi.start, quasi.end ],
replaceHyphenWithEnDash( quasi.value.raw )
)
);
}
return fixes;
}, [] );
case 'Literal':
return [
fixer.replaceText(
arg,
replaceHyphenWithEnDash( arg.raw )
),
];
case 'BinaryExpression':
return [
...makeFixerFunction( arg.left )( fixer ),
...makeFixerFunction( arg.right )( fixer ),
];
}
};
}
module.exports = {
meta: {
type: 'problem',
schema: [],
messages: {
foundHyphen:
'Use dashes (en or em) in place of hyphens for numeric ranges.',
},
fixable: 'code',
},
create( context ) {
return {
CallExpression( node ) {
const { callee, arguments: args } = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const candidates = getTranslateFunctionArgs(
functionName,
args
);
for ( const arg of candidates ) {
const argumentString = getTextContentFromNode( arg );
if (
! argumentString ||
! argumentString.match( HYPHEN_IN_RANGE )
) {
continue;
}
context.report( {
node,
messageId: 'foundHyphen',
fix: makeFixerFunction( arg ),
} );
}
},
};
},
};

View File

@@ -0,0 +1,73 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
getTextContentFromNode,
getTranslateFunctionName,
getTranslateFunctionArgs,
} = require( '../utils' );
const PROBLEMS_BY_CHAR_CODE = {
9: '\\t',
10: '\\n',
13: '\\r',
32: 'consecutive spaces',
};
module.exports = {
meta: {
type: 'problem',
schema: [],
messages: {
noCollapsibleWhitespace:
'Translations should not contain collapsible whitespace{{problem}}',
},
},
create( context ) {
return {
CallExpression( node ) {
const { callee, arguments: args } = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const candidates = getTranslateFunctionArgs(
functionName,
args
);
for ( const arg of candidates ) {
const argumentString = getTextContentFromNode( arg );
if ( ! argumentString ) {
continue;
}
const collapsibleWhitespace =
argumentString.match( /(\n|\t|\r| {2})/ );
if ( ! collapsibleWhitespace ) {
continue;
}
const problem =
PROBLEMS_BY_CHAR_CODE[
collapsibleWhitespace[ 0 ].charCodeAt( 0 )
];
const problemString = problem ? ` (${ problem })` : '';
context.report( {
node,
messageId: 'noCollapsibleWhitespace',
data: {
problem: problemString,
},
} );
}
},
};
},
};

View File

@@ -0,0 +1,90 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
getTextContentFromNode,
getTranslateFunctionName,
getTranslateFunctionArgs,
} = require( '../utils' );
const PROBLEMS_BY_CHAR_CODE = {
9: '\\t',
10: '\\n',
13: '\\r',
32: 'whitespace',
};
function makeFixerFunction( arg ) {
return ( fixer ) => {
switch ( arg.type ) {
case 'Literal':
return [ fixer.replaceText( arg, `'${ arg.value.trim() }'` ) ];
case 'BinaryExpression':
return [
...makeFixerFunction( arg.left )( fixer ),
...makeFixerFunction( arg.right )( fixer ),
];
}
};
}
module.exports = {
meta: {
type: 'problem',
schema: [],
messages: {
noFlankingWhitespace:
'Translations should not contain flanking whitespace{{problem}}',
},
fixable: 'code',
},
create( context ) {
return {
CallExpression( node ) {
const { callee, arguments: args } = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const candidates = getTranslateFunctionArgs(
functionName,
args
);
for ( const arg of candidates ) {
const argumentString = getTextContentFromNode( arg );
if ( ! argumentString ) {
continue;
}
const trimmableWhitespace =
argumentString.match( /^\s|\s$/ );
if ( ! trimmableWhitespace ) {
continue;
}
const problem =
PROBLEMS_BY_CHAR_CODE[
trimmableWhitespace[ 0 ].charCodeAt( 0 )
];
const problemString = problem ? ` (${ problem })` : '';
context.report( {
node,
messageId: 'noFlankingWhitespace',
data: {
problem: problemString,
},
fix: makeFixerFunction( arg ),
} );
}
},
};
},
};

View File

@@ -0,0 +1,59 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
REGEXP_SPRINTF_PLACEHOLDER,
getTextContentFromNode,
getTranslateFunctionName,
getTranslateFunctionArgs,
} = require( '../utils' );
module.exports = {
meta: {
type: 'problem',
schema: [],
messages: {
noPlaceholdersOnly:
'Translatable strings should not contain nothing but placeholders',
},
},
create( context ) {
return {
CallExpression( node ) {
const { callee, arguments: args } = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const candidates = getTranslateFunctionArgs(
functionName,
args
);
for ( const arg of candidates ) {
const argumentString = getTextContentFromNode( arg );
if ( ! argumentString ) {
continue;
}
const modifiedString = argumentString
.replace( /%%/g, 'VALID_ESCAPED_PERCENTAGE_SIGN' )
.replace( REGEXP_SPRINTF_PLACEHOLDER, '' );
if ( modifiedString.length > 0 ) {
continue;
}
context.report( {
node,
messageId: 'noPlaceholdersOnly',
} );
}
},
};
},
};

View File

@@ -0,0 +1,66 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
getTranslateFunctionName,
getTranslateFunctionArgs,
} = require( '../utils' );
function isAcceptableLiteralNode( node ) {
if ( 'BinaryExpression' === node.type ) {
return (
'+' === node.operator &&
isAcceptableLiteralNode( node.left ) &&
isAcceptableLiteralNode( node.right )
);
}
if ( 'TemplateLiteral' === node.type ) {
// Backticks are fine, but if there's any interpolation in it,
// that's a problem.
return node.expressions.length === 0;
}
return 'Literal' === node.type;
}
module.exports = {
meta: {
type: 'problem',
schema: [],
messages: {
invalidArgument:
'Translate function arguments must be string literals.',
},
},
create( context ) {
return {
CallExpression( node ) {
const { callee, arguments: args } = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const candidates = getTranslateFunctionArgs(
functionName,
args
);
for ( const arg of candidates ) {
if ( isAcceptableLiteralNode( arg ) ) {
continue;
}
context.report( {
node,
messageId: 'invalidArgument',
} );
}
},
};
},
};

View File

@@ -0,0 +1,162 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
getTranslateFunctionName,
} = require( '../utils' );
/**
* Returns the text domain passed to the given translation function.
*
* @param {string} functionName Translation function name.
* @param {Array} args Function arguments.
* @return {undefined|*} Text domain argument.
*/
function getTextDomain( functionName, args ) {
switch ( functionName ) {
case '__':
return args[ 1 ];
case '_x':
return args[ 2 ];
case '_n':
return args[ 3 ];
case '_nx':
return args[ 4 ];
default:
return undefined;
}
}
module.exports = {
meta: {
type: 'problem',
schema: [
{
type: 'object',
properties: {
// Supports a single string as the majority use case,
// but also an array of text domains.
allowedTextDomain: {
anyOf: [
{
type: 'array',
items: {
type: 'string',
},
uniqueItems: true,
},
{
type: 'string',
},
],
},
},
additionalProperties: false,
},
],
messages: {
invalidValue: "Invalid text domain '{{ textDomain }}'",
invalidType: 'Text domain is not a string literal',
unnecessaryDefault: 'Unnecessary default text domain',
missing: 'Missing text domain',
useAllowedValue:
'Use one of the allowed text domains: {{ textDomains }}',
},
fixable: 'code',
},
create( context ) {
const options = context.options[ 0 ] || {};
const { allowedTextDomain } = options;
const allowedTextDomains = Array.isArray( allowedTextDomain )
? allowedTextDomain
: [ allowedTextDomain ].filter( ( value ) => value );
const canFixTextDomain = allowedTextDomains.length === 1;
const allowDefault =
allowedTextDomains.length === 0 ||
allowedTextDomains.includes( 'default' );
return {
CallExpression( node ) {
const { callee, arguments: args } = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const textDomain = getTextDomain( functionName, args );
if ( textDomain === undefined ) {
if ( ! allowDefault ) {
const addMissingTextDomain = ( fixer ) => {
const lastArg = args[ args.length - 1 ];
return fixer.insertTextAfter(
lastArg,
`, '${ allowedTextDomains[ 0 ] }'`
);
};
context.report( {
node,
messageId: 'missing',
fix: canFixTextDomain ? addMissingTextDomain : null,
} );
}
return;
}
const { type, value, range } = textDomain;
if ( type !== 'Literal' ) {
context.report( {
node,
messageId: 'invalidType',
} );
return;
}
if ( 'default' === value && allowDefault ) {
const removeDefaultTextDomain = ( fixer ) => {
const previousArgIndex = args.indexOf( textDomain ) - 1;
const previousArg = args[ previousArgIndex ];
return fixer.removeRange( [
previousArg.range[ 1 ],
range[ 1 ],
] );
};
context.report( {
node,
messageId: 'unnecessaryDefault',
fix: removeDefaultTextDomain,
} );
return;
}
if (
allowedTextDomains.length &&
! allowedTextDomains.includes( value )
) {
const replaceTextDomain = ( fixer ) => {
return fixer.replaceTextRange(
// Account for quotes.
[ range[ 0 ] + 1, range[ 1 ] - 1 ],
allowedTextDomains[ 0 ]
);
};
context.report( {
node,
messageId: 'invalidValue',
data: {
textDomain: value,
},
fix: canFixTextDomain ? replaceTextDomain : null,
} );
}
},
};
},
};

View File

@@ -0,0 +1,112 @@
/**
* Internal dependencies
*/
const {
TRANSLATION_FUNCTIONS,
REGEXP_SPRINTF_PLACEHOLDER,
getTranslateFunctionName,
getTranslateFunctionArgs,
getTextContentFromNode,
} = require( '../utils' );
module.exports = {
meta: {
type: 'problem',
messages: {
missing:
'Translation function with placeholders is missing preceding translator comment',
},
},
create( context ) {
return {
CallExpression( node ) {
const {
callee,
loc: {
start: { line: currentLine },
},
parent,
arguments: args,
} = node;
const functionName = getTranslateFunctionName( callee );
if ( ! TRANSLATION_FUNCTIONS.has( functionName ) ) {
return;
}
const candidates = getTranslateFunctionArgs(
functionName,
args
).map( getTextContentFromNode );
if ( candidates.filter( Boolean ).length === 0 ) {
return;
}
const hasPlaceholders = candidates.some( ( candidate ) =>
REGEXP_SPRINTF_PLACEHOLDER.test( candidate )
);
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#Using_test()_on_a_regex_with_the_global_flag.
REGEXP_SPRINTF_PLACEHOLDER.lastIndex = 0;
if ( ! hasPlaceholders ) {
return;
}
const comments = context.getCommentsBefore( node ).slice();
let parentNode = parent;
/**
* Loop through all parent nodes and get their preceding comments as well.
*
* This way we can gather comments that are not directly preceding the translation
* function call, but are just on the line above it. This case is commonly supported
* by string extraction tools like WP-CLI's i18n command.
*/
while (
parentNode &&
parentNode.type !== 'Program' &&
Math.abs( parentNode.loc.start.line - currentLine ) <= 1
) {
comments.push( ...context.getCommentsBefore( parentNode ) );
parentNode = parentNode.parent;
}
for ( const comment of comments ) {
const {
value: commentText,
loc: {
end: { line: commentLine },
},
} = comment;
/*
Skip cases like this:
// translators: %s: Preference
console.log(
sprintf(
__( 'Preference: %s' ),
preference
)
);
*/
if ( Math.abs( commentLine - currentLine ) > 1 ) {
break;
}
if ( /translators:\s*\S+/i.test( commentText ) ) {
return;
}
}
context.report( {
node,
messageId: 'missing',
} );
},
};
},
};

1
node_modules/@wordpress/eslint-plugin/rules/index.js generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require( 'requireindex' )( __dirname );

View File

@@ -0,0 +1,94 @@
/**
* Traverse up through the chain of parent AST nodes returning the first parent
* the predicate returns a truthy value for.
*
* @param {Object} sourceNode The AST node to search from.
* @param {Function} predicate A predicate invoked for each parent.
*
* @return {Object | undefined} The first encountered parent node where the predicate
* returns a truthy value.
*/
function findParent( sourceNode, predicate ) {
if ( ! sourceNode.parent ) {
return;
}
if ( predicate( sourceNode.parent ) ) {
return sourceNode.parent;
}
return findParent( sourceNode.parent, predicate );
}
/**
* Tests whether the IS_GUTENBERG_PLUGIN variable is used as the condition for an
* if statement or ternary, triggering a violation if not.
*
* @example
* ```js
* // good
* if ( process.env.IS_GUTENBERG_PLUGIN ) {
*
* // bad
* const isFeatureActive = process.env.IS_GUTENBERG_PLUGIN;
* ```
*
* @param {Object} node The IS_GUTENBERG_PLUGIN identifier node.
* @param {Object} context The eslint context object.
*/
function isUsedInConditional( node, context ) {
const conditionalParent = findParent( node, ( candidate ) =>
[ 'IfStatement', 'ConditionalExpression' ].includes( candidate.type )
);
if ( ! conditionalParent ) {
return false;
}
// Allow for whitespace as prettier sometimes breaks this on separate lines.
const textRegex = /^\s*!?\s*process\s*\.\s*env\s*\.\s*IS_GUTENBERG_PLUGIN$/;
const testSource = context.getSource( conditionalParent.test );
if ( ! textRegex.test( testSource ) ) {
return false;
}
return true;
}
const ERROR_MESSAGE =
'The `process.env.IS_GUTENBERG_PLUGIN` constant should only be used as the condition in an if statement or ternary expression.';
module.exports = {
meta: {
type: 'problem',
schema: [],
},
create( context ) {
return {
Identifier( node ) {
// Bypass any identifiers with a node name different to `IS_GUTENBERG_PLUGIN`.
if ( node.name !== 'IS_GUTENBERG_PLUGIN' ) {
return;
}
if ( ! isUsedInConditional( node, context ) ) {
context.report( node, ERROR_MESSAGE );
}
},
// Check for literals, e.g. when 'IS_GUTENBERG_PLUGIN' is used as a string via something like 'window[ 'IS_GUTENBERG_PLUGIN' ]'.
Literal( node ) {
// Bypass any identifiers with a node value different to `IS_GUTENBERG_PLUGIN`.
if ( node.value !== 'IS_GUTENBERG_PLUGIN' ) {
return;
}
if ( node.parent && node.parent.type === 'MemberExpression' ) {
if ( ! isUsedInConditional( node, context ) ) {
context.report( node, ERROR_MESSAGE );
}
}
},
};
},
};

View File

@@ -0,0 +1,29 @@
module.exports = {
meta: {
type: 'problem',
schema: [],
},
create( context ) {
return {
"JSXOpeningElement[name.name='BaseControl']": ( node ) => {
const containsAttribute = ( attrName ) => {
return node.attributes.some( ( attribute ) => {
return (
attribute.name && attribute.name.name === attrName
);
} );
};
if (
containsAttribute( 'label' ) &&
! containsAttribute( 'id' )
) {
context.report( {
node,
message:
'When using BaseControl component if a label property is passed an id property should also be passed.',
} );
}
},
};
},
};

View File

@@ -0,0 +1,19 @@
module.exports = {
meta: {
type: 'problem',
schema: [],
},
create( context ) {
return {
'MemberExpression[object.name="document"][property.name="activeElement"]'(
node
) {
context.report( {
node,
message:
'Avoid accessing the active element with a global. Use the ownerDocument property on a node ref instead.',
} );
},
};
},
};

View File

@@ -0,0 +1,19 @@
module.exports = {
meta: {
type: 'problem',
schema: [],
},
create( context ) {
return {
'CallExpression[callee.object.name="window"][callee.property.name="getSelection"]'(
node
) {
context.report( {
node,
message:
'Avoid accessing the selection with a global. Use the ownerDocument.defaultView property on a node ref instead.',
} );
},
};
},
};

View File

@@ -0,0 +1,18 @@
module.exports = {
meta: {
type: 'problem',
schema: [],
},
create( context ) {
return {
'CallExpression[callee.object.callee.property.name="getSelection"][callee.property.name="getRangeAt"]'(
node
) {
context.report( {
node,
message: 'Avoid unguarded getRangeAt',
} );
},
};
},
};

View File

@@ -0,0 +1,88 @@
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
type: 'problem',
meta: {
schema: [
{
type: 'object',
additionalProperties: false,
patternProperties: {
'^@wordpress\\/[a-zA-Z0-9_-]+$': {
type: 'array',
uniqueItems: true,
minItems: 1,
items: {
type: 'string',
pattern: '^(?:__experimental|__unstable)',
},
},
},
},
],
},
create( context ) {
/** @type {AllowedImportsMap} */
const allowedImports =
( context.options &&
typeof context.options[ 0 ] === 'object' &&
context.options[ 0 ] ) ||
{};
const reporter = makeListener( { allowedImports, context } );
return { ImportDeclaration: reporter };
},
};
/**
* @param {Object} _
* @param {AllowedImportsMap} _.allowedImports
* @param {import('eslint').Rule.RuleContext} _.context
*
* @return {(node: Node) => void} Listener function
*/
function makeListener( { allowedImports, context } ) {
return function reporter( node ) {
if ( node.type !== 'ImportDeclaration' ) {
return;
}
if ( typeof node.source.value !== 'string' ) {
return;
}
const sourceModule = node.source.value.trim();
// Ignore non-WordPress packages.
if ( ! sourceModule.startsWith( '@wordpress/' ) ) {
return;
}
const allowedImportNames = allowedImports[ sourceModule ] || [];
node.specifiers.forEach( ( specifierNode ) => {
if ( specifierNode.type !== 'ImportSpecifier' ) {
return;
}
const importedName = specifierNode.imported.name;
if (
! importedName.startsWith( '__unstable' ) &&
! importedName.startsWith( '__experimental' )
) {
return;
}
if ( allowedImportNames.includes( importedName ) ) {
return;
}
context.report( {
message: `Usage of \`${ importedName }\` from \`${ sourceModule }\` is not allowed.\nSee https://developer.wordpress.org/block-editor/contributors/develop/coding-guidelines/#experimental-and-unstable-apis for details.`,
node: specifierNode,
} );
} );
};
}
/** @typedef {import('estree').Node} Node */
/** @typedef {Record<string, string[]|undefined>} AllowedImportsMap */

View File

@@ -0,0 +1,156 @@
/** @typedef {import('eslint').Scope.Scope} ESLintScope */
/** @typedef {import('eslint').Rule.RuleContext} ESLintRuleContext */
/** @typedef {import('estree').Node} ESTreeNode */
/**
* Mapping of function scope objects to a set of identified JSX identifiers
* within that scope.
*
* @type {WeakMap<ESLintScope,Set<ESTreeNode>>}
*/
const FUNCTION_SCOPE_JSX_IDENTIFIERS = new WeakMap();
/**
* Returns the closest function scope for the current ESLint context object, or
* undefined if it cannot be determined.
*
* @param {ESLintRuleContext} context ESLint context object.
*
* @return {ESLintScope|undefined} Function scope, if known.
*/
function getClosestFunctionScope( context ) {
let functionScope = context.getScope();
while ( functionScope.type !== 'function' && functionScope.upper ) {
functionScope = functionScope.upper;
}
return functionScope;
}
module.exports = /** @type {import('eslint').Rule} */ ( {
meta: {
type: 'problem',
schema: [
{
type: 'object',
properties: {
excludePattern: {
type: 'string',
},
},
additionalProperties: false,
},
],
},
/**
* @param {ESLintRuleContext} context Rule context.
*/
create( context ) {
const options = context.options[ 0 ] || {};
const { excludePattern } = options;
/**
* Given an Espree VariableDeclarator node, returns true if the node
* can be exempted from consideration as unused, or false otherwise. A
* node can be exempt if it destructures to multiple variables, since
* those other variables may be used prior to the return statement. A
* future enhancement could validate that they are in-fact referenced.
*
* @param {Object} node Node to test.
*
* @return {boolean} Whether declarator is emempt from consideration.
*/
function isExemptObjectDestructureDeclarator( node ) {
return (
node.id.type === 'ObjectPattern' &&
node.id.properties.length > 1
);
}
return {
JSXIdentifier( node ) {
// Currently, a scope's variable references does not include JSX
// identifiers. Account for this by visiting JSX identifiers
// first, and tracking them in a map per function scope, which
// is later merged with the known variable references.
const functionScope = getClosestFunctionScope( context );
if ( ! functionScope ) {
return;
}
if ( ! FUNCTION_SCOPE_JSX_IDENTIFIERS.has( functionScope ) ) {
FUNCTION_SCOPE_JSX_IDENTIFIERS.set(
functionScope,
new Set()
);
}
FUNCTION_SCOPE_JSX_IDENTIFIERS.get( functionScope ).add( node );
},
'ReturnStatement:exit'( node ) {
const functionScope = getClosestFunctionScope( context );
if ( ! functionScope ) {
return;
}
for ( const variable of functionScope.variables ) {
const declaratorCandidate = variable.defs.find( ( def ) => {
return (
def.node.type === 'VariableDeclarator' &&
// Allow declarations which are not initialized.
def.node.init &&
// Target function calls as "expensive".
def.node.init.type === 'CallExpression' &&
// Allow unused if part of an object destructuring.
! isExemptObjectDestructureDeclarator( def.node ) &&
// Only target assignments preceding `return`.
def.node.range[ 1 ] < node.range[ 1 ]
);
} );
if ( ! declaratorCandidate ) {
continue;
}
if (
excludePattern !== undefined &&
new RegExp( excludePattern ).test(
declaratorCandidate.node.init.callee.name
)
) {
continue;
}
// The first entry in `references` is the declaration
// itself, which can be ignored.
const identifiers = variable.references
.slice( 1 )
.map( ( reference ) => reference.identifier );
// Merge with any JSX identifiers in scope, if any.
if ( FUNCTION_SCOPE_JSX_IDENTIFIERS.has( functionScope ) ) {
const jsxIdentifiers =
FUNCTION_SCOPE_JSX_IDENTIFIERS.get( functionScope );
identifiers.push( ...jsxIdentifiers );
}
const isUsedBeforeReturn = identifiers.some(
( identifier ) =>
identifier.range[ 1 ] < node.range[ 1 ]
);
if ( isUsedBeforeReturn ) {
continue;
}
context.report(
declaratorCandidate.node,
'Variables should not be assigned until just prior its first reference. ' +
'An early return statement may leave this variable unused.'
);
}
},
};
},
} );

View File

@@ -0,0 +1,93 @@
/**
* Given an Espree Node, returns true if the node is a component.
*
* @param {espree.Node} node Node to check.
*
* @return {boolean} Whether node is a component.
*/
function isComponent( node ) {
// Assume function component by naming convention of UpperCamelCase.
if (
node.type === 'FunctionDeclaration' &&
node.id &&
/^[A-Z]/.test( node.id.name )
) {
return true;
}
// Assume class component by extends name `Component`.
if ( node.type === 'ClassDeclaration' && node.superClass ) {
let superClassName;
switch ( node.superClass.type ) {
case 'Identifier':
superClassName = node.superClass.name;
break;
case 'MemberExpression':
superClassName = node.superClass.property.name;
break;
}
if ( superClassName === 'Component' ) {
return true;
}
}
return false;
}
module.exports = {
meta: {
type: 'problem',
schema: [],
},
create( context ) {
return {
'CallExpression[callee.name="setTimeout"]'( node ) {
// If the result of a `setTimeout` call is assigned to a
// variable, assume the timer ID is handled by a cancellation.
const hasAssignment =
node.parent.type === 'AssignmentExpression' ||
node.parent.type === 'VariableDeclarator';
if ( hasAssignment ) {
return;
}
let isInComponent = false;
let parent = node;
while ( ( parent = parent.parent ) ) {
if ( isComponent( parent ) ) {
isInComponent = true;
break;
}
}
// Only consider `setTimeout` which occur within a component.
if ( ! isInComponent ) {
return;
}
// Consider whether `setTimeout` is a reference to the global
// by checking references to see if `setTimeout` resolves to a
// variable in scope.
const { references } = context.getScope();
const hasResolvedReference = references.some(
( reference ) =>
reference.identifier.name === 'setTimeout' &&
!! reference.resolved &&
reference.resolved.scope.type !== 'global'
);
if ( hasResolvedReference ) {
return;
}
context.report(
node,
'setTimeout in a component must be cancelled on unmount'
);
},
};
},
};

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