Release Helper Tools 0.1.0

This commit is contained in:
2026-09-01 02:33:45 +02:00
commit daff326b20
78 changed files with 11635 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
node_modules/
dist/
lib-dist/
release/*.zip
release/*.zip.sha256
release/*.tgz
release/*.tgz.sha256
coverage/
playwright-report/
test-results/
*.tsbuildinfo
.DS_Store
+1
View File
@@ -0,0 +1 @@
@add-ideas:registry=https://git.add-ideas.de/api/packages/lotobo/npm/
+21
View File
@@ -0,0 +1,21 @@
# Changelog
All notable changes are documented here.
## Unreleased
## 0.1.0 - 2026-09-01
- Added a deep-linkable local browser workbench for encodings, text and
Unicode, number bases and units, networks, time, structured data, checksums,
cryptographic digests, and random values.
- Added the side-effect-free `@add-ideas/toolbox-helpers` ESM package with
generated TypeScript declarations and a single stable root export.
- Added explicit input, item, nesting and output limits with typed limit errors.
- Added strict IPv4, IPv6 and CIDR handling, hardened JSON/CSV processing,
canonical encodings, deterministic JSON and seeded random primitives.
- Hardened canonical Base64URL padding, large-output encoding, negative
human-duration round trips, finite unit conversion and portable filenames.
- Added the Toolbox 0.2.3 shell, system/light/dark themes, offline shell,
nested-path browser tests, licence/source documentation, and deterministic
application and library artifacts.
+11
View File
@@ -0,0 +1,11 @@
# Contributing
Use Node.js 22 and npm 11, install with `npm ci`, and run `npm run check` before
submitting a change. New helpers must be framework-free, deterministic unless
their name explicitly promises secure randomness, and bounded before allocating
from untrusted input. Add known vectors and malicious/boundary tests alongside
each implementation.
Do not add runtime network calls, telemetry, persistence, implicit evaluation,
or a second UI-only implementation of library logic. Preserve the stable root
exports or document a deliberate breaking change.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU 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 instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+5
View File
@@ -0,0 +1,5 @@
# Runtime licence inventory
`npm run release:prepare` generates `npm-runtime-licenses.txt` from the exact
runtime packages locked in `package-lock.json`. The reusable helper library has
no runtime dependency. The project licence is reproduced at `../LICENSE`.
+82
View File
@@ -0,0 +1,82 @@
# Helper Tools
Helper Tools is a local-first browser workbench and the source of the
`@add-ideas/toolbox-helpers` TypeScript package. It provides small, explicit,
bounded building blocks for common developer calculations without network
requests, telemetry, persistence, or server processing.
Version 0.1.0 includes:
- strict Base64, Base64URL, hexadecimal, UTF-8, UTF-16 and Latin-1 conversion;
- URL component and form encoding, Unicode scalar/grapheme inspection, case,
normalization and line-ending transforms;
- exact BigInt base conversion, SI/IEC data sizes, and common physical units;
- CRC-32, Adler-32, FNV-1a and Web Crypto SHA digests;
- strict IPv4/IPv6 parsing and exact CIDR ranges and containment;
- timestamp and bounded duration parsing and formatting;
- hardened JSON parsing, deterministic JSON and bounded CSV conversion; and
- secure random bytes/integers plus explicitly non-cryptographic seeded random
primitives for repeatable tests and samples.
## Browser app
```sh
npm ci
npm run dev
```
All workspaces are deep-linkable through URL hashes. Values live only in React
component state and disappear on refresh. Downloads use short-lived object URLs
that are revoked after use.
## Reusable package
The package is framework-free ESM with generated TypeScript declarations and no
install/runtime dependency. React and the Toolbox SDK are development-only app
build inputs and are not dependencies of package consumers. Every helper is
exported from one stable root:
```ts
import {
bytesToBase64Url,
digestHex,
parseCidr,
safeJsonParse,
} from "@add-ideas/toolbox-helpers";
const token = bytesToBase64Url(new Uint8Array([1, 2, 3]));
const hash = await digestHex(new TextEncoder().encode("local"));
const network = parseCidr("2001:db8::1/64");
const data = safeJsonParse('{"enabled":true}');
```
See [`docs/API.md`](docs/API.md) for the export groups and their security
boundaries. The browser app imports the same public root implementation; it does
not maintain a second calculator code path.
Build and inspect the package locally:
```sh
npm run build:library
npm pack --dry-run
```
## Verification and artifacts
```sh
npm run check
npm run test:browser
npm run package:release -- --force
npm run package:library -- --force
```
The application ZIP and npm-compatible `.tgz` are produced deterministically
with adjacent SHA-256 sidecars in `release/`. Neither artifact is published by
these commands.
## Licence
Helper Tools and `@add-ideas/toolbox-helpers` are licensed under
GPL-3.0-or-later. See [`LICENSE`](LICENSE). Shared Toolbox SDK and React notices
remain under their respective licences in `THIRD_PARTY_NOTICES.md` and the
generated release inventory.
+13
View File
@@ -0,0 +1,13 @@
# Security policy
Report suspected vulnerabilities privately to the repository owner through the
Gitea security contact rather than filing a public exploit description.
Helper Tools processes values locally. It does not make runtime network
requests, persist calculator inputs, evaluate parsed data, or inject generated
markup. Inputs, decoded outputs, collections and nesting are bounded. Downloads
use sanitized names and revocable object URLs.
Consumers remain responsible for treating decoded URLs, CSV cells, JSON values,
random-looking data and generated text as untrusted when handing them to another
system. Seeded randomness is reproducible and must never be used for secrets.
+28
View File
@@ -0,0 +1,28 @@
# Corresponding source and provenance
The corresponding source for Helper Tools 0.1.0 will be published at:
https://git.add-ideas.de/lotobo/helper-tools/src/tag/v0.1.0
Before that tag exists, the `main` branch in the same public repository is the
preferred source under active review. Build the release with Node.js 22 and the
exact dependency graph in `package-lock.json`:
```sh
npm ci
npm run release:artifact
```
The JavaScript/CSS bundles, npm tarball and generated declarations are outputs,
not the preferred form for modification. No runtime code is loaded from a CDN.
## Implementation provenance
- The helpers and interface are original TypeScript and React project code.
- Toolbox manifest, shell and artifact checks use the shared Toolbox SDK 0.2.3.
- Encoding formats, IP notation, JSON, CSV, SI/IEC units, Unicode, ISO 8601,
checksum and digest algorithms were implemented from public specifications
and established interoperable formats; no source from an online calculator
is bundled.
- Cryptographic digests and secure randomness use the browser Web Crypto API.
The seeded generator is deliberately labelled non-cryptographic.
+15
View File
@@ -0,0 +1,15 @@
# Third-party notices
The reusable `@add-ideas/toolbox-helpers` bundle has no runtime dependency. The
browser application uses these packages:
| Package | Version | Licence | Role |
| -------------------------------- | ------- | ---------- | ------------------------------- |
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 | manifest and context contract |
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 | shared shell, theme and actions |
| `react` | 19.2.8 | MIT | browser interface |
| `react-dom` | 19.2.8 | MIT | browser rendering |
Release preparation copies exact package-local licence texts from the locked
runtime graph into `LICENSES/npm-runtime-licenses.txt`. Development-only tools
are not shipped as runtime modules.
+7
View File
@@ -0,0 +1,7 @@
# Accessibility
Each workspace is reachable through a labelled tab and URL hash. Forms use
explicit labels, native controls, status/error regions, visible focus, and real
buttons for actions. Results remain selectable text and do not rely on colour.
The layout supports keyboard use, zoom, narrow screens, reduced motion and the
shared system/light/dark Toolbox themes.
+168
View File
@@ -0,0 +1,168 @@
# Package API
`@add-ideas/toolbox-helpers` is a side-effect-free ESM package with generated
TypeScript declarations and no runtime dependency. Import named helpers from
the package root; internal deep paths are not public API.
## Bounds
```ts
type BytesLike = ArrayBuffer | ArrayBufferView;
const DEFAULT_HELPER_LIMITS: Readonly<{
maxInputBytes: number; // 16 MiB
maxTextChars: 2_000_000;
maxItems: 100_000;
maxDepth: 128;
}>;
assertBoundedText(value: string, maximum?: number, label?: string): string;
assertBoundedBytes(value: BytesLike, maximum?: number, label?: string): Uint8Array;
assertBoundedItems(count: number, maximum?: number, label?: string): number;
assertPositiveSafeInteger(value: number, label: string): number;
asUint8Array(value: BytesLike): Uint8Array;
```
`HelperLimitError` extends `RangeError` and exposes numeric `actual` and `limit`
properties. Per-operation ceilings can be made narrower. They are compatibility
and denial-of-service boundaries, not a substitute for an application-wide
memory budget.
## Encoding and URLs
```ts
type TextEncoding = "utf-8" | "utf-16le" | "utf-16be" | "latin1";
interface DecodeBinaryOptions {
maxOutputBytes?: number;
allowWhitespace?: boolean;
}
bytesToBase64(input: BytesLike): string;
bytesToBase64Url(input: BytesLike, padded?: boolean): string;
base64ToBytes(input: string, options?: DecodeBinaryOptions): Uint8Array;
base64UrlToBytes(input: string, options?: DecodeBinaryOptions): Uint8Array;
bytesToHex(input: BytesLike, uppercase?: boolean): string;
hexToBytes(
input: string,
options?: DecodeBinaryOptions & { allowPrefix?: boolean },
): Uint8Array;
encodeText(input: string, encoding?: TextEncoding): Uint8Array;
decodeText(input: BytesLike, encoding?: TextEncoding, fatal?: boolean): string;
encodeUrlComponent(value: string): string;
decodeUrlComponent(value: string): string;
inspectUrl(value: string, base?: string): UrlParts;
parseFormEncoded(input: string, maximumFields?: number): FormEntries;
stringifyFormEncoded(entries: Iterable<readonly [string, string]>, maximumFields?: number): string;
```
Base64 decoders reject non-canonical alphabets, malformed padding and non-zero
unused bits. Base64URL accepts either no padding or the exact RFC 4648 padding
required for that value. URL inspection is inert: it parses text but never
opens or fetches the result.
## Checksums and digests
```ts
type DigestAlgorithm = "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512";
crc32(input: BytesLike, maximumBytes?: number): number;
adler32(input: BytesLike, maximumBytes?: number): number;
fnv1a32(input: BytesLike, maximumBytes?: number): number;
formatChecksum(value: number): string;
digestBytes(
input: BytesLike,
algorithm?: DigestAlgorithm,
maximumBytes?: number,
cryptoProvider?: Pick<Crypto, "subtle">,
): Promise<Uint8Array>;
digestHex(
input: BytesLike,
algorithm?: DigestAlgorithm,
maximumBytes?: number,
cryptoProvider?: Pick<Crypto, "subtle">,
): Promise<string>;
```
Digests use Web Crypto. SHA-1 is available only for interoperability. Checksums
and hashes do not establish authorship, and none of these functions is a
password-hashing API.
## Network
```ts
type IpVersion = 4 | 6;
interface ParsedIpAddress {
version: IpVersion;
bytes: Uint8Array;
value: bigint;
canonical: string;
}
interface ParsedCidr {
version: IpVersion;
prefixLength: number;
address: ParsedIpAddress;
network: ParsedIpAddress;
first: ParsedIpAddress;
last: ParsedIpAddress;
broadcast?: ParsedIpAddress;
size: bigint;
canonical: string;
}
parseIpAddress(input: string): ParsedIpAddress;
parseIpv4(input: string): ParsedIpAddress;
parseIpv6(input: string): ParsedIpAddress;
formatIpv4(input: bigint | BytesLike): string;
formatIpv6(input: bigint | BytesLike): string;
parseCidr(input: string): ParsedCidr;
cidrContains(
cidr: string | ParsedCidr,
address: string | ParsedIpAddress,
): boolean;
```
IPv4 leading zeroes and IPv6 zone identifiers are rejected rather than guessed.
The helpers perform no DNS, HTTP, probing or scanning. `bigint` fields preserve
128-bit values exactly and must be converted explicitly before JSON encoding.
## Downloads
```ts
interface ObjectUrlLease {
readonly url: string;
readonly revoked: boolean;
revoke(): void;
}
sanitizeDownloadFilename(input: string, fallback?: string, maximumLength?: number): string;
createObjectUrlLease(
blob: Blob,
urlApi?: Pick<typeof URL, "createObjectURL" | "revokeObjectURL">,
): ObjectUrlLease;
triggerBlobDownload(
blob: Blob,
filename: string,
ownerDocument?: Document,
): ObjectUrlLease;
```
`triggerBlobDownload` removes its temporary anchor synchronously and schedules
object URL revocation for the next task. Long-lived previews should instead
keep a lease and call `revoke()` when replaced or unmounted.
## Remaining groups
| Group | Exports |
| ----------------- | -------------------------------------------------------------------------------------------------------------------- |
| Unicode and text | `inspectCodePoints`, `fromCodePoints`, `segmentGraphemes`, `normalizeUnicode`, `transformCase`, `convertLineEndings` |
| Numbers and units | `parseBigIntRadix`, `formatBigIntRadix`, `convertNumberBase`, `convertDataUnit`, `convertUnit`, `unitDimension` |
| Time | `parseTimestamp`, `formatTimestamp`, `parseDuration`, `formatDuration` |
| Structured data | `safeJsonParse`, `stableStringify`, `parseCsv`, `stringifyCsv` |
| Random | `secureRandomBytes`, `secureRandomInt`, `createSeededRandom`, `shuffleSeeded` |
JSON dangerous object keys are rejected by default, cycles and unsupported
values are rejected by deterministic JSON, and CSV dimensions and fields are
bounded. Secure random functions use Web Crypto. The seeded generator is
reproducible and deliberately unsuitable for any secret, nonce, key, salt or
token.
+16
View File
@@ -0,0 +1,16 @@
# Architecture
`src/helpers` contains all framework-free production logic and is bundled as a
single tree-shakeable ESM entry with declaration files. `src/components` imports
that same root for the browser workspaces. React owns only ephemeral input and
presentation state.
The app uses the shared Toolbox shell, relative URLs, a small same-scope offline
service worker, and a static restrictive deployment model. There are no workers
in v0.1.0 because the bounded calculator operations are intentionally small;
cryptographic digests are asynchronous Web Crypto operations.
Application ZIP and npm package assembly are separate. The app includes the
shell and documentation. The npm package contains the library bundle,
declarations, API guide, source and security pointers, project licence and
third-party notices, but no React or Toolbox code in its executable bundle.
+17
View File
@@ -0,0 +1,17 @@
# Privacy and security boundaries
- No calculator performs runtime network access, telemetry or persistence.
- No input is restored after refresh. The service worker caches only static app
files, never calculator values.
- Binary/text allocation, structured nesting, row/column counts, random output
and numeric digits have explicit ceilings.
- JSON dangerous object keys are rejected by default. CSV and URL values remain
text; they are never evaluated or opened automatically.
- IP helpers calculate notation and CIDR membership without scanning, DNS or
connectivity checks.
- SHA results are digests, not proof of authenticity. CRC, Adler and FNV are not
cryptographic. Seeded random output is not secret.
- Download names remove path/control and bidirectional-override characters,
avoid Windows device names and are truncated without splitting surrogate
pairs. Object URLs are revoked. A user must still choose how and where
downloaded text is used.
+41
View File
@@ -0,0 +1,41 @@
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{
ignores: [
"dist",
"lib-dist",
"release",
"coverage",
"test-results",
"playwright-report",
],
},
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2023,
globals: { ...globals.browser, ...globals.worker },
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
},
},
{
files: ["scripts/**/*.mjs", "playwright.config.ts"],
languageOptions: { globals: globals.node },
},
);
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="Encode, convert, inspect and calculate common developer values locally in your browser."
/>
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
<link rel="manifest" href="./manifest.webmanifest" />
<meta name="theme-color" content="#24324a" />
<title>Helper Tools</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/main.tsx"></script>
</body>
</html>
+3603
View File
File diff suppressed because it is too large Load Diff
+93
View File
@@ -0,0 +1,93 @@
{
"name": "@add-ideas/toolbox-helpers",
"version": "0.1.0",
"description": "Bounded, local-first TypeScript helpers and browser calculators for the add·ideas Toolbox.",
"license": "GPL-3.0-or-later",
"author": "Albrecht Degering",
"repository": {
"type": "git",
"url": "git+https://git.add-ideas.de/lotobo/helper-tools.git"
},
"homepage": "https://git.add-ideas.de/lotobo/helper-tools",
"bugs": {
"url": "https://git.add-ideas.de/lotobo/helper-tools/issues"
},
"publishConfig": {
"registry": "https://git.add-ideas.de/api/packages/lotobo/npm/",
"access": "public"
},
"type": "module",
"sideEffects": false,
"main": "./lib-dist/index.js",
"module": "./lib-dist/index.js",
"types": "./lib-dist/types/index.d.ts",
"exports": {
".": {
"types": "./lib-dist/types/index.d.ts",
"import": "./lib-dist/index.js"
}
},
"files": [
"lib-dist/",
"LICENSE",
"README.md",
"SOURCE.md",
"CHANGELOG.md",
"SECURITY.md",
"THIRD_PARTY_NOTICES.md",
"docs/API.md"
],
"engines": {
"node": ">=22"
},
"scripts": {
"predev": "npm run manifest:generate",
"dev": "vite",
"prebuild": "npm run release:prepare && npm run manifest:generate",
"build": "tsc -b && vite build && npm run build:library",
"build:library": "vite build --config vite.lib.config.ts && tsc -p tsconfig.lib.json --emitDeclarationOnly",
"preview": "vite preview",
"typecheck": "tsc -b --pretty false",
"lint": "eslint . --max-warnings=0",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "vitest run",
"test:watch": "vitest",
"test:browser": "playwright test",
"manifest:generate": "node scripts/generate-toolbox-manifest.mjs",
"manifest:check": "node scripts/generate-toolbox-manifest.mjs --check",
"release:prepare": "node scripts/prepare-release-files.mjs",
"toolbox:check": "toolbox-check dist",
"package:release": "node scripts/package-release.mjs",
"package:library": "node scripts/package-library.mjs",
"check": "npm run manifest:check && npm run typecheck && npm run lint && npm run format:check && npm run test && npm run build && npm run toolbox:check",
"release:artifact": "npm run check && npm run test:browser && npm run package:release -- --force && npm run package:library -- --force"
},
"devDependencies": {
"@add-ideas/toolbox-contract": "0.2.3",
"@add-ideas/toolbox-shell-react": "0.2.3",
"@add-ideas/toolbox-testkit": "0.2.3",
"@eslint/js": "10.0.1",
"@playwright/test": "1.62.1",
"@testing-library/jest-dom": "6.9.1",
"@testing-library/react": "16.3.2",
"@testing-library/user-event": "14.6.1",
"@types/node": "25.9.5",
"@types/react": "19.2.17",
"@types/react-dom": "19.2.5",
"@vitejs/plugin-react": "6.0.3",
"eslint": "10.7.0",
"eslint-plugin-react-hooks": "7.1.1",
"eslint-plugin-react-refresh": "0.5.2",
"globals": "17.7.0",
"jsdom": "29.1.1",
"prettier": "3.9.5",
"react": "19.2.8",
"react-dom": "19.2.8",
"typescript": "6.0.3",
"typescript-eslint": "8.64.0",
"vite": "8.2.2",
"vitest": "4.1.11"
},
"packageManager": "npm@11.17.0"
}
+24
View File
@@ -0,0 +1,24 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests/browser",
fullyParallel: false,
workers: 1,
timeout: 120_000,
expect: { timeout: 10_000 },
reporter: [["list"]],
use: {
baseURL: "http://127.0.0.1:4173",
trace: "retain-on-failure",
},
webServer: {
command: "npm run build && node scripts/serve-test.mjs",
url: "http://127.0.0.1:4173/deep/nested/helpers/",
reuseExistingServer: !process.env.CI,
timeout: 180_000,
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
],
});
+21
View File
@@ -0,0 +1,21 @@
# Changelog
All notable changes are documented here.
## Unreleased
## 0.1.0 - 2026-09-01
- Added a deep-linkable local browser workbench for encodings, text and
Unicode, number bases and units, networks, time, structured data, checksums,
cryptographic digests, and random values.
- Added the side-effect-free `@add-ideas/toolbox-helpers` ESM package with
generated TypeScript declarations and a single stable root export.
- Added explicit input, item, nesting and output limits with typed limit errors.
- Added strict IPv4, IPv6 and CIDR handling, hardened JSON/CSV processing,
canonical encodings, deterministic JSON and seeded random primitives.
- Hardened canonical Base64URL padding, large-output encoding, negative
human-duration round trips, finite unit conversion and portable filenames.
- Added the Toolbox 0.2.3 shell, system/light/dark themes, offline shell,
nested-path browser tests, licence/source documentation, and deterministic
application and library artifacts.
+11
View File
@@ -0,0 +1,11 @@
# Contributing
Use Node.js 22 and npm 11, install with `npm ci`, and run `npm run check` before
submitting a change. New helpers must be framework-free, deterministic unless
their name explicitly promises secure randomness, and bounded before allocating
from untrusted input. Add known vectors and malicious/boundary tests alongside
each implementation.
Do not add runtime network calls, telemetry, persistence, implicit evaluation,
or a second UI-only implementation of library logic. Preserve the stable root
exports or document a deliberate breaking change.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU 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 instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+5
View File
@@ -0,0 +1,5 @@
# Runtime licence inventory
`npm run release:prepare` generates `npm-runtime-licenses.txt` from the exact
runtime packages locked in `package-lock.json`. The reusable helper library has
no runtime dependency. The project licence is reproduced at `../LICENSE`.
+485
View File
@@ -0,0 +1,485 @@
==============================================================================
@add-ideas/toolbox-contract@0.2.3
Declared licence: Apache-2.0
Installed from: node_modules/@add-ideas/toolbox-contract
==============================================================================
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
Copyright 2026 ADD Ideas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
@add-ideas/toolbox-shell-react@0.2.3
Declared licence: Apache-2.0
Installed from: node_modules/@add-ideas/toolbox-shell-react
==============================================================================
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
Copyright 2026 ADD Ideas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
react@19.2.8
Declared licence: MIT
Installed from: node_modules/react
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
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.
==============================================================================
react-dom@19.2.8
Declared licence: MIT
Installed from: node_modules/react-dom
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
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.
==============================================================================
scheduler@0.27.0
Declared licence: MIT
Installed from: node_modules/scheduler
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
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.
+82
View File
@@ -0,0 +1,82 @@
# Helper Tools
Helper Tools is a local-first browser workbench and the source of the
`@add-ideas/toolbox-helpers` TypeScript package. It provides small, explicit,
bounded building blocks for common developer calculations without network
requests, telemetry, persistence, or server processing.
Version 0.1.0 includes:
- strict Base64, Base64URL, hexadecimal, UTF-8, UTF-16 and Latin-1 conversion;
- URL component and form encoding, Unicode scalar/grapheme inspection, case,
normalization and line-ending transforms;
- exact BigInt base conversion, SI/IEC data sizes, and common physical units;
- CRC-32, Adler-32, FNV-1a and Web Crypto SHA digests;
- strict IPv4/IPv6 parsing and exact CIDR ranges and containment;
- timestamp and bounded duration parsing and formatting;
- hardened JSON parsing, deterministic JSON and bounded CSV conversion; and
- secure random bytes/integers plus explicitly non-cryptographic seeded random
primitives for repeatable tests and samples.
## Browser app
```sh
npm ci
npm run dev
```
All workspaces are deep-linkable through URL hashes. Values live only in React
component state and disappear on refresh. Downloads use short-lived object URLs
that are revoked after use.
## Reusable package
The package is framework-free ESM with generated TypeScript declarations and no
install/runtime dependency. React and the Toolbox SDK are development-only app
build inputs and are not dependencies of package consumers. Every helper is
exported from one stable root:
```ts
import {
bytesToBase64Url,
digestHex,
parseCidr,
safeJsonParse,
} from "@add-ideas/toolbox-helpers";
const token = bytesToBase64Url(new Uint8Array([1, 2, 3]));
const hash = await digestHex(new TextEncoder().encode("local"));
const network = parseCidr("2001:db8::1/64");
const data = safeJsonParse('{"enabled":true}');
```
See [`docs/API.md`](docs/API.md) for the export groups and their security
boundaries. The browser app imports the same public root implementation; it does
not maintain a second calculator code path.
Build and inspect the package locally:
```sh
npm run build:library
npm pack --dry-run
```
## Verification and artifacts
```sh
npm run check
npm run test:browser
npm run package:release -- --force
npm run package:library -- --force
```
The application ZIP and npm-compatible `.tgz` are produced deterministically
with adjacent SHA-256 sidecars in `release/`. Neither artifact is published by
these commands.
## Licence
Helper Tools and `@add-ideas/toolbox-helpers` are licensed under
GPL-3.0-or-later. See [`LICENSE`](LICENSE). Shared Toolbox SDK and React notices
remain under their respective licences in `THIRD_PARTY_NOTICES.md` and the
generated release inventory.
+13
View File
@@ -0,0 +1,13 @@
# Security policy
Report suspected vulnerabilities privately to the repository owner through the
Gitea security contact rather than filing a public exploit description.
Helper Tools processes values locally. It does not make runtime network
requests, persist calculator inputs, evaluate parsed data, or inject generated
markup. Inputs, decoded outputs, collections and nesting are bounded. Downloads
use sanitized names and revocable object URLs.
Consumers remain responsible for treating decoded URLs, CSV cells, JSON values,
random-looking data and generated text as untrusted when handing them to another
system. Seeded randomness is reproducible and must never be used for secrets.
+28
View File
@@ -0,0 +1,28 @@
# Corresponding source and provenance
The corresponding source for Helper Tools 0.1.0 will be published at:
https://git.add-ideas.de/lotobo/helper-tools/src/tag/v0.1.0
Before that tag exists, the `main` branch in the same public repository is the
preferred source under active review. Build the release with Node.js 22 and the
exact dependency graph in `package-lock.json`:
```sh
npm ci
npm run release:artifact
```
The JavaScript/CSS bundles, npm tarball and generated declarations are outputs,
not the preferred form for modification. No runtime code is loaded from a CDN.
## Implementation provenance
- The helpers and interface are original TypeScript and React project code.
- Toolbox manifest, shell and artifact checks use the shared Toolbox SDK 0.2.3.
- Encoding formats, IP notation, JSON, CSV, SI/IEC units, Unicode, ISO 8601,
checksum and digest algorithms were implemented from public specifications
and established interoperable formats; no source from an online calculator
is bundled.
- Cryptographic digests and secure randomness use the browser Web Crypto API.
The seeded generator is deliberately labelled non-cryptographic.
+15
View File
@@ -0,0 +1,15 @@
# Third-party notices
The reusable `@add-ideas/toolbox-helpers` bundle has no runtime dependency. The
browser application uses these packages:
| Package | Version | Licence | Role |
| -------------------------------- | ------- | ---------- | ------------------------------- |
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 | manifest and context contract |
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 | shared shell, theme and actions |
| `react` | 19.2.8 | MIT | browser interface |
| `react-dom` | 19.2.8 | MIT | browser rendering |
Release preparation copies exact package-local licence texts from the locked
runtime graph into `LICENSES/npm-runtime-licenses.txt`. Development-only tools
are not shipped as runtime modules.
+7
View File
@@ -0,0 +1,7 @@
# Accessibility
Each workspace is reachable through a labelled tab and URL hash. Forms use
explicit labels, native controls, status/error regions, visible focus, and real
buttons for actions. Results remain selectable text and do not rely on colour.
The layout supports keyboard use, zoom, narrow screens, reduced motion and the
shared system/light/dark Toolbox themes.
+168
View File
@@ -0,0 +1,168 @@
# Package API
`@add-ideas/toolbox-helpers` is a side-effect-free ESM package with generated
TypeScript declarations and no runtime dependency. Import named helpers from
the package root; internal deep paths are not public API.
## Bounds
```ts
type BytesLike = ArrayBuffer | ArrayBufferView;
const DEFAULT_HELPER_LIMITS: Readonly<{
maxInputBytes: number; // 16 MiB
maxTextChars: 2_000_000;
maxItems: 100_000;
maxDepth: 128;
}>;
assertBoundedText(value: string, maximum?: number, label?: string): string;
assertBoundedBytes(value: BytesLike, maximum?: number, label?: string): Uint8Array;
assertBoundedItems(count: number, maximum?: number, label?: string): number;
assertPositiveSafeInteger(value: number, label: string): number;
asUint8Array(value: BytesLike): Uint8Array;
```
`HelperLimitError` extends `RangeError` and exposes numeric `actual` and `limit`
properties. Per-operation ceilings can be made narrower. They are compatibility
and denial-of-service boundaries, not a substitute for an application-wide
memory budget.
## Encoding and URLs
```ts
type TextEncoding = "utf-8" | "utf-16le" | "utf-16be" | "latin1";
interface DecodeBinaryOptions {
maxOutputBytes?: number;
allowWhitespace?: boolean;
}
bytesToBase64(input: BytesLike): string;
bytesToBase64Url(input: BytesLike, padded?: boolean): string;
base64ToBytes(input: string, options?: DecodeBinaryOptions): Uint8Array;
base64UrlToBytes(input: string, options?: DecodeBinaryOptions): Uint8Array;
bytesToHex(input: BytesLike, uppercase?: boolean): string;
hexToBytes(
input: string,
options?: DecodeBinaryOptions & { allowPrefix?: boolean },
): Uint8Array;
encodeText(input: string, encoding?: TextEncoding): Uint8Array;
decodeText(input: BytesLike, encoding?: TextEncoding, fatal?: boolean): string;
encodeUrlComponent(value: string): string;
decodeUrlComponent(value: string): string;
inspectUrl(value: string, base?: string): UrlParts;
parseFormEncoded(input: string, maximumFields?: number): FormEntries;
stringifyFormEncoded(entries: Iterable<readonly [string, string]>, maximumFields?: number): string;
```
Base64 decoders reject non-canonical alphabets, malformed padding and non-zero
unused bits. Base64URL accepts either no padding or the exact RFC 4648 padding
required for that value. URL inspection is inert: it parses text but never
opens or fetches the result.
## Checksums and digests
```ts
type DigestAlgorithm = "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512";
crc32(input: BytesLike, maximumBytes?: number): number;
adler32(input: BytesLike, maximumBytes?: number): number;
fnv1a32(input: BytesLike, maximumBytes?: number): number;
formatChecksum(value: number): string;
digestBytes(
input: BytesLike,
algorithm?: DigestAlgorithm,
maximumBytes?: number,
cryptoProvider?: Pick<Crypto, "subtle">,
): Promise<Uint8Array>;
digestHex(
input: BytesLike,
algorithm?: DigestAlgorithm,
maximumBytes?: number,
cryptoProvider?: Pick<Crypto, "subtle">,
): Promise<string>;
```
Digests use Web Crypto. SHA-1 is available only for interoperability. Checksums
and hashes do not establish authorship, and none of these functions is a
password-hashing API.
## Network
```ts
type IpVersion = 4 | 6;
interface ParsedIpAddress {
version: IpVersion;
bytes: Uint8Array;
value: bigint;
canonical: string;
}
interface ParsedCidr {
version: IpVersion;
prefixLength: number;
address: ParsedIpAddress;
network: ParsedIpAddress;
first: ParsedIpAddress;
last: ParsedIpAddress;
broadcast?: ParsedIpAddress;
size: bigint;
canonical: string;
}
parseIpAddress(input: string): ParsedIpAddress;
parseIpv4(input: string): ParsedIpAddress;
parseIpv6(input: string): ParsedIpAddress;
formatIpv4(input: bigint | BytesLike): string;
formatIpv6(input: bigint | BytesLike): string;
parseCidr(input: string): ParsedCidr;
cidrContains(
cidr: string | ParsedCidr,
address: string | ParsedIpAddress,
): boolean;
```
IPv4 leading zeroes and IPv6 zone identifiers are rejected rather than guessed.
The helpers perform no DNS, HTTP, probing or scanning. `bigint` fields preserve
128-bit values exactly and must be converted explicitly before JSON encoding.
## Downloads
```ts
interface ObjectUrlLease {
readonly url: string;
readonly revoked: boolean;
revoke(): void;
}
sanitizeDownloadFilename(input: string, fallback?: string, maximumLength?: number): string;
createObjectUrlLease(
blob: Blob,
urlApi?: Pick<typeof URL, "createObjectURL" | "revokeObjectURL">,
): ObjectUrlLease;
triggerBlobDownload(
blob: Blob,
filename: string,
ownerDocument?: Document,
): ObjectUrlLease;
```
`triggerBlobDownload` removes its temporary anchor synchronously and schedules
object URL revocation for the next task. Long-lived previews should instead
keep a lease and call `revoke()` when replaced or unmounted.
## Remaining groups
| Group | Exports |
| ----------------- | -------------------------------------------------------------------------------------------------------------------- |
| Unicode and text | `inspectCodePoints`, `fromCodePoints`, `segmentGraphemes`, `normalizeUnicode`, `transformCase`, `convertLineEndings` |
| Numbers and units | `parseBigIntRadix`, `formatBigIntRadix`, `convertNumberBase`, `convertDataUnit`, `convertUnit`, `unitDimension` |
| Time | `parseTimestamp`, `formatTimestamp`, `parseDuration`, `formatDuration` |
| Structured data | `safeJsonParse`, `stableStringify`, `parseCsv`, `stringifyCsv` |
| Random | `secureRandomBytes`, `secureRandomInt`, `createSeededRandom`, `shuffleSeeded` |
JSON dangerous object keys are rejected by default, cycles and unsupported
values are rejected by deterministic JSON, and CSV dimensions and fields are
bounded. Secure random functions use Web Crypto. The seeded generator is
reproducible and deliberately unsuitable for any secret, nonce, key, salt or
token.
+16
View File
@@ -0,0 +1,16 @@
# Architecture
`src/helpers` contains all framework-free production logic and is bundled as a
single tree-shakeable ESM entry with declaration files. `src/components` imports
that same root for the browser workspaces. React owns only ephemeral input and
presentation state.
The app uses the shared Toolbox shell, relative URLs, a small same-scope offline
service worker, and a static restrictive deployment model. There are no workers
in v0.1.0 because the bounded calculator operations are intentionally small;
cryptographic digests are asynchronous Web Crypto operations.
Application ZIP and npm package assembly are separate. The app includes the
shell and documentation. The npm package contains the library bundle,
declarations, API guide, source and security pointers, project licence and
third-party notices, but no React or Toolbox code in its executable bundle.
+17
View File
@@ -0,0 +1,17 @@
# Privacy and security boundaries
- No calculator performs runtime network access, telemetry or persistence.
- No input is restored after refresh. The service worker caches only static app
files, never calculator values.
- Binary/text allocation, structured nesting, row/column counts, random output
and numeric digits have explicit ceilings.
- JSON dangerous object keys are rejected by default. CSV and URL values remain
text; they are never evaluated or opened automatically.
- IP helpers calculate notation and CIDR membership without scanning, DNS or
connectivity checks.
- SHA results are digests, not proof of authenticity. CRC, Adler and FNV are not
cryptographic. Seeded random output is not secret.
- Download names remove path/control and bidirectional-override characters,
avoid Windows device names and are truncated without splitting surrogate
pairs. Object URLs are revoked. A user must still choose how and where
downloaded text is used.
+15
View File
@@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<defs>
<linearGradient id="paper" x1="9" y1="5" x2="54" y2="60" gradientUnits="userSpaceOnUse">
<stop stop-color="#fff"/>
<stop offset="1" stop-color="#e9edf5"/>
</linearGradient>
<linearGradient id="mark" x1="17" y1="22" x2="47" y2="49" gradientUnits="userSpaceOnUse">
<stop stop-color="#596bd8"/>
<stop offset="1" stop-color="#26a39a"/>
</linearGradient>
</defs>
<path d="M12 5h27l13 13v39a3 3 0 0 1-3 3H12a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z" fill="url(#paper)" stroke="#34405f" stroke-width="3"/>
<path d="M39 5v13h13" fill="#dbe1ef" stroke="#34405f" stroke-width="3" stroke-linejoin="round"/>
<path d="m25 25-8 9 8 9M39 25l8 9-8 9M35 22l-6 25" fill="none" stroke="url(#mark)" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 860 B

+18
View File
@@ -0,0 +1,18 @@
{
"name": "Helper Tools",
"short_name": "Helpers",
"description": "Encode, convert, inspect and calculate common values locally.",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#f6f7fb",
"theme_color": "#24324a",
"icons": [
{
"src": "./favicon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any maskable"
}
]
}
+79
View File
@@ -0,0 +1,79 @@
const CACHE_PREFIX = "helper-tools-shell-";
const CACHE_NAME = `${CACHE_PREFIX}0.1.0`;
const CORE = ["./", "./manifest.webmanifest", "./favicon.svg"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(async (cache) => {
await cache.addAll(CORE);
const response = await fetch("./");
const html = await response.text();
const assets = [...html.matchAll(/(?:src|href)="(\.\/assets\/[^"]+)"/g)]
.map((match) => match[1])
.filter(Boolean);
await cache.addAll(assets);
}),
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
.map((key) => caches.delete(key)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
const url = new URL(event.request.url);
if (url.origin !== self.location.origin) return;
const scope = new URL(self.registration.scope);
if (!url.pathname.startsWith(scope.pathname)) return;
if (event.request.mode === "navigate") {
event.respondWith(
fetch(event.request)
.then((response) => {
if (response.ok) {
const copy = response.clone();
void caches
.open(CACHE_NAME)
.then((cache) => cache.put(event.request, copy));
}
return response;
})
.catch(async () => {
const cached = await caches.match(event.request);
if (cached) return cached;
const shellUrl = new URL("./", self.registration.scope).href;
return (await caches.match(shellUrl)) ?? Response.error();
}),
);
return;
}
event.respondWith(
caches.match(event.request).then(
(cached) =>
cached ??
fetch(event.request).then((response) => {
if (response.ok) {
const copy = response.clone();
void caches
.open(CACHE_NAME)
.then((cache) => cache.put(event.request, copy));
}
return response;
}),
),
);
});
+52
View File
@@ -0,0 +1,52 @@
{
"$schema": "https://git.add-ideas.de/lotobo/toolbox-sdk/raw/branch/main/schemas/toolbox-app.v1.schema.json",
"schemaVersion": 1,
"id": "de.add-ideas.helper-tools",
"name": "Helper Tools",
"version": "0.1.0",
"description": "Encode, convert, inspect and calculate locally.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["developer", "data", "utilities"],
"tags": [
"base64",
"hex",
"unicode",
"units",
"cidr",
"timestamp",
"csv",
"json",
"checksum",
"random"
],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
"embedding": "unsupported"
},
"requirements": {
"secureContext": false,
"workers": false,
"indexedDb": false,
"crossOriginIsolated": false,
"topLevelContext": false
},
"privacy": {
"processing": "local",
"fileUploads": false,
"telemetry": false,
"label": "Inputs stay in this browser; nothing is uploaded or retained."
},
"source": {
"repository": "https://git.add-ideas.de/lotobo/helper-tools",
"license": "GPL-3.0-or-later"
},
"actions": [
{
"id": "source",
"label": "Source",
"url": "https://git.add-ideas.de/lotobo/helper-tools"
}
]
}
+59
View File
@@ -0,0 +1,59 @@
import { lstat, readFile, writeFile } from "node:fs/promises";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { format } from "prettier";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const sourcePath = join(root, "src", "toolbox", "manifest.source.json");
const outputPath = join(root, "public", "toolbox-app.json");
const source = JSON.parse(await readFile(sourcePath, "utf8"));
const packageJson = JSON.parse(
await readFile(join(root, "package.json"), "utf8"),
);
const versionSource = await readFile(join(root, "src", "version.ts"), "utf8");
const applicationVersion =
/^export const APPLICATION_VERSION = "([^"]+)";$/mu.exec(versionSource)?.[1];
if (
source.version !== packageJson.version ||
applicationVersion !== packageJson.version
)
throw new Error(
`Version drift: manifest ${source.version}, application ${String(applicationVersion)}, package ${packageJson.version}`,
);
if (
source.id !== "de.add-ideas.helper-tools" ||
source.source?.repository !==
"https://git.add-ideas.de/lotobo/helper-tools" ||
source.source?.license !== "GPL-3.0-or-later"
)
throw new Error("Manifest source identity is incomplete or inconsistent");
for (const asset of source.assets ?? []) {
if (
typeof asset !== "string" ||
!asset.startsWith("./") ||
asset.includes("\\") ||
asset.split("/").includes("..")
)
throw new Error(`Unsafe manifest asset path: ${JSON.stringify(asset)}`);
const details = await lstat(join(root, "public", asset.slice(2))).catch(
() => null,
);
if (!details?.isFile() || details.isSymbolicLink())
throw new Error(`Manifest asset is missing or unsafe: ${asset}`);
}
const serialized = await format(JSON.stringify(source), {
filepath: outputPath,
});
if (process.argv.includes("--check")) {
if ((await readFile(outputPath, "utf8").catch(() => "")) !== serialized)
throw new Error(
`${relative(root, outputPath)} is stale; run npm run manifest:generate`,
);
console.log("Toolbox manifest is synchronized");
} else {
await writeFile(outputPath, serialized);
console.log(`Generated ${relative(root, outputPath)}`);
}
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import {
access,
copyFile,
mkdir,
mkdtemp,
readFile,
rename,
rm,
writeFile,
} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
const execute = promisify(execFile);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const details = JSON.parse(
await readFile(path.join(root, "package.json"), "utf8"),
);
const filename = `add-ideas-toolbox-helpers-${details.version}.tgz`;
const output = path.join(root, "release", filename);
const checksumOutput = `${output}.sha256`;
const force = process.argv.includes("--force");
const exists = (file) =>
access(file).then(
() => true,
() => false,
);
if (!force && ((await exists(output)) || (await exists(checksumOutput))))
throw new Error(
"Library package output already exists; use --force to replace it",
);
for (const required of [
"lib-dist/index.js",
"lib-dist/types/index.d.ts",
"LICENSE",
"README.md",
"SOURCE.md",
])
await access(path.join(root, required));
await mkdir(path.dirname(output), { recursive: true });
const staging = await mkdtemp(path.join(os.tmpdir(), "helper-npm-pack-"));
try {
const { stdout } = await execute(
"npm",
["pack", "--json", "--pack-destination", staging],
{
cwd: root,
env: { ...process.env, TZ: "UTC", SOURCE_DATE_EPOCH: "315532800" },
maxBuffer: 4 * 1024 * 1024,
},
);
const packed = JSON.parse(stdout)[0];
if (packed?.filename !== filename)
throw new Error(`Unexpected npm package name: ${packed?.filename}`);
const packedPaths = new Set(
Array.isArray(packed?.files)
? packed.files.map((entry) => entry?.path).filter(Boolean)
: [],
);
for (const required of [
"LICENSE",
"README.md",
"SOURCE.md",
"SECURITY.md",
"THIRD_PARTY_NOTICES.md",
"docs/API.md",
"lib-dist/index.js",
"lib-dist/types/index.d.ts",
]) {
if (!packedPaths.has(required))
throw new Error(`npm package is missing required file: ${required}`);
}
const staged = path.join(staging, filename);
const archive = await readFile(staged);
const digest = createHash("sha256").update(archive).digest("hex");
const tempOutput = `${output}.new`;
const tempChecksum = `${checksumOutput}.new`;
await copyFile(staged, tempOutput);
await writeFile(tempChecksum, `${digest} ${filename}\n`, { mode: 0o644 });
if (force) {
await rm(output, { force: true });
await rm(checksumOutput, { force: true });
}
await rename(tempOutput, output);
await rename(tempChecksum, checksumOutput);
console.log(
`Created release/${filename} (${archive.byteLength} bytes)\nSHA-256 ${digest}`,
);
} finally {
await rm(staging, { recursive: true, force: true });
}
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import {
access,
chmod,
copyFile,
cp,
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rename,
rm,
utimes,
writeFile,
} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
const execute = promisify(execFile);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageJson = JSON.parse(
await readFile(path.join(root, "package.json"), "utf8"),
);
const argument = (name, fallback) => {
const index = process.argv.indexOf(name);
return index >= 0 ? process.argv[index + 1] : fallback;
};
const output = path.resolve(
root,
argument("--output", `release/helper-tools-${packageJson.version}.zip`),
);
const checksumOutput = `${output}.sha256`;
const force = process.argv.includes("--force");
if (
path.extname(output).toLowerCase() !== ".zip" ||
output === root ||
output === path.parse(output).root
)
throw new Error("Release output is not a safe ZIP target");
const exists = (file) =>
access(file).then(
() => true,
() => false,
);
if (!force && ((await exists(output)) || (await exists(checksumOutput))))
throw new Error("Release output already exists; use --force to replace it");
const input = path.join(root, "dist");
for (const name of [
"index.html",
"manifest.webmanifest",
"sw.js",
"toolbox-app.json",
"favicon.svg",
"README.md",
"CHANGELOG.md",
"CONTRIBUTING.md",
"LICENSE",
"SECURITY.md",
"SOURCE.md",
"THIRD_PARTY_NOTICES.md",
"LICENSES/README.md",
"LICENSES/npm-runtime-licenses.txt",
"docs/ACCESSIBILITY.md",
"docs/ARCHITECTURE.md",
"docs/API.md",
"docs/PRIVACY-SECURITY.md",
]) {
const details = await lstat(path.join(input, name)).catch(() => null);
if (!details?.isFile() || details.isSymbolicLink())
throw new Error(`Release is missing a regular file: ${name}`);
}
const manifest = JSON.parse(
await readFile(path.join(input, "toolbox-app.json"), "utf8"),
);
if (
manifest.id !== "de.add-ideas.helper-tools" ||
manifest.version !== packageJson.version ||
manifest.entry !== "./" ||
manifest.icon !== "./favicon.svg" ||
manifest.source?.repository !== "https://git.add-ideas.de/lotobo/helper-tools"
)
throw new Error("Packaged Toolbox manifest identity is invalid");
const html = await readFile(path.join(input, "index.html"), "utf8");
if (/\b(?:src|href)=["']\//iu.test(html))
throw new Error("index.html contains a root-absolute asset reference");
async function collect(directory, prefix = "") {
const files = [];
for (const entry of (await readdir(directory, { withFileTypes: true })).sort(
(a, b) => (a.name === b.name ? 0 : a.name < b.name ? -1 : 1),
)) {
const absolute = path.join(directory, entry.name);
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isSymbolicLink())
throw new Error(`Release contains a symbolic link: ${relative}`);
if (entry.isDirectory()) files.push(...(await collect(absolute, relative)));
else if (entry.isFile()) files.push({ absolute, relative });
else throw new Error(`Unsupported release entry: ${relative}`);
}
return files;
}
const sourceFiles = await collect(input);
for (const file of sourceFiles) {
if (
file.relative.endsWith(".map") ||
/(?:^|\/)(?:\.env(?:\.|$)|id_rsa|id_ed25519|.*\.pem$|.*\.key$)/iu.test(
file.relative,
) ||
file.relative.startsWith("/") ||
file.relative.split("/").includes("..")
)
throw new Error(`Forbidden release entry: ${file.relative}`);
}
await mkdir(path.dirname(output), { recursive: true });
const stagingRoot = await mkdtemp(path.join(os.tmpdir(), "helper-release-"));
const publicationRoot = await mkdtemp(
path.join(path.dirname(output), ".helper-publish-"),
);
const stagedTree = path.join(stagingRoot, "tree");
const stagedArchive = path.join(stagingRoot, path.basename(output));
try {
await cp(input, stagedTree, { recursive: true });
const timestamp = new Date("1980-01-01T00:00:00.000Z");
for (const file of await collect(stagedTree)) {
await chmod(file.absolute, 0o644);
await utimes(file.absolute, timestamp, timestamp);
}
await execute(
"zip",
[
"-X",
"-q",
"-9",
stagedArchive,
...sourceFiles.map((file) => file.relative),
],
{
cwd: stagedTree,
env: { ...process.env, TZ: "UTC" },
maxBuffer: 1024 * 1024,
},
);
const archive = await readFile(stagedArchive);
const digest = createHash("sha256").update(archive).digest("hex");
const stagedChecksum = `${stagedArchive}.sha256`;
await writeFile(stagedChecksum, `${digest} ${path.basename(output)}\n`, {
mode: 0o644,
});
const publicationArchive = path.join(publicationRoot, path.basename(output));
const publicationChecksum = `${publicationArchive}.sha256`;
await copyFile(stagedArchive, publicationArchive);
await copyFile(stagedChecksum, publicationChecksum);
if (force) {
await rm(output, { force: true });
await rm(checksumOutput, { force: true });
}
await rename(publicationArchive, output);
await rename(publicationChecksum, checksumOutput);
console.log(
`Created ${path.relative(root, output)} (${archive.byteLength} bytes, ${sourceFiles.length} files)\nSHA-256 ${digest}`,
);
} finally {
await rm(stagingRoot, { recursive: true, force: true });
await rm(publicationRoot, { recursive: true, force: true });
}
+80
View File
@@ -0,0 +1,80 @@
import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const destination = path.join(root, "public");
const required = [
"LICENSE",
"README.md",
"CHANGELOG.md",
"CONTRIBUTING.md",
"SECURITY.md",
"SOURCE.md",
"THIRD_PARTY_NOTICES.md",
];
await mkdir(destination, { recursive: true });
for (const name of required) {
await readFile(path.join(root, name));
await cp(path.join(root, name), path.join(destination, name));
}
for (const directory of ["LICENSES", "docs"]) {
const output = path.join(destination, directory);
await rm(output, { recursive: true, force: true });
await cp(path.join(root, directory), output, { recursive: true });
}
const lock = JSON.parse(
await readFile(path.join(root, "package-lock.json"), "utf8"),
);
const sections = [];
const bundledApplicationPackages = new Set([
"node_modules/@add-ideas/toolbox-contract",
"node_modules/@add-ideas/toolbox-shell-react",
"node_modules/react",
"node_modules/react-dom",
"node_modules/scheduler",
]);
for (const [location, locked] of Object.entries(lock.packages ?? {}).sort(
([left], [right]) => (left === right ? 0 : left < right ? -1 : 1),
)) {
if (
!location.includes("node_modules/") ||
(locked.dev === true && !bundledApplicationPackages.has(location))
)
continue;
const packageDirectory = path.join(root, location);
const details = JSON.parse(
await readFile(path.join(packageDirectory, "package.json"), "utf8"),
);
const candidates = (await readdir(packageDirectory))
.filter((name) => /^(?:licen[cs]e|copying|notice)(?:\.|$)/iu.test(name))
.sort();
const texts = [];
for (const candidate of candidates) {
try {
texts.push(
`--- ${candidate} ---\n${await readFile(path.join(packageDirectory, candidate), "utf8")}`,
);
} catch {
/* Ignore directories and non-text aliases. */
}
}
sections.push(
[
"=".repeat(78),
`${details.name}@${details.version}`,
`Declared licence: ${details.license ?? locked.license ?? "See upstream"}`,
`Installed from: ${location}`,
"=".repeat(78),
texts.join("\n\n") ||
"No package-local licence file was present; see THIRD_PARTY_NOTICES.md.",
].join("\n"),
);
}
await writeFile(
path.join(destination, "LICENSES", "npm-runtime-licenses.txt"),
`${sections.join("\n\n").trimEnd()}\n`,
);
console.log("Prepared static release documentation and notices");
+68
View File
@@ -0,0 +1,68 @@
import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"..",
"dist",
);
const nestedPrefix = "/deep/nested/helpers/";
const mediaTypes = new Map([
[".css", "text/css; charset=utf-8"],
[".html", "text/html; charset=utf-8"],
[".js", "application/javascript; charset=utf-8"],
[".json", "application/json; charset=utf-8"],
[".md", "text/markdown; charset=utf-8"],
[".svg", "image/svg+xml"],
[".txt", "text/plain; charset=utf-8"],
[".webmanifest", "application/manifest+json"],
]);
const headers = {
"Content-Security-Policy":
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; object-src 'none'; base-uri 'self'; form-action 'none'; frame-ancestors 'none'",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
"Referrer-Policy": "no-referrer",
"X-Content-Type-Options": "nosniff",
};
createServer(async (request, response) => {
try {
const url = new URL(request.url ?? "/", "http://127.0.0.1");
if (!url.pathname.startsWith(nestedPrefix)) {
response.writeHead(404, headers).end("Not found");
return;
}
let relative = decodeURIComponent(url.pathname.slice(nestedPrefix.length));
if (!relative || relative.endsWith("/")) relative += "index.html";
if (relative.includes("\\") || relative.split("/").includes("..")) {
response.writeHead(400, headers).end("Bad path");
return;
}
const absolute = path.resolve(root, relative);
if (
!absolute.startsWith(`${root}${path.sep}`) ||
!(await stat(absolute)).isFile()
) {
response.writeHead(404, headers).end("Not found");
return;
}
const body = await readFile(absolute);
response.writeHead(200, {
...headers,
"Content-Type":
mediaTypes.get(path.extname(absolute)) ?? "application/octet-stream",
"Cache-Control": relative.startsWith("assets/")
? "public, max-age=31536000, immutable"
: "no-cache",
});
response.end(body);
} catch {
response.writeHead(404, headers).end("Not found");
}
}).listen(4173, "127.0.0.1", () => {
console.log(`Serving Helper Tools at http://127.0.0.1:4173${nestedPrefix}`);
});
+41
View File
@@ -0,0 +1,41 @@
import { lazy, Suspense, useState } from "react";
import { AppShell } from "@add-ideas/toolbox-shell-react";
import "@add-ideas/toolbox-shell-react/styles.css";
import "./styles.css";
import { AppErrorBoundary } from "./components/AppErrorBoundary";
import { HelpDialog } from "./components/HelpDialog";
import { manifest } from "./toolbox/manifest";
const Workbench = lazy(async () => ({
default: (await import("./components/Workbench")).Workbench,
}));
export function App() {
const [helpOpen, setHelpOpen] = useState(false);
return (
<AppErrorBoundary>
<AppShell
app={manifest}
manifestUrl="./toolbox-app.json"
helpAction={{ onClick: () => setHelpOpen(true) }}
onContextError={(error) =>
console.warn(
"Toolbox context unavailable; continuing standalone.",
error,
)
}
>
<Suspense
fallback={
<p className="workbench-loading" role="status">
Preparing local helpers
</p>
}
>
<Workbench />
</Suspense>
</AppShell>
<HelpDialog open={helpOpen} onClose={() => setHelpOpen(false)} />
</AppErrorBoundary>
);
}
+34
View File
@@ -0,0 +1,34 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
interface Props {
children: ReactNode;
}
interface State {
error: Error | null;
}
export class AppErrorBoundary extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
console.error("Helper Tools encountered an interface error", error, info);
}
render(): ReactNode {
if (!this.state.error) return this.props.children;
return (
<main className="fatal-error" role="alert">
<h1>Helper Tools could not continue</h1>
<p>{this.state.error.message}</p>
<button type="button" onClick={() => globalThis.location.reload()}>
Reload application
</button>
</main>
);
}
}
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, useRef } from "react";
interface HelpDialogProps {
open: boolean;
onClose(): void;
}
export function HelpDialog({ open, onClose }: HelpDialogProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
useEffect(() => {
const dialog = dialogRef.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
return (
<dialog
ref={dialogRef}
className="helper-dialog"
aria-labelledby="help-title"
onClose={onClose}
onCancel={(event) => {
event.preventDefault();
onClose();
}}
onClick={(event) => {
if (event.target === event.currentTarget) onClose();
}}
>
<article className="dialog-card">
<header className="dialog-heading">
<div>
<p className="eyebrow">Local utility bench</p>
<h2 id="help-title">Helper Tools help</h2>
</div>
<button type="button" className="icon-button" onClick={onClose}>
<span aria-hidden="true">×</span>
<span className="sr-only">Close help</span>
</button>
</header>
<div className="help-grid">
<section>
<h3>Small, explicit transforms</h3>
<p>
Choose a workspace, enter a value, and inspect labelled outputs.
Deep links use the URL hash, so reloading intentionally clears
values while retaining the selected calculator.
</p>
</section>
<section>
<h3>Safety boundaries</h3>
<p>
Inputs and decoded outputs are bounded. JSON remains inert, URLs
are never opened, IP tools never scan, and formulas or code are
never evaluated.
</p>
</section>
<section>
<h3>Randomness and hashes</h3>
<p>
Secure random values and SHA digests use Web Crypto. CRC, Adler,
FNV and seeded random output are useful for checks and repeatable
tests, not for secrets or authenticity.
</p>
</section>
<section>
<h3>Privacy</h3>
<p>
There is no runtime network access, telemetry, history, or local
persistence. The offline cache contains application files only.
</p>
</section>
</div>
</article>
</dialog>
);
}
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
import {
assertBoundedBytes,
DEFAULT_HELPER_LIMITS,
type BytesLike,
} from "./limits";
import { bytesToHex } from "./encoding";
export type DigestAlgorithm = "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512";
const CRC_TABLE = (() => {
const result = new Uint32Array(256);
for (let index = 0; index < result.length; index += 1) {
let value = index;
for (let bit = 0; bit < 8; bit += 1) {
value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
}
result[index] = value >>> 0;
}
return result;
})();
export function crc32(
input: BytesLike,
maximumBytes: number = DEFAULT_HELPER_LIMITS.maxInputBytes,
): number {
const bytes = assertBoundedBytes(input, maximumBytes);
let value = 0xffffffff;
for (const byte of bytes) {
value = (CRC_TABLE[(value ^ byte) & 0xff] ?? 0) ^ (value >>> 8);
}
return (value ^ 0xffffffff) >>> 0;
}
export function adler32(
input: BytesLike,
maximumBytes: number = DEFAULT_HELPER_LIMITS.maxInputBytes,
): number {
const bytes = assertBoundedBytes(input, maximumBytes);
let first = 1;
let second = 0;
for (let offset = 0; offset < bytes.length; offset += 5552) {
const end = Math.min(bytes.length, offset + 5552);
for (let index = offset; index < end; index += 1) {
first += bytes[index] ?? 0;
second += first;
}
first %= 65_521;
second %= 65_521;
}
return ((second << 16) | first) >>> 0;
}
export function fnv1a32(
input: BytesLike,
maximumBytes: number = DEFAULT_HELPER_LIMITS.maxInputBytes,
): number {
const bytes = assertBoundedBytes(input, maximumBytes);
let hash = 0x811c9dc5;
for (const byte of bytes) {
hash ^= byte;
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
export function formatChecksum(value: number): string {
if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
throw new RangeError("Checksum must be an unsigned 32-bit integer");
}
return value.toString(16).padStart(8, "0");
}
export async function digestBytes(
input: BytesLike,
algorithm: DigestAlgorithm = "SHA-256",
maximumBytes: number = DEFAULT_HELPER_LIMITS.maxInputBytes,
cryptoProvider: Pick<Crypto, "subtle"> = crypto,
): Promise<Uint8Array<ArrayBuffer>> {
const bytes = assertBoundedBytes(input, maximumBytes);
const owned = new Uint8Array(bytes.byteLength);
owned.set(bytes);
const digest = await cryptoProvider.subtle.digest(algorithm, owned);
return new Uint8Array(digest);
}
export async function digestHex(
input: BytesLike,
algorithm: DigestAlgorithm = "SHA-256",
maximumBytes: number = DEFAULT_HELPER_LIMITS.maxInputBytes,
cryptoProvider: Pick<Crypto, "subtle"> = crypto,
): Promise<string> {
return bytesToHex(
await digestBytes(input, algorithm, maximumBytes, cryptoProvider),
);
}
+91
View File
@@ -0,0 +1,91 @@
import { assertBoundedText, assertPositiveSafeInteger } from "./limits";
export interface ObjectUrlLease {
readonly url: string;
readonly revoked: boolean;
revoke(): void;
}
export function sanitizeDownloadFilename(
input: string,
fallback = "download.bin",
maximumLength = 180,
): string {
assertPositiveSafeInteger(maximumLength, "Maximum filename length");
const cleaned = cleanFilename(input);
const fallbackName = cleanFilename(fallback) || "download.bin";
const safe = cleaned || fallbackName;
if (safe.length <= maximumLength) return safe;
const dot = safe.lastIndexOf(".");
const extension = dot > 0 && safe.length - dot <= 16 ? safe.slice(dot) : "";
let stem = safe.slice(0, Math.max(1, maximumLength - extension.length));
const finalCodeUnit = stem.charCodeAt(stem.length - 1);
if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff)
stem = stem.slice(0, -1);
return `${stem || "_"}${extension}`;
}
function cleanFilename(input: string): string {
const normalized = assertBoundedText(
input,
4096,
"Filename length",
).normalize("NFC");
const cleaned = Array.from(normalized, (character) => {
const codePoint = character.codePointAt(0) ?? 0;
return codePoint <= 31 ||
(codePoint >= 127 && codePoint <= 159) ||
(codePoint >= 0x202a && codePoint <= 0x202e) ||
(codePoint >= 0x2066 && codePoint <= 0x2069) ||
'/\\:*?"<>|'.includes(character)
? "_"
: character;
})
.join("")
.replace(/\s+/gu, " ")
.replace(/^\.+|[. ]+$/gu, "")
.trim();
return /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(cleaned)
? `_${cleaned}`
: cleaned;
}
export function createObjectUrlLease(
blob: Blob,
urlApi: Pick<typeof URL, "createObjectURL" | "revokeObjectURL"> = URL,
): ObjectUrlLease {
const url = urlApi.createObjectURL(blob);
let revoked = false;
return {
url,
get revoked() {
return revoked;
},
revoke() {
if (revoked) return;
revoked = true;
urlApi.revokeObjectURL(url);
},
};
}
export function triggerBlobDownload(
blob: Blob,
filename: string,
ownerDocument: Document = document,
): ObjectUrlLease {
const lease = createObjectUrlLease(blob);
const anchor = ownerDocument.createElement("a");
anchor.href = lease.url;
anchor.download = sanitizeDownloadFilename(filename);
anchor.rel = "noopener";
anchor.hidden = true;
ownerDocument.body.append(anchor);
try {
anchor.click();
} finally {
anchor.remove();
globalThis.setTimeout(() => lease.revoke(), 0);
}
return lease;
}
+225
View File
@@ -0,0 +1,225 @@
import {
assertBoundedBytes,
assertBoundedText,
assertPositiveSafeInteger,
DEFAULT_HELPER_LIMITS,
HelperLimitError,
type BytesLike,
} from "./limits";
const BASE64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BASE64_URL =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
export interface DecodeBinaryOptions {
maxOutputBytes?: number;
allowWhitespace?: boolean;
}
export type TextEncoding = "utf-8" | "utf-16le" | "utf-16be" | "latin1";
export function bytesToBase64(input: BytesLike): string {
return encodeBase64(assertBoundedBytes(input), BASE64, true);
}
export function bytesToBase64Url(input: BytesLike, padded = false): string {
return encodeBase64(assertBoundedBytes(input), BASE64_URL, padded);
}
function encodeBase64(
bytes: Uint8Array<ArrayBufferLike>,
alphabet: string,
padded: boolean,
): string {
const chunks: string[] = [];
let block: string[] = [];
for (let offset = 0; offset < bytes.length; offset += 3) {
const first = bytes[offset] ?? 0;
const second = bytes[offset + 1];
const third = bytes[offset + 2];
block.push(
alphabet[first >>> 2] ?? "",
alphabet[((first & 3) << 4) | ((second ?? 0) >>> 4)] ?? "",
second === undefined
? padded
? "="
: ""
: (alphabet[((second & 15) << 2) | ((third ?? 0) >>> 6)] ?? ""),
third === undefined ? (padded ? "=" : "") : (alphabet[third & 63] ?? ""),
);
if (block.length >= 16_384) {
chunks.push(block.join(""));
block = [];
}
}
if (block.length > 0) chunks.push(block.join(""));
return chunks.join("");
}
export function base64ToBytes(
input: string,
options: DecodeBinaryOptions = {},
): Uint8Array<ArrayBuffer> {
return decodeBase64(input, false, options);
}
export function base64UrlToBytes(
input: string,
options: DecodeBinaryOptions = {},
): Uint8Array<ArrayBuffer> {
return decodeBase64(input, true, options);
}
function decodeBase64(
input: string,
urlSafe: boolean,
options: DecodeBinaryOptions,
): Uint8Array<ArrayBuffer> {
const maximum = options.maxOutputBytes ?? DEFAULT_HELPER_LIMITS.maxInputBytes;
assertPositiveSafeInteger(maximum, "Maximum decoded length");
let value = assertBoundedText(input, maximum * 2 + 16, "Encoded text length");
if (options.allowWhitespace) value = value.replace(/\s/gu, "");
else if (/\s/u.test(value))
throw new SyntaxError("Base64 must not contain whitespace");
const alphabet = urlSafe ? BASE64_URL : BASE64;
const expression = urlSafe
? /^[A-Za-z0-9_-]*={0,2}$/u
: /^[A-Za-z0-9+/]*={0,2}$/u;
if (
!expression.test(value) ||
value.length % 4 === 1 ||
/=/.test(value.slice(0, -2))
) {
throw new SyntaxError(`Invalid ${urlSafe ? "Base64URL" : "Base64"} input`);
}
const withoutPadding = value.replace(/=+$/u, "");
if (!urlSafe && value.length % 4 !== 0) {
throw new SyntaxError(
"Standard Base64 requires padding to a multiple of four characters",
);
}
if (urlSafe && value.includes("=")) {
const requiredPadding = (4 - (withoutPadding.length % 4)) % 4;
if (
requiredPadding === 0 ||
value.length - withoutPadding.length !== requiredPadding
) {
throw new SyntaxError("Base64URL padding is not canonical");
}
}
const outputLength = Math.floor((withoutPadding.length * 6) / 8);
if (outputLength > maximum)
throw new HelperLimitError("Decoded byte length", outputLength, maximum);
const output = new Uint8Array(outputLength);
let accumulator = 0;
let bits = 0;
let outputIndex = 0;
for (const character of withoutPadding) {
const index = alphabet.indexOf(character);
if (index < 0) throw new SyntaxError("Invalid Base64 alphabet");
accumulator = accumulator * 64 + index;
bits += 6;
if (bits >= 8) {
bits -= 8;
if (outputIndex < output.length)
output[outputIndex++] = (accumulator >>> bits) & 0xff;
accumulator &= (1 << bits) - 1;
}
}
if (accumulator !== 0)
throw new SyntaxError("Base64 contains non-zero unused bits");
const canonical = encodeBase64(output, alphabet, !urlSafe);
if (
(urlSafe ? canonical.replace(/=+$/u, "") : canonical) !==
(urlSafe ? withoutPadding : value)
) {
throw new SyntaxError("Base64 input is not canonical");
}
return output;
}
export function bytesToHex(input: BytesLike, uppercase = false): string {
const bytes = assertBoundedBytes(input);
const chunks: string[] = [];
let block: string[] = [];
for (const byte of bytes) {
block.push(byte.toString(16).padStart(2, "0"));
if (block.length >= 8_192) {
chunks.push(block.join(""));
block = [];
}
}
if (block.length > 0) chunks.push(block.join(""));
const result = chunks.join("");
return uppercase ? result.toUpperCase() : result;
}
export function hexToBytes(
input: string,
options: DecodeBinaryOptions & { allowPrefix?: boolean } = {},
): Uint8Array<ArrayBuffer> {
const maximum = options.maxOutputBytes ?? DEFAULT_HELPER_LIMITS.maxInputBytes;
let value = assertBoundedText(input, maximum * 3 + 2, "Hex text length");
if (options.allowWhitespace) value = value.replace(/\s/gu, "");
if (options.allowPrefix !== false && /^0x/iu.test(value))
value = value.slice(2);
if (value.length % 2 !== 0 || !/^[0-9a-f]*$/iu.test(value)) {
throw new SyntaxError(
"Hex input must contain complete hexadecimal byte pairs",
);
}
const length = value.length / 2;
if (length > maximum)
throw new HelperLimitError("Decoded byte length", length, maximum);
const output = new Uint8Array(length);
for (let index = 0; index < length; index += 1) {
output[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);
}
return output;
}
export function encodeText(
input: string,
encoding: TextEncoding = "utf-8",
): Uint8Array<ArrayBuffer> {
const text = assertBoundedText(input);
if (encoding === "utf-8") return new TextEncoder().encode(text);
if (encoding === "latin1") {
const output = new Uint8Array(text.length);
for (let index = 0; index < text.length; index += 1) {
const code = text.charCodeAt(index);
if (code > 0xff)
throw new RangeError(
`Character at UTF-16 index ${index} is not Latin-1`,
);
output[index] = code;
}
return output;
}
const output = new Uint8Array(text.length * 2);
const littleEndian = encoding === "utf-16le";
const view = new DataView(output.buffer);
for (let index = 0; index < text.length; index += 1) {
view.setUint16(index * 2, text.charCodeAt(index), littleEndian);
}
return output;
}
export function decodeText(
input: BytesLike,
encoding: TextEncoding = "utf-8",
fatal = true,
): string {
const bytes = assertBoundedBytes(input);
if (encoding === "latin1") {
const chunks: string[] = [];
for (let offset = 0; offset < bytes.length; offset += 8192) {
chunks.push(
String.fromCharCode(...bytes.subarray(offset, offset + 8192)),
);
}
return chunks.join("");
}
return new TextDecoder(encoding, { fatal }).decode(bytes);
}
+12
View File
@@ -0,0 +1,12 @@
export * from "./checksums";
export * from "./downloads";
export * from "./encoding";
export * from "./limits";
export * from "./network";
export * from "./numbers";
export * from "./random";
export * from "./structured";
export * from "./time";
export * from "./unicode";
export * from "./units";
export * from "./url";
+71
View File
@@ -0,0 +1,71 @@
export const DEFAULT_HELPER_LIMITS = Object.freeze({
maxInputBytes: 16 * 1024 * 1024,
maxTextChars: 2_000_000,
maxItems: 100_000,
maxDepth: 128,
});
export type BytesLike = ArrayBuffer | ArrayBufferView;
export class HelperLimitError extends RangeError {
readonly limit: number;
readonly actual: number;
constructor(label: string, actual: number, limit: number) {
super(`${label} is ${actual}; the limit is ${limit}`);
this.name = "HelperLimitError";
this.actual = actual;
this.limit = limit;
}
}
export function assertPositiveSafeInteger(
value: number,
label: string,
): number {
if (!Number.isSafeInteger(value) || value <= 0) {
throw new TypeError(`${label} must be a positive safe integer`);
}
return value;
}
export function assertBoundedText(
value: string,
maximum: number = DEFAULT_HELPER_LIMITS.maxTextChars,
label = "Text length",
): string {
assertPositiveSafeInteger(maximum, "Maximum text length");
if (value.length > maximum)
throw new HelperLimitError(label, value.length, maximum);
return value;
}
export function asUint8Array(value: BytesLike): Uint8Array<ArrayBufferLike> {
if (value instanceof ArrayBuffer) return new Uint8Array(value);
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
}
export function assertBoundedBytes(
value: BytesLike,
maximum: number = DEFAULT_HELPER_LIMITS.maxInputBytes,
label = "Byte length",
): Uint8Array<ArrayBufferLike> {
assertPositiveSafeInteger(maximum, "Maximum byte length");
const bytes = asUint8Array(value);
if (bytes.byteLength > maximum) {
throw new HelperLimitError(label, bytes.byteLength, maximum);
}
return bytes;
}
export function assertBoundedItems(
count: number,
maximum: number = DEFAULT_HELPER_LIMITS.maxItems,
label = "Item count",
): number {
assertPositiveSafeInteger(maximum, "Maximum item count");
if (!Number.isSafeInteger(count) || count < 0)
throw new TypeError(`${label} is invalid`);
if (count > maximum) throw new HelperLimitError(label, count, maximum);
return count;
}
+226
View File
@@ -0,0 +1,226 @@
import { assertBoundedText, type BytesLike, asUint8Array } from "./limits";
export type IpVersion = 4 | 6;
export interface ParsedIpAddress {
version: IpVersion;
bytes: Uint8Array<ArrayBuffer>;
value: bigint;
canonical: string;
}
export interface ParsedCidr {
version: IpVersion;
prefixLength: number;
address: ParsedIpAddress;
network: ParsedIpAddress;
first: ParsedIpAddress;
last: ParsedIpAddress;
broadcast?: ParsedIpAddress;
size: bigint;
canonical: string;
}
export function parseIpAddress(input: string): ParsedIpAddress {
const value = assertBoundedText(input, 128, "IP address length").trim();
return value.includes(":") ? parseIpv6(value) : parseIpv4(value);
}
export function parseIpv4(input: string): ParsedIpAddress {
const value = assertBoundedText(input, 32, "IPv4 address length").trim();
const parts = value.split(".");
if (parts.length !== 4)
throw new SyntaxError("IPv4 requires four decimal octets");
const bytes = new Uint8Array(4);
for (let index = 0; index < parts.length; index += 1) {
const part = parts[index] ?? "";
if (!/^(?:0|[1-9]\d{0,2})$/u.test(part)) {
throw new SyntaxError(`Invalid IPv4 octet: ${part || "(empty)"}`);
}
const octet = Number(part);
if (octet > 255) throw new RangeError(`IPv4 octet exceeds 255: ${part}`);
bytes[index] = octet;
}
return addressFromBytes(bytes, 4);
}
export function parseIpv6(input: string): ParsedIpAddress {
const value = assertBoundedText(input, 128, "IPv6 address length").trim();
if (!value || value.includes("%") || (value.match(/::/gu)?.length ?? 0) > 1) {
throw new SyntaxError("Invalid or scoped IPv6 address");
}
const halves = value.split("::");
let left = parseIpv6Side(halves[0] ?? "");
let right = halves.length === 2 ? parseIpv6Side(halves[1] ?? "") : [];
const ipv4Segments = value.split(":").filter((part) => part.includes("."));
const hasIpv4 = ipv4Segments.length > 0;
if (hasIpv4) {
if (ipv4Segments.length !== 1 || !value.endsWith(ipv4Segments[0] ?? "")) {
throw new SyntaxError(
"An embedded IPv4 address must be the final IPv6 component",
);
}
const target = right.length > 0 ? right : left;
const rawSide =
(halves.length === 2 && right.length > 0 ? halves[1] : halves[0]) ?? "";
const tail = rawSide.split(":").at(-1) ?? "";
const ipv4 = parseIpv4(tail);
target.splice(
-1,
1,
(ipv4.bytes[0]! << 8) | ipv4.bytes[1]!,
(ipv4.bytes[2]! << 8) | ipv4.bytes[3]!,
);
if (right.length > 0) right = target;
else left = target;
}
const explicit = left.length + right.length;
if (halves.length === 1 ? explicit !== 8 : explicit >= 8) {
throw new SyntaxError(
"IPv6 must contain exactly eight hextets after expansion",
);
}
const groups =
halves.length === 2
? [...left, ...new Array<number>(8 - explicit).fill(0), ...right]
: left;
if (groups.length !== 8) throw new SyntaxError("Invalid IPv6 expansion");
const bytes = new Uint8Array(16);
groups.forEach((group, index) => {
bytes[index * 2] = group >>> 8;
bytes[index * 2 + 1] = group & 0xff;
});
return addressFromBytes(bytes, 6);
}
function parseIpv6Side(value: string): number[] {
if (!value) return [];
return value.split(":").map((part) => {
if (/\./u.test(part)) return -1;
if (!/^[0-9a-f]{1,4}$/iu.test(part))
throw new SyntaxError(`Invalid IPv6 hextet: ${part || "(empty)"}`);
return Number.parseInt(part, 16);
});
}
export function formatIpv4(input: bigint | BytesLike): string {
const bytes = normalizeAddressInput(input, 4);
return [...bytes].join(".");
}
export function formatIpv6(input: bigint | BytesLike): string {
const bytes = normalizeAddressInput(input, 6);
const groups = Array.from(
{ length: 8 },
(_, index) => ((bytes[index * 2] ?? 0) << 8) | (bytes[index * 2 + 1] ?? 0),
);
let bestStart = -1;
let bestLength = 0;
for (let start = 0; start < groups.length; start += 1) {
if (groups[start] !== 0) continue;
let end = start;
while (end < groups.length && groups[end] === 0) end += 1;
if (end - start > bestLength && end - start >= 2) {
bestStart = start;
bestLength = end - start;
}
start = end - 1;
}
if (bestStart < 0) return groups.map((group) => group.toString(16)).join(":");
const left = groups
.slice(0, bestStart)
.map((group) => group.toString(16))
.join(":");
const right = groups
.slice(bestStart + bestLength)
.map((group) => group.toString(16))
.join(":");
return `${left}::${right}`;
}
export function parseCidr(input: string): ParsedCidr {
const value = assertBoundedText(input, 160, "CIDR length").trim();
const slash = value.lastIndexOf("/");
if (slash <= 0)
throw new SyntaxError("CIDR requires an address and prefix length");
const address = parseIpAddress(value.slice(0, slash));
const prefixText = value.slice(slash + 1);
if (!/^\d{1,3}$/u.test(prefixText))
throw new SyntaxError("Invalid CIDR prefix length");
const prefixLength = Number(prefixText);
const bits = address.version === 4 ? 32 : 128;
if (prefixLength > bits)
throw new RangeError(`IPv${address.version} prefix cannot exceed ${bits}`);
const hostBits = bits - prefixLength;
const all = (1n << BigInt(bits)) - 1n;
const hostMask = hostBits === 0 ? 0n : (1n << BigInt(hostBits)) - 1n;
const networkValue = address.value & (all ^ hostMask);
const lastValue = networkValue | hostMask;
const network = addressFromValue(networkValue, address.version);
const last = addressFromValue(lastValue, address.version);
return {
version: address.version,
prefixLength,
address,
network,
first: network,
last,
broadcast: address.version === 4 ? last : undefined,
size: 1n << BigInt(hostBits),
canonical: `${network.canonical}/${prefixLength}`,
};
}
export function cidrContains(
cidr: string | ParsedCidr,
address: string | ParsedIpAddress,
): boolean {
const range = typeof cidr === "string" ? parseCidr(cidr) : cidr;
const candidate =
typeof address === "string" ? parseIpAddress(address) : address;
return (
candidate.version === range.version &&
candidate.value >= range.first.value &&
candidate.value <= range.last.value
);
}
function addressFromBytes(
input: Uint8Array<ArrayBuffer>,
version: IpVersion,
): ParsedIpAddress {
let value = 0n;
for (const byte of input) value = (value << 8n) | BigInt(byte);
return {
version,
bytes: input,
value,
canonical: version === 4 ? formatIpv4(input) : formatIpv6(input),
};
}
function addressFromValue(value: bigint, version: IpVersion): ParsedIpAddress {
const length = version === 4 ? 4 : 16;
const maximum = 1n << BigInt(length * 8);
if (value < 0n || value >= maximum)
throw new RangeError(`Value is outside IPv${version} range`);
const bytes = new Uint8Array(length);
let remaining = value;
for (let index = length - 1; index >= 0; index -= 1) {
bytes[index] = Number(remaining & 0xffn);
remaining >>= 8n;
}
return addressFromBytes(bytes, version);
}
function normalizeAddressInput(
input: bigint | BytesLike,
version: IpVersion,
): Uint8Array<ArrayBufferLike> {
if (typeof input === "bigint") return addressFromValue(input, version).bytes;
const bytes = asUint8Array(input);
const expected = version === 4 ? 4 : 16;
if (bytes.byteLength !== expected)
throw new RangeError(`IPv${version} requires ${expected} bytes`);
return bytes;
}
+106
View File
@@ -0,0 +1,106 @@
import { assertBoundedText, assertPositiveSafeInteger } from "./limits";
export interface BigIntRadixOptions {
maxDigits?: number;
allowSeparators?: boolean;
allowPrefix?: boolean;
}
export interface FormatBigIntOptions {
uppercase?: boolean;
prefix?: boolean;
groupSize?: number;
separator?: string;
}
const DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz";
export function parseBigIntRadix(
input: string,
radix: number,
options: BigIntRadixOptions = {},
): bigint {
validateRadix(radix);
const maximum = options.maxDigits ?? 4096;
assertPositiveSafeInteger(maximum, "Maximum digit count");
let value = assertBoundedText(
input,
maximum * 2 + 8,
"Number text length",
).trim();
let sign = 1n;
if (value.startsWith("+") || value.startsWith("-")) {
if (value[0] === "-") sign = -1n;
value = value.slice(1);
}
if (options.allowPrefix !== false) {
const prefix =
radix === 2 ? "0b" : radix === 8 ? "0o" : radix === 16 ? "0x" : "";
if (prefix && value.toLowerCase().startsWith(prefix))
value = value.slice(2);
}
if (options.allowSeparators !== false) {
if (/^_|_$|__/u.test(value))
throw new SyntaxError("Invalid numeric separator placement");
value = value.replace(/_/gu, "");
}
if (!value || value.length > maximum)
throw new RangeError("Number has no digits or exceeds the digit limit");
let result = 0n;
for (const character of value.toLowerCase()) {
const digit = DIGITS.indexOf(character);
if (digit < 0 || digit >= radix)
throw new SyntaxError(`Digit ${character} is invalid in base ${radix}`);
result = result * BigInt(radix) + BigInt(digit);
}
return result * sign;
}
export function formatBigIntRadix(
input: bigint,
radix: number,
options: FormatBigIntOptions = {},
): string {
validateRadix(radix);
const negative = input < 0n;
let digits = (negative ? -input : input).toString(radix);
if (options.uppercase) digits = digits.toUpperCase();
const groupSize = options.groupSize ?? 0;
if (groupSize) {
assertPositiveSafeInteger(groupSize, "Group size");
const groups: string[] = [];
for (let end = digits.length; end > 0; end -= groupSize) {
groups.unshift(digits.slice(Math.max(0, end - groupSize), end));
}
digits = groups.join(options.separator ?? "_");
}
const prefix = options.prefix
? radix === 2
? "0b"
: radix === 8
? "0o"
: radix === 16
? "0x"
: ""
: "";
return `${negative ? "-" : ""}${prefix}${digits}`;
}
export function convertNumberBase(
input: string,
fromRadix: number,
toRadix: number,
options: BigIntRadixOptions & FormatBigIntOptions = {},
): string {
return formatBigIntRadix(
parseBigIntRadix(input, fromRadix, options),
toRadix,
options,
);
}
function validateRadix(radix: number): void {
if (!Number.isInteger(radix) || radix < 2 || radix > 36) {
throw new RangeError("Radix must be an integer from 2 through 36");
}
}
+149
View File
@@ -0,0 +1,149 @@
import {
asUint8Array,
assertBoundedBytes,
assertBoundedItems,
assertPositiveSafeInteger,
type BytesLike,
} from "./limits";
export type RandomSeed = string | number | bigint | BytesLike;
export interface SeededRandom {
nextUint32(): number;
nextFloat(): number;
integer(minimum: number, maximumExclusive: number): number;
bytes(length: number): Uint8Array<ArrayBuffer>;
shuffle<T>(values: readonly T[]): T[];
state(): readonly [number, number, number, number];
}
export function secureRandomBytes(
length: number,
cryptoProvider: Pick<Crypto, "getRandomValues"> = crypto,
maximumLength = 1024 * 1024,
): Uint8Array<ArrayBuffer> {
assertPositiveSafeInteger(maximumLength, "Maximum random byte length");
if (!Number.isSafeInteger(length) || length < 0)
throw new TypeError(
"Random byte length must be a non-negative safe integer",
);
if (length > maximumLength)
throw new RangeError(`Random byte length exceeds ${maximumLength}`);
const output = new Uint8Array(length);
for (let offset = 0; offset < output.length; offset += 65_536) {
cryptoProvider.getRandomValues(
output.subarray(offset, Math.min(output.length, offset + 65_536)),
);
}
return output;
}
export function secureRandomInt(
minimum: number,
maximumExclusive: number,
cryptoProvider: Pick<Crypto, "getRandomValues"> = crypto,
): number {
validateIntegerRange(minimum, maximumExclusive);
const range = maximumExclusive - minimum;
if (range > 0x1_0000_0000)
throw new RangeError("Secure random integer range cannot exceed 2^32");
const limit = Math.floor(0x1_0000_0000 / range) * range;
const sample = new Uint32Array(1);
do cryptoProvider.getRandomValues(sample);
while ((sample[0] ?? 0) >= limit);
return minimum + ((sample[0] ?? 0) % range);
}
export function createSeededRandom(seed: RandomSeed): SeededRandom {
const state = seedState(seed);
const nextUint32 = () => {
const result = Math.imul(rotl(Math.imul(state[1] ?? 0, 5), 7), 9) >>> 0;
const temporary = ((state[1] ?? 0) << 9) >>> 0;
state[2] = ((state[2] ?? 0) ^ (state[0] ?? 0)) >>> 0;
state[3] = ((state[3] ?? 0) ^ (state[1] ?? 0)) >>> 0;
state[1] = ((state[1] ?? 0) ^ (state[2] ?? 0)) >>> 0;
state[0] = ((state[0] ?? 0) ^ (state[3] ?? 0)) >>> 0;
state[2] = ((state[2] ?? 0) ^ temporary) >>> 0;
state[3] = rotl(state[3] ?? 0, 11);
return result;
};
const integer = (minimum: number, maximumExclusive: number) => {
validateIntegerRange(minimum, maximumExclusive);
const range = maximumExclusive - minimum;
if (range > 0x1_0000_0000)
throw new RangeError("Seeded integer range cannot exceed 2^32");
const limit = Math.floor(0x1_0000_0000 / range) * range;
let sample: number;
do sample = nextUint32();
while (sample >= limit);
return minimum + (sample % range);
};
return {
nextUint32,
nextFloat: () => nextUint32() / 0x1_0000_0000,
integer,
bytes(length) {
assertBoundedItems(length, 1024 * 1024, "Random byte length");
const output = new Uint8Array(length);
let word = 0;
for (let index = 0; index < length; index += 1) {
if (index % 4 === 0) word = nextUint32();
output[index] = word & 0xff;
word >>>= 8;
}
return output;
},
shuffle<T>(values: readonly T[]): T[] {
assertBoundedItems(values.length);
const output = [...values];
for (let index = output.length - 1; index > 0; index -= 1) {
const swap = integer(0, index + 1);
[output[index], output[swap]] = [output[swap]!, output[index]!];
}
return output;
},
state: () =>
[state[0] ?? 0, state[1] ?? 0, state[2] ?? 0, state[3] ?? 0] as const,
};
}
export function shuffleSeeded<T>(values: readonly T[], seed: RandomSeed): T[] {
return createSeededRandom(seed).shuffle(values);
}
function seedState(seed: RandomSeed): Uint32Array<ArrayBuffer> {
let bytes: Uint8Array<ArrayBufferLike>;
if (typeof seed === "string") bytes = new TextEncoder().encode(seed);
else if (typeof seed === "number" || typeof seed === "bigint")
bytes = new TextEncoder().encode(String(seed));
else bytes = assertBoundedBytes(seed, 1024 * 1024, "Seed byte length");
if (bytes.byteLength === 0) bytes = asUint8Array(new Uint8Array([0]));
const state = new Uint32Array(4);
let hash = 0x811c9dc5;
for (let lane = 0; lane < state.length; lane += 1) {
for (const byte of bytes) {
hash ^= byte + lane;
hash = Math.imul(hash, 0x01000193) >>> 0;
hash ^= hash >>> 13;
}
hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b) >>> 0;
state[lane] = hash || 0x9e3779b9 ^ lane;
}
return state;
}
function rotl(value: number, count: number): number {
return ((value << count) | (value >>> (32 - count))) >>> 0;
}
function validateIntegerRange(minimum: number, maximumExclusive: number): void {
if (
!Number.isSafeInteger(minimum) ||
!Number.isSafeInteger(maximumExclusive) ||
maximumExclusive <= minimum
) {
throw new RangeError(
"Random integer bounds must be safe integers with maximum greater than minimum",
);
}
}
+308
View File
@@ -0,0 +1,308 @@
import {
assertBoundedItems,
assertBoundedText,
assertPositiveSafeInteger,
DEFAULT_HELPER_LIMITS,
HelperLimitError,
} from "./limits";
export type JsonPrimitive = null | boolean | number | string;
export type JsonValue =
JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
export interface StructuredLimits {
maxTextChars?: number;
maxDepth?: number;
maxNodes?: number;
rejectDangerousKeys?: boolean;
}
export interface CsvOptions {
delimiter?: string;
maxRows?: number;
maxColumns?: number;
maxFieldChars?: number;
}
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);
export function safeJsonParse(
input: string,
options: StructuredLimits = {},
): JsonValue {
const limits = resolveStructuredLimits(options);
const text = assertBoundedText(
input,
limits.maxTextChars,
"JSON text length",
);
let value: unknown;
try {
value = JSON.parse(text) as unknown;
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown JSON parse failure";
throw new SyntaxError(`Invalid JSON: ${message}`, { cause: error });
}
validateJsonValue(value, limits);
return value as JsonValue;
}
export function stableStringify(
value: unknown,
space: number | string = 0,
options: StructuredLimits = {},
): string {
const limits = resolveStructuredLimits(options);
const seen = new WeakSet<object>();
let nodes = 0;
const normalize = (
current: unknown,
depth: number,
arrayItem: boolean,
): JsonValue | undefined => {
nodes += 1;
if (nodes > limits.maxNodes)
throw new HelperLimitError("JSON node count", nodes, limits.maxNodes);
if (depth > limits.maxDepth)
throw new HelperLimitError("JSON depth", depth, limits.maxDepth);
if (
current === null ||
typeof current === "string" ||
typeof current === "boolean"
)
return current;
if (typeof current === "number") {
if (!Number.isFinite(current))
throw new TypeError("Stable JSON rejects non-finite numbers");
return current;
}
if (
current === undefined ||
typeof current === "function" ||
typeof current === "symbol"
) {
return arrayItem ? null : undefined;
}
if (typeof current === "bigint")
throw new TypeError("Stable JSON does not encode BigInt");
if (typeof current !== "object")
throw new TypeError("Unsupported JSON value");
if (seen.has(current))
throw new TypeError("Stable JSON rejects cyclic values");
const prototype = Object.getPrototypeOf(current) as unknown;
if (
!Array.isArray(current) &&
prototype !== Object.prototype &&
prototype !== null
) {
throw new TypeError("Stable JSON accepts only arrays and plain objects");
}
seen.add(current);
try {
if (Array.isArray(current)) {
return current.map((item) => normalize(item, depth + 1, true) ?? null);
}
const output: Record<string, JsonValue> = Object.create(null) as Record<
string,
JsonValue
>;
for (const key of Object.keys(current).sort()) {
if (limits.rejectDangerousKeys && DANGEROUS_KEYS.has(key)) {
throw new TypeError(
`Dangerous JSON object key is prohibited: ${key}`,
);
}
const normalized = normalize(
(current as Record<string, unknown>)[key],
depth + 1,
false,
);
if (normalized !== undefined) output[key] = normalized;
}
return output;
} finally {
seen.delete(current);
}
};
const normalized = normalize(value, 0, false);
if (normalized === undefined)
throw new TypeError("Top-level value is not JSON serializable");
const result = JSON.stringify(normalized, null, space);
return assertBoundedText(
result,
limits.maxTextChars,
"Serialized JSON length",
);
}
export function parseCsv(input: string, options: CsvOptions = {}): string[][] {
const text = assertBoundedText(input);
if (!text) return [];
const delimiter = options.delimiter ?? ",";
if (
Array.from(delimiter).length !== 1 ||
delimiter === '"' ||
/[\r\n]/u.test(delimiter)
) {
throw new TypeError(
"CSV delimiter must be one non-quote, non-newline character",
);
}
const maxRows = options.maxRows ?? 100_000;
const maxColumns = options.maxColumns ?? 10_000;
const maxFieldChars = options.maxFieldChars ?? 1_000_000;
assertPositiveSafeInteger(maxRows, "Maximum CSV rows");
assertPositiveSafeInteger(maxColumns, "Maximum CSV columns");
assertPositiveSafeInteger(maxFieldChars, "Maximum CSV field length");
const rows: string[][] = [];
let row: string[] = [];
let field = "";
let quoted = false;
let afterQuote = false;
const pushField = () => {
if (field.length > maxFieldChars)
throw new HelperLimitError(
"CSV field length",
field.length,
maxFieldChars,
);
row.push(field);
if (row.length > maxColumns)
throw new HelperLimitError("CSV column count", row.length, maxColumns);
field = "";
afterQuote = false;
};
const pushRow = () => {
pushField();
rows.push(row);
if (rows.length > maxRows)
throw new HelperLimitError("CSV row count", rows.length, maxRows);
row = [];
};
for (let index = 0; index < text.length; index += 1) {
const character = text[index] ?? "";
if (quoted) {
if (character === '"') {
if (text[index + 1] === '"') {
field += '"';
index += 1;
} else {
quoted = false;
afterQuote = true;
}
} else field += character;
} else if (character === '"') {
if (field || afterQuote)
throw new SyntaxError("Quote may only begin an empty CSV field");
quoted = true;
} else if (character === delimiter) {
pushField();
} else if (character === "\r" || character === "\n") {
if (character === "\r" && text[index + 1] === "\n") index += 1;
pushRow();
} else {
if (afterQuote && !/\s/u.test(character))
throw new SyntaxError("Unexpected text after closing CSV quote");
if (!afterQuote) field += character;
}
if (field.length > maxFieldChars)
throw new HelperLimitError(
"CSV field length",
field.length,
maxFieldChars,
);
}
if (quoted) throw new SyntaxError("CSV has an unterminated quoted field");
if (row.length > 0 || field || !/[\r\n]$/u.test(text)) pushRow();
return rows;
}
export function stringifyCsv(
rows: readonly (readonly unknown[])[],
options: CsvOptions = {},
): string {
const delimiter = options.delimiter ?? ",";
if (
Array.from(delimiter).length !== 1 ||
delimiter === '"' ||
/[\r\n]/u.test(delimiter)
) {
throw new TypeError(
"CSV delimiter must be one non-quote, non-newline character",
);
}
const maxRows = options.maxRows ?? 100_000;
const maxColumns = options.maxColumns ?? 10_000;
const maxFieldChars = options.maxFieldChars ?? 1_000_000;
assertBoundedItems(rows.length, maxRows, "CSV row count");
const lines = rows.map((row) => {
assertBoundedItems(row.length, maxColumns, "CSV column count");
return row
.map((value) => {
const field = assertBoundedText(
value == null ? "" : String(value),
maxFieldChars,
"CSV field length",
);
return field.includes(delimiter) || /["\r\n]/u.test(field)
? `"${field.replace(/"/gu, '""')}"`
: field;
})
.join(delimiter);
});
return assertBoundedText(lines.join("\r\n"));
}
function resolveStructuredLimits(options: StructuredLimits) {
const limits = {
maxTextChars: options.maxTextChars ?? DEFAULT_HELPER_LIMITS.maxTextChars,
maxDepth: options.maxDepth ?? DEFAULT_HELPER_LIMITS.maxDepth,
maxNodes: options.maxNodes ?? DEFAULT_HELPER_LIMITS.maxItems,
rejectDangerousKeys: options.rejectDangerousKeys ?? true,
};
assertPositiveSafeInteger(limits.maxTextChars, "Maximum JSON text length");
assertPositiveSafeInteger(limits.maxDepth, "Maximum JSON depth");
assertPositiveSafeInteger(limits.maxNodes, "Maximum JSON node count");
return limits;
}
function validateJsonValue(
value: unknown,
limits: ReturnType<typeof resolveStructuredLimits>,
): void {
const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];
let nodes = 0;
while (stack.length > 0) {
const current = stack.pop();
if (!current) break;
nodes += 1;
if (nodes > limits.maxNodes)
throw new HelperLimitError("JSON node count", nodes, limits.maxNodes);
if (current.depth > limits.maxDepth)
throw new HelperLimitError("JSON depth", current.depth, limits.maxDepth);
if (
typeof current.value === "string" &&
current.value.length > limits.maxTextChars
) {
throw new HelperLimitError(
"JSON string length",
current.value.length,
limits.maxTextChars,
);
}
if (Array.isArray(current.value)) {
for (const child of current.value)
stack.push({ value: child, depth: current.depth + 1 });
} else if (current.value && typeof current.value === "object") {
for (const [key, child] of Object.entries(current.value)) {
if (limits.rejectDangerousKeys && DANGEROUS_KEYS.has(key)) {
throw new TypeError(
`Dangerous JSON object key is prohibited: ${key}`,
);
}
stack.push({ value: child, depth: current.depth + 1 });
}
}
}
}
+183
View File
@@ -0,0 +1,183 @@
import { assertBoundedText } from "./limits";
export type UnixTimestampUnit = "seconds" | "milliseconds" | "auto";
export type DurationStyle = "iso" | "clock" | "human";
export interface TimestampInfo {
epochMilliseconds: number;
epochSeconds: number;
iso: string;
utcDate: string;
utcTime: string;
timezoneOffsetMinutes: number;
}
export function parseTimestamp(
input: string | number | Date,
numericUnit: UnixTimestampUnit = "auto",
): TimestampInfo {
let milliseconds: number;
if (input instanceof Date) milliseconds = input.getTime();
else if (typeof input === "number")
milliseconds = unixToMilliseconds(input, numericUnit);
else {
const value = assertBoundedText(input, 256, "Timestamp length").trim();
if (/^[+-]?\d+(?:\.\d+)?$/u.test(value)) {
milliseconds = unixToMilliseconds(Number(value), numericUnit);
} else {
milliseconds = Date.parse(value);
}
}
if (!Number.isFinite(milliseconds) || Math.abs(milliseconds) > 8.64e15) {
throw new RangeError("Timestamp is outside the ECMAScript date range");
}
const date = new Date(milliseconds);
const iso = date.toISOString();
return {
epochMilliseconds: milliseconds,
epochSeconds: milliseconds / 1000,
iso,
utcDate: iso.slice(0, 10),
utcTime: iso.slice(11, -1),
timezoneOffsetMinutes: date.getTimezoneOffset(),
};
}
function unixToMilliseconds(value: number, unit: UnixTimestampUnit): number {
if (!Number.isFinite(value))
throw new TypeError("Unix timestamp must be finite");
const resolved =
unit === "auto"
? Math.abs(value) < 100_000_000_000
? "seconds"
: "milliseconds"
: unit;
return resolved === "seconds" ? value * 1000 : value;
}
export function formatTimestamp(
input: string | number | Date,
timeZone = "UTC",
locale = "en-CA",
): string {
const date = new Date(parseTimestamp(input).epochMilliseconds);
return new Intl.DateTimeFormat(locale, {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hourCycle: "h23",
timeZoneName: "shortOffset",
}).format(date);
}
export function parseDuration(input: string): number {
const value = assertBoundedText(input, 1024, "Duration length").trim();
if (!value) throw new SyntaxError("Duration is empty");
const iso =
/^([+-])?P(?:(\d+(?:\.\d+)?)W)?(?:(\d+(?:\.\d+)?)D)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$/iu.exec(
value,
);
if (iso) {
if (!iso.slice(2).some((part) => part !== undefined))
throw new SyntaxError("ISO duration has no components");
const milliseconds =
numberPart(iso[2]) * 604_800_000 +
numberPart(iso[3]) * 86_400_000 +
numberPart(iso[4]) * 3_600_000 +
numberPart(iso[5]) * 60_000 +
numberPart(iso[6]) * 1000;
return checkedDuration(iso[1] === "-" ? -milliseconds : milliseconds);
}
const clock =
/^([+-])?(?:(\d+):)?([0-5]?\d):([0-5]?\d)(?:\.(\d{1,3}))?$/u.exec(value);
if (clock) {
const milliseconds =
numberPart(clock[2]) * 3_600_000 +
numberPart(clock[3]) * 60_000 +
numberPart(clock[4]) * 1000 +
Number((clock[5] ?? "").padEnd(3, "0") || 0);
return checkedDuration(clock[1] === "-" ? -milliseconds : milliseconds);
}
const tokenSign =
value.startsWith("+") || value.startsWith("-") ? value[0] : "";
const tokenValue = tokenSign ? value.slice(1).trimStart() : value;
const tokenPattern = /(\d+(?:\.\d+)?)\s*(w|d|h|ms|m|s)\b/giu;
let milliseconds = 0;
let matched = "";
for (const match of tokenValue.matchAll(tokenPattern)) {
const amount = Number(match[1]);
const unit = match[2]?.toLowerCase();
const factor =
unit === "w"
? 604_800_000
: unit === "d"
? 86_400_000
: unit === "h"
? 3_600_000
: unit === "m"
? 60_000
: unit === "s"
? 1000
: 1;
milliseconds += amount * factor;
matched += match[0];
}
if (
!matched ||
matched.replace(/\s/gu, "") !== tokenValue.replace(/\s/gu, "")
) {
throw new SyntaxError(
"Duration must be ISO 8601, clock notation, or unit tokens",
);
}
return checkedDuration(tokenSign === "-" ? -milliseconds : milliseconds);
}
export function formatDuration(
inputMilliseconds: number,
style: DurationStyle = "iso",
): string {
const milliseconds = checkedDuration(inputMilliseconds);
const negative = milliseconds < 0;
let remaining = Math.round(Math.abs(milliseconds));
const days = Math.floor(remaining / 86_400_000);
remaining -= days * 86_400_000;
const hours = Math.floor(remaining / 3_600_000);
remaining -= hours * 3_600_000;
const minutes = Math.floor(remaining / 60_000);
remaining -= minutes * 60_000;
const seconds = Math.floor(remaining / 1000);
const millis = Math.round(remaining - seconds * 1000);
const sign = negative ? "-" : "";
if (style === "clock") {
const totalHours = days * 24 + hours;
return `${sign}${totalHours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}.${millis.toString().padStart(3, "0")}`;
}
if (style === "human") {
const parts = [
days ? `${days}d` : "",
hours ? `${hours}h` : "",
minutes ? `${minutes}m` : "",
seconds || millis ? `${seconds + millis / 1000}s` : "",
].filter(Boolean);
return `${sign}${parts.join(" ") || "0s"}`;
}
const secondValue = seconds + millis / 1000;
const time = `${hours ? `${hours}H` : ""}${minutes ? `${minutes}M` : ""}${secondValue || (!days && !hours && !minutes) ? `${secondValue}S` : ""}`;
return `${sign}P${days ? `${days}D` : ""}${time ? `T${time}` : ""}`;
}
function numberPart(value: string | undefined): number {
return value === undefined ? 0 : Number(value);
}
function checkedDuration(value: number): number {
if (!Number.isFinite(value) || !Number.isSafeInteger(Math.trunc(value))) {
throw new RangeError("Duration is outside the safe millisecond range");
}
return value;
}
+150
View File
@@ -0,0 +1,150 @@
import { assertBoundedItems, assertBoundedText } from "./limits";
export interface CodePointInfo {
character: string;
codePoint: number;
hex: string;
utf16Index: number;
utf16Length: number;
}
export interface GraphemeInfo {
segment: string;
utf16Index: number;
}
export type CaseTransform =
| "upper"
| "lower"
| "title"
| "sentence"
| "camel"
| "pascal"
| "snake"
| "kebab";
export type LineEnding = "lf" | "crlf" | "cr";
export function inspectCodePoints(input: string): CodePointInfo[] {
const text = assertBoundedText(input);
const result: CodePointInfo[] = [];
let utf16Index = 0;
for (const character of text) {
const codePoint = character.codePointAt(0);
if (codePoint === undefined) continue;
result.push({
character,
codePoint,
hex: `U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}`,
utf16Index,
utf16Length: character.length,
});
utf16Index += character.length;
}
assertBoundedItems(result.length);
return result;
}
export function fromCodePoints(values: Iterable<number>): string {
const points = [...values];
assertBoundedItems(points.length);
for (const point of points) {
if (
!Number.isInteger(point) ||
point < 0 ||
point > 0x10ffff ||
(point >= 0xd800 && point <= 0xdfff)
) {
throw new RangeError(`Invalid Unicode scalar value: ${point}`);
}
}
const chunks: string[] = [];
for (let offset = 0; offset < points.length; offset += 16_384) {
chunks.push(String.fromCodePoint(...points.slice(offset, offset + 16_384)));
}
return assertBoundedText(chunks.join(""));
}
export function segmentGraphemes(
input: string,
locale = "und",
): GraphemeInfo[] {
const text = assertBoundedText(input);
if (typeof Intl.Segmenter === "function") {
const segmenter = new Intl.Segmenter(locale, { granularity: "grapheme" });
const result = [...segmenter.segment(text)].map(({ segment, index }) => ({
segment,
utf16Index: index,
}));
assertBoundedItems(result.length);
return result;
}
let index = 0;
return Array.from(text, (segment) => {
const item = { segment, utf16Index: index };
index += segment.length;
return item;
});
}
export function normalizeUnicode(
input: string,
form: "NFC" | "NFD" | "NFKC" | "NFKD" = "NFC",
): string {
return assertBoundedText(assertBoundedText(input).normalize(form));
}
export function transformCase(
input: string,
transform: CaseTransform,
locale?: string,
): string {
const text = assertBoundedText(input);
const lower = (value: string) =>
locale ? value.toLocaleLowerCase(locale) : value.toLowerCase();
const upper = (value: string) =>
locale ? value.toLocaleUpperCase(locale) : value.toUpperCase();
if (transform === "upper") return assertBoundedText(upper(text));
if (transform === "lower") return assertBoundedText(lower(text));
if (transform === "sentence") {
return assertBoundedText(
text.replace(
/(^|[.!?]\s+)(\p{L})/gu,
(_all, prefix: string, letter: string) => `${prefix}${upper(letter)}`,
),
);
}
if (transform === "title") {
return assertBoundedText(
lower(text).replace(
/(^|[^\p{L}\p{N}])(\p{L})/gu,
(_all, prefix: string, letter: string) => `${prefix}${upper(letter)}`,
),
);
}
const words = splitWords(text).map(lower);
if (transform === "snake") return assertBoundedText(words.join("_"));
if (transform === "kebab") return assertBoundedText(words.join("-"));
const pascal = words
.map((word) => (word ? upper(word[0] ?? "") + word.slice(1) : ""))
.join("");
return assertBoundedText(
transform === "pascal"
? pascal
: lower(pascal.slice(0, 1)) + pascal.slice(1),
);
}
function splitWords(value: string): string[] {
return value
.replace(/([\p{Ll}\d])(\p{Lu})/gu, "$1 $2")
.split(/[^\p{L}\p{N}]+/u)
.filter(Boolean);
}
export function convertLineEndings(input: string, ending: LineEnding): string {
const newline = ending === "lf" ? "\n" : ending === "crlf" ? "\r\n" : "\r";
return assertBoundedText(
assertBoundedText(input).replace(/\r\n?|\n/gu, newline),
);
}
+128
View File
@@ -0,0 +1,128 @@
export type DataUnit =
"b" | "B" | "kB" | "MB" | "GB" | "TB" | "KiB" | "MiB" | "GiB" | "TiB";
export type CommonUnit =
| "mm"
| "cm"
| "m"
| "km"
| "in"
| "ft"
| "yd"
| "mi"
| "mg"
| "g"
| "kg"
| "oz"
| "lb"
| "ms"
| "s"
| "min"
| "h"
| "day"
| "week"
| "C"
| "F"
| "K";
const DATA_FACTORS: Readonly<Record<DataUnit, number>> = Object.freeze({
b: 1 / 8,
B: 1,
kB: 1_000,
MB: 1_000_000,
GB: 1_000_000_000,
TB: 1_000_000_000_000,
KiB: 1024,
MiB: 1024 ** 2,
GiB: 1024 ** 3,
TiB: 1024 ** 4,
});
type Dimension = "length" | "mass" | "time" | "temperature";
interface UnitDefinition {
dimension: Dimension;
toBase(value: number): number;
fromBase(value: number): number;
}
const factor = (dimension: Dimension, amount: number): UnitDefinition => ({
dimension,
toBase: (value) => value * amount,
fromBase: (value) => value / amount,
});
const UNITS: Readonly<Record<CommonUnit, UnitDefinition>> = Object.freeze({
mm: factor("length", 0.001),
cm: factor("length", 0.01),
m: factor("length", 1),
km: factor("length", 1000),
in: factor("length", 0.0254),
ft: factor("length", 0.3048),
yd: factor("length", 0.9144),
mi: factor("length", 1609.344),
mg: factor("mass", 0.000001),
g: factor("mass", 0.001),
kg: factor("mass", 1),
oz: factor("mass", 0.028349523125),
lb: factor("mass", 0.45359237),
ms: factor("time", 0.001),
s: factor("time", 1),
min: factor("time", 60),
h: factor("time", 3600),
day: factor("time", 86_400),
week: factor("time", 604_800),
C: {
dimension: "temperature",
toBase: (value) => value + 273.15,
fromBase: (value) => value - 273.15,
},
F: {
dimension: "temperature",
toBase: (value) => ((value - 32) * 5) / 9 + 273.15,
fromBase: (value) => ((value - 273.15) * 9) / 5 + 32,
},
K: {
dimension: "temperature",
toBase: (value) => value,
fromBase: (value) => value,
},
});
export function convertDataUnit(
value: number,
from: DataUnit,
to: DataUnit,
): number {
assertFinite(value);
const result = (value * DATA_FACTORS[from]) / DATA_FACTORS[to];
if (!Number.isFinite(result))
throw new RangeError("Converted value is outside the finite number range");
return result;
}
export function convertUnit(
value: number,
from: CommonUnit,
to: CommonUnit,
): number {
assertFinite(value);
const source = UNITS[from];
const destination = UNITS[to];
if (source.dimension !== destination.dimension) {
throw new TypeError(
`Cannot convert ${source.dimension} to ${destination.dimension}`,
);
}
const result = destination.fromBase(source.toBase(value));
if (!Number.isFinite(result))
throw new RangeError("Converted value is outside the finite number range");
return result;
}
export function unitDimension(unit: CommonUnit): Dimension {
return UNITS[unit].dimension;
}
function assertFinite(value: number): void {
if (!Number.isFinite(value))
throw new TypeError("Value must be a finite number");
}
+88
View File
@@ -0,0 +1,88 @@
import {
assertBoundedItems,
assertBoundedText,
DEFAULT_HELPER_LIMITS,
} from "./limits";
export interface UrlParts {
href: string;
protocol: string;
username: string;
passwordPresent: boolean;
hostname: string;
port: string;
pathname: string;
search: string;
hash: string;
origin: string;
}
export function encodeUrlComponent(value: string): string {
return encodeURIComponent(assertBoundedText(value));
}
export function decodeUrlComponent(value: string): string {
return assertBoundedText(decodeURIComponent(assertBoundedText(value)));
}
export function inspectUrl(value: string, base?: string): UrlParts {
const input = assertBoundedText(value, 32_768, "URL length");
const parsed = base
? new URL(input, assertBoundedText(base, 32_768, "Base URL length"))
: new URL(input);
return {
href: parsed.href,
protocol: parsed.protocol,
username: parsed.username,
passwordPresent: parsed.password !== "",
hostname: parsed.hostname,
port: parsed.port,
pathname: parsed.pathname,
search: parsed.search,
hash: parsed.hash,
origin: parsed.origin,
};
}
export type FormEntries = Array<readonly [string, string]>;
export function parseFormEncoded(
input: string,
maximumFields = 10_000,
): FormEntries {
const value = assertBoundedText(input);
if (!value) return [];
const fields = value.split("&");
assertBoundedItems(fields.length, maximumFields, "Form field count");
return fields.map((field) => {
const equals = field.indexOf("=");
const rawKey = equals < 0 ? field : field.slice(0, equals);
const rawValue = equals < 0 ? "" : field.slice(equals + 1);
return [decodeFormPart(rawKey), decodeFormPart(rawValue)] as const;
});
}
export function stringifyFormEncoded(
entries: Iterable<readonly [string, string]>,
maximumFields = 10_000,
): string {
const result: string[] = [];
for (const [key, value] of entries) {
assertBoundedItems(result.length + 1, maximumFields, "Form field count");
result.push(`${encodeFormPart(key)}=${encodeFormPart(value)}`);
}
const output = result.join("&");
return assertBoundedText(
output,
DEFAULT_HELPER_LIMITS.maxTextChars,
"Encoded form length",
);
}
function decodeFormPart(value: string): string {
return assertBoundedText(decodeURIComponent(value.replace(/\+/gu, " ")));
}
function encodeFormPart(value: string): string {
return encodeURIComponent(assertBoundedText(value)).replace(/%20/gu, "+");
}
+20
View File
@@ -0,0 +1,20 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);
if ("serviceWorker" in navigator && import.meta.env.PROD) {
window.addEventListener("load", () => {
const url = new URL("./sw.js", document.baseURI);
void navigator.serviceWorker
.register(url, { scope: new URL("./", document.baseURI).pathname })
.catch(() => {
// Offline installation is progressive enhancement.
});
});
}
+632
View File
@@ -0,0 +1,632 @@
:root {
--helper-indigo: #4f46c8;
--helper-teal: #147d72;
--helper-danger: var(--toolbox-danger, #b42342);
--toolbox-background: #f7f7fb;
--toolbox-surface: #ffffff;
--toolbox-surface-soft: #f0f1f7;
--toolbox-text: #202332;
--toolbox-muted: #656b7d;
--toolbox-border: #d9dbe6;
--toolbox-accent: var(--helper-indigo);
--toolbox-accent-hover: #4138ae;
--toolbox-accent-soft: #eeecff;
--toolbox-accent-contrast: #ffffff;
--toolbox-focus: var(--helper-teal);
--toolbox-font:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html {
min-width: 20rem;
min-height: 100%;
background: var(--toolbox-background);
scrollbar-gutter: stable;
}
body {
min-width: 20rem;
min-height: 100vh;
margin: 0;
background: var(--toolbox-background);
color: var(--toolbox-text);
font-family: var(--toolbox-font);
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
}
#root {
min-height: 100vh;
}
::selection {
background: color-mix(in srgb, var(--toolbox-focus) 38%, transparent);
}
.toolbox-shell__main {
width: min(100%, 90rem);
padding: clamp(0.75rem, 1.8vw, 1.5rem);
}
.helper-workbench,
.helper-dialog,
.fatal-error {
--panel-shadow: 0 1px 2px rgb(25 30 60 / 4%), 0 10px 30px rgb(25 30 60 / 3%);
color: var(--toolbox-text);
font-family: var(--toolbox-font);
}
.helper-workbench :where(h1, h2, h3),
.helper-dialog :where(h2, h3),
.fatal-error h1 {
margin: 0;
color: var(--toolbox-text);
font-weight: 760;
letter-spacing: -0.027em;
line-height: 1.16;
}
.helper-workbench h1 {
font-size: clamp(1.65rem, 3vw, 2.45rem);
}
.helper-workbench h2,
.helper-dialog h2 {
font-size: clamp(1.35rem, 2.2vw, 1.75rem);
}
.helper-workbench h3,
.helper-dialog h3 {
font-size: 1rem;
letter-spacing: -0.014em;
}
.helper-workbench :where(p, dl),
.helper-dialog :where(p, dl) {
margin-block: 0;
}
.helper-workbench p,
.helper-dialog p {
line-height: 1.58;
}
.eyebrow {
margin: 0 0 0.28rem !important;
color: var(--toolbox-accent);
font-size: 0.68rem;
font-weight: 820;
letter-spacing: 0.115em;
line-height: 1.35 !important;
text-transform: uppercase;
}
.sr-only {
position: absolute !important;
width: 1px !important;
height: 1px !important;
padding: 0 !important;
margin: -1px !important;
overflow: hidden !important;
clip: rect(0, 0, 0, 0) !important;
white-space: nowrap !important;
border: 0 !important;
}
:where(.helper-workbench, .helper-dialog, .fatal-error)
:where(button, input, select, textarea) {
font: inherit;
}
:where(.helper-workbench, .helper-dialog, .fatal-error) button {
min-height: 2.55rem;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.42rem;
padding: 0.55rem 0.78rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.62rem;
background: var(--toolbox-surface);
box-shadow: 0 1px 1px rgb(20 30 60 / 4%);
color: var(--toolbox-text);
font-size: 0.81rem;
font-weight: 720;
line-height: 1.2;
cursor: pointer;
touch-action: manipulation;
transition:
border-color 140ms ease,
background-color 140ms ease,
color 140ms ease,
transform 140ms ease;
}
:where(.helper-workbench, .helper-dialog) button:hover:not(:disabled) {
border-color: color-mix(
in srgb,
var(--toolbox-accent) 55%,
var(--toolbox-border)
);
background: var(--toolbox-surface-soft);
}
:where(.helper-workbench, .helper-dialog) button:active:not(:disabled) {
transform: translateY(1px);
}
:where(.helper-workbench, .helper-dialog, .fatal-error)
:where(button, input, select, textarea):focus-visible {
outline: 3px solid color-mix(in srgb, var(--toolbox-focus) 42%, transparent);
outline-offset: 2px;
}
.primary-button,
.fatal-error button {
border-color: var(--toolbox-accent) !important;
background: var(--toolbox-accent) !important;
color: var(--toolbox-accent-contrast) !important;
}
.icon-button {
width: 2.55rem;
min-width: 2.55rem;
padding: 0 !important;
font-size: 1rem !important;
}
.helper-workbench {
display: grid;
gap: 1rem;
}
.intro-panel {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: clamp(1rem, 2.5vw, 1.65rem);
border: 1px solid var(--toolbox-border);
border-radius: 0.95rem;
background:
radial-gradient(
circle at 88% 20%,
color-mix(in srgb, var(--toolbox-focus) 13%, transparent),
transparent 34%
),
var(--toolbox-surface);
box-shadow: var(--panel-shadow);
}
.intro-panel > div {
max-width: 52rem;
}
.intro-panel p:last-child,
.workspace-heading p:last-child {
margin-top: 0.45rem;
color: var(--toolbox-muted);
}
.privacy-badge {
flex: none;
display: inline-flex;
align-items: center;
gap: 0.42rem;
padding: 0.5rem 0.72rem;
border: 1px solid
color-mix(in srgb, var(--toolbox-focus) 30%, var(--toolbox-border));
border-radius: 999px;
background: color-mix(
in srgb,
var(--toolbox-focus) 9%,
var(--toolbox-surface)
);
color: var(--toolbox-focus);
font-size: 0.76rem;
font-weight: 760;
white-space: nowrap;
}
.privacy-badge span {
font-size: 0.55rem;
}
.workspace-tabs {
display: grid;
grid-template-columns: repeat(8, minmax(7.25rem, 1fr));
gap: 0.5rem;
overflow-x: auto;
padding: 0.12rem 0.12rem 0.38rem;
}
.workspace-tabs button {
min-width: 7.25rem;
min-height: 4.2rem;
align-items: flex-start;
flex-direction: column;
padding: 0.62rem 0.7rem;
text-align: left;
}
.workspace-tabs button strong {
font-size: 0.79rem;
}
.workspace-tabs button span {
color: var(--toolbox-muted);
font-size: 0.68rem;
font-weight: 520;
}
.workspace-tabs button.is-active {
border-color: var(--toolbox-accent);
background: var(--toolbox-accent-soft);
color: var(--toolbox-accent);
box-shadow: inset 0 -2px 0 var(--toolbox-accent);
}
.workspace-tabs button.is-active span {
color: color-mix(in srgb, var(--toolbox-accent) 75%, var(--toolbox-text));
}
.workspace-panel,
.workspace-content {
min-width: 0;
}
.workspace-content {
display: grid;
gap: 1rem;
}
.workspace-heading {
padding-inline: 0.15rem;
}
.two-column {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1rem;
}
.tool-card {
min-width: 0;
display: grid;
align-content: start;
gap: 0.85rem;
padding: clamp(0.85rem, 1.8vw, 1.15rem);
border: 1px solid var(--toolbox-border);
border-radius: 0.85rem;
background: var(--toolbox-surface);
box-shadow: var(--panel-shadow);
}
.stacked-controls {
min-width: 0;
display: grid;
align-content: start;
gap: 0.85rem;
}
.control-row,
.button-row {
display: flex;
align-items: end;
flex-wrap: wrap;
gap: 0.7rem;
}
.control-row > .field {
flex: 1 1 10rem;
}
.field {
min-width: 0;
display: grid;
gap: 0.34rem;
}
.field label,
.output > div > span {
color: var(--toolbox-muted);
font-size: 0.72rem;
font-weight: 740;
letter-spacing: 0.015em;
}
.field :where(input, select, textarea) {
width: 100%;
min-height: 2.65rem;
padding: 0.58rem 0.66rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.6rem;
background: var(--toolbox-surface);
color: var(--toolbox-text);
line-height: 1.4;
}
.field textarea {
min-height: 6rem;
resize: vertical;
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
font-size: 0.82rem;
tab-size: 2;
}
.output {
min-width: 0;
display: grid;
gap: 0.35rem;
}
.output > div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.output output,
.result-list dd code {
overflow-wrap: anywhere;
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
}
.output output {
display: block;
min-height: 2.7rem;
padding: 0.68rem;
overflow: auto;
border: 1px solid var(--toolbox-border);
border-radius: 0.6rem;
background: var(--toolbox-surface-soft);
font-size: 0.8rem;
white-space: pre-wrap;
}
.output output.is-multiline {
max-height: 24rem;
}
.copy-button {
min-height: 1.85rem !important;
padding: 0.25rem 0.5rem !important;
font-size: 0.68rem !important;
}
.result-list {
display: grid;
gap: 0;
overflow: hidden;
border: 1px solid var(--toolbox-border);
border-radius: 0.65rem;
}
.result-list > div {
min-width: 0;
display: grid;
grid-template-columns: minmax(7.5rem, 0.32fr) minmax(0, 1fr);
gap: 0.7rem;
align-items: center;
padding: 0.55rem 0.65rem;
background: var(--toolbox-surface);
}
.result-list > div + div {
border-top: 1px solid var(--toolbox-border);
}
.result-list dt {
color: var(--toolbox-muted);
font-size: 0.72rem;
font-weight: 720;
}
.result-list dd {
min-width: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
margin: 0;
font-size: 0.78rem;
}
.result-list dd code {
min-width: 0;
white-space: pre-wrap;
}
.scope-callout,
.error-text {
padding: 0.7rem 0.82rem;
border-radius: 0.65rem;
font-size: 0.8rem;
}
.scope-callout {
border: 1px solid
color-mix(in srgb, var(--toolbox-focus) 28%, var(--toolbox-border));
background: color-mix(
in srgb,
var(--toolbox-focus) 7%,
var(--toolbox-surface)
);
color: var(--toolbox-muted);
}
.scope-callout.warning {
border-color: color-mix(in srgb, #b46600 35%, var(--toolbox-border));
background: color-mix(in srgb, #b46600 8%, var(--toolbox-surface));
}
.error-text {
border: 1px solid
color-mix(in srgb, var(--helper-danger) 32%, var(--toolbox-border));
background: color-mix(
in srgb,
var(--helper-danger) 7%,
var(--toolbox-surface)
);
color: var(--helper-danger);
overflow-wrap: anywhere;
}
.table-scroll {
max-height: 26rem;
overflow: auto;
border: 1px solid var(--toolbox-border);
border-radius: 0.65rem;
}
.table-scroll table {
width: 100%;
border-collapse: collapse;
font-size: 0.78rem;
}
.table-scroll :where(th, td) {
padding: 0.5rem 0.6rem;
border-bottom: 1px solid var(--toolbox-border);
text-align: left;
}
.table-scroll th {
position: sticky;
top: 0;
background: var(--toolbox-surface-soft);
color: var(--toolbox-muted);
}
.table-scroll .note {
padding: 0.6rem;
color: var(--toolbox-muted);
}
.helper-dialog {
width: min(calc(100% - 2rem), 48rem);
max-height: min(48rem, calc(100vh - 2rem));
padding: 0;
overflow: auto;
border: 1px solid var(--toolbox-border);
border-radius: 0.95rem;
background: var(--toolbox-surface);
color: var(--toolbox-text);
box-shadow: 0 24px 80px rgb(12 20 45 / 24%);
}
.helper-dialog::backdrop {
background: rgb(15 20 40 / 48%);
backdrop-filter: blur(2px);
}
.dialog-card {
padding: clamp(1rem, 2.8vw, 1.5rem);
}
.dialog-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1rem;
}
.help-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.8rem;
}
.help-grid section {
display: grid;
gap: 0.45rem;
padding: 0.85rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.7rem;
background: var(--toolbox-surface-soft);
}
.help-grid p {
color: var(--toolbox-muted);
font-size: 0.82rem;
}
.workbench-loading,
.fatal-error {
width: min(100%, 50rem);
margin: 2rem auto;
padding: 1rem;
}
.fatal-error {
display: grid;
gap: 1rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.8rem;
background: var(--toolbox-surface);
}
@media (max-width: 52rem) {
.intro-panel,
.two-column {
grid-template-columns: 1fr;
}
.intro-panel {
display: grid;
}
.privacy-badge {
justify-self: start;
}
.two-column,
.help-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 34rem) {
.toolbox-shell__main {
padding: 0.65rem;
}
.result-list > div {
grid-template-columns: 1fr;
gap: 0.3rem;
}
.button-row > button {
width: 100%;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
}
}
@media (prefers-contrast: more) {
:where(
.tool-card,
.intro-panel,
.field input,
.field select,
.field textarea
) {
border-width: 2px;
}
}
+5
View File
@@ -0,0 +1,5 @@
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(() => cleanup());
+52
View File
@@ -0,0 +1,52 @@
{
"$schema": "https://git.add-ideas.de/lotobo/toolbox-sdk/raw/branch/main/schemas/toolbox-app.v1.schema.json",
"schemaVersion": 1,
"id": "de.add-ideas.helper-tools",
"name": "Helper Tools",
"version": "0.1.0",
"description": "Encode, convert, inspect and calculate locally.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["developer", "data", "utilities"],
"tags": [
"base64",
"hex",
"unicode",
"units",
"cidr",
"timestamp",
"csv",
"json",
"checksum",
"random"
],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
"embedding": "unsupported"
},
"requirements": {
"secureContext": false,
"workers": false,
"indexedDb": false,
"crossOriginIsolated": false,
"topLevelContext": false
},
"privacy": {
"processing": "local",
"fileUploads": false,
"telemetry": false,
"label": "Inputs stay in this browser; nothing is uploaded or retained."
},
"source": {
"repository": "https://git.add-ideas.de/lotobo/helper-tools",
"license": "GPL-3.0-or-later"
},
"actions": [
{
"id": "source",
"label": "Source",
"url": "https://git.add-ideas.de/lotobo/helper-tools"
}
]
}
+4
View File
@@ -0,0 +1,4 @@
import { defineToolboxApp, parseToolboxApp } from "@add-ideas/toolbox-contract";
import source from "./manifest.source.json";
export const manifest = defineToolboxApp(parseToolboxApp(source));
+1
View File
@@ -0,0 +1 @@
export const APPLICATION_VERSION = "0.1.0";
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+131
View File
@@ -0,0 +1,131 @@
import { expect, test, type Page } from "@playwright/test";
const APP_ORIGIN = "http://127.0.0.1:4173";
async function keepNetworkLocal(page: Page): Promise<string[]> {
const externalRequests: string[] = [];
await page.route("**/*", async (route) => {
const requestUrl = new URL(route.request().url());
if (requestUrl.origin !== APP_ORIGIN) {
externalRequests.push(requestUrl.href);
await route.abort();
return;
}
await route.continue();
});
return externalRequests;
}
function recordRuntimeErrors(page: Page): string[] {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") errors.push(message.text());
});
return errors;
}
test("encodes text and navigates the local workspaces", async ({ page }) => {
const runtimeErrors = recordRuntimeErrors(page);
const externalRequests = await keepNetworkLocal(page);
await page.goto("/deep/nested/helpers/");
await expect(
page.getByRole("heading", { name: "Useful values, without a round trip" }),
).toBeVisible();
await page.getByLabel("Text", { exact: true }).fill("local ✓");
const encodeCard = page
.getByRole("heading", { name: "Encode text" })
.locator("..");
await expect(encodeCard).toContainText("bG9jYWwg4pyT");
await page.getByLabel("URL component", { exact: true }).fill("a b/✓");
await expect(page.getByText("a%20b%2F%E2%9C%93")).toBeVisible();
await page.getByRole("tab", { name: /^Text & Unicode/u }).click();
await expect(page).toHaveURL(/#text$/u);
await expect(
page.getByRole("heading", { name: "Text & Unicode" }),
).toBeVisible();
expect(externalRequests).toEqual([]);
expect(runtimeErrors).toEqual([]);
});
test("calculates network, structured data and seeded values", async ({
page,
}) => {
const runtimeErrors = recordRuntimeErrors(page);
const externalRequests = await keepNetworkLocal(page);
await page.goto("/deep/nested/helpers/#network");
await expect(page.getByText("2001:db8::/64")).toBeVisible();
await page.getByLabel("IPv4 or IPv6 CIDR").fill("192.0.2.99/24");
await page.getByLabel("Address to test").fill("192.0.3.1");
await expect(page.getByText("192.0.2.0/24")).toBeVisible();
await expect(page.getByText("No", { exact: true })).toBeVisible();
await page.getByRole("tab", { name: /^Structured/u }).click();
await page.getByLabel("JSON input").fill('{"z":1,"a":2}');
await expect(page.getByText(/"a": 2/u)).toBeVisible();
await page.getByLabel("CSV input").fill('name,note\nalpha,"a,b"');
await expect(
page.getByText("Rows", { exact: true }).locator(".."),
).toContainText("2");
await page.getByRole("tab", { name: /^Random/u }).click();
await page.getByLabel("Byte count (maximum 4096 here)").fill("8");
const generate = page.getByRole("button", { name: "Generate seeded bytes" });
await generate.click();
const output = page.locator("output").filter({ hasText: /^[0-9a-f]{16}$/u });
const first = await output.textContent();
await generate.click();
await expect(output).toHaveText(first ?? "");
expect(externalRequests).toEqual([]);
expect(runtimeErrors).toEqual([]);
});
test("produces browser digests without clearing the previous result", async ({
page,
}) => {
const runtimeErrors = recordRuntimeErrors(page);
const externalRequests = await keepNetworkLocal(page);
await page.goto("/deep/nested/helpers/#checksums");
await expect(page.getByText("cbf43926")).toBeVisible();
await expect(
page.getByText(
"15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225",
),
).toBeVisible();
await page.getByLabel("UTF-8 input").fill("abc");
await expect(
page.getByText(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
),
).toBeVisible();
expect(externalRequests).toEqual([]);
expect(runtimeErrors).toEqual([]);
});
test("serves a relocatable production artifact with hardened headers", async ({
request,
}) => {
const index = await request.get("/deep/nested/helpers/");
expect(index.ok()).toBe(true);
expect(index.headers()["content-security-policy"]).toContain(
"default-src 'self'",
);
expect(index.headers()["permissions-policy"]).toContain("geolocation=()");
expect(index.headers()["x-content-type-options"]).toBe("nosniff");
expect(await index.text()).not.toMatch(/\b(?:src|href)=["']\//u);
const manifest = await request.get("/deep/nested/helpers/toolbox-app.json");
expect(manifest.headers()["content-type"]).toContain("application/json");
await expect(manifest.json()).resolves.toMatchObject({
id: "de.add-ideas.helper-tools",
version: "0.1.0",
entry: "./",
icon: "./favicon.svg",
});
});
+89
View File
@@ -0,0 +1,89 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it } from "vitest";
import { Workbench } from "../../src/components/Workbench";
describe("Helper Tools workbench", () => {
beforeEach(() => {
history.replaceState(null, "", "/");
});
it("exposes all workspaces and performs strict text encoding", () => {
render(<Workbench />);
expect(
screen.getByRole("heading", {
name: "Useful values, without a round trip",
}),
).toBeVisible();
expect(
within(
screen.getByRole("tablist", { name: "Helper workspaces" }),
).getAllByRole("tab"),
).toHaveLength(8);
const encodeCard = screen
.getByRole("heading", { name: "Encode text" })
.closest("section");
expect(encodeCard).not.toBeNull();
expect(
within(encodeCard!).getAllByText("SGVsbG8sIGxvY2FsIHRvb2xib3gh"),
).toHaveLength(2);
});
it("supports direct hashes and canonicalizes an IPv6 CIDR", () => {
history.replaceState(null, "", "/#network");
render(<Workbench />);
expect(screen.getByRole("heading", { name: "Network" })).toBeVisible();
const canonical = screen.getByText("Canonical").parentElement;
expect(canonical).not.toBeNull();
expect(within(canonical!).getByText("2001:db8::/64")).toBeVisible();
expect(screen.getByText("Yes")).toBeVisible();
});
it("moves between workspace tabs with the keyboard", async () => {
const user = userEvent.setup();
render(<Workbench />);
const encoding = screen.getByRole("tab", { name: /^Encoding/u });
encoding.focus();
await user.keyboard("{ArrowRight}");
expect(
screen.getByRole("tab", { name: /^Text & Unicode/u }),
).toHaveAttribute("aria-selected", "true");
expect(location.hash).toBe("#text");
});
it("keeps unsafe JSON inert and reports the rejected key", async () => {
const user = userEvent.setup();
render(<Workbench />);
await user.click(screen.getByRole("tab", { name: /^Structured/u }));
const input = screen.getByLabelText("JSON input");
fireEvent.change(input, {
target: { value: '{"__proto__":{"polluted":true}}' },
});
expect(screen.getByRole("alert")).toHaveTextContent(/dangerous.*key/iu);
expect(({} as { polluted?: boolean }).polluted).toBeUndefined();
});
it("repeats seeded random output and labels it as non-secure", async () => {
const user = userEvent.setup();
render(<Workbench />);
await user.click(screen.getByRole("tab", { name: /^Random/u }));
const generate = screen.getByRole("button", {
name: "Generate seeded bytes",
});
await user.click(generate);
const first = screen.getByText("Seeded hexadecimal (not secure)")
.parentElement?.nextElementSibling?.textContent;
await user.click(generate);
const second = screen.getByText("Seeded hexadecimal (not secure)")
.parentElement?.nextElementSibling?.textContent;
expect(first).toMatch(/^[0-9a-f]{32}$/u);
expect(second).toBe(first);
expect(screen.getByText(/must never be used for tokens/u)).toBeVisible();
});
});
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import {
adler32,
cidrContains,
digestHex,
encodeText,
fnv1a32,
formatChecksum,
formatIpv4,
formatIpv6,
parseCidr,
parseIpAddress,
parseIpv4,
parseIpv6,
crc32,
} from "../../src/helpers";
describe("checksums and cryptographic digests", () => {
it("matches published checksum vectors", async () => {
const input = encodeText("123456789");
expect(formatChecksum(crc32(input))).toBe("cbf43926");
expect(formatChecksum(adler32(input))).toBe("091e01de");
expect(formatChecksum(fnv1a32(encodeText("hello")))).toBe("4f9f2cab");
await expect(digestHex(encodeText("abc"), "SHA-256")).resolves.toBe(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
);
});
it("applies byte ceilings before digest work", async () => {
expect(() => crc32(new Uint8Array(2), 1)).toThrow(/limit/u);
await expect(digestHex(new Uint8Array(2), "SHA-256", 1)).rejects.toThrow(
/limit/u,
);
});
});
describe("IPv4, IPv6, and CIDR", () => {
it("parses strict IPv4 and canonical IPv6", () => {
expect(parseIpv4("192.0.2.1")).toMatchObject({
version: 4,
canonical: "192.0.2.1",
value: 3221225985n,
});
expect(formatIpv4(parseIpv4("203.0.113.4").bytes)).toBe("203.0.113.4");
expect(parseIpv6("2001:0db8:0:0:0:ff00:0042:8329").canonical).toBe(
"2001:db8::ff00:42:8329",
);
expect(parseIpv6("::ffff:192.0.2.128").canonical).toBe("::ffff:c000:280");
expect(formatIpv6(1n)).toBe("::1");
expect(parseIpAddress("::1").version).toBe(6);
});
it("computes exact network ranges and containment", () => {
const ipv4 = parseCidr("192.0.2.129/25");
expect(ipv4).toMatchObject({
canonical: "192.0.2.128/25",
size: 128n,
});
expect(ipv4.first.canonical).toBe("192.0.2.128");
expect(ipv4.last.canonical).toBe("192.0.2.255");
expect(ipv4.broadcast?.canonical).toBe("192.0.2.255");
expect(cidrContains(ipv4, "192.0.2.200")).toBe(true);
expect(cidrContains(ipv4, "192.0.3.1")).toBe(false);
const ipv6 = parseCidr("2001:db8::1/126");
expect(ipv6.canonical).toBe("2001:db8::/126");
expect(ipv6.last.canonical).toBe("2001:db8::3");
expect(cidrContains(ipv6, "2001:db8::2")).toBe(true);
});
it("rejects ambiguous and malformed addresses", () => {
expect(() => parseIpv4("127.00.0.1")).toThrow(/octet/u);
expect(() => parseIpv4("256.0.0.1")).toThrow(/255/u);
expect(() => parseIpv6("1::2::3")).toThrow(/IPv6/u);
expect(() => parseIpv6("fe80::1%eth0")).toThrow(/scoped/u);
expect(() => parseIpv6("::192.0.2.1:192.0.2.2")).toThrow(/final/u);
expect(() => parseCidr("192.0.2.1/33")).toThrow(/32/u);
});
});
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from "vitest";
import {
base64ToBytes,
base64UrlToBytes,
bytesToBase64,
bytesToBase64Url,
bytesToHex,
convertLineEndings,
decodeText,
decodeUrlComponent,
encodeText,
encodeUrlComponent,
fromCodePoints,
hexToBytes,
inspectCodePoints,
inspectUrl,
normalizeUnicode,
parseFormEncoded,
segmentGraphemes,
stringifyFormEncoded,
transformCase,
} from "../../src/helpers";
describe("binary and text encoding", () => {
it("round-trips canonical Base64, Base64URL, hex, and text encodings", () => {
const bytes = encodeText("Hello, 🌍", "utf-8");
expect(bytesToBase64(bytes)).toBe("SGVsbG8sIPCfjI0=");
expect(decodeText(base64ToBytes("SGVsbG8sIPCfjI0="))).toBe("Hello, 🌍");
expect(bytesToBase64Url(new Uint8Array([251, 255]), false)).toBe("-_8");
expect(base64UrlToBytes("-_8")).toEqual(new Uint8Array([251, 255]));
expect(base64UrlToBytes("Zg==")).toEqual(new Uint8Array([102]));
expect(bytesToHex(bytes).startsWith("48656c6c6f")).toBe(true);
expect(hexToBytes("0x00 ff", { allowWhitespace: true })).toEqual(
new Uint8Array([0, 255]),
);
expect(decodeText(encodeText("Aé", "latin1"), "latin1")).toBe("Aé");
expect(decodeText(encodeText("A🌍", "utf-16le"), "utf-16le")).toBe("A🌍");
expect(decodeText(encodeText("A🌍", "utf-16be"), "utf-16be")).toBe("A🌍");
});
it("rejects ambiguous, malformed, and oversized encodings", () => {
expect(() => base64ToBytes("Zg")).toThrow(/padding/u);
expect(() => base64ToBytes("Zh==")).toThrow(/unused|canonical/u);
expect(() => base64UrlToBytes("+w")).toThrow(/Invalid/u);
expect(() => base64UrlToBytes("Zg=")).toThrow(/padding/u);
expect(() => base64ToBytes("Z g==")).toThrow(/whitespace/u);
expect(() => hexToBytes("abc")).toThrow(/pairs/u);
expect(() => hexToBytes("ffff", { maxOutputBytes: 1 })).toThrow(/limit/u);
expect(() => encodeText("€", "latin1")).toThrow(/Latin-1/u);
});
});
describe("URL, Unicode, case, and line helpers", () => {
it("handles URL components and repeated form fields without object coercion", () => {
expect(decodeUrlComponent(encodeUrlComponent("a b/✓"))).toBe("a b/✓");
const entries = parseFormEncoded("tag=one&tag=two+words&empty=");
expect(entries).toEqual([
["tag", "one"],
["tag", "two words"],
["empty", ""],
]);
expect(stringifyFormEncoded(entries)).toBe("tag=one&tag=two+words&empty=");
expect(
inspectUrl("../a?q=1#x", "https://example.test/base/"),
).toMatchObject({
href: "https://example.test/a?q=1#x",
protocol: "https:",
hostname: "example.test",
passwordPresent: false,
});
});
it("inspects scalar values and user-perceived graphemes", () => {
const points = inspectCodePoints("A🌍");
expect(points).toEqual([
{
character: "A",
codePoint: 65,
hex: "U+0041",
utf16Index: 0,
utf16Length: 1,
},
{
character: "🌍",
codePoint: 0x1f30d,
hex: "U+1F30D",
utf16Index: 1,
utf16Length: 2,
},
]);
expect(fromCodePoints(points.map((point) => point.codePoint))).toBe("A🌍");
expect(segmentGraphemes("👨‍👩‍👧‍👦é")).toHaveLength(2);
expect(normalizeUnicode("e\u0301", "NFC")).toBe("é");
expect(() => fromCodePoints([0xd800])).toThrow(/scalar/u);
expect(fromCodePoints(new Array(100_000).fill(0x61))).toHaveLength(100_000);
});
it("transforms case and line endings deterministically", () => {
expect(transformCase("XML http value", "camel")).toBe("xmlHttpValue");
expect(transformCase("hello-world", "pascal")).toBe("HelloWorld");
expect(transformCase("helloWorld", "snake")).toBe("hello_world");
expect(convertLineEndings("a\r\nb\rc\n", "lf")).toBe("a\nb\nc\n");
expect(convertLineEndings("a\nb", "crlf")).toBe("a\r\nb");
});
});
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import {
convertDataUnit,
convertNumberBase,
convertUnit,
formatBigIntRadix,
parseBigIntRadix,
unitDimension,
} from "../../src/helpers";
describe("BigInt number bases", () => {
it("parses and formats exact large integers from base 2 through 36", () => {
expect(parseBigIntRadix("-0xFF_FF", 16)).toBe(-65_535n);
expect(convertNumberBase("11111111", 2, 16, { uppercase: true })).toBe(
"FF",
);
expect(
formatBigIntRadix(0x1234abcdn, 16, { prefix: true, groupSize: 4 }),
).toBe("0x1234_abcd");
expect(parseBigIntRadix("zz", 36)).toBe(1295n);
});
it("rejects invalid radices, digits, separators, and digit bombs", () => {
expect(() => parseBigIntRadix("2", 2)).toThrow(/Digit/u);
expect(() => parseBigIntRadix("10", 1)).toThrow(/Radix/u);
expect(() => parseBigIntRadix("_1", 10)).toThrow(/separator/u);
expect(() => parseBigIntRadix("1234", 10, { maxDigits: 3 })).toThrow(
/exceeds/u,
);
});
});
describe("unit conversion", () => {
it("distinguishes decimal and binary data units", () => {
expect(convertDataUnit(1, "MiB", "B")).toBe(1_048_576);
expect(convertDataUnit(1, "MB", "B")).toBe(1_000_000);
expect(convertDataUnit(8, "b", "B")).toBe(1);
expect(() => convertDataUnit(Number.MAX_VALUE, "TB", "b")).toThrow(
/finite number range/u,
);
});
it("converts compatible physical units and affine temperatures", () => {
expect(convertUnit(1, "mi", "km")).toBeCloseTo(1.609344, 12);
expect(convertUnit(1, "lb", "kg")).toBeCloseTo(0.45359237, 12);
expect(convertUnit(32, "F", "C")).toBeCloseTo(0, 12);
expect(convertUnit(0, "C", "K")).toBeCloseTo(273.15, 12);
expect(convertUnit(2, "week", "day")).toBe(14);
expect(unitDimension("cm")).toBe("length");
expect(() => convertUnit(1, "m", "kg")).toThrow(/Cannot convert/u);
});
});
@@ -0,0 +1,133 @@
import { describe, expect, it, vi } from "vitest";
import {
HelperLimitError,
assertBoundedBytes,
assertBoundedItems,
assertBoundedText,
createObjectUrlLease,
createSeededRandom,
sanitizeDownloadFilename,
secureRandomBytes,
secureRandomInt,
shuffleSeeded,
triggerBlobDownload,
} from "../../src/helpers";
describe("shared ceilings and download safety", () => {
it("reports actual and configured bounds", () => {
expect(() => assertBoundedText("123", 2)).toThrow(HelperLimitError);
expect(() => assertBoundedBytes(new Uint8Array(3), 2)).toThrow(/limit/u);
expect(() => assertBoundedItems(3, 2)).toThrow(/limit/u);
try {
assertBoundedText("123", 2, "Sample");
} catch (error) {
expect(error).toMatchObject({ actual: 3, limit: 2 });
}
});
it("sanitizes filenames and revokes object URLs exactly once", () => {
expect(sanitizeDownloadFilename("../bad:\0name?.txt")).toBe(
"_bad__name_.txt",
);
expect(sanitizeDownloadFilename("...", "../fallback?.txt")).toBe(
"_fallback_.txt",
);
expect(sanitizeDownloadFilename("CON.txt")).toBe("_CON.txt");
expect(sanitizeDownloadFilename("report\u202egnp.exe")).toBe(
"report_gnp.exe",
);
const emojiBoundary = sanitizeDownloadFilename(
`${"a".repeat(179)}😀.txt`,
"fallback.txt",
180,
);
expect(emojiBoundary).not.toMatch(/[\uD800-\uDBFF]$/u);
expect(emojiBoundary.length).toBeLessThanOrEqual(180);
expect(() => sanitizeDownloadFilename("x", "fallback", 0)).toThrow(
/positive/u,
);
const createObjectURL = vi.fn(() => "blob:test");
const revokeObjectURL = vi.fn();
const lease = createObjectUrlLease(new Blob(["x"]), {
createObjectURL,
revokeObjectURL,
});
expect(lease).toMatchObject({ url: "blob:test", revoked: false });
lease.revoke();
lease.revoke();
expect(lease.revoked).toBe(true);
expect(revokeObjectURL).toHaveBeenCalledOnce();
});
it("removes download anchors and revokes their URL on the next task", () => {
const originalUrl = globalThis.URL;
const createObjectURL = vi.fn(() => "blob:download");
const revokeObjectURL = vi.fn();
const click = vi
.spyOn(HTMLAnchorElement.prototype, "click")
.mockImplementation(() => undefined);
vi.stubGlobal("URL", { createObjectURL, revokeObjectURL });
vi.useFakeTimers();
try {
const lease = triggerBlobDownload(new Blob(["local"]), "../safe?.txt");
expect(click).toHaveBeenCalledOnce();
expect(click.mock.instances[0]).toMatchObject({
download: "_safe_.txt",
});
expect(document.querySelector('a[href="blob:download"]')).toBeNull();
expect(lease.revoked).toBe(false);
vi.runAllTimers();
expect(lease.revoked).toBe(true);
expect(revokeObjectURL).toHaveBeenCalledWith("blob:download");
} finally {
vi.useRealTimers();
vi.stubGlobal("URL", originalUrl);
}
});
});
describe("secure and seeded randomness", () => {
it("fills secure byte requests in Web Crypto-sized chunks", () => {
const getRandomValues = vi.fn(<T extends ArrayBufferView>(array: T) => {
new Uint8Array(array.buffer, array.byteOffset, array.byteLength).fill(7);
return array;
});
const cryptoSource = { getRandomValues } as unknown as Pick<
Crypto,
"getRandomValues"
>;
expect(secureRandomBytes(70_000, cryptoSource)).toEqual(
new Uint8Array(70_000).fill(7),
);
expect(getRandomValues).toHaveBeenCalledTimes(2);
expect(() => secureRandomBytes(2, cryptoSource, 1)).toThrow(/exceeds/u);
});
it("uses rejection sampling for bounded secure integers", () => {
const samples = [0xffffffff, 7];
const getRandomValues = <T extends ArrayBufferView>(array: T): T => {
new Uint32Array(array.buffer, array.byteOffset, 1)[0] =
samples.shift() ?? 0;
return array;
};
expect(secureRandomInt(10, 20, { getRandomValues })).toBe(17);
});
it("produces reproducible seeded primitives without mutating inputs", () => {
const first = createSeededRandom("repeatable");
const second = createSeededRandom("repeatable");
expect(Array.from({ length: 8 }, () => first.nextUint32())).toEqual(
Array.from({ length: 8 }, () => second.nextUint32()),
);
const input = [1, 2, 3, 4, 5];
const shuffled = shuffleSeeded(input, 42);
expect(shuffled).toEqual(shuffleSeeded(input, 42));
expect(shuffled).not.toEqual(input);
expect(input).toEqual([1, 2, 3, 4, 5]);
expect(createSeededRandom("bytes").bytes(7)).toHaveLength(7);
const value = createSeededRandom("float").nextFloat();
expect(value).toBeGreaterThanOrEqual(0);
expect(value).toBeLessThan(1);
});
});
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from "vitest";
import {
formatDuration,
formatTimestamp,
parseCsv,
parseDuration,
parseTimestamp,
safeJsonParse,
stableStringify,
stringifyCsv,
} from "../../src/helpers";
describe("bounded structured data", () => {
it("parses hardened JSON and serializes deterministic key order", () => {
expect(safeJsonParse('{"b":2,"a":[true,null]}')).toEqual({
b: 2,
a: [true, null],
});
expect(stableStringify({ z: 1, a: { d: 4, c: 3 } }, 2)).toBe(
'{\n "a": {\n "c": 3,\n "d": 4\n },\n "z": 1\n}',
);
expect(() => safeJsonParse('{"__proto__":{"polluted":true}}')).toThrow(
/Dangerous/u,
);
expect(() => safeJsonParse("[[[0]]]", { maxDepth: 2 })).toThrow(/depth/u);
expect(() => safeJsonParse("[1,2,3]", { maxNodes: 3 })).toThrow(/node/u);
const cycle: Record<string, unknown> = {};
cycle.self = cycle;
expect(() => stableStringify(cycle)).toThrow(/cyclic/u);
expect(() => stableStringify({ value: 1n })).toThrow(/BigInt/u);
});
it("handles quoted CSV, embedded newlines, and round trips", () => {
const rows = [
["name", "note"],
["Ada", 'comma, quote " and\nnewline'],
["", "last"],
];
const csv = stringifyCsv(rows);
expect(csv).toContain('"comma, quote "" and\nnewline"');
expect(parseCsv(csv)).toEqual(rows);
expect(parseCsv("a;b\r\n1;2", { delimiter: ";" })).toEqual([
["a", "b"],
["1", "2"],
]);
expect(() => parseCsv('"unterminated')).toThrow(/unterminated/u);
expect(() => parseCsv("a,b,c", { maxColumns: 2 })).toThrow(/column/u);
});
});
describe("timestamps and durations", () => {
it("normalizes ISO and Unix timestamps", () => {
expect(parseTimestamp(0, "seconds")).toMatchObject({
epochMilliseconds: 0,
epochSeconds: 0,
iso: "1970-01-01T00:00:00.000Z",
});
expect(parseTimestamp("2000-01-01T00:00:00Z").epochSeconds).toBe(946684800);
expect(formatTimestamp(0, "UTC")).toMatch(/1970/u);
expect(() => parseTimestamp("not a date")).toThrow(/range/u);
});
it("parses ISO, clock, and token durations and formats them", () => {
expect(parseDuration("P1DT2H3M4.5S")).toBe(93_784_500);
expect(parseDuration("01:02:03.004")).toBe(3_723_004);
expect(parseDuration("2h 30m")).toBe(9_000_000);
expect(parseDuration("-2h 30m")).toBe(-9_000_000);
expect(parseDuration(formatDuration(-9_000_000, "human"))).toBe(-9_000_000);
expect(formatDuration(93_784_500, "iso")).toBe("P1DT2H3M4.5S");
expect(formatDuration(3_723_004, "clock")).toBe("01:02:03.004");
expect(formatDuration(9_000_000, "human")).toBe("2h 30m");
expect(formatDuration(86_400_000, "iso")).toBe("P1D");
expect(formatDuration(59_999.6, "clock")).toBe("00:01:00.000");
expect(() => parseDuration("1 month")).toThrow(/Duration/u);
});
});
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"useDefineForClassFields": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"include": ["src", "tests"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"declaration": true,
"emitDeclarationOnly": true,
"declarationDir": "./lib-dist/types",
"rootDir": "./src/helpers",
"skipLibCheck": true
},
"include": ["src/helpers/**/*.ts"]
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": [
"vite.config.ts",
"vite.lib.config.ts",
"playwright.config.ts",
"eslint.config.mjs",
"scripts/**/*.mjs"
]
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="vitest/config" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
base: "./",
plugins: [react()],
test: {
environment: "jsdom",
setupFiles: "./src/test/setup.ts",
css: true,
maxWorkers: 2,
restoreMocks: true,
exclude: ["tests/browser/**", "node_modules/**", "dist/**"],
},
});
+17
View File
@@ -0,0 +1,17 @@
import { resolve } from "node:path";
import { defineConfig } from "vite";
export default defineConfig({
build: {
outDir: "lib-dist",
emptyOutDir: true,
copyPublicDir: false,
sourcemap: false,
minify: false,
lib: {
entry: resolve(import.meta.dirname, "src/helpers/index.ts"),
formats: ["es"],
fileName: () => "index.js",
},
},
});