diff --git a/.gitignore b/.gitignore index 8c2b884..da79429 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,7 @@ -# ---> VisualStudioCode +node_modules/ +dist/ +coverage/ +*.tsbuildinfo .vscode/* !.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json !.vscode/extensions.json -!.vscode/*.code-snippets - -# Local History for Visual Studio Code -.history/ - -# Built Visual Studio Code Extensions -*.vsix - diff --git a/CHANGES.md b/CHANGES.md new file mode 100644 index 0000000..9e27ee5 --- /dev/null +++ b/CHANGES.md @@ -0,0 +1,24 @@ +# Herkunft und Änderungen + +Nach GPL §5a: was aus welcher Quelle übertragen und wie es verändert wurde. +Swift-Pfade relativ zu `filius-ipad/ios/FiliusPad/TopologyEditor/` (Stand +`3b5ded0`, 27.08.2026), Tests relativ zu `filius-ipad/ios/FiliusPadTests/`. + +## packages/core + +| Datei | Quelle | Art der Übertragung | +| --- | --- | --- | +| `src/ids.ts` | Swift-Sortierung nach `UUID.uuidString` | neu, bildet die Swift-Ordnung nach | +| `src/model/node.ts` | `Model/TopologyNode.swift` | übertragen; Standard-Ports und -Namen wie Java | +| `src/runtime/config.ts` | `State/TopologyEditorState.swift` (Laufzeit-Konfigurationen, Firewall) | übertragen; Java-Beschriftungen der Oberfläche weggelassen | +| `src/runtime/engine.ts` | `State/TopologyNetworkRuntimeEngine.swift` Z. ~313–3585, ~4753–4850 | übertragen: Warteschlange, Uhr, Ethernet, Switch, ARP, IPv4, ICMP, Routing, Firewall. Klasse statt Werttyp. Noch nicht übertragen (wirft `NotPortedError`): Gateway-NAT, UDP, TCP, DHCP, DNS, RIP, Remote Link, WLAN | +| `src/runtime/ipv4.ts` | Engine `parseIPv4`/`sameSubnet` | übertragen | +| `src/runtime/packets.ts` | Engine, Paketmodelle | übertragen; `Data` → `Uint8Array` | +| `src/runtime/random.ts` | Engine, `TopologyJavaCompatibleRandom` | übertragen; BigInt für die 48-Bit-Arithmetik | +| `src/runtime/routeTable.ts` | `State/TopologyJavaRouteTable.swift` | übertragen ohne Tabellengeometrie (gehört in den Editor) | +| `src/runtime/snapshot.ts` | Engine, `TopologyNetworkRuntimeTopologySnapshot` | übertragen, bisher mit den Feldern der übertragenen Schichten | +| `src/runtime/speed.ts` | Engine, `TopologyNetworkRuntimeSpeed` | übertragen | +| `src/runtime/trace.ts` | Engine, Paketspur-Modell | übertragen | +| `src/util/equal.ts` | — | neu (Ersatz für Swifts `Equatable`) | +| `test/engine.test.ts` | `TopologyNetworkRuntimeEngineTests.swift` (21 von 72 Tests) | übertragen; `nextInt`-Referenzwerte an OpenJDK 21 gemessen | +| `test/routeTable.test.ts` | `TopologyJavaRouteTableTests.swift` (8 von 12 Tests) | übertragen; Geometrie- und Reducer-Tests folgen mit Editor und Dokument | diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/README.md b/README.md index fb992d0..cbdffaa 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,45 @@ # mdg-filius +Netzwerksimulation nach [FILIUS](https://www.lernsoftware-filius.de) für den +Browser — als App „Filius" im MDG-Dashboard, gemeinsam bearbeitbar. + +> Based on Filius by Dr. Stefan Freischlad and the Filius project. +> +> Dieses Projekt ist unabhängig. Es wird weder vom ursprünglichen +> Filius-Projekt (Universität Siegen) noch von `filius-project` +> (Filius on iPad) herausgegeben, betrieben oder unterstützt. + +## Herkunft + +Der Simulationskern ist eine Übertragung nach TypeScript aus + +* [`filius-project/filius-ipad`](https://github.com/filius-project/filius-ipad) + (Swift, GPLv2 oder GPLv3) — Vorlage für Kern, `.fls`-Codec und Tests, +* [`filius1/filius`](https://gitlab.com/filius1/filius) (Java, GPLv2 oder + GPLv3) — Referenz für Dateiformat und Verhalten. + +Jede übertragene Datei nennt in ihrem Kopf die Quelldatei. `CHANGES.md` führt +die Herkunft je Paket. Lizenz dieses Repos: **GPL-3.0** (`LICENSE`). + +## Aufbau + +| Pfad | Inhalt | +| --- | --- | +| `packages/core` | Simulationskern: Modell, Ereignis-Warteschlange, Protokolle, Anwendungen — ohne DOM, ohne Node | +| `packages/fls` | `.fls` lesen, schreiben, Unbekanntes bewahren *(folgt)* | +| `packages/doc` | gemeinsames Dokument (Yjs) *(folgt)* | +| `packages/editor` | Oberfläche im Iframe des Dashboards *(folgt)* | +| `server` | Filius-Dienst auf Server F *(folgt)* | + +Plan und Entscheidungen: `knowledge/plans/FILIUS_WEB_PLAN.md` im Dashboard. + +## Entwickeln + +```bash +npm install +npm run hooks # Sprachprüfung vor jedem Commit (braucht das Dashboard drumherum) +npm run check # Typprüfung + Tests +``` + +Code, Kommentare und Testnamen sind englisch; sichtbare Texte stehen hinter +i18n-Schlüsseln (Deutsch/Englisch). diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e3e37fa --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1650 @@ +{ + "name": "mdg-filius", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mdg-filius", + "license": "GPL-3.0-only", + "workspaces": [ + "packages/*" + ], + "devDependencies": { + "@types/node": "^20.19.0", + "typescript": "^5.9.0", + "vitest": "^3.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@mdg-filius/core": { + "resolved": "packages/core", + "link": true + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.5.tgz", + "integrity": "sha512-J25QJU+B78T4FhhBsNpLJyVWOi31mwtpcMwywHmOKH65Q9IWGA81gPj+dnwlhU8wktVriYE+tFAaQgrnJRzAZg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.5.tgz", + "integrity": "sha512-LDopB3zuZM5Ux9TT2luNEBJW/tYbGU2g1d+VpKk6I+gSKDb+/7sYE6M225gRQt4RbMX6MSwMsVR/phdjVUgRLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.5.tgz", + "integrity": "sha512-wlJEERGfeuHeBavCL2qVnNacOK43NDoZM4sjkeRPymd04OAE9T1zBqDJgmZ+CIsPTYKwdzpUC8vmOw84dwY4Tg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.5.tgz", + "integrity": "sha512-4nJJGg5jbo2wwPP4JP+LfEBA3bvP8rU9CLuhp7jWvq9sxEyhjQFTFdrqi+/dHEin/pd8jpT0vcehIpnZtmEdcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.5.tgz", + "integrity": "sha512-DrZbyCDF1hneuO6jRbvZ2D7+PIBM6yIwYnJpg2vIk58T+wuFpiaGZrfUr59lDWw45bg+IrpTGLPiNi/Fk4w3Cg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.5.tgz", + "integrity": "sha512-gqfUVMJMB3mehqywxp6hTBFfgtMQykZY19+cfiaYP0toIJLb/1DZRJHVkQQGP13W4TAwfZDWeg1qBcheTRioXQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.5.tgz", + "integrity": "sha512-CFmhpvAwzSaWMlN3VN7UtmoTihlZNzoP0juQib5TQRnYUyDV8dXeWOp29sobWAT6gXl/hQgAClLlEiYozQG3OQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.5.tgz", + "integrity": "sha512-Uc9H8eXCOayV6JLTH5bXKMId6qbhNHa818/BgYjm4jrlq3vZquC9cqyvHBw17xy5Mnj5f+I3gFK5JcEf3hSqrw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.5.tgz", + "integrity": "sha512-VcPr/szv/1BFw112Kt//fxulXt/JPqzzidU84iW68L2DdjnOO8QFUv2zTSYBEPHD6movBD4z+bbr5y60GYM7Jw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.5.tgz", + "integrity": "sha512-BnxtJ5/91BrIHYIkGrmjz/lbMhqEHt1dPFqIxIFR+jPn0xVc/oUSCtIT089zfp5ufwGDlYz2UC+Fe1SRBpYFbQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.5.tgz", + "integrity": "sha512-LrYcHZwF+fAMNKHYTOQ5osWM4AZF7YF6D+XtsjDyEvljtt11twc+zHVXBLNEjxVSUnKYsOhvVz4Z213eW02COQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.5.tgz", + "integrity": "sha512-nj7QKQePAAUpCpJHtg0pR0W/b92A9NO17JS3BAQmHDn/yhmkir2p8llrKY9TOhleKIaSzy1JhxS3T9FVld6coA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.5.tgz", + "integrity": "sha512-5ylkX6dWMeBKge9nTU+Rxfb+ZfaCIJ9lRqIFaK0eAMcWp7OJbYnLveLgXmm0VrvuLKb8qIK+mHyH0qu88RM+iA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.5.tgz", + "integrity": "sha512-oHK4ZHYFDKjZviK34I+NwgfbGxgI7ztrNxj2hPTSSNFgeq1a/lEd7dHV2fdGAuTH4Iym3RHJg+vAbWaWG4B7Zg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.5.tgz", + "integrity": "sha512-UcetmHZ6XOXuUByiKZyQmb55ZPr0LABr3Ec/HB9wKZn6CEAFWZkE+hsJErJ9hbPBC7nI0dKuELx7CoV6IM7TMg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.5.tgz", + "integrity": "sha512-C5CmDPQBtvjVo8cgQsBs+w6WB0JLkiixhgi6hVLV11hERWdn/p0XcPU2OUcZzac9BPOFq7SbaHFa8r3SWEysCQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.5.tgz", + "integrity": "sha512-lHVQHJFKsuuxLMi3MQO9XVL8Tje3JR82CzB+QDKC5NWBcsIWuwsn9uIM5e3lBhI+fF1/s63qnyYqsg65+8rV/w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.5.tgz", + "integrity": "sha512-3W9bTFcQNJn71cSJVM9RKIiZOy8DO/XLDii8Uv/Pm6WKqDRj7JV3ZfuXIEfyuy5LXpIzAbB/1M4Ukp9GKNa7nA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.5.tgz", + "integrity": "sha512-VDC7rRJlee/scpki96GZ27Omf6yU87s1YXwVTpjE5841faVlDYYT565rgfmoR1U0sqL7z5ivQSDjcsF6VRXyBA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.5.tgz", + "integrity": "sha512-z86Ok2p4pTdv5xqCKZsTooO7yBEiaJR/HzU3Wx8RmWsPoLppnMKROhJusQob8B3IE1ghC343kUW9rC2r+Wf3ig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.5.tgz", + "integrity": "sha512-IzQmj+xXwQFGhMAMKMQVXkMwMZN3TqkJgAE0nSsqvVwWWciP4AIPMmWRqOQ2GfX7TUDZr+xqGFcBS36CRPGw0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.5.tgz", + "integrity": "sha512-F6qpTaPc9bwBH85kjy0/BLmLSW1uv7AoOXCoRIkg2arlgCYlWYcAbiMkvZuAcaWk9TpCRG//okznLAqLGshkMw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.5.tgz", + "integrity": "sha512-igoDsTFhhwECBeGbUuLeIk7t8Y1apa+cs6mDWpx2EZ0ch7oEQgzHbFUXN9euoHekCAQzXdXApAGkV6jznS7tWw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.5.tgz", + "integrity": "sha512-U3teMeMbXFmaM5D+OTJpsOXd+wV/qftIeYF9kBKL4v73641qyJmoXFtA28DQLsnmlyayEsTe72xpLHrArq6vHw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.5.tgz", + "integrity": "sha512-ypfC34F3RKXvCXBglGqGMsUSMKlgwd1HX9AOAlx9RoZZ6GaI42YHVeKpzg3JG+wpBUJYTG+NNZhqbDWL8tBZkw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.5.tgz", + "integrity": "sha512-KRWwmNLlPw5M7HcdYfm15oBv9n9LPtjzpzCIxS/phwqvPyxHSoKX6Y2YU3pxSPfy0CLquVgsx/j/hBi6OvH1Nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.63.5", + "@rollup/rollup-android-arm64": "4.63.5", + "@rollup/rollup-darwin-arm64": "4.63.5", + "@rollup/rollup-darwin-x64": "4.63.5", + "@rollup/rollup-freebsd-arm64": "4.63.5", + "@rollup/rollup-freebsd-x64": "4.63.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.63.5", + "@rollup/rollup-linux-arm-musleabihf": "4.63.5", + "@rollup/rollup-linux-arm64-gnu": "4.63.5", + "@rollup/rollup-linux-arm64-musl": "4.63.5", + "@rollup/rollup-linux-loong64-gnu": "4.63.5", + "@rollup/rollup-linux-loong64-musl": "4.63.5", + "@rollup/rollup-linux-ppc64-gnu": "4.63.5", + "@rollup/rollup-linux-ppc64-musl": "4.63.5", + "@rollup/rollup-linux-riscv64-gnu": "4.63.5", + "@rollup/rollup-linux-riscv64-musl": "4.63.5", + "@rollup/rollup-linux-s390x-gnu": "4.63.5", + "@rollup/rollup-linux-x64-gnu": "4.63.5", + "@rollup/rollup-linux-x64-musl": "4.63.5", + "@rollup/rollup-openbsd-x64": "4.63.5", + "@rollup/rollup-openharmony-arm64": "4.63.5", + "@rollup/rollup-win32-arm64-msvc": "4.63.5", + "@rollup/rollup-win32-ia32-msvc": "4.63.5", + "@rollup/rollup-win32-x64-gnu": "4.63.5", + "@rollup/rollup-win32-x64-msvc": "4.63.5", + "fsevents": "~2.3.2" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.3.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", + "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "packages/core": { + "name": "@mdg-filius/core", + "version": "0.0.0", + "license": "GPL-3.0-only" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..b853742 --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "mdg-filius", + "private": true, + "license": "GPL-3.0-only", + "type": "module", + "workspaces": [ + "packages/*" + ], + "engines": { + "node": ">=20" + }, + "scripts": { + "test": "vitest run", + "typecheck": "tsc -b", + "check": "npm run typecheck && npm run test", + "hooks": "git config core.hooksPath scripts/hooks" + }, + "devDependencies": { + "@types/node": "^20.19.0", + "typescript": "^5.9.0", + "vitest": "^3.2.0" + } +} diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..55fd066 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,10 @@ +{ + "name": "@mdg-filius/core", + "version": "0.0.0", + "private": true, + "license": "GPL-3.0-only", + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/core/src/ids.ts b/packages/core/src/ids.ts new file mode 100644 index 0000000..efc9d24 --- /dev/null +++ b/packages/core/src/ids.ts @@ -0,0 +1,19 @@ +// Ported from filius-ipad (GPLv2/GPLv3), ios/FiliusPad/TopologyEditor. +// Swift orders identifiers by `UUID.uuidString`, which is upper case. Every +// deterministic ordering in the runtime depends on it, so identifiers are +// compared the same way here whatever case they were written in. + +/** A node, port, link or socket identifier: a UUID string. */ +export type Id = string; + +/** `lhs.uuidString < rhs.uuidString` in Swift. */ +export function idLess(lhs: Id, rhs: Id): boolean { + return lhs.toUpperCase() < rhs.toUpperCase(); +} + +/** Comparator for `Array.prototype.sort` with the Swift ordering. */ +export function compareIds(lhs: Id, rhs: Id): number { + const left = lhs.toUpperCase(); + const right = rhs.toUpperCase(); + return left < right ? -1 : left > right ? 1 : 0; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..3232dc4 --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,13 @@ +// Public surface of the simulation core. +export * from './ids.js'; +export * from './model/node.js'; +export * from './runtime/config.js'; +export * from './runtime/engine.js'; +export * from './runtime/ipv4.js'; +export * from './runtime/packets.js'; +export * from './runtime/random.js'; +export * from './runtime/routeTable.js'; +export * from './runtime/snapshot.js'; +export * from './runtime/speed.js'; +export * from './runtime/trace.js'; +export * from './util/equal.js'; diff --git a/packages/core/src/model/node.ts b/packages/core/src/model/node.ts new file mode 100644 index 0000000..57024f6 --- /dev/null +++ b/packages/core/src/model/node.ts @@ -0,0 +1,102 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// ios/FiliusPad/TopologyEditor/Model/TopologyNode.swift +// Java counterpart: filius.hardware.knoten.* (port counts per device kind). + +import type { Id } from '../ids.js'; + +export type NodeKind = + | 'pc' + | 'notebook' + | 'networkSwitch' + | 'router' + | 'gateway' + | 'remoteLink' + | 'unsupported'; + +export function isPcClassEndpoint(kind: NodeKind): boolean { + return kind === 'pc' || kind === 'notebook'; +} + +export type HostLabelPolicy = 'manual' | 'ipAddress' | 'macAddress' | 'ipAndMAC'; + +export interface PortMetadata { + readonly id: Id; + label: string; + isOccupied: boolean; + /** Canonical (upper case, colon separated) or undefined. */ + readonly importedMacAddress?: string; +} + +/** + * The MAC address of a port nobody gave one: `02:` followed by the last ten + * hex digits of the port's UUID — stable across saves, locally administered. + */ +export function stableGeneratedMacAddress(portId: Id): string { + const compact = portId.toUpperCase().replaceAll('-', ''); + const suffix = compact.slice(-10); + const octets = ['02']; + for (let offset = 0; offset < suffix.length; offset += 2) { + octets.push(suffix.slice(offset, offset + 2).toUpperCase()); + } + return octets.join(':'); +} + +/** Six colon-separated pairs of hex digits, upper-cased; anything else is undefined. */ +export function canonicalMacAddress(value: string | undefined | null): string | undefined { + if (value === undefined || value === null) return undefined; + const segments = value.trim().split(':'); + if (segments.length !== 6) return undefined; + if (!segments.every((segment) => /^[0-9A-Fa-f]{2}$/.test(segment))) return undefined; + return segments.map((segment) => segment.toUpperCase()).join(':'); +} + +export function effectiveMacAddress(port: PortMetadata): string { + return port.importedMacAddress ?? stableGeneratedMacAddress(port.id); +} + +/** + * The name a new device gets. These are the Java FILIUS device names; the + * editor shows them translated (packages/editor i18n), the model keeps them + * as they appear in a Java .fls file. + */ +export function defaultDisplayName(kind: NodeKind): string { + switch (kind) { + case 'pc': + return 'Rechner'; + case 'notebook': + return 'Notebook'; + case 'networkSwitch': + return 'Switch'; + case 'router': + return 'Vermittlungsrechner'; + case 'gateway': + return 'Gateway'; + case 'remoteLink': + return 'Remote Link'; + case 'unsupported': + return 'Unbekanntes Gerät'; + } +} + +/** Labels of the ports a new device of this kind has, in order. */ +export function defaultPortLabels(kind: NodeKind): string[] { + switch (kind) { + case 'pc': + case 'notebook': + return ['eth0']; + case 'networkSwitch': + // Java Switch constructs exactly 24 physical ports. + return Array.from({ length: 24 }, (_, index) => `sw${index + 1}`); + case 'router': + // Java Vermittlungsrechner starts with one configurable network interface. + return ['rt1']; + case 'gateway': + // Java Gateway has fixed WAN (index 0) and LAN (index 1) interfaces. + return ['wan0', 'lan0']; + case 'remoteLink': + // One local physical attachment, matching the Java Modem. + return ['remote0']; + case 'unsupported': + return []; + } +} diff --git a/packages/core/src/runtime/config.ts b/packages/core/src/runtime/config.ts new file mode 100644 index 0000000..6b6972e --- /dev/null +++ b/packages/core/src/runtime/config.ts @@ -0,0 +1,150 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyEditorState.swift (runtime configuration value types) + +import type { Id } from '../ids.js'; +import { maskAddress, parseIPv4 } from './ipv4.js'; + +/** The IP settings of a PC or notebook (its single interface) — and a router's gateway. */ +export interface DeviceConfiguration { + readonly ipAddress: string; + readonly subnetMask: string; + readonly defaultGateway: string; + readonly dnsServer: string; +} + +export function deviceConfiguration( + ipAddress: string, + subnetMask: string, + defaultGateway = '', + dnsServer = '', +): DeviceConfiguration { + return { ipAddress, subnetMask, defaultGateway, dnsServer }; +} + +/** One interface of a router or gateway. */ +export interface InterfaceConfiguration { + readonly ipAddress: string; + readonly subnetMask: string; +} + +/** Map key for an interface: node and port. */ +export type InterfaceKey = string; + +export function interfaceKey(nodeId: Id, portId: Id): InterfaceKey { + return `${nodeId}/${portId}`; +} + +/** A row of the manual routing table (Java `Weiterleitungstabelle`). */ +export interface ManualRoute { + readonly destinationNetwork: string; + readonly subnetMask: string; + readonly gateway: string; + readonly interfaceIPAddress: string; +} + +/** Longest numeric mask wins; on a tie the first row stays. */ +export function bestMatchingManualRoute( + targetIPAddress: string, + routes: readonly ManualRoute[], +): ManualRoute | undefined { + const target = parseIPv4(targetIPAddress); + if (target === undefined) return undefined; + let best: ManualRoute | undefined; + let bestMask: number | undefined; + for (const route of routes) { + const destination = parseIPv4(route.destinationNetwork); + const mask = parseIPv4(route.subnetMask); + if (destination === undefined || mask === undefined) continue; + if (destination !== maskAddress(target, mask)) continue; + if (bestMask !== undefined && mask <= bestMask) continue; + bestMask = mask; + best = route; + } + return best; +} + +export interface SwitchConfiguration { + readonly ssid: string; + readonly retentionTimeMilliseconds: number; +} + +/** Java SwitchFirmware keeps a learned MAC address for five minutes. */ +export const DEFAULT_SWITCH_RETENTION_MILLISECONDS = 300_000; + +export function switchConfiguration( + ssid: string, + retentionTimeMilliseconds = DEFAULT_SWITCH_RETENTION_MILLISECONDS, +): SwitchConfiguration { + return { ssid, retentionTimeMilliseconds }; +} + +/** The first six hex digits of the node's UUID, lower case. */ +export function defaultSwitchConfiguration(nodeId: Id): SwitchConfiguration { + const compact = nodeId.replaceAll('-', '').toLowerCase(); + return switchConfiguration(compact.slice(0, 6)); +} + +// ── Firewall (Java filius.software.firewall.Firewall, FirewallRule) ───────── + +export const FIREWALL_PROTOCOL = { all: -1, icmp: 1, tcp: 6, udp: 17 } as const; +export type FirewallProtocol = keyof typeof FIREWALL_PROTOCOL; + +export type FirewallAction = 'drop' | 'accept'; + +/** Java writes this as the source of a rule that means "any directly connected network". */ +export const DIRECTLY_CONNECTED_SOURCE_MARKER = '999.999.999.999'; +export const ALL_PORTS = -1; + +export interface FirewallRule { + readonly sourceIPAddress: string; + readonly sourceSubnetMask: string; + readonly destinationIPAddress: string; + readonly destinationSubnetMask: string; + /** A port number or ALL_PORTS. */ + readonly port: number; + readonly protocol: FirewallProtocol; + readonly action: FirewallAction; +} + +export function firewallRule(fields: Partial = {}): FirewallRule { + return { + sourceIPAddress: fields.sourceIPAddress ?? '', + sourceSubnetMask: fields.sourceSubnetMask ?? '', + destinationIPAddress: fields.destinationIPAddress ?? '', + destinationSubnetMask: fields.destinationSubnetMask ?? '', + port: fields.port ?? ALL_PORTS, + protocol: fields.protocol ?? 'tcp', + action: fields.action ?? 'drop', + }; +} + +export interface FirewallConfiguration { + readonly isActive: boolean; + readonly defaultPolicy: FirewallAction; + readonly dropIcmp: boolean; + readonly filterSynSegmentsOnly: boolean; + readonly filterUdp: boolean; + readonly rules: readonly FirewallRule[]; +} + +/** What a router or gateway has without a firewall configured: inactive. */ +export function firewallConfiguration(fields: Partial = {}): FirewallConfiguration { + return { + isActive: fields.isActive ?? false, + defaultPolicy: fields.defaultPolicy ?? 'drop', + dropIcmp: fields.dropIcmp ?? false, + filterSynSegmentsOnly: fields.filterSynSegmentsOnly ?? true, + filterUdp: fields.filterUdp ?? true, + rules: fields.rules ?? [], + }; +} + +/** What Java installs as the personal firewall of a PC: active, drop by default. */ +export const JAVA_PERSONAL_FIREWALL_DEFAULTS: FirewallConfiguration = firewallConfiguration({ + isActive: true, + defaultPolicy: 'drop', + dropIcmp: false, + filterSynSegmentsOnly: true, + filterUdp: true, + rules: [], +}); diff --git a/packages/core/src/runtime/engine.ts b/packages/core/src/runtime/engine.ts new file mode 100644 index 0000000..e283f52 --- /dev/null +++ b/packages/core/src/runtime/engine.ts @@ -0,0 +1,1939 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyNetworkRuntimeEngine.swift +// "Runtime snapshots and transient state" (lines ~313–938) +// "Deterministic runtime engine" (lines ~984–1284) +// "Ethernet, ARP, IPv4, and ICMP packet runtime" (lines ~1284–3585, +// without remote link, wireless and gateway NAT; with the firewall) +// processScheduledRuntimeEvent, dropForGlobalPacketLoss (lines ~4753–4850) +// Java counterparts: filius.hardware.Verbindung, filius.software.netzzugangsschicht, +// filius.software.vermittlungsschicht (ARP, IP, ICMP), system.SwitchFirmware. +// +// The Swift engine is a value type driven by a reducer; here it is a class +// with the same inputs and outputs. Time is virtual: nothing sleeps, every +// delay is an event in the queue, ordered by deadline and then by insertion. +// Calls that block in Java (resolving an address, waiting for an echo reply) +// advance the virtual clock inside the call, exactly as the Swift port does. +// +// Not ported yet — each place throws NotPortedError instead of guessing: +// gateway NAT, UDP and TCP delivery, RIP routing, remote links. + +import { compareIds, type Id } from '../ids.js'; +import { isPcClassEndpoint, stableGeneratedMacAddress } from '../model/node.js'; +import type { + DeviceConfiguration, + FirewallConfiguration, + FirewallRule, + InterfaceConfiguration, + ManualRoute, +} from './config.js'; +import { + ALL_PORTS, + DEFAULT_SWITCH_RETENTION_MILLISECONDS, + DIRECTLY_CONNECTED_SOURCE_MARKER, + FIREWALL_PROTOCOL, + firewallConfiguration, + interfaceKey, +} from './config.js'; +import { deepEqual } from '../util/equal.js'; +import { maskAddress, parseIPv4, sameSubnet } from './ipv4.js'; +import { + forwardingClone, + icmpMessage, + IPV4_PROTOCOL, + packetIdentityInFrame, + TCP_FLAG, + type ArpPacket, + type EthernetFrame, + type IcmpMessage, + type IcmpMessageKind, + type IPv4Packet, +} from './packets.js'; +import { JavaCompatibleRandom } from './random.js'; +import { routeTableRows, type RouteRow } from './routeTable.js'; +import { EMPTY_TOPOLOGY_SNAPSHOT, withSnapshot, type NodeSnapshot, type TopologySnapshot } from './snapshot.js'; +import { RuntimeSpeed } from './speed.js'; +import { + PRODUCTION_TRACE_RETENTION, + type HeaderField, + type TraceDirection, + type TraceEvent, + type TraceLayer, + type TraceOperation, + type TraceRetentionPolicy, +} from './trace.js'; + +export const ETHERNET_BROADCAST_MAC_ADDRESS = 'FF:FF:FF:FF:FF:FF'; +export const UNSPECIFIED_MAC_ADDRESS = '00:00:00:00:00:00'; +export const LIMITED_BROADCAST_IP_ADDRESS = '255.255.255.255'; +export const UNSPECIFIED_IP_ADDRESS = '0.0.0.0'; +export const LOCALHOST_IP_ADDRESS = '127.0.0.1'; + +/** The seed a simulation uses unless told otherwise. */ +export const DEFAULT_SEED = 0xf11a5n; + +/** A part of the Swift engine that has not been carried over yet. */ +export class NotPortedError extends Error { + constructor(feature: string) { + super(`Not ported yet: ${feature}`); + this.name = 'NotPortedError'; + } +} + +// ── Events, inputs, outputs ──────────────────────────────────────────────── + +export type ScheduledEventKind = + | { readonly kind: 'parityMarker'; readonly label: string } + | { readonly kind: 'ripBeacon'; readonly nodeId: Id } + | { readonly kind: 'dhcpClientStart'; readonly nodeId: Id } + | { readonly kind: 'dhcpTimeout'; readonly nodeId: Id } + | { readonly kind: 'tcpTimeout'; readonly sessionId: Id } + | { + readonly kind: 'ethernetLinkDelivery'; + readonly sourceNodeId: Id; + readonly targetNodeId: Id; + readonly targetPortId: Id; + readonly latencyMilliseconds: number; + readonly frame: EthernetFrame; + } + | { + readonly kind: 'remoteLinkDelivery'; + readonly sourceNodeId: Id; + readonly partnerNodeId: Id; + readonly partnerPortId: Id; + readonly pairIdentifier: string; + readonly latencyMilliseconds: number; + readonly frame: EthernetFrame; + } + | { + readonly kind: 'lanRemoteLinkTransmission'; + readonly nodeId: Id; + readonly pairIdentifier: string; + readonly latencyMilliseconds: number; + readonly frame: EthernetFrame; + } + | { readonly kind: 'natExpirySweep' }; + +export interface ScheduledEvent { + readonly id: number; + readonly deadlineMilliseconds: number; + readonly sequenceNumber: number; + readonly kind: ScheduledEventKind; +} + +export type CompatibilityOperationKind = 'terminalCommand' | 'applicationOperation' | 'socketOperation'; + +export interface CompatibilityOperation { + readonly kind: CompatibilityOperationKind; + readonly nodeId: Id; + readonly interfaceId?: Id; + readonly detail: string; +} + +export type RuntimeInput = + | { + readonly type: 'start'; + readonly snapshot: TopologySnapshot; + readonly seed: bigint | number; + readonly initialTimeMilliseconds: number; + } + | { readonly type: 'stop' } + | { readonly type: 'advance'; readonly toMilliseconds: number } + | { readonly type: 'schedule'; readonly deadlineMilliseconds: number; readonly kind: ScheduledEventKind } + | { readonly type: 'compatibilityOperation'; readonly operation: CompatibilityOperation }; + +export type RuntimeOutputKind = + | { readonly type: 'started' } + | { readonly type: 'startIgnoredAlreadyRunning' } + | { readonly type: 'stopped' } + | { readonly type: 'stopIgnoredAlreadyStopped' } + | { readonly type: 'advanced'; readonly fromMilliseconds: number; readonly toMilliseconds: number } + | { readonly type: 'advanceIgnoredWhileStopped' } + | { readonly type: 'advanceRejectedPastTime' } + | { readonly type: 'scheduleRejectedPastTime'; readonly deadlineMilliseconds: number } + | { readonly type: 'scheduled'; readonly event: ScheduledEvent } + | { readonly type: 'fired'; readonly event: ScheduledEvent } + | { readonly type: 'compatibilityOperationRecorded'; readonly operation: CompatibilityOperation }; + +export interface RuntimeOutput { + readonly timeMilliseconds: number; + readonly kind: RuntimeOutputKind; +} + +/** A named, seeded list of events to replay without any user interface. */ +export interface RuntimeScenario { + readonly name: string; + readonly seed: bigint | number; + readonly advanceToMilliseconds: number; + readonly scheduledEvents: readonly { deadlineMilliseconds: number; kind: ScheduledEventKind }[]; +} + +// ── Runtime state ────────────────────────────────────────────────────────── + +export interface ArpCacheEntry { + readonly ipAddress: string; + readonly macAddress: string; + readonly updatedAtMilliseconds: number; +} + +export interface SwitchSatEntry { + readonly macAddress: string; + readonly portId: Id; + readonly portLabel: string; + readonly updatedAtMilliseconds: number; +} + +/** An interface of a node that has an IP configuration. */ +export interface NetworkInterface { + readonly nodeId: Id; + readonly portId: Id; + readonly index: number; + readonly ipAddress: string; + readonly subnetMask: string; + readonly defaultGateway: string; + readonly macAddress: string; +} + +export interface DeliveredIPv4Packet { + readonly nodeId: Id; + readonly interfaceId: Id; + readonly packet: IPv4Packet; +} + +export interface IcmpObservation { + readonly nodeId: Id; + readonly interfaceId?: Id; + readonly packet: IPv4Packet; + readonly message: IcmpMessage; +} + +export type IPv4DeliveryResult = + | { readonly type: 'delivered'; readonly packetIdentity: number; readonly nodeId: Id } + | { + readonly type: 'icmpError'; + readonly packetIdentity: number; + readonly nodeId: Id; + readonly kind: IcmpMessageKind; + } + | { readonly type: 'dropped'; readonly packetIdentity: number; readonly nodeId?: Id }; + +export interface FirewallDecision { + readonly packetIdentity: number; + readonly nodeId: Id; + readonly accepted: boolean; + readonly ruleIndex?: number; +} + +export type RuntimePhase = 'stopped' | 'running'; + +export interface RuntimeState { + phase: RuntimePhase; + currentTimeMilliseconds: number; + simulationSpeedPercent: number; + globalPacketLossEnabled: boolean; + seed: bigint; + topologySnapshot: TopologySnapshot; + pendingEvents: ScheduledEvent[]; + packetTraces: TraceEvent[]; + discardedPacketTraceCount: number; + arpCachesByNodeId: Map>; + switchForwardingTablesByNodeId: Map>; + switchForwardingUpdatedAtMillisecondsByNodeId: Map>; + switchSeenFrameIdentitiesByNodeId: Map>; + deliveredIPv4PacketsByNodeId: Map; + icmpObservationsByNodeId: Map; + firewallDecisions: FirewallDecision[]; + nextEventSequenceNumber: number; + nextFrameIdentity: number; + nextPacketIdentity: number; + nextTraceIdentity: number; +} + +function initialState(seed: bigint): RuntimeState { + return { + phase: 'stopped', + currentTimeMilliseconds: 0, + simulationSpeedPercent: new RuntimeSpeed().percent, + globalPacketLossEnabled: false, + seed, + topologySnapshot: EMPTY_TOPOLOGY_SNAPSHOT, + pendingEvents: [], + packetTraces: [], + discardedPacketTraceCount: 0, + arpCachesByNodeId: new Map(), + switchForwardingTablesByNodeId: new Map(), + switchForwardingUpdatedAtMillisecondsByNodeId: new Map(), + switchSeenFrameIdentitiesByNodeId: new Map(), + deliveredIPv4PacketsByNodeId: new Map(), + icmpObservationsByNodeId: new Map(), + firewallDecisions: [], + nextEventSequenceNumber: 0, + nextFrameIdentity: 1, + nextPacketIdentity: 1, + nextTraceIdentity: 1, + }; +} + +export interface TraceInput { + frameIdentity?: number | undefined; + packetIdentity?: number | undefined; + nodeId: Id; + interfaceId?: Id | undefined; + direction: TraceDirection; + layer: TraceLayer; + operation: TraceOperation; + beforeHeaders?: readonly HeaderField[]; + afterHeaders?: readonly HeaderField[]; + detail?: string | undefined; +} + +type PacketRoute = + | { readonly type: 'local'; readonly interface: NetworkInterface | undefined } + | { readonly type: 'broadcast' } + | { readonly type: 'egress'; readonly interface: NetworkInterface; readonly nextHop: string } + | { readonly type: 'unavailable' }; + +interface PendingIPv4Transmission { + readonly packet: IPv4Packet; + readonly interface: NetworkInterface; + readonly operation: TraceOperation; +} + +function toSeed(seed: bigint | number): bigint { + return BigInt.asUintN(64, BigInt(seed)); +} + +function isNetworkDeliveryEvent(kind: ScheduledEventKind): boolean { + return kind.kind === 'ethernetLinkDelivery' || kind.kind === 'remoteLinkDelivery'; +} + +function isRemoteLinkWaitEvent(kind: ScheduledEventKind): boolean { + return isNetworkDeliveryEvent(kind) || kind.kind === 'lanRemoteLinkTransmission'; +} + +function getOrCreate(map: Map, key: K, create: () => V): V { + let value = map.get(key); + if (value === undefined) { + value = create(); + map.set(key, value); + } + return value; +} + +// ── Engine ───────────────────────────────────────────────────────────────── + +export class NetworkRuntimeEngine { + private stateValue: RuntimeState; + private random: JavaCompatibleRandom; + private udpPortRandom: JavaCompatibleRandom; + private tcpPortRandom: JavaCompatibleRandom; + private runtimeSpeed: RuntimeSpeed; + private readonly packetTraceRetentionPolicy: TraceRetentionPolicy; + private isProcessingScheduledEvents = false; + private pendingIPv4TransmissionsByArpKey = new Map(); + + constructor( + seed: bigint | number = DEFAULT_SEED, + packetTraceRetentionPolicy: TraceRetentionPolicy = PRODUCTION_TRACE_RETENTION, + ) { + const normalizedSeed = toSeed(seed); + this.stateValue = initialState(normalizedSeed); + this.random = new JavaCompatibleRandom(normalizedSeed); + this.udpPortRandom = new JavaCompatibleRandom(normalizedSeed ^ 0x5544_5050n); + this.tcpPortRandom = new JavaCompatibleRandom(normalizedSeed ^ 0x5443_5050n); + this.runtimeSpeed = new RuntimeSpeed(); + this.packetTraceRetentionPolicy = packetTraceRetentionPolicy; + this.stateValue.simulationSpeedPercent = this.runtimeSpeed.percent; + } + + /** The runtime state. Read it; change it only through the engine's methods. */ + get state(): RuntimeState { + return this.stateValue; + } + + get simulationSpeed(): RuntimeSpeed { + return this.runtimeSpeed; + } + + setSimulationSpeed(percent: number): void { + this.runtimeSpeed = new RuntimeSpeed(percent); + this.stateValue.simulationSpeedPercent = this.runtimeSpeed.percent; + } + + setGlobalPacketLossEnabled(enabled: boolean): void { + this.stateValue.globalPacketLossEnabled = this.stateValue.phase === 'running' && enabled; + } + + handle(input: RuntimeInput): RuntimeOutput[] { + switch (input.type) { + case 'start': { + if (this.stateValue.phase !== 'stopped') return [this.output({ type: 'startIgnoredAlreadyRunning' })]; + const seed = toSeed(input.seed); + this.stateValue = initialState(seed); + this.stateValue.phase = 'running'; + this.stateValue.currentTimeMilliseconds = input.initialTimeMilliseconds; + this.stateValue.simulationSpeedPercent = this.runtimeSpeed.percent; + this.stateValue.topologySnapshot = input.snapshot; + this.random = new JavaCompatibleRandom(seed); + this.udpPortRandom = new JavaCompatibleRandom(seed ^ 0x5544_5050n); + this.tcpPortRandom = new JavaCompatibleRandom(seed ^ 0x5443_5050n); + this.isProcessingScheduledEvents = false; + this.pendingIPv4TransmissionsByArpKey.clear(); + this.initializeRipState(); + this.initializeDhcpState(); + this.initializeNatState(); + return [this.output({ type: 'started' })]; + } + + case 'stop': { + if (this.stateValue.phase !== 'running') return [this.output({ type: 'stopIgnoredAlreadyStopped' })]; + const state = this.stateValue; + state.phase = 'stopped'; + state.globalPacketLossEnabled = false; + this.isProcessingScheduledEvents = false; + this.pendingIPv4TransmissionsByArpKey.clear(); + state.pendingEvents = []; + state.arpCachesByNodeId.clear(); + state.switchForwardingTablesByNodeId.clear(); + state.switchForwardingUpdatedAtMillisecondsByNodeId.clear(); + state.switchSeenFrameIdentitiesByNodeId.clear(); + state.deliveredIPv4PacketsByNodeId.clear(); + state.icmpObservationsByNodeId.clear(); + state.firewallDecisions = []; + return [this.output({ type: 'stopped' })]; + } + + case 'advance': + return this.advance(input.toMilliseconds); + + case 'schedule': { + if (this.stateValue.phase !== 'running') return [this.output({ type: 'advanceIgnoredWhileStopped' })]; + if (input.deadlineMilliseconds < this.stateValue.currentTimeMilliseconds) { + return [ + this.output({ type: 'scheduleRejectedPastTime', deadlineMilliseconds: input.deadlineMilliseconds }), + ]; + } + const event = this.schedule(input.deadlineMilliseconds, input.kind); + return [this.output({ type: 'scheduled', event })]; + } + + case 'compatibilityOperation': + if (this.stateValue.phase !== 'running') return [this.output({ type: 'advanceIgnoredWhileStopped' })]; + this.recordCompatibilityTrace(input.operation); + return [this.output({ type: 'compatibilityOperationRecorded', operation: input.operation })]; + } + } + + nextRipJitterMilliseconds(): number { + return this.random.nextRipJitterMilliseconds(); + } + + allocateFrameIdentity(): number { + return this.stateValue.nextFrameIdentity++; + } + + allocatePacketIdentity(): number { + return this.stateValue.nextPacketIdentity++; + } + + recordTrace(input: TraceInput): void { + const state = this.stateValue; + const trace: TraceEvent = { + id: state.nextTraceIdentity, + timeMilliseconds: state.currentTimeMilliseconds, + ...(input.frameIdentity === undefined ? {} : { frameIdentity: input.frameIdentity }), + ...(input.packetIdentity === undefined ? {} : { packetIdentity: input.packetIdentity }), + nodeId: input.nodeId, + ...(input.interfaceId === undefined ? {} : { interfaceId: input.interfaceId }), + direction: input.direction, + layer: input.layer, + operation: input.operation, + beforeHeaders: input.beforeHeaders ?? [], + afterHeaders: input.afterHeaders ?? [], + ...(input.detail === undefined ? {} : { detail: input.detail }), + }; + state.nextTraceIdentity += 1; + if (state.packetTraces.length >= this.packetTraceRetentionPolicy.maximumEventCount) { + const evictionCount = Math.min(this.packetTraceRetentionPolicy.evictionBatchSize, state.packetTraces.length); + state.packetTraces.splice(0, evictionCount); + state.discardedPacketTraceCount += evictionCount; + } + state.packetTraces.push(trace); + } + + static run(scenario: RuntimeScenario, snapshot: TopologySnapshot = EMPTY_TOPOLOGY_SNAPSHOT): RuntimeState { + const engine = new NetworkRuntimeEngine(scenario.seed); + engine.handle({ type: 'start', snapshot, seed: scenario.seed, initialTimeMilliseconds: 0 }); + for (const scheduled of scenario.scheduledEvents) { + engine.handle({ type: 'schedule', deadlineMilliseconds: scheduled.deadlineMilliseconds, kind: scheduled.kind }); + } + engine.handle({ type: 'advance', toMilliseconds: scenario.advanceToMilliseconds }); + return engine.state; + } + + private schedule(deadlineMilliseconds: number, kind: ScheduledEventKind): ScheduledEvent { + const state = this.stateValue; + const event: ScheduledEvent = { + id: state.nextEventSequenceNumber, + deadlineMilliseconds, + sequenceNumber: state.nextEventSequenceNumber, + kind, + }; + state.nextEventSequenceNumber += 1; + state.pendingEvents.push(event); + return event; + } + + private advance(targetTimeMilliseconds: number): RuntimeOutput[] { + const state = this.stateValue; + if (state.phase !== 'running') return [this.output({ type: 'advanceIgnoredWhileStopped' })]; + if (targetTimeMilliseconds < state.currentTimeMilliseconds) { + return [this.output({ type: 'advanceRejectedPastTime' })]; + } + + const startTime = state.currentTimeMilliseconds; + const outputs: RuntimeOutput[] = []; + const wasProcessingScheduledEvents = this.isProcessingScheduledEvents; + this.isProcessingScheduledEvents = true; + try { + for (;;) { + const nextEventIndex = this.nextDueEventIndex(targetTimeMilliseconds); + if (nextEventIndex === undefined) break; + const [event] = this.stateValue.pendingEvents.splice(nextEventIndex, 1) as [ScheduledEvent]; + this.stateValue.currentTimeMilliseconds = event.deadlineMilliseconds; + this.ageAllSwitchSatEntries(); + this.expireRipRoutes(); + this.processScheduledRuntimeEvent(event.kind); + outputs.push(this.output({ type: 'fired', event })); + } + + this.stateValue.currentTimeMilliseconds = targetTimeMilliseconds; + this.ageAllSwitchSatEntries(); + this.expireRipRoutes(); + outputs.push( + this.output({ type: 'advanced', fromMilliseconds: startTime, toMilliseconds: targetTimeMilliseconds }), + ); + return outputs; + } finally { + this.isProcessingScheduledEvents = wasProcessingScheduledEvents; + } + } + + private nextDueEventIndex(targetTimeMilliseconds: number): number | undefined { + let best: number | undefined; + const events = this.stateValue.pendingEvents; + for (let index = 0; index < events.length; index += 1) { + const candidate = events[index]!; + if (candidate.deadlineMilliseconds > targetTimeMilliseconds) continue; + if (best === undefined) { + best = index; + continue; + } + const current = events[best]!; + if ( + candidate.deadlineMilliseconds < current.deadlineMilliseconds || + (candidate.deadlineMilliseconds === current.deadlineMilliseconds && + candidate.sequenceNumber < current.sequenceNumber) + ) { + best = index; + } + } + return best; + } + + private recordCompatibilityTrace(operation: CompatibilityOperation): void { + this.recordTrace({ + nodeId: operation.nodeId, + interfaceId: operation.interfaceId, + direction: 'local', + layer: 'application', + operation: 'compatibilityAdapter', + afterHeaders: [{ name: 'kind', value: operation.kind }], + detail: operation.detail, + }); + } + + private output(kind: RuntimeOutputKind): RuntimeOutput { + return { timeMilliseconds: this.stateValue.currentTimeMilliseconds, kind }; + } + + private processScheduledRuntimeEvent(kind: ScheduledEventKind): void { + switch (kind.kind) { + case 'ethernetLinkDelivery': + if (this.dropForGlobalPacketLoss(kind.frame, kind.targetNodeId, kind.targetPortId, 'inbound', 'physical')) { + return; + } + this.receiveEthernetFrame(kind.frame, kind.targetNodeId, kind.targetPortId); + return; + case 'parityMarker': + return; + case 'ripBeacon': + throw new NotPortedError('RIP beacons'); + case 'dhcpClientStart': + case 'dhcpTimeout': + throw new NotPortedError('DHCP client'); + case 'tcpTimeout': + throw new NotPortedError('TCP timeouts'); + case 'remoteLinkDelivery': + case 'lanRemoteLinkTransmission': + throw new NotPortedError('remote links'); + case 'natExpirySweep': + throw new NotPortedError('gateway NAT'); + } + } + + private dropForGlobalPacketLoss( + frame: EthernetFrame, + nodeId: Id, + interfaceId: Id | undefined, + direction: TraceDirection, + layer: TraceLayer, + ): boolean { + if (!this.stateValue.globalPacketLossEnabled) return false; + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId, + interfaceId, + direction, + layer, + operation: 'dropped', + afterHeaders: ethernetHeaders(frame), + detail: 'global packet-loss simulation', + }); + return true; + } + + // ── Later slices hook in here ──────────────────────────────────────────── + + private initializeRipState(): void { + // RIP (F2): builds the per-router tables and schedules the first beacons. + for (const node of this.stateValue.topologySnapshot.nodes) { + if (this.isRipEnabledRouter(node.id)) throw new NotPortedError('RIP'); + } + } + + private initializeDhcpState(): void { + // DHCP (F2): no DHCP configuration exists in the snapshot yet. + } + + private initializeNatState(): void { + // Gateway NAT (F2): schedules the expiry sweep when a gateway exists. + if (this.stateValue.topologySnapshot.nodes.some((node) => node.kind === 'gateway')) { + throw new NotPortedError('gateway NAT'); + } + } + + private expireRipRoutes(): void { + // RIP (F2): marks timed-out learned routes with metric infinity. + } + + private isRipEnabledRouter(nodeId: Id): boolean { + return ( + this.nodeSnapshot(nodeId)?.kind === 'router' && + this.stateValue.topologySnapshot.ripEnabledByNodeId.get(nodeId) === true + ); + } + + // ── Interfaces and addresses ───────────────────────────────────────────── + + networkInterfaces(nodeId: Id): NetworkInterface[] { + const snapshot = this.stateValue.topologySnapshot; + const node = snapshot.nodes.find((candidate) => candidate.id === nodeId); + if (node === undefined) return []; + const deviceConfiguration = snapshot.deviceConfigurations.get(nodeId); + const result: NetworkInterface[] = []; + node.ports.forEach((port, index) => { + let configuration: InterfaceConfiguration | undefined; + switch (node.kind) { + case 'pc': + case 'notebook': + if (index !== 0 || deviceConfiguration === undefined) return; + configuration = { ipAddress: deviceConfiguration.ipAddress, subnetMask: deviceConfiguration.subnetMask }; + break; + case 'router': + case 'gateway': + configuration = snapshot.interfaceConfigurations.get(interfaceKey(nodeId, port.id)); + break; + case 'networkSwitch': + case 'remoteLink': + case 'unsupported': + configuration = undefined; + break; + } + if (configuration === undefined) return; + result.push({ + nodeId, + portId: port.id, + index, + ipAddress: configuration.ipAddress, + subnetMask: configuration.subnetMask, + defaultGateway: deviceConfiguration?.defaultGateway ?? '', + macAddress: port.macAddress ?? stableMacAddress(port.id), + }); + }); + return result; + } + + clearArpCache(nodeId?: Id): void { + if (nodeId === undefined) { + this.stateValue.arpCachesByNodeId.clear(); + } else { + this.stateValue.arpCachesByNodeId.set(nodeId, new Map()); + } + } + + /** + * The MAC address for `targetIPAddress`, asking by ARP broadcast when it is + * not cached. Blocks like Java: the frames travel (virtual time passes) + * before the call returns. + */ + resolveMacAddress( + nodeId: Id, + targetIPAddress: string, + options: { preferredInterfaceId?: Id | undefined; maxRetries?: number; selectInterfaceByAddress?: boolean } = {}, + ): string | undefined { + const maxRetries = options.maxRetries ?? 2; + const selectInterfaceByAddress = options.selectInterfaceByAddress ?? true; + const interfaces = this.networkInterfaces(nodeId); + const primaryInterface = interfaces[0]; + if (primaryInterface === undefined) return undefined; + if (targetIPAddress === LOCALHOST_IP_ADDRESS) return primaryInterface.macAddress; + const localInterface = interfaces.find((candidate) => candidate.ipAddress === targetIPAddress); + if (localInterface !== undefined) return localInterface.macAddress; + const cached = this.stateValue.arpCachesByNodeId.get(nodeId)?.get(targetIPAddress); + if (cached !== undefined) return cached.macAddress; + + let selectedInterface: NetworkInterface | undefined; + if (options.preferredInterfaceId !== undefined) { + selectedInterface = interfaces.find((candidate) => candidate.portId === options.preferredInterfaceId); + } else if (selectInterfaceByAddress) { + selectedInterface = bestInterface(targetIPAddress, interfaces); + } else { + selectedInterface = interfaces[0]; + } + if (selectedInterface === undefined) return undefined; + + for (let attempt = 0; attempt < Math.max(0, maxRetries); attempt += 1) { + const request: ArpPacket = { + operation: 'request', + senderMacAddress: selectedInterface.macAddress, + senderIPAddress: selectedInterface.ipAddress, + targetMacAddress: UNSPECIFIED_MAC_ADDRESS, + targetIPAddress, + }; + const frame: EthernetFrame = { + identity: this.allocateFrameIdentity(), + sourceMacAddress: selectedInterface.macAddress, + destinationMacAddress: ETHERNET_BROADCAST_MAC_ADDRESS, + payload: { kind: 'arp', packet: request }, + }; + this.recordTrace({ + frameIdentity: frame.identity, + nodeId, + interfaceId: selectedInterface.portId, + direction: 'outbound', + layer: 'dataLink', + operation: 'created', + afterHeaders: ethernetHeaders(frame), + detail: `ARP request for ${targetIPAddress}`, + }); + this.sendEthernetFrame(nodeId, selectedInterface.portId, frame); + this.advanceRemoteLinkEventsUntilArpCacheResolves(nodeId, targetIPAddress); + const resolved = this.stateValue.arpCachesByNodeId.get(nodeId)?.get(targetIPAddress); + if (resolved !== undefined) return resolved.macAddress; + } + return undefined; + } + + private advanceRemoteLinkEventsUntilArpCacheResolves(nodeId: Id, targetIPAddress: string): void { + if (this.isProcessingScheduledEvents) return; + this.advancePendingRemoteLinkEvents( + () => this.stateValue.arpCachesByNodeId.get(nodeId)?.get(targetIPAddress) !== undefined, + ); + } + + private advanceRemoteLinkEventsUntilIcmpObservation( + nodeId: Id, + observationCount: number, + identifier: number, + sequenceNumber: number, + ): void { + if (this.isProcessingScheduledEvents) return; + this.advancePendingRemoteLinkEvents(() => { + const newObservations = (this.stateValue.icmpObservationsByNodeId.get(nodeId) ?? []).slice(observationCount); + return newObservations.some( + (observation) => + observation.message.identifier === identifier && observation.message.sequenceNumber === sequenceNumber, + ); + }); + } + + private advancePendingRemoteLinkEvents(condition: () => boolean): void { + const maximumEvents = 1_024; + let processedEventCount = 0; + while (!condition() && processedEventCount < maximumEvents) { + const nextDeadline = this.earliestDeadline(isRemoteLinkWaitEvent); + if (nextDeadline === undefined) return; + this.advance(nextDeadline); + processedEventCount += 1; + } + } + + private earliestDeadline(filter: (kind: ScheduledEventKind) => boolean): number | undefined { + let earliest: number | undefined; + for (const event of this.stateValue.pendingEvents) { + if (!filter(event.kind)) continue; + if (earliest === undefined || event.deadlineMilliseconds < earliest) earliest = event.deadlineMilliseconds; + } + return earliest; + } + + // ── Ethernet ───────────────────────────────────────────────────────────── + + sendEthernetFrame(fromNodeId: Id, outgoingPortId: Id, frame: EthernetFrame): void { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId: fromNodeId, + interfaceId: outgoingPortId, + direction: 'outbound', + layer: 'physical', + operation: 'sent', + afterHeaders: ethernetHeaders(frame), + }); + const endpoint = this.attachedEndpoint(fromNodeId, outgoingPortId); + if (endpoint === undefined) return; + const latencyMilliseconds = this.runtimeSpeed.linkTransmissionDelayMilliseconds; + const deadlineMilliseconds = this.stateValue.currentTimeMilliseconds + latencyMilliseconds; + if (!Number.isSafeInteger(deadlineMilliseconds)) { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId: fromNodeId, + interfaceId: outgoingPortId, + direction: 'outbound', + layer: 'physical', + operation: 'dropped', + afterHeaders: ethernetHeaders(frame), + detail: 'link transmission deadline overflow', + }); + return; + } + + this.schedule(deadlineMilliseconds, { + kind: 'ethernetLinkDelivery', + sourceNodeId: fromNodeId, + targetNodeId: endpoint.nodeId, + targetPortId: endpoint.portId, + latencyMilliseconds, + frame, + }); + this.drainPendingNetworkDeliveryEventsIfNeeded(); + } + + private drainPendingNetworkDeliveryEventsIfNeeded(): void { + if (this.isProcessingScheduledEvents) return; + const maximumEvents = 16_384; + let processedEventCount = 0; + while (processedEventCount < maximumEvents) { + const nextDeadline = this.earliestDeadline(isNetworkDeliveryEvent); + if (nextDeadline === undefined) return; + this.advance(nextDeadline); + processedEventCount += 1; + } + } + + private attachedEndpoint(nodeId: Id, portId: Id): { nodeId: Id; portId: Id } | undefined { + for (const link of this.stateValue.topologySnapshot.links) { + if (link.sourceNodeId === nodeId && link.sourcePortId === portId) { + return { nodeId: link.targetNodeId, portId: link.targetPortId }; + } + if (link.targetNodeId === nodeId && link.targetPortId === portId) { + return { nodeId: link.sourceNodeId, portId: link.sourcePortId }; + } + } + return undefined; + } + + private nodeSnapshot(nodeId: Id): NodeSnapshot | undefined { + return this.stateValue.topologySnapshot.nodes.find((node) => node.id === nodeId); + } + + private receiveEthernetFrame(frame: EthernetFrame, nodeId: Id, incomingPortId: Id): void { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId, + interfaceId: incomingPortId, + direction: 'inbound', + layer: 'physical', + operation: 'received', + beforeHeaders: ethernetHeaders(frame), + }); + const node = this.nodeSnapshot(nodeId); + if (node === undefined) return; + if (node.kind === 'networkSwitch') { + this.forwardFrameThroughSwitch(frame, node, incomingPortId); + return; + } + if (node.kind === 'remoteLink') throw new NotPortedError('remote links'); + + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId, + interfaceId: incomingPortId, + direction: 'inbound', + layer: 'dataLink', + operation: 'received', + beforeHeaders: ethernetHeaders(frame), + }); + const networkInterface = this.networkInterfaces(nodeId).find((candidate) => candidate.portId === incomingPortId); + if (networkInterface === undefined) return; + const destination = frame.destinationMacAddress.toUpperCase(); + if (destination !== networkInterface.macAddress.toUpperCase() && destination !== ETHERNET_BROADCAST_MAC_ADDRESS) { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId, + interfaceId: incomingPortId, + direction: 'inbound', + layer: 'dataLink', + operation: 'dropped', + beforeHeaders: ethernetHeaders(frame), + detail: 'destination MAC does not match interface', + }); + return; + } + switch (frame.payload.kind) { + case 'arp': + this.receiveArpPacket(frame.payload.packet, frame.identity, nodeId, networkInterface); + return; + case 'ipv4': + this.receiveIPv4Packet(frame.payload.packet, frame.identity, nodeId, networkInterface); + return; + } + } + + // ── Switch ─────────────────────────────────────────────────────────────── + + private forwardFrameThroughSwitch(frame: EthernetFrame, switchNode: NodeSnapshot, incomingPortId: Id): void { + const state = this.stateValue; + const seen = state.switchSeenFrameIdentitiesByNodeId.get(switchNode.id); + if (seen?.has(frame.identity) === true) { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId: switchNode.id, + interfaceId: incomingPortId, + direction: 'inbound', + layer: 'dataLink', + operation: 'dropped', + beforeHeaders: ethernetHeaders(frame), + detail: 'switch cycle suppression', + }); + return; + } + getOrCreate(state.switchSeenFrameIdentitiesByNodeId, switchNode.id, () => new Set()).add(frame.identity); + this.ageSwitchSatEntries(switchNode.id); + + const source = frame.sourceMacAddress.toUpperCase(); + getOrCreate(state.switchForwardingTablesByNodeId, switchNode.id, () => new Map()).set(source, incomingPortId); + getOrCreate(state.switchForwardingUpdatedAtMillisecondsByNodeId, switchNode.id, () => new Map()).set( + source, + state.currentTimeMilliseconds, + ); + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId: switchNode.id, + interfaceId: incomingPortId, + direction: 'inbound', + layer: 'dataLink', + operation: 'accepted', + beforeHeaders: ethernetHeaders(frame), + detail: 'switch learned source MAC', + }); + + const destination = frame.destinationMacAddress.toUpperCase(); + const connectedPorts = switchNode.ports + .filter((port) => port.id !== incomingPortId && this.attachedEndpoint(switchNode.id, port.id) !== undefined) + .map((port) => port.id); + + let outgoingPorts: Id[]; + let forwardingDetail: string; + const learnedPort = state.switchForwardingTablesByNodeId.get(switchNode.id)?.get(destination); + if (destination === ETHERNET_BROADCAST_MAC_ADDRESS) { + outgoingPorts = connectedPorts; + forwardingDetail = 'switch broadcast flooding'; + } else if (learnedPort !== undefined) { + if (learnedPort === incomingPortId) { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId: switchNode.id, + interfaceId: incomingPortId, + direction: 'inbound', + layer: 'dataLink', + operation: 'dropped', + beforeHeaders: ethernetHeaders(frame), + detail: 'switch filtered destination on incoming port', + }); + return; + } + if (this.attachedEndpoint(switchNode.id, learnedPort) !== undefined) { + outgoingPorts = [learnedPort]; + forwardingDetail = 'switch learned unicast forwarding'; + } else { + state.switchForwardingTablesByNodeId.get(switchNode.id)?.delete(destination); + state.switchForwardingUpdatedAtMillisecondsByNodeId.get(switchNode.id)?.delete(destination); + outgoingPorts = connectedPorts; + forwardingDetail = 'switch unknown unicast flooding'; + } + } else { + outgoingPorts = connectedPorts; + forwardingDetail = 'switch unknown unicast flooding'; + } + + for (const portId of outgoingPorts) { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packetIdentityInFrame(frame), + nodeId: switchNode.id, + interfaceId: portId, + direction: 'outbound', + layer: 'dataLink', + operation: 'forwarded', + afterHeaders: ethernetHeaders(frame), + detail: forwardingDetail, + }); + this.sendEthernetFrame(switchNode.id, portId, frame); + } + } + + clearSwitchSat(nodeId: Id): void { + this.stateValue.switchForwardingTablesByNodeId.delete(nodeId); + this.stateValue.switchForwardingUpdatedAtMillisecondsByNodeId.delete(nodeId); + } + + /** The switch's source address table (Java "SAT"), sorted by MAC address. */ + switchSatEntries(nodeId: Id): SwitchSatEntry[] { + const node = this.nodeSnapshot(nodeId); + if (node === undefined || node.kind !== 'networkSwitch') return []; + const labelsByPortId = new Map(node.ports.map((port) => [port.id, port.label])); + const updatedAtByMac = this.stateValue.switchForwardingUpdatedAtMillisecondsByNodeId.get(nodeId) ?? new Map(); + const table = this.stateValue.switchForwardingTablesByNodeId.get(nodeId) ?? new Map(); + return [...table] + .map(([macAddress, portId]) => ({ + macAddress, + portId, + portLabel: labelsByPortId.get(portId) ?? '?', + updatedAtMilliseconds: updatedAtByMac.get(macAddress) ?? 0, + })) + .sort((lhs, rhs) => + lhs.macAddress === rhs.macAddress + ? compareIds(lhs.portId, rhs.portId) + : lhs.macAddress < rhs.macAddress + ? -1 + : 1, + ); + } + + private ageAllSwitchSatEntries(): void { + for (const nodeId of [...this.stateValue.switchForwardingTablesByNodeId.keys()]) { + this.ageSwitchSatEntries(nodeId); + } + } + + private ageSwitchSatEntries(nodeId: Id): void { + const state = this.stateValue; + const retention = + state.topologySnapshot.switchConfigurationsByNodeId.get(nodeId)?.retentionTimeMilliseconds ?? + DEFAULT_SWITCH_RETENTION_MILLISECONDS; + const updatedAtByMac = state.switchForwardingUpdatedAtMillisecondsByNodeId.get(nodeId); + if (updatedAtByMac === undefined) return; + const expired: string[] = []; + for (const [macAddress, updatedAt] of updatedAtByMac) { + if (state.currentTimeMilliseconds >= updatedAt && state.currentTimeMilliseconds - updatedAt >= retention) { + expired.push(macAddress); + } + } + if (expired.length === 0) return; + for (const macAddress of expired) { + state.switchForwardingTablesByNodeId.get(nodeId)?.delete(macAddress); + state.switchForwardingUpdatedAtMillisecondsByNodeId.get(nodeId)?.delete(macAddress); + } + if (state.switchForwardingTablesByNodeId.get(nodeId)?.size === 0) { + state.switchForwardingTablesByNodeId.delete(nodeId); + } + if (state.switchForwardingUpdatedAtMillisecondsByNodeId.get(nodeId)?.size === 0) { + state.switchForwardingUpdatedAtMillisecondsByNodeId.delete(nodeId); + } + } + + // ── ARP ────────────────────────────────────────────────────────────────── + + private receiveArpPacket( + packet: ArpPacket, + frameIdentity: number, + nodeId: Id, + networkInterface: NetworkInterface, + ): void { + if (packet.senderIPAddress !== UNSPECIFIED_IP_ADDRESS) { + getOrCreate(this.stateValue.arpCachesByNodeId, nodeId, () => new Map()).set(packet.senderIPAddress, { + ipAddress: packet.senderIPAddress, + macAddress: packet.senderMacAddress, + updatedAtMilliseconds: this.stateValue.currentTimeMilliseconds, + }); + this.flushIPv4TransmissionsAwaitingArp(nodeId, packet.senderIPAddress, packet.senderMacAddress); + } + this.recordTrace({ + frameIdentity, + nodeId, + interfaceId: networkInterface.portId, + direction: 'inbound', + layer: 'network', + operation: 'accepted', + beforeHeaders: arpHeaders(packet), + }); + if (packet.operation !== 'request' || packet.targetIPAddress !== networkInterface.ipAddress) return; + + const unspecifiedSender = packet.senderIPAddress === UNSPECIFIED_IP_ADDRESS; + const replyTargetIPAddress = unspecifiedSender ? LIMITED_BROADCAST_IP_ADDRESS : packet.senderIPAddress; + const replyTargetMacAddress = unspecifiedSender ? ETHERNET_BROADCAST_MAC_ADDRESS : packet.senderMacAddress; + const reply: ArpPacket = { + operation: 'reply', + senderMacAddress: networkInterface.macAddress, + senderIPAddress: networkInterface.ipAddress, + targetMacAddress: replyTargetMacAddress, + targetIPAddress: replyTargetIPAddress, + }; + const replyFrame: EthernetFrame = { + identity: this.allocateFrameIdentity(), + sourceMacAddress: networkInterface.macAddress, + destinationMacAddress: replyTargetMacAddress, + payload: { kind: 'arp', packet: reply }, + }; + this.recordTrace({ + frameIdentity: replyFrame.identity, + nodeId, + interfaceId: networkInterface.portId, + direction: 'outbound', + layer: 'dataLink', + operation: 'created', + afterHeaders: ethernetHeaders(replyFrame), + detail: `ARP reply for ${networkInterface.ipAddress}`, + }); + this.sendEthernetFrame(nodeId, networkInterface.portId, replyFrame); + } + + // ── IPv4 ───────────────────────────────────────────────────────────────── + + sendIPv4Packet(fromNodeId: Id, packet: IPv4Packet, preferredInterfaceId?: Id): IPv4DeliveryResult { + return this.sendIPv4PacketWithOptions(fromNodeId, packet, preferredInterfaceId, true, 'sent'); + } + + updateDeviceConfiguration(nodeId: Id, configuration: DeviceConfiguration): void { + const state = this.stateValue; + if (state.phase !== 'running' || !state.topologySnapshot.nodes.some((node) => node.id === nodeId)) return; + const deviceConfigurations = new Map(state.topologySnapshot.deviceConfigurations); + deviceConfigurations.set(nodeId, configuration); + state.topologySnapshot = withSnapshot(state.topologySnapshot, { deviceConfigurations }); + } + + /** Send one ICMP echo request and wait (virtually) for its answer. */ + sendIcmpEcho( + fromNodeId: Id, + targetIPAddress: string, + options: { timeToLive?: number; identifier?: number; sequenceNumber?: number; data?: Uint8Array } = {}, + ): IPv4DeliveryResult { + const timeToLive = options.timeToLive ?? 64; + const identifier = options.identifier ?? 1; + const sequenceNumber = options.sequenceNumber ?? 1; + const interfaces = this.networkInterfaces(fromNodeId); + const firstInterface = interfaces[0]; + if (firstInterface === undefined) return { type: 'dropped', packetIdentity: 0, nodeId: fromNodeId }; + const route = this.routeForPacket(fromNodeId, targetIPAddress); + let sourceInterface: NetworkInterface; + switch (route.type) { + case 'local': + sourceInterface = route.interface ?? firstInterface; + break; + case 'egress': + sourceInterface = route.interface; + break; + case 'broadcast': + case 'unavailable': + sourceInterface = firstInterface; + break; + } + const packet: IPv4Packet = { + identity: this.allocatePacketIdentity(), + senderIPAddress: sourceInterface.ipAddress, + receiverIPAddress: targetIPAddress, + timeToLive, + protocol: 'icmp', + payload: { + kind: 'icmp', + message: icmpMessage('echoRequest', { identifier, sequenceNumber, data: options.data ?? new Uint8Array() }), + }, + }; + this.recordTrace({ + packetIdentity: packet.identity, + nodeId: fromNodeId, + interfaceId: sourceInterface.portId, + direction: 'outbound', + layer: 'network', + operation: 'created', + afterHeaders: ipv4Headers(packet), + detail: 'ICMP echo request', + }); + const observationCount = this.stateValue.icmpObservationsByNodeId.get(fromNodeId)?.length ?? 0; + const result = this.sendIPv4Packet(fromNodeId, packet, sourceInterface.portId); + this.advanceRemoteLinkEventsUntilIcmpObservation(fromNodeId, observationCount, identifier, sequenceNumber); + const newObservations = (this.stateValue.icmpObservationsByNodeId.get(fromNodeId) ?? []).slice(observationCount); + const observation = newObservations.findLast( + (candidate) => candidate.message.identifier === identifier && candidate.message.sequenceNumber === sequenceNumber, + ); + if (observation !== undefined) { + switch (observation.message.kind) { + case 'echoReply': + return { type: 'delivered', packetIdentity: packet.identity, nodeId: observation.nodeId }; + case 'destinationNetworkUnreachable': + case 'destinationHostUnreachable': + case 'timeExceeded': + return { + type: 'icmpError', + packetIdentity: packet.identity, + nodeId: observation.nodeId, + kind: observation.message.kind, + }; + case 'echoRequest': + break; + } + } + return result; + } + + /** `traceroute`: echoes with TTL 1, 2, … until one is answered. */ + traceIcmpEcho( + fromNodeId: Id, + targetIPAddress: string, + options: { maximumTimeToLive?: number; identifier?: number } = {}, + ): IcmpObservation[] { + const maximumTimeToLive = options.maximumTimeToLive ?? 64; + const identifier = options.identifier ?? 1; + const observations: IcmpObservation[] = []; + for (let ttl = 1; ttl <= maximumTimeToLive; ttl += 1) { + const previousCount = this.stateValue.icmpObservationsByNodeId.get(fromNodeId)?.length ?? 0; + this.sendIcmpEcho(fromNodeId, targetIPAddress, { timeToLive: ttl, identifier, sequenceNumber: ttl }); + const newItems = (this.stateValue.icmpObservationsByNodeId.get(fromNodeId) ?? []).slice(previousCount); + const observation = newItems.at(-1); + if (observation === undefined) continue; + observations.push(observation); + if (observation.message.kind === 'echoReply') break; + } + return observations; + } + + /** The nodes a packet passed, in the order it first reached them. */ + tracedNodePath(packetIdentity: number): Id[] { + const result: Id[] = []; + for (const trace of this.stateValue.packetTraces) { + if (trace.packetIdentity !== packetIdentity || result.includes(trace.nodeId)) continue; + result.push(trace.nodeId); + } + return result; + } + + private sendIPv4PacketWithOptions( + fromNodeId: Id, + packet: IPv4Packet, + preferredInterfaceId: Id | undefined, + allowIcmpErrorGeneration: boolean, + operation: TraceOperation, + ): IPv4DeliveryResult { + const route = this.routeForPacket(fromNodeId, packet.receiverIPAddress, preferredInterfaceId); + switch (route.type) { + case 'local': { + const networkInterface = route.interface ?? this.networkInterfaces(fromNodeId)[0]; + if (networkInterface === undefined) return { type: 'dropped', packetIdentity: packet.identity, nodeId: fromNodeId }; + this.receiveIPv4Packet(packet, undefined, fromNodeId, networkInterface); + return { type: 'delivered', packetIdentity: packet.identity, nodeId: fromNodeId }; + } + + case 'broadcast': { + const interfaces = this.networkInterfaces(fromNodeId); + if (interfaces.length === 0) return { type: 'dropped', packetIdentity: packet.identity, nodeId: fromNodeId }; + const broadcastPacket: IPv4Packet = { ...packet, timeToLive: 1 }; + for (const networkInterface of interfaces) { + const frame: EthernetFrame = { + identity: this.allocateFrameIdentity(), + sourceMacAddress: networkInterface.macAddress, + destinationMacAddress: ETHERNET_BROADCAST_MAC_ADDRESS, + payload: { kind: 'ipv4', packet: broadcastPacket }, + }; + this.recordIPv4Send(broadcastPacket, frame, fromNodeId, networkInterface.portId, operation); + this.sendEthernetFrame(fromNodeId, networkInterface.portId, frame); + } + return { type: 'delivered', packetIdentity: packet.identity, nodeId: fromNodeId }; + } + + case 'egress': { + const destinationMacAddress = this.resolveMacAddress(fromNodeId, route.nextHop, { + preferredInterfaceId: route.interface.portId, + maxRetries: 2, + }); + if (destinationMacAddress === undefined) { + if (this.isProcessingScheduledEvents && this.hasConfiguredInterface(route.nextHop)) { + this.enqueueIPv4TransmissionAwaitingArp(fromNodeId, route.nextHop, packet, route.interface, operation); + return { type: 'delivered', packetIdentity: packet.identity, nodeId: fromNodeId }; + } + if (allowIcmpErrorGeneration) { + this.observeLocalIcmpError(fromNodeId, route.interface.portId, 'destinationHostUnreachable', packet); + return { + type: 'icmpError', + packetIdentity: packet.identity, + nodeId: fromNodeId, + kind: 'destinationHostUnreachable', + }; + } + return { type: 'dropped', packetIdentity: packet.identity, nodeId: fromNodeId }; + } + this.transmitIPv4Packet(fromNodeId, packet, route.interface, destinationMacAddress, operation); + return { type: 'delivered', packetIdentity: packet.identity, nodeId: fromNodeId }; + } + + case 'unavailable': + if (allowIcmpErrorGeneration) { + this.observeLocalIcmpError(fromNodeId, preferredInterfaceId, 'destinationNetworkUnreachable', packet); + return { + type: 'icmpError', + packetIdentity: packet.identity, + nodeId: fromNodeId, + kind: 'destinationNetworkUnreachable', + }; + } + return { type: 'dropped', packetIdentity: packet.identity, nodeId: fromNodeId }; + } + } + + private hasConfiguredInterface(ipAddress: string): boolean { + return this.stateValue.topologySnapshot.nodes.some((node) => + this.networkInterfaces(node.id).some((candidate) => candidate.ipAddress === ipAddress), + ); + } + + private enqueueIPv4TransmissionAwaitingArp( + fromNodeId: Id, + nextHop: string, + packet: IPv4Packet, + networkInterface: NetworkInterface, + operation: TraceOperation, + ): void { + const key = arpKey(fromNodeId, nextHop); + const transmission: PendingIPv4Transmission = { packet, interface: networkInterface, operation }; + const pending = this.pendingIPv4TransmissionsByArpKey.get(key); + if (pending?.some((candidate) => deepEqual(candidate, transmission)) === true) return; + getOrCreate(this.pendingIPv4TransmissionsByArpKey, key, () => []).push(transmission); + this.recordTrace({ + packetIdentity: packet.identity, + nodeId: fromNodeId, + interfaceId: networkInterface.portId, + direction: 'outbound', + layer: 'network', + operation: 'created', + beforeHeaders: ipv4Headers(packet), + detail: `waiting for ARP resolution of ${nextHop}`, + }); + } + + private flushIPv4TransmissionsAwaitingArp(nodeId: Id, ipAddress: string, macAddress: string): void { + const key = arpKey(nodeId, ipAddress); + const transmissions = this.pendingIPv4TransmissionsByArpKey.get(key); + if (transmissions === undefined) return; + this.pendingIPv4TransmissionsByArpKey.delete(key); + for (const transmission of transmissions) { + this.transmitIPv4Packet(nodeId, transmission.packet, transmission.interface, macAddress, transmission.operation); + } + } + + private transmitIPv4Packet( + fromNodeId: Id, + packet: IPv4Packet, + networkInterface: NetworkInterface, + destinationMacAddress: string, + operation: TraceOperation, + ): void { + const frame: EthernetFrame = { + identity: this.allocateFrameIdentity(), + sourceMacAddress: networkInterface.macAddress, + destinationMacAddress, + payload: { kind: 'ipv4', packet }, + }; + this.recordIPv4Send(packet, frame, fromNodeId, networkInterface.portId, operation); + this.sendEthernetFrame(fromNodeId, networkInterface.portId, frame); + } + + private receiveIPv4Packet( + packet: IPv4Packet, + frameIdentity: number | undefined, + nodeId: Id, + networkInterface: NetworkInterface, + ): void { + this.recordTrace({ + frameIdentity, + packetIdentity: packet.identity, + nodeId, + interfaceId: networkInterface.portId, + direction: 'inbound', + layer: 'network', + operation: 'received', + beforeHeaders: ipv4Headers(packet), + }); + const node = this.nodeSnapshot(nodeId); + if (node === undefined) return; + + // Swift: the gateway branch (WAN/LAN, firewall, NAT rewrite) comes here. + if (node.kind === 'gateway') throw new NotPortedError('gateway NAT'); + if (node.kind === 'router') { + const decision = this.evaluateFirewall(packet, nodeId, networkInterface.portId, frameIdentity); + if (!decision.accepted) return; + } + const packetForProcessing = packet; + + const localAddresses = new Set(this.networkInterfaces(nodeId).map((candidate) => candidate.ipAddress)); + if ( + localAddresses.has(packetForProcessing.receiverIPAddress) || + packetForProcessing.receiverIPAddress === LIMITED_BROADCAST_IP_ADDRESS + ) { + if ( + isPcClassEndpoint(node.kind) && + this.stateValue.topologySnapshot.firewallConfigurationsByNodeId.has(nodeId) + ) { + const decision = this.evaluateFirewall(packetForProcessing, nodeId, networkInterface.portId, frameIdentity); + if (!decision.accepted) return; + } + this.deliverIPv4Locally(packetForProcessing, nodeId, networkInterface); + return; + } + if (node.kind !== 'router') { + this.recordTrace({ + frameIdentity, + packetIdentity: packetForProcessing.identity, + nodeId, + interfaceId: networkInterface.portId, + direction: 'inbound', + layer: 'network', + operation: 'dropped', + beforeHeaders: ipv4Headers(packetForProcessing), + detail: 'IPv4 forwarding disabled', + }); + return; + } + if (packetForProcessing.timeToLive <= 1) { + this.emitIcmpError(nodeId, networkInterface, 'timeExceeded', packet); + return; + } + + const forwarded = forwardingClone(packetForProcessing); + this.recordTrace({ + frameIdentity, + packetIdentity: forwarded.identity, + nodeId, + interfaceId: networkInterface.portId, + direction: 'outbound', + layer: 'network', + operation: 'forwarded', + beforeHeaders: ipv4Headers(packetForProcessing), + afterHeaders: ipv4Headers(forwarded), + detail: 'TTL decremented', + }); + const result = this.sendIPv4PacketWithOptions(nodeId, forwarded, undefined, false, 'forwarded'); + if (result.type === 'dropped') { + const route = this.routeForPacket(nodeId, packetForProcessing.receiverIPAddress); + this.emitIcmpError( + nodeId, + networkInterface, + route.type === 'unavailable' ? 'destinationNetworkUnreachable' : 'destinationHostUnreachable', + packet, + ); + } + } + + private deliverIPv4Locally(packet: IPv4Packet, nodeId: Id, networkInterface: NetworkInterface): void { + const payload = packet.payload; + switch (payload.kind) { + case 'icmp': { + const message = payload.message; + switch (message.kind) { + case 'echoRequest': { + if (packet.receiverIPAddress === LIMITED_BROADCAST_IP_ADDRESS && packet.timeToLive !== 1) return; + const reply: IPv4Packet = { + identity: this.allocatePacketIdentity(), + senderIPAddress: networkInterface.ipAddress, + receiverIPAddress: packet.senderIPAddress, + timeToLive: 64, + protocol: 'icmp', + payload: { + kind: 'icmp', + message: icmpMessage('echoReply', { + identifier: message.identifier, + sequenceNumber: message.sequenceNumber, + data: message.data, + }), + }, + }; + this.recordTrace({ + packetIdentity: reply.identity, + nodeId, + interfaceId: networkInterface.portId, + direction: 'outbound', + layer: 'network', + operation: 'created', + afterHeaders: ipv4Headers(reply), + detail: 'ICMP echo reply', + }); + this.sendIPv4PacketWithOptions(nodeId, reply, undefined, false, 'sent'); + return; + } + case 'echoReply': + case 'destinationNetworkUnreachable': + case 'destinationHostUnreachable': + case 'timeExceeded': + getOrCreate(this.stateValue.icmpObservationsByNodeId, nodeId, () => []).push({ + nodeId, + interfaceId: networkInterface.portId, + packet, + message, + }); + this.recordTrace({ + packetIdentity: packet.identity, + nodeId, + interfaceId: networkInterface.portId, + direction: 'local', + layer: 'transport', + operation: 'accepted', + beforeHeaders: icmpHeaders(message), + detail: 'ICMP observation queued', + }); + return; + } + return; + } + case 'udp': + getOrCreate(this.stateValue.deliveredIPv4PacketsByNodeId, nodeId, () => []).push({ + nodeId, + interfaceId: networkInterface.portId, + packet, + }); + throw new NotPortedError('UDP delivery'); + case 'tcp': + getOrCreate(this.stateValue.deliveredIPv4PacketsByNodeId, nodeId, () => []).push({ + nodeId, + interfaceId: networkInterface.portId, + packet, + }); + throw new NotPortedError('TCP delivery'); + } + } + + private emitIcmpError( + fromNodeId: Id, + incomingInterface: NetworkInterface, + kind: IcmpMessageKind, + originalPacket: IPv4Packet, + ): void { + if ( + originalPacket.senderIPAddress === UNSPECIFIED_IP_ADDRESS || + originalPacket.senderIPAddress === LIMITED_BROADCAST_IP_ADDRESS + ) { + return; + } + const errorPacket: IPv4Packet = { + identity: this.allocatePacketIdentity(), + senderIPAddress: incomingInterface.ipAddress, + receiverIPAddress: originalPacket.senderIPAddress, + timeToLive: 64, + protocol: 'icmp', + payload: { + kind: 'icmp', + message: icmpMessage(kind, { + identifier: icmpIdentifier(originalPacket), + sequenceNumber: icmpSequenceNumber(originalPacket), + embeddedOriginalPacket: embeddedOriginal(originalPacket), + }), + }, + }; + this.recordTrace({ + packetIdentity: errorPacket.identity, + nodeId: fromNodeId, + interfaceId: incomingInterface.portId, + direction: 'outbound', + layer: 'network', + operation: 'created', + afterHeaders: ipv4Headers(errorPacket), + detail: `ICMP ${kind}`, + }); + this.sendIPv4PacketWithOptions(fromNodeId, errorPacket, undefined, false, 'sent'); + } + + private observeLocalIcmpError( + nodeId: Id, + interfaceId: Id | undefined, + kind: IcmpMessageKind, + originalPacket: IPv4Packet, + ): void { + const message = icmpMessage(kind, { + identifier: icmpIdentifier(originalPacket), + sequenceNumber: icmpSequenceNumber(originalPacket), + embeddedOriginalPacket: embeddedOriginal(originalPacket), + }); + const packet: IPv4Packet = { + identity: this.allocatePacketIdentity(), + senderIPAddress: this.networkInterfaces(nodeId)[0]?.ipAddress ?? UNSPECIFIED_IP_ADDRESS, + receiverIPAddress: originalPacket.senderIPAddress, + timeToLive: 64, + protocol: 'icmp', + payload: { kind: 'icmp', message }, + }; + getOrCreate(this.stateValue.icmpObservationsByNodeId, nodeId, () => []).push({ + nodeId, + ...(interfaceId === undefined ? {} : { interfaceId }), + packet, + message, + }); + this.recordTrace({ + packetIdentity: packet.identity, + nodeId, + interfaceId, + direction: 'local', + layer: 'network', + operation: 'created', + afterHeaders: ipv4Headers(packet), + detail: `ICMP ${kind}`, + }); + } + + // ── Routing ────────────────────────────────────────────────────────────── + + private routeForPacket(nodeId: Id, targetIPAddress: string, preferredInterfaceId?: Id): PacketRoute { + const interfaces = this.networkInterfaces(nodeId); + if (targetIPAddress === LIMITED_BROADCAST_IP_ADDRESS) return { type: 'broadcast' }; + if (targetIPAddress === LOCALHOST_IP_ADDRESS) return { type: 'local', interface: interfaces[0] }; + const local = interfaces.find((candidate) => candidate.ipAddress === targetIPAddress); + if (local !== undefined) return { type: 'local', interface: local }; + if (this.isRipEnabledRouter(nodeId)) throw new NotPortedError('RIP routing'); + if (preferredInterfaceId !== undefined) { + const preferred = interfaces.find((candidate) => candidate.portId === preferredInterfaceId); + if (preferred !== undefined && sameSubnet(preferred.ipAddress, targetIPAddress, preferred.subnetMask)) { + return { type: 'egress', interface: preferred, nextHop: targetIPAddress }; + } + } + + const snapshot = this.stateValue.topologySnapshot; + const rows = routeTableRows( + interfaces.map((candidate) => ({ ipAddress: candidate.ipAddress, subnetMask: candidate.subnetMask })), + snapshot.manualRoutesByNodeId.get(nodeId) ?? [], + snapshot.deviceConfigurations.get(nodeId)?.defaultGateway, + ); + const target = parseIPv4(targetIPAddress); + if (target === undefined) return { type: 'unavailable' }; + let selected: RouteRow | undefined; + let selectedMask: number | undefined; + for (const row of rows) { + const destination = parseIPv4(row.destinationNetwork); + const mask = parseIPv4(row.subnetMask); + if (destination === undefined || mask === undefined || destination !== maskAddress(target, mask)) continue; + if (selectedMask !== undefined && mask <= selectedMask) continue; + selected = row; + selectedMask = mask; + } + if (selected === undefined) return { type: 'unavailable' }; + if (selected.interfaceIPAddress === LOCALHOST_IP_ADDRESS) { + return { + type: 'local', + interface: interfaces.find((candidate) => candidate.ipAddress === targetIPAddress) ?? interfaces[0], + }; + } + const egress = interfaces.find((candidate) => candidate.ipAddress === selected.interfaceIPAddress); + if (egress === undefined) return { type: 'unavailable' }; + const nextHop = sameSubnet(egress.ipAddress, targetIPAddress, egress.subnetMask) + ? targetIPAddress + : selected.nextHop; + return { type: 'egress', interface: egress, nextHop }; + } + + private recordIPv4Send( + packet: IPv4Packet, + frame: EthernetFrame, + nodeId: Id, + interfaceId: Id, + operation: TraceOperation, + ): void { + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packet.identity, + nodeId, + interfaceId, + direction: 'outbound', + layer: 'network', + operation, + afterHeaders: ipv4Headers(packet), + }); + this.recordTrace({ + frameIdentity: frame.identity, + packetIdentity: packet.identity, + nodeId, + interfaceId, + direction: 'outbound', + layer: 'dataLink', + operation: 'created', + afterHeaders: ethernetHeaders(frame), + }); + } + + // ── Firewall ───────────────────────────────────────────────────────────── + + setFirewallConfiguration(nodeId: Id, configuration: FirewallConfiguration): void { + const configurations = new Map(this.stateValue.topologySnapshot.firewallConfigurationsByNodeId); + configurations.set(nodeId, configuration); + this.stateValue.topologySnapshot = withSnapshot(this.stateValue.topologySnapshot, { + firewallConfigurationsByNodeId: configurations, + }); + } + + /** + * Java Firewall: inactive accepts; ICMP obeys only the general setting; + * TCP (optionally only opening SYNs) and UDP go through the ordered rules, + * first match wins; otherwise the default policy. Every decision is + * recorded, including "firewall inactive". + */ + evaluateFirewall(packet: IPv4Packet, nodeId: Id, incomingInterfaceId?: Id, frameIdentity?: number): FirewallDecision { + const configuration = + this.stateValue.topologySnapshot.firewallConfigurationsByNodeId.get(nodeId) ?? firewallConfiguration(); + const decide = (accepted: boolean, ruleIndex: number | undefined, detail: string): FirewallDecision => + this.recordFirewallDecision(packet, frameIdentity, nodeId, incomingInterfaceId, accepted, ruleIndex, detail); + + if (!configuration.isActive) return decide(true, undefined, 'firewall inactive'); + + if (packet.protocol === 'icmp') { + return decide( + !configuration.dropIcmp, + undefined, + configuration.dropIcmp ? 'ICMP blocked by general setting' : 'ICMP bypasses ordered rules', + ); + } + + const payload = packet.payload; + switch (payload.kind) { + case 'tcp': { + const flags = payload.segment.flags; + const isOpeningSyn = (flags & TCP_FLAG.synchronize) !== 0 && (flags & TCP_FLAG.acknowledgement) === 0; + if (configuration.filterSynSegmentsOnly && !isOpeningSyn) { + return decide(true, undefined, 'established TCP traffic bypasses SYN-only filtering'); + } + for (const [index, rule] of configuration.rules.entries()) { + if (!firewallProtocolMatches(packet.protocol, rule)) continue; + if ( + !this.firewallEndpointsMatch( + packet.senderIPAddress, + packet.receiverIPAddress, + payload.segment.destinationPort, + rule, + nodeId, + ) + ) { + continue; + } + return decide(rule.action === 'accept', index, `TCP matched rule #${index + 1}`); + } + break; + } + case 'udp': { + if (!configuration.filterUdp) return decide(true, undefined, 'UDP filtering disabled'); + const datagram = payload.datagram; + for (const [index, rule] of configuration.rules.entries()) { + if (!firewallProtocolMatches(packet.protocol, rule)) continue; + const requestMatches = this.firewallEndpointsMatch( + packet.senderIPAddress, + packet.receiverIPAddress, + datagram.destinationPort, + rule, + nodeId, + ); + const responseMatches = + rule.port !== ALL_PORTS && + this.firewallEndpointsMatch( + packet.receiverIPAddress, + packet.senderIPAddress, + datagram.sourcePort, + rule, + nodeId, + ); + if (!requestMatches && !responseMatches) continue; + return decide(rule.action === 'accept', index, `UDP matched rule #${index + 1}`); + } + break; + } + case 'icmp': + break; + } + + return decide(configuration.defaultPolicy === 'accept', undefined, 'firewall default policy'); + } + + private recordFirewallDecision( + packet: IPv4Packet, + frameIdentity: number | undefined, + nodeId: Id, + interfaceId: Id | undefined, + accepted: boolean, + ruleIndex: number | undefined, + detail: string, + ): FirewallDecision { + const decision: FirewallDecision = { + packetIdentity: packet.identity, + nodeId, + accepted, + ...(ruleIndex === undefined ? {} : { ruleIndex }), + }; + this.stateValue.firewallDecisions.push(decision); + this.recordTrace({ + frameIdentity, + packetIdentity: packet.identity, + nodeId, + interfaceId, + direction: 'inbound', + layer: 'network', + operation: accepted ? 'accepted' : 'dropped', + beforeHeaders: ipv4Headers(packet), + detail, + }); + return decision; + } + + private firewallEndpointsMatch( + sourceIPAddress: string, + destinationIPAddress: string, + port: number, + rule: FirewallRule, + nodeId: Id, + ): boolean { + return ( + this.firewallSourceMatches(sourceIPAddress, rule, nodeId) && + firewallAddressMatches(destinationIPAddress, rule.destinationIPAddress, rule.destinationSubnetMask) && + (rule.port === ALL_PORTS || rule.port === port) + ); + } + + private firewallSourceMatches(sourceIPAddress: string, rule: FirewallRule, nodeId: Id): boolean { + if (rule.sourceIPAddress.length === 0) return true; + if (rule.sourceIPAddress === DIRECTLY_CONNECTED_SOURCE_MARKER) { + return this.networkInterfaces(nodeId).some((candidate) => + sameSubnet(sourceIPAddress, candidate.ipAddress, candidate.subnetMask), + ); + } + return firewallAddressMatches(sourceIPAddress, rule.sourceIPAddress, rule.sourceSubnetMask); + } + + /** Replace the manual routes of a router (or gateway) while the simulation runs. */ + replaceManualRoutes(nodeId: Id, routes: readonly ManualRoute[]): boolean { + const state = this.stateValue; + const node = state.topologySnapshot.nodes.find((candidate) => candidate.id === nodeId); + if (state.phase !== 'running' || node === undefined || (node.kind !== 'router' && node.kind !== 'gateway')) { + return false; + } + const routesByNodeId = new Map(state.topologySnapshot.manualRoutesByNodeId); + if (routes.length === 0) { + routesByNodeId.delete(nodeId); + } else { + routesByNodeId.set(nodeId, [...routes]); + } + state.topologySnapshot = withSnapshot(state.topologySnapshot, { manualRoutesByNodeId: routesByNodeId }); + return true; + } +} + +// ── Helpers ──────────────────────────────────────────────────────────────── + +export function stableMacAddress(portId: Id): string { + return stableGeneratedMacAddress(portId); +} + +function firewallProtocolMatches(protocol: IPv4Packet['protocol'], rule: FirewallRule): boolean { + return rule.protocol === 'all' || FIREWALL_PROTOCOL[rule.protocol] === IPV4_PROTOCOL[protocol]; +} + +function firewallAddressMatches(packetIPAddress: string, configuredIPAddress: string, subnetMask: string): boolean { + if (configuredIPAddress.length === 0) return true; + if (subnetMask.length === 0) return false; + return sameSubnet(packetIPAddress, configuredIPAddress, subnetMask); +} + +function arpKey(nodeId: Id, ipAddress: string): string { + return `${nodeId}|${ipAddress}`; +} + +function bestInterface(targetIPAddress: string, interfaces: readonly NetworkInterface[]): NetworkInterface | undefined { + let selected: NetworkInterface | undefined; + let selectedMask: number | undefined; + for (const candidate of interfaces) { + const mask = parseIPv4(candidate.subnetMask); + if (!sameSubnet(candidate.ipAddress, targetIPAddress, candidate.subnetMask) || mask === undefined) continue; + if (selectedMask !== undefined && mask <= selectedMask) continue; + selected = candidate; + selectedMask = mask; + } + return selected; +} + +/** An ICMP error about an ICMP error carries the packet the first one was about. */ +function embeddedOriginal(packet: IPv4Packet): IPv4Packet { + if (packet.payload.kind === 'icmp' && packet.payload.message.embeddedOriginalPacket !== undefined) { + return packet.payload.message.embeddedOriginalPacket; + } + return packet; +} + +function icmpIdentifier(packet: IPv4Packet): number { + return packet.payload.kind === 'icmp' ? packet.payload.message.identifier : 0; +} + +function icmpSequenceNumber(packet: IPv4Packet): number { + return packet.payload.kind === 'icmp' ? packet.payload.message.sequenceNumber : 0; +} + +export function ethernetHeaders(frame: EthernetFrame): HeaderField[] { + return [ + { name: 'sourceMAC', value: frame.sourceMacAddress }, + { name: 'destinationMAC', value: frame.destinationMacAddress }, + ]; +} + +export function arpHeaders(packet: ArpPacket): HeaderField[] { + return [ + { name: 'operation', value: packet.operation }, + { name: 'senderMAC', value: packet.senderMacAddress }, + { name: 'senderIP', value: packet.senderIPAddress }, + { name: 'targetMAC', value: packet.targetMacAddress }, + { name: 'targetIP', value: packet.targetIPAddress }, + ]; +} + +export function ipv4Headers(packet: IPv4Packet): HeaderField[] { + return [ + { name: 'senderIP', value: packet.senderIPAddress }, + { name: 'receiverIP', value: packet.receiverIPAddress }, + { name: 'ttl', value: String(packet.timeToLive) }, + { name: 'protocol', value: String(IPV4_PROTOCOL[packet.protocol]) }, + ]; +} + +export function icmpHeaders(message: IcmpMessage): HeaderField[] { + return [ + { name: 'kind', value: message.kind }, + { name: 'identifier', value: String(message.identifier) }, + { name: 'sequence', value: String(message.sequenceNumber) }, + ]; +} diff --git a/packages/core/src/runtime/ipv4.ts b/packages/core/src/runtime/ipv4.ts new file mode 100644 index 0000000..9395efe --- /dev/null +++ b/packages/core/src/runtime/ipv4.ts @@ -0,0 +1,48 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyNetworkRuntimeEngine.swift (parseIPv4, sameSubnet) +// State/TopologyEditorState.swift (TopologyRuntimeManualRoute.parseIPv4) +// +// Two parsers exist on purpose, as in the Swift source: the runtime reads an +// octet the way Swift's `UInt8(String)` does, the route editor the way Java +// FILIUS validates its table cells (see routeTable.ts). + +/** + * Swift `UInt8(segment)`: an optional sign, then decimal digits, value 0…255. + * Leading zeros are allowed ("007" is 7), whitespace is not. + */ +function parseSwiftOctet(segment: string): number | undefined { + if (!/^[+-]?[0-9]+$/.test(segment)) return undefined; + const value = Number(segment); + if (!Number.isInteger(value) || value < 0 || value > 255) return undefined; + return Object.is(value, -0) ? 0 : value; +} + +/** Dotted quad to an unsigned 32-bit number, or undefined. */ +export function parseIPv4(value: string): number | undefined { + const segments = value.split('.'); + if (segments.length !== 4) return undefined; + let address = 0; + for (const segment of segments) { + const octet = parseSwiftOctet(segment); + if (octet === undefined) return undefined; + address = ((address << 8) | octet) >>> 0; + } + return address; +} + +export function formatIPv4(address: number): string { + return [24, 16, 8, 0].map((shift) => String((address >>> shift) & 0xff)).join('.'); +} + +export function sameSubnet(lhs: string, rhs: string, mask: string): boolean { + const left = parseIPv4(lhs); + const right = parseIPv4(rhs); + const netmask = parseIPv4(mask); + if (left === undefined || right === undefined || netmask === undefined) return false; + return ((left & netmask) >>> 0) === ((right & netmask) >>> 0); +} + +/** `address & mask` as an unsigned number. */ +export function maskAddress(address: number, mask: number): number { + return (address & mask) >>> 0; +} diff --git a/packages/core/src/runtime/packets.ts b/packages/core/src/runtime/packets.ts new file mode 100644 index 0000000..9c17509 --- /dev/null +++ b/packages/core/src/runtime/packets.ts @@ -0,0 +1,124 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyNetworkRuntimeEngine.swift ("Java-observable packet and route models") +// Frames and packets are typed values, not bytes — what the Java packet viewer +// shows, not what a real wire would carry. + +export interface EthernetFrame { + readonly identity: number; + readonly sourceMacAddress: string; + readonly destinationMacAddress: string; + readonly payload: EthernetPayload; +} + +export type EthernetPayload = + | { readonly kind: 'arp'; readonly packet: ArpPacket } + | { readonly kind: 'ipv4'; readonly packet: IPv4Packet }; + +export type ArpOperation = 'request' | 'reply'; + +export interface ArpPacket { + readonly operation: ArpOperation; + readonly senderMacAddress: string; + readonly senderIPAddress: string; + readonly targetMacAddress: string; + readonly targetIPAddress: string; +} + +export const IPV4_PROTOCOL = { icmp: 1, tcp: 6, udp: 17 } as const; +export type IPv4Protocol = keyof typeof IPV4_PROTOCOL; + +export interface IPv4Packet { + readonly identity: number; + readonly senderIPAddress: string; + readonly receiverIPAddress: string; + /** 0…255 */ + readonly timeToLive: number; + readonly protocol: IPv4Protocol; + readonly payload: IPv4Payload; +} + +export type IPv4Payload = + | { readonly kind: 'icmp'; readonly message: IcmpMessage } + | { readonly kind: 'tcp'; readonly segment: TcpSegment } + | { readonly kind: 'udp'; readonly datagram: UdpDatagram }; + +/** The same packet one hop further: identity kept, TTL lowered, never below 0. */ +export function forwardingClone(packet: IPv4Packet, decrementingTtlBy = 1): IPv4Packet { + return { + ...packet, + timeToLive: decrementingTtlBy >= packet.timeToLive ? 0 : packet.timeToLive - decrementingTtlBy, + }; +} + +export type IcmpMessageKind = + | 'echoRequest' + | 'echoReply' + | 'destinationNetworkUnreachable' + | 'destinationHostUnreachable' + | 'timeExceeded'; + +export interface IcmpMessage { + readonly kind: IcmpMessageKind; + /** 0…65535 */ + readonly identifier: number; + /** 0…65535 */ + readonly sequenceNumber: number; + readonly data: Uint8Array; + readonly embeddedOriginalPacket?: IPv4Packet; +} + +export function icmpMessage( + kind: IcmpMessageKind, + fields: Partial> = {}, +): IcmpMessage { + const message: IcmpMessage = { + kind, + identifier: fields.identifier ?? 0, + sequenceNumber: fields.sequenceNumber ?? 0, + data: fields.data ?? new Uint8Array(), + }; + return fields.embeddedOriginalPacket === undefined + ? message + : { ...message, embeddedOriginalPacket: fields.embeddedOriginalPacket }; +} + +export const TCP_FLAG = { + finish: 1 << 0, + synchronize: 1 << 1, + reset: 1 << 2, + push: 1 << 3, + acknowledgement: 1 << 4, +} as const; + +export type TcpSocketState = + | 'CLOSED' + | 'LISTEN' + | 'SYN_RCVD' + | 'SYN_SENT' + | 'ESTABLISHED' + | 'CLOSE_WAIT' + | 'LAST_ACK' + | 'FIN_WAIT_1' + | 'FIN_WAIT_2' + | 'CLOSING' + | 'TIME_WAIT'; + +export interface TcpSegment { + readonly sourcePort: number; + readonly destinationPort: number; + readonly sequenceNumber: number; + readonly acknowledgementNumber: number; + /** Bit set of TCP_FLAG values. */ + readonly flags: number; + readonly payload: Uint8Array; +} + +export interface UdpDatagram { + readonly sourcePort: number; + readonly destinationPort: number; + readonly payload: Uint8Array; +} + +export function packetIdentityInFrame(frame: EthernetFrame): number | undefined { + return frame.payload.kind === 'ipv4' ? frame.payload.packet.identity : undefined; +} diff --git a/packages/core/src/runtime/random.ts b/packages/core/src/runtime/random.ts new file mode 100644 index 0000000..cd69fc4 --- /dev/null +++ b/packages/core/src/runtime/random.ts @@ -0,0 +1,58 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyNetworkRuntimeEngine.swift (TopologyJavaCompatibleRandom) +// A bit-exact java.util.Random: the 48-bit linear congruential generator +// Java FILIUS draws its RIP beacon jitter and ephemeral ports from. BigInt +// keeps the 48-bit arithmetic exact; a double would lose the low bits. + +const MULTIPLIER = 0x5deece66dn; +const ADDEND = 0xbn; +const MASK = (1n << 48n) - 1n; +const INT32_MAX = 2147483647n; + +export class JavaCompatibleRandom { + private state: bigint; + + constructor(seed: bigint | number) { + this.state = (BigInt.asUintN(64, BigInt(seed)) ^ MULTIPLIER) & MASK; + } + + /** The internal 48-bit state, for tests and for copying a generator. */ + get seed(): bigint { + return this.state; + } + + clone(): JavaCompatibleRandom { + const copy = new JavaCompatibleRandom(0); + copy.state = this.state; + return copy; + } + + next(bits: number): number { + if (!(bits > 0 && bits <= 32)) throw new RangeError(`bits out of range: ${bits}`); + this.state = (this.state * MULTIPLIER + ADDEND) & MASK; + return Number(this.state >> BigInt(48 - bits)); + } + + nextInt(upperBound: number): number { + if (!(upperBound > 0)) throw new RangeError(`upperBound must be positive: ${upperBound}`); + const bound = BigInt(upperBound); + if ((upperBound & -upperBound) === upperBound) { + return Number((bound * BigInt(this.next(31))) >> 31n); + } + for (;;) { + const bits = BigInt(this.next(31)); + const value = bits % bound; + if (bits - value + (bound - 1n) <= INT32_MAX) return Number(value); + } + } + + nextFloat(): number { + return Math.fround(this.next(24) / (1 << 24)); + } + + /** Java RIP: 30 s · (f/3 + 0.84), truncated — somewhere between 25.2 s and 35.2 s. */ + nextRipJitterMilliseconds(): number { + const javaFloat = this.nextFloat(); + return Math.trunc(30_000.0 * (javaFloat / 3.0 + 0.84)); + } +} diff --git a/packages/core/src/runtime/routeTable.ts b/packages/core/src/runtime/routeTable.ts new file mode 100644 index 0000000..ee6be1c --- /dev/null +++ b/packages/core/src/runtime/routeTable.ts @@ -0,0 +1,222 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyJavaRouteTable.swift (row projection, validation, drafts) +// Java counterpart: filius.software.vermittlungsschicht.Weiterleitungstabelle +// (holeTabelle: the order of the generated rows). +// The Swift file also carries table geometry for SwiftUI; that belongs to the +// editor and is not ported here. + +import { formatIPv4, maskAddress } from './ipv4.js'; +import type { InterfaceConfiguration, ManualRoute } from './config.js'; + +export type RouteOrigin = 'localHost' | 'connected' | 'localhost' | 'manual' | 'defaultGateway' | 'rip'; + +export interface RouteRow { + readonly destinationNetwork: string; + readonly subnetMask: string; + readonly nextHop: string; + readonly interfaceIPAddress: string; + readonly origin: RouteOrigin; + readonly isEditable: boolean; + readonly metric?: number; + readonly expiresAtMilliseconds?: number; +} + +export type RouteTableColumn = 'destination' | 'subnetMask' | 'nextGateway' | 'interface'; + +/** + * A Java table octet: digits only, leading zeros allowed, at most three + * significant digits, 0…255 ("001" is valid, " 1" and "+1" are not). + */ +function parseJavaOctet(segment: string): number | undefined { + if (segment.length === 0 || !/^[0-9]+$/.test(segment)) return undefined; + const significant = segment.replace(/^0+/, ''); + if (significant.length === 0) return 0; + if (significant.length > 3) return undefined; + const value = Number(significant); + return value <= 255 ? value : undefined; +} + +function parseJavaIPv4(value: string): number | undefined { + const segments = value.split('.'); + if (segments.length !== 4) return undefined; + let address = 0; + for (const segment of segments) { + const octet = parseJavaOctet(segment); + if (octet === undefined) return undefined; + address = ((address << 8) | octet) >>> 0; + } + return address; +} + +export function isValidJavaIPAddress(value: string): boolean { + return parseJavaIPv4(value) !== undefined; +} + +/** + * FILIUS uses `musterSubNetz`, a dotted-decimal syntax check. It deliberately + * accepts non-contiguous masks in the route editor. + */ +export function isValidJavaSubnetMask(value: string): boolean { + return parseJavaIPv4(value) !== undefined; +} + +export function isValidRouteCell(value: string, column: RouteTableColumn): boolean { + return column === 'subnetMask' ? isValidJavaSubnetMask(value) : isValidJavaIPAddress(value); +} + +function sameNetwork(lhs: string, rhs: string, mask: string): boolean { + const left = parseJavaIPv4(lhs); + const right = parseJavaIPv4(rhs); + const netmask = parseJavaIPv4(mask); + if (left === undefined || right === undefined || netmask === undefined) return false; + return maskAddress(left, netmask) === maskAddress(right, netmask); +} + +function networkAddress(ipAddress: string, subnetMask: string): string | undefined { + const address = parseJavaIPv4(ipAddress); + const mask = parseJavaIPv4(subnetMask); + if (address === undefined || mask === undefined) return undefined; + return formatIPv4(maskAddress(address, mask)); +} + +/** + * The static table as Java shows it: the interfaces' own addresses (newest + * first), their networks, loopback, the manual rows, then the default route. + */ +export function routeTableRows( + interfaceConfigurations: readonly InterfaceConfiguration[], + manualRoutes: readonly ManualRoute[], + defaultGateway: string | undefined, +): RouteRow[] { + const validInterfaces = interfaceConfigurations.filter( + (configuration) => + parseJavaIPv4(configuration.ipAddress) !== undefined && + parseJavaIPv4(configuration.subnetMask) !== undefined, + ); + + const result: RouteRow[] = manualRoutes.map((route) => ({ + destinationNetwork: route.destinationNetwork, + subnetMask: route.subnetMask, + nextHop: route.gateway, + interfaceIPAddress: route.interfaceIPAddress, + origin: 'manual', + isEditable: true, + })); + + result.unshift({ + destinationNetwork: '127.0.0.0', + subnetMask: '255.0.0.0', + nextHop: '127.0.0.1', + interfaceIPAddress: '127.0.0.1', + origin: 'localhost', + isEditable: false, + }); + + for (const configuration of validInterfaces) { + const network = networkAddress(configuration.ipAddress, configuration.subnetMask); + if (network === undefined) continue; + result.unshift({ + destinationNetwork: network, + subnetMask: configuration.subnetMask, + nextHop: configuration.ipAddress, + interfaceIPAddress: configuration.ipAddress, + origin: 'connected', + isEditable: false, + }); + } + + for (const configuration of validInterfaces) { + result.unshift({ + destinationNetwork: configuration.ipAddress, + subnetMask: '255.255.255.255', + nextHop: '127.0.0.1', + interfaceIPAddress: '127.0.0.1', + origin: 'localHost', + isEditable: false, + }); + } + + const trimmedGateway = defaultGateway?.trim() ?? ''; + const primaryInterface = validInterfaces[0]; + if (parseJavaIPv4(trimmedGateway) !== undefined && primaryInterface !== undefined) { + let selectedInterface = primaryInterface.ipAddress; + for (const configuration of validInterfaces) { + if (sameNetwork(trimmedGateway, configuration.ipAddress, configuration.subnetMask)) { + selectedInterface = configuration.ipAddress; + } + } + result.push({ + destinationNetwork: '0.0.0.0', + subnetMask: '0.0.0.0', + nextHop: trimmedGateway, + interfaceIPAddress: selectedInterface, + origin: 'defaultGateway', + isEditable: false, + }); + } + + return result; +} + +export function visibleRouteRows(rows: readonly RouteRow[], showAllEntries: boolean): RouteRow[] { + return showAllEntries ? [...rows] : rows.filter((row) => row.isEditable); +} + +/** One row being edited in the route editor. */ +export interface RouteDraft { + readonly id: string; + destinationNetwork: string; + subnetMask: string; + nextGateway: string; + interfaceIPAddress: string; + isPendingInsertion: boolean; +} + +export function blankRouteDraft(id: string): RouteDraft { + return { + id, + destinationNetwork: '', + subnetMask: '', + nextGateway: '', + interfaceIPAddress: '', + isPendingInsertion: true, + }; +} + +export function routeDraftFromRoute(id: string, route: ManualRoute): RouteDraft { + return { + id, + destinationNetwork: route.destinationNetwork, + subnetMask: route.subnetMask, + nextGateway: route.gateway, + interfaceIPAddress: route.interfaceIPAddress, + isPendingInsertion: false, + }; +} + +/** The route a draft stands for — only once all four cells are valid. */ +export function manualRouteFromDraft(draft: RouteDraft): ManualRoute | undefined { + if ( + !isValidRouteCell(draft.destinationNetwork, 'destination') || + !isValidRouteCell(draft.subnetMask, 'subnetMask') || + !isValidRouteCell(draft.nextGateway, 'nextGateway') || + !isValidRouteCell(draft.interfaceIPAddress, 'interface') + ) { + return undefined; + } + return { + destinationNetwork: draft.destinationNetwork, + subnetMask: draft.subnetMask, + gateway: draft.nextGateway, + interfaceIPAddress: draft.interfaceIPAddress, + }; +} + +/** At most one blank row waits at the end of the editor. */ +export function appendingBlankDraftIfNeeded( + drafts: readonly RouteDraft[], + newId: () => string, +): RouteDraft[] { + if (drafts.some((draft) => draft.isPendingInsertion)) return [...drafts]; + return [...drafts, blankRouteDraft(newId())]; +} diff --git a/packages/core/src/runtime/snapshot.ts b/packages/core/src/runtime/snapshot.ts new file mode 100644 index 0000000..7edb555 --- /dev/null +++ b/packages/core/src/runtime/snapshot.ts @@ -0,0 +1,90 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyNetworkRuntimeEngine.swift (TopologyNetworkRuntimeTopologySnapshot) +// What the runtime starts from: the topology and every configuration, frozen +// at the moment the simulation starts. Later protocol slices add their +// configuration maps here (DHCP, NAT, remote link, wireless). + +import { compareIds, type Id } from '../ids.js'; +import type { NodeKind } from '../model/node.js'; +import { canonicalMacAddress } from '../model/node.js'; +import type { + DeviceConfiguration, + FirewallConfiguration, + InterfaceConfiguration, + InterfaceKey, + ManualRoute, + SwitchConfiguration, +} from './config.js'; + +export interface PortSnapshot { + readonly id: Id; + readonly label: string; + /** Canonical, or undefined for a port whose MAC address is derived from its id. */ + readonly macAddress?: string; +} + +export function portSnapshot(id: Id, label: string, macAddress?: string): PortSnapshot { + const canonical = canonicalMacAddress(macAddress); + return canonical === undefined ? { id, label } : { id, label, macAddress: canonical }; +} + +export interface NodeSnapshot { + readonly id: Id; + readonly kind: NodeKind; + readonly ports: readonly PortSnapshot[]; +} + +export interface LinkSnapshot { + readonly id: Id; + readonly sourceNodeId: Id; + readonly sourcePortId: Id; + readonly targetNodeId: Id; + readonly targetPortId: Id; +} + +export interface TopologySnapshot { + /** Sorted by id (Swift `uuidString` order). */ + readonly nodes: readonly NodeSnapshot[]; + /** Sorted by id (Swift `uuidString` order). */ + readonly links: readonly LinkSnapshot[]; + readonly deviceConfigurations: ReadonlyMap; + readonly interfaceConfigurations: ReadonlyMap; + readonly manualRoutesByNodeId: ReadonlyMap; + readonly ripEnabledByNodeId: ReadonlyMap; + readonly firewallConfigurationsByNodeId: ReadonlyMap; + readonly switchConfigurationsByNodeId: ReadonlyMap; +} + +export interface TopologySnapshotInput { + nodes: readonly NodeSnapshot[]; + links: readonly LinkSnapshot[]; + deviceConfigurations?: ReadonlyMap; + interfaceConfigurations?: ReadonlyMap; + manualRoutesByNodeId?: ReadonlyMap; + ripEnabledByNodeId?: ReadonlyMap; + firewallConfigurationsByNodeId?: ReadonlyMap; + switchConfigurationsByNodeId?: ReadonlyMap; +} + +export function topologySnapshot(input: TopologySnapshotInput): TopologySnapshot { + return { + nodes: [...input.nodes].sort((lhs, rhs) => compareIds(lhs.id, rhs.id)), + links: [...input.links].sort((lhs, rhs) => compareIds(lhs.id, rhs.id)), + deviceConfigurations: input.deviceConfigurations ?? new Map(), + interfaceConfigurations: input.interfaceConfigurations ?? new Map(), + manualRoutesByNodeId: input.manualRoutesByNodeId ?? new Map(), + ripEnabledByNodeId: input.ripEnabledByNodeId ?? new Map(), + firewallConfigurationsByNodeId: input.firewallConfigurationsByNodeId ?? new Map(), + switchConfigurationsByNodeId: input.switchConfigurationsByNodeId ?? new Map(), + }; +} + +/** The same snapshot with some fields replaced (Swift rebuilds it field by field). */ +export function withSnapshot( + snapshot: TopologySnapshot, + changes: Partial, +): TopologySnapshot { + return topologySnapshot({ ...snapshot, ...changes }); +} + +export const EMPTY_TOPOLOGY_SNAPSHOT: TopologySnapshot = topologySnapshot({ nodes: [], links: [] }); diff --git a/packages/core/src/runtime/speed.ts b/packages/core/src/runtime/speed.ts new file mode 100644 index 0000000..483359c --- /dev/null +++ b/packages/core/src/runtime/speed.ts @@ -0,0 +1,33 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyNetworkRuntimeEngine.swift (TopologyNetworkRuntimeSpeed) +// Java counterpart: filius.hardware.Verbindung (MIN_VERZOEGERUNG_IN_MILLIS, +// verzoegerungsFaktor) and GUIMainMenu.updateLatency. + +export const MINIMUM_SPEED_PERCENT = 1; +export const MAXIMUM_SPEED_PERCENT = 100; +export const DEFAULT_SPEED_PERCENT = 90; +export const JAVA_MINIMUM_LINK_DELAY_MILLISECONDS = 5; + +export class RuntimeSpeed { + readonly percent: number; + + constructor(percent: number = DEFAULT_SPEED_PERCENT) { + this.percent = Math.min(MAXIMUM_SPEED_PERCENT, Math.max(MINIMUM_SPEED_PERCENT, Math.trunc(percent))); + } + + /** Java's delay factor: 1 at full speed, 100 at the slowest. */ + get javaDelayFactor(): number { + return MAXIMUM_SPEED_PERCENT - this.percent + 1; + } + + /** How long a frame travels over one cable. */ + get linkTransmissionDelayMilliseconds(): number { + return JAVA_MINIMUM_LINK_DELAY_MILLISECONDS * this.javaDelayFactor; + } + + /** A base delay scaled like a cable, or undefined past the safe integer range. */ + scaledLinkDelay(baseMilliseconds: number): number | undefined { + const delay = baseMilliseconds * this.javaDelayFactor; + return Number.isSafeInteger(delay) ? delay : undefined; + } +} diff --git a/packages/core/src/runtime/trace.ts b/packages/core/src/runtime/trace.ts new file mode 100644 index 0000000..8cc42f3 --- /dev/null +++ b/packages/core/src/runtime/trace.ts @@ -0,0 +1,58 @@ +// Ported from filius-ipad (GPLv2/GPLv3): +// State/TopologyNetworkRuntimeEngine.swift (packet trace model) +// Java counterpart: filius.rahmenprogramm.nachrichten.Lauscher — here every +// step a frame or packet takes is one trace event; the packet viewer groups them. + +import type { Id } from '../ids.js'; + +export type TraceDirection = 'inbound' | 'outbound' | 'local'; + +export type TraceLayer = 'application' | 'transport' | 'network' | 'dataLink' | 'physical'; + +export type TraceOperation = + | 'created' + | 'sent' + | 'received' + | 'forwarded' + | 'accepted' + | 'dropped' + | 'rewritten' + | 'retransmitted' + | 'compatibilityAdapter'; + +export interface HeaderField { + readonly name: string; + readonly value: string; +} + +export interface TraceEvent { + readonly id: number; + readonly timeMilliseconds: number; + readonly frameIdentity?: number; + readonly packetIdentity?: number; + readonly nodeId: Id; + readonly interfaceId?: Id; + readonly direction: TraceDirection; + readonly layer: TraceLayer; + readonly operation: TraceOperation; + readonly beforeHeaders: readonly HeaderField[]; + readonly afterHeaders: readonly HeaderField[]; + readonly detail?: string; +} + +/** How many trace events the runtime keeps, and how many it drops at once when full. */ +export interface TraceRetentionPolicy { + readonly maximumEventCount: number; + readonly evictionBatchSize: number; +} + +export function traceRetentionPolicy(maximumEventCount: number, evictionBatchSize: number): TraceRetentionPolicy { + if (!(maximumEventCount > 0)) throw new RangeError('Packet-trace retention must keep at least one event'); + if (!(evictionBatchSize > 0)) throw new RangeError('Packet-trace eviction must remove at least one event'); + if (evictionBatchSize > maximumEventCount) { + throw new RangeError('Packet-trace eviction cannot exceed the retention limit'); + } + return { maximumEventCount, evictionBatchSize }; +} + +export const PRODUCTION_TRACE_RETENTION = traceRetentionPolicy(10_000, 1_000); diff --git a/packages/core/src/util/equal.ts b/packages/core/src/util/equal.ts new file mode 100644 index 0000000..60d6f53 --- /dev/null +++ b/packages/core/src/util/equal.ts @@ -0,0 +1,37 @@ +/** + * Structural equality for the runtime's value types — what Swift's synthesized + * `Equatable` gives a struct or enum for free. Handles plain objects, arrays, + * `Uint8Array`, `Map` and `Set`; everything else is compared with `Object.is`. + */ +export function deepEqual(lhs: unknown, rhs: unknown): boolean { + if (Object.is(lhs, rhs)) return true; + if (typeof lhs !== 'object' || typeof rhs !== 'object' || lhs === null || rhs === null) { + return false; + } + if (lhs instanceof Uint8Array || rhs instanceof Uint8Array) { + if (!(lhs instanceof Uint8Array && rhs instanceof Uint8Array)) return false; + return lhs.length === rhs.length && lhs.every((byte, index) => byte === rhs[index]); + } + if (Array.isArray(lhs) || Array.isArray(rhs)) { + if (!(Array.isArray(lhs) && Array.isArray(rhs)) || lhs.length !== rhs.length) return false; + return lhs.every((item, index) => deepEqual(item, rhs[index])); + } + if (lhs instanceof Map || rhs instanceof Map) { + if (!(lhs instanceof Map && rhs instanceof Map) || lhs.size !== rhs.size) return false; + for (const [key, value] of lhs) { + if (!rhs.has(key) || !deepEqual(value, rhs.get(key))) return false; + } + return true; + } + if (lhs instanceof Set || rhs instanceof Set) { + if (!(lhs instanceof Set && rhs instanceof Set) || lhs.size !== rhs.size) return false; + for (const value of lhs) if (!rhs.has(value)) return false; + return true; + } + const leftKeys = Object.keys(lhs).filter((key) => (lhs as Record)[key] !== undefined); + const rightKeys = Object.keys(rhs).filter((key) => (rhs as Record)[key] !== undefined); + if (leftKeys.length !== rightKeys.length) return false; + return leftKeys.every((key) => + deepEqual((lhs as Record)[key], (rhs as Record)[key]), + ); +} diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.ts new file mode 100644 index 0000000..e60489a --- /dev/null +++ b/packages/core/test/engine.test.ts @@ -0,0 +1,631 @@ +// Ported from filius-ipad ios/FiliusPadTests/TopologyNetworkRuntimeEngineTests.swift: +// the event queue, the virtual clock, Java-compatible randomness, restart, +// Ethernet/switch/ARP/IPv4/ICMP, routing errors, the firewall, packet loss +// and trace retention. The remaining Swift tests (UDP, TCP, DHCP, DNS, RIP, +// NAT, remote link, packet viewer) follow with their protocol slices. + +import { describe, expect, it } from 'vitest'; +import { + EMPTY_TOPOLOGY_SNAPSHOT, + ETHERNET_BROADCAST_MAC_ADDRESS, + firewallConfiguration, + firewallRule, + DIRECTLY_CONNECTED_SOURCE_MARKER, + forwardingClone, + icmpMessage, + interfaceKey, + JavaCompatibleRandom, + NetworkRuntimeEngine, + portSnapshot, + stableMacAddress, + switchConfiguration, + TCP_FLAG, + topologySnapshot, + traceRetentionPolicy, + UNSPECIFIED_MAC_ADDRESS, + type EthernetFrame, + type EthernetPayload, + type FirewallConfiguration, + type IPv4Packet, + type NodeSnapshot, + type RuntimeOutput, + type ScheduledEventKind, +} from '../src/index.js'; +import { device, link, pc, startedEngine, uuid } from './fixtures.js'; + +const marker = (label: string): ScheduledEventKind => ({ kind: 'parityMarker', label }); + +function firedKinds(outputs: RuntimeOutput[]): ScheduledEventKind[] { + return outputs.flatMap((output) => (output.kind.type === 'fired' ? [output.kind.event.kind] : [])); +} + +function routedTopology() { + const sourceNodeId = uuid(0x1451); + const sourcePortId = uuid(0x1461); + const routerNodeId = uuid(0x1452); + const routerPortA = uuid(0x1462); + const routerPortB = uuid(0x1463); + const targetNodeId = uuid(0x1453); + const targetPortId = uuid(0x1464); + const router: NodeSnapshot = { + id: routerNodeId, + kind: 'router', + ports: [portSnapshot(routerPortA, 'rt1'), portSnapshot(routerPortB, 'rt2')], + }; + const snapshot = topologySnapshot({ + nodes: [pc(sourceNodeId, sourcePortId), router, pc(targetNodeId, targetPortId)], + links: [ + link(sourceNodeId, sourcePortId, routerNodeId, routerPortA), + link(routerNodeId, routerPortB, targetNodeId, targetPortId), + ], + deviceConfigurations: new Map([ + [sourceNodeId, device('10.0.0.2', { gateway: '10.0.0.1' })], + [routerNodeId, device('10.0.0.1')], + [targetNodeId, device('20.0.0.2', { gateway: '20.0.0.1' })], + ]), + interfaceConfigurations: new Map([ + [interfaceKey(routerNodeId, routerPortA), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }], + [interfaceKey(routerNodeId, routerPortB), { ipAddress: '20.0.0.1', subnetMask: '255.255.255.0' }], + ]), + }); + const engine = new NetworkRuntimeEngine(14); + engine.handle({ type: 'start', snapshot, seed: 14, initialTimeMilliseconds: 0 }); + return { engine, sourceNodeId, routerNodeId }; +} + +function firewallEngine(configuration: FirewallConfiguration) { + const routerId = uuid(0x1802); + const portId = uuid(0x1812); + const engine = startedEngine( + { + nodes: [{ id: routerId, kind: 'router', ports: [portSnapshot(portId, 'rt1')] }], + links: [], + interfaceConfigurations: new Map([ + [interfaceKey(routerId, portId), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }], + ]), + firewallConfigurationsByNodeId: new Map([[routerId, configuration]]), + }, + 18, + ); + return { engine, routerId }; +} + +function tcpPacket(identity: number, destinationPort: number, flags: number): IPv4Packet { + return { + identity, + senderIPAddress: '203.0.113.10', + receiverIPAddress: '10.0.0.1', + timeToLive: 64, + protocol: 'tcp', + payload: { + kind: 'tcp', + segment: { + sourcePort: 50_000, + destinationPort, + sequenceNumber: identity, + acknowledgementNumber: 0, + flags, + payload: new Uint8Array(), + }, + }, + }; +} + +describe('event queue and virtual clock', () => { + it('orders events by deadline, then by insertion sequence', () => { + const engine = new NetworkRuntimeEngine(42); + engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 }); + engine.handle({ type: 'schedule', deadlineMilliseconds: 100, kind: marker('first-at-100') }); + engine.handle({ type: 'schedule', deadlineMilliseconds: 50, kind: marker('at-50') }); + engine.handle({ type: 'schedule', deadlineMilliseconds: 100, kind: marker('second-at-100') }); + + const outputs = engine.handle({ type: 'advance', toMilliseconds: 100 }); + + expect(firedKinds(outputs)).toEqual([marker('at-50'), marker('first-at-100'), marker('second-at-100')]); + expect(engine.state.currentTimeMilliseconds).toBe(100); + expect(engine.state.pendingEvents).toEqual([]); + }); + + it('rejects a past time without changing the clock', () => { + const engine = new NetworkRuntimeEngine(7); + engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 7, initialTimeMilliseconds: 10 }); + engine.handle({ type: 'advance', toMilliseconds: 25 }); + + const outputs = engine.handle({ type: 'advance', toMilliseconds: 24 }); + + expect(outputs.map((output) => output.kind)).toEqual([{ type: 'advanceRejectedPastTime' }]); + expect(engine.state.currentTimeMilliseconds).toBe(25); + }); + + it('rejects a past deadline without using up a sequence number', () => { + const engine = new NetworkRuntimeEngine(8); + engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 8, initialTimeMilliseconds: 25 }); + + const outputs = engine.handle({ type: 'schedule', deadlineMilliseconds: 24, kind: marker('past') }); + + expect(outputs.map((output) => output.kind)).toEqual([ + { type: 'scheduleRejectedPastTime', deadlineMilliseconds: 24 }, + ]); + expect(engine.state.pendingEvents).toEqual([]); + expect(engine.state.nextEventSequenceNumber).toBe(0); + expect(engine.state.currentTimeMilliseconds).toBe(25); + }); + + it('replays a named scenario straight to a stable state', () => { + const finalState = NetworkRuntimeEngine.run({ + name: 'equal-deadline-order', + seed: 1, + advanceToMilliseconds: 1_000, + scheduledEvents: [ + { deadlineMilliseconds: 500, kind: marker('a') }, + { deadlineMilliseconds: 500, kind: marker('b') }, + ], + }); + + expect(finalState.currentTimeMilliseconds).toBe(1_000); + expect(finalState.pendingEvents).toEqual([]); + expect(finalState.seed).toBe(1n); + }); + + it('clears transient state on restart and numbers packets from one again', () => { + const nodeId = uuid(0x12); + const engine = new NetworkRuntimeEngine(12); + engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 12, initialTimeMilliseconds: 0 }); + engine.handle({ type: 'schedule', deadlineMilliseconds: 40, kind: marker('stale') }); + expect(engine.allocateFrameIdentity()).toBe(1); + expect(engine.allocatePacketIdentity()).toBe(1); + engine.recordTrace({ packetIdentity: 1, nodeId, direction: 'local', layer: 'application', operation: 'created' }); + engine.handle({ type: 'stop' }); + + engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 12, initialTimeMilliseconds: 0 }); + + const state = engine.state; + expect(state.pendingEvents).toEqual([]); + expect(state.packetTraces).toEqual([]); + expect(state.arpCachesByNodeId.size).toBe(0); + expect(state.switchForwardingTablesByNodeId.size).toBe(0); + expect(state.switchSeenFrameIdentitiesByNodeId.size).toBe(0); + expect(state.deliveredIPv4PacketsByNodeId.size).toBe(0); + expect(state.icmpObservationsByNodeId.size).toBe(0); + expect(state.firewallDecisions).toEqual([]); + expect(engine.allocateFrameIdentity()).toBe(1); + expect(engine.allocatePacketIdentity()).toBe(1); + }); +}); + +describe('Java-compatible randomness', () => { + it('draws the same RIP jitter as java.util.Random', () => { + const random = new JavaCompatibleRandom(42); + + expect(Array.from({ length: 5 }, () => random.nextRipJitterMilliseconds())).toEqual([ + 32_475, 25_746, 32_032, 25_679, 28_287, + ]); + }); + + it('matches java.util.Random.nextInt for bounded and power-of-two ranges', () => { + // Measured on OpenJDK 21 (29.09.2026): new java.util.Random(42), + // nextInt(100) three times, then nextInt(16) three times. + const random = new JavaCompatibleRandom(42); + + expect([random.nextInt(100), random.nextInt(100), random.nextInt(100)]).toEqual([30, 63, 48]); + expect([random.nextInt(16), random.nextInt(16), random.nextInt(16)]).toEqual([0, 4, 15]); + }); +}); + +describe('IPv4 packets', () => { + it('keeps the identity and lowers the TTL when forwarding', () => { + const packet: IPv4Packet = { + identity: 99, + senderIPAddress: '192.168.0.10', + receiverIPAddress: '192.168.1.20', + timeToLive: 2, + protocol: 'icmp', + payload: { kind: 'icmp', message: icmpMessage('echoRequest', { identifier: 3, sequenceNumber: 4 }) }, + }; + + const forwarded = forwardingClone(packet); + const expired = forwardingClone(forwarded); + + expect(forwarded).toMatchObject({ identity: 99, timeToLive: 1 }); + expect(expired).toMatchObject({ identity: 99, timeToLive: 0 }); + }); +}); + +describe('Ethernet, ARP and ICMP', () => { + it('fills both ARP caches with one request and reply over a direct cable', () => { + const sourceNodeId = uuid(0x1401); + const sourcePortId = uuid(0x1411); + const targetNodeId = uuid(0x1402); + const targetPortId = uuid(0x1412); + const engine = startedEngine({ + nodes: [pc(sourceNodeId, sourcePortId), pc(targetNodeId, targetPortId)], + links: [link(sourceNodeId, sourcePortId, targetNodeId, targetPortId)], + deviceConfigurations: new Map([ + [sourceNodeId, device('192.168.0.10')], + [targetNodeId, device('192.168.0.20')], + ]), + }); + + const resolved = engine.resolveMacAddress(sourceNodeId, '192.168.0.20'); + + expect(resolved).toBe(stableMacAddress(targetPortId)); + expect(engine.state.arpCachesByNodeId.get(sourceNodeId)?.get('192.168.0.20')?.macAddress).toBe(resolved); + expect(engine.state.arpCachesByNodeId.get(targetNodeId)?.get('192.168.0.10')?.macAddress).toBe( + stableMacAddress(sourcePortId), + ); + }); + + it('pings across a switch with Ethernet, ARP and ICMP packets', () => { + const sourceNodeId = uuid(0x1421); + const sourcePortId = uuid(0x1431); + const switchNodeId = uuid(0x1422); + const switchPortA = uuid(0x1432); + const switchPortB = uuid(0x1433); + const targetNodeId = uuid(0x1423); + const targetPortId = uuid(0x1434); + const switchNode: NodeSnapshot = { + id: switchNodeId, + kind: 'networkSwitch', + ports: [portSnapshot(switchPortA, 'sw1'), portSnapshot(switchPortB, 'sw2')], + }; + const engine = startedEngine({ + nodes: [pc(sourceNodeId, sourcePortId), switchNode, pc(targetNodeId, targetPortId)], + links: [ + link(sourceNodeId, sourcePortId, switchNodeId, switchPortA), + link(switchNodeId, switchPortB, targetNodeId, targetPortId), + ], + deviceConfigurations: new Map([ + [sourceNodeId, device('192.168.0.10')], + [targetNodeId, device('192.168.0.20')], + ]), + }); + + const result = engine.sendIcmpEcho(sourceNodeId, '192.168.0.20', { identifier: 14, sequenceNumber: 1 }); + + expect(result.type).toBe('delivered'); + expect(engine.state.icmpObservationsByNodeId.get(sourceNodeId)?.at(-1)?.message.kind).toBe('echoReply'); + expect(engine.state.switchForwardingTablesByNodeId.get(switchNodeId)?.size).toBe(2); + expect(engine.state.packetTraces.some((trace) => trace.detail === 'ARP request for 192.168.0.20')).toBe(true); + expect( + engine.state.packetTraces.some((trace) => trace.packetIdentity !== undefined && trace.layer === 'network'), + ).toBe(true); + }); + + it('answers an expired TTL at the router with time exceeded and the original packet', () => { + const topology = routedTopology(); + + const result = topology.engine.sendIcmpEcho(topology.sourceNodeId, '20.0.0.2', { + timeToLive: 1, + identifier: 140, + sequenceNumber: 1, + }); + + expect(result).toMatchObject({ type: 'icmpError', kind: 'timeExceeded' }); + const observation = topology.engine.state.icmpObservationsByNodeId.get(topology.sourceNodeId)?.at(-1); + expect(observation?.message.kind).toBe('timeExceeded'); + expect(observation?.message.embeddedOriginalPacket?.timeToLive).toBe(1); + expect(observation?.message.embeddedOriginalPacket?.receiverIPAddress).toBe('20.0.0.2'); + }); + + it('keeps the packet identity and lowers the TTL when a router forwards', () => { + const topology = routedTopology(); + + const result = topology.engine.sendIcmpEcho(topology.sourceNodeId, '20.0.0.2', { + timeToLive: 8, + identifier: 141, + sequenceNumber: 1, + }); + + expect(result.type).toBe('delivered'); + const forwardingTrace = topology.engine.state.packetTraces.find( + (trace) => + trace.nodeId === topology.routerNodeId && trace.operation === 'forwarded' && trace.detail === 'TTL decremented', + ); + expect(forwardingTrace?.packetIdentity).toBeDefined(); + expect(forwardingTrace?.beforeHeaders.find((field) => field.name === 'ttl')?.value).toBe('8'); + expect(forwardingTrace?.afterHeaders.find((field) => field.name === 'ttl')?.value).toBe('7'); + }); + + it('reports network unreachable when the router has no route', () => { + const topology = routedTopology(); + const snapshot = topology.engine.state.topologySnapshot; + const sourceToRouter = snapshot.links.find( + (candidate) => candidate.sourceNodeId === topology.sourceNodeId || candidate.targetNodeId === topology.sourceNodeId, + ); + const engine = new NetworkRuntimeEngine(14); + engine.handle({ + type: 'start', + snapshot: topologySnapshot({ + nodes: snapshot.nodes, + links: sourceToRouter === undefined ? [] : [sourceToRouter], + deviceConfigurations: snapshot.deviceConfigurations, + interfaceConfigurations: snapshot.interfaceConfigurations, + manualRoutesByNodeId: snapshot.manualRoutesByNodeId, + }), + seed: 14, + initialTimeMilliseconds: 0, + }); + + const result = engine.sendIcmpEcho(topology.sourceNodeId, '30.0.0.2', { identifier: 142, sequenceNumber: 1 }); + + expect(result).toMatchObject({ type: 'icmpError', kind: 'destinationNetworkUnreachable' }); + }); + + it('reports host unreachable when a connected target never answers ARP', () => { + const sourceNodeId = uuid(0x1481); + const sourcePortId = uuid(0x1491); + const engine = startedEngine({ + nodes: [pc(sourceNodeId, sourcePortId)], + links: [], + deviceConfigurations: new Map([[sourceNodeId, device('192.168.50.10')]]), + }); + + const result = engine.sendIcmpEcho(sourceNodeId, '192.168.50.99', { identifier: 143, sequenceNumber: 1 }); + + expect(result).toMatchObject({ type: 'icmpError', kind: 'destinationHostUnreachable' }); + }); +}); + +describe('switch', () => { + it('learns, floods, forwards, filters and ages its address table', () => { + const hostAId = uuid(0x1a01); + const hostAPortId = uuid(0x1a11); + const hostBId = uuid(0x1a02); + const hostBPortId = uuid(0x1a12); + const hostCId = uuid(0x1a03); + const hostCPortId = uuid(0x1a13); + const switchId = uuid(0x1a04); + const switchPorts = [1, 2, 3].map((index) => portSnapshot(uuid(0x1a20 + index), `sw${index}`)); + const engine = startedEngine( + { + nodes: [ + pc(hostAId, hostAPortId), + pc(hostBId, hostBPortId), + pc(hostCId, hostCPortId), + { id: switchId, kind: 'networkSwitch', ports: switchPorts }, + ], + links: [ + link(hostAId, hostAPortId, switchId, switchPorts[0]!.id), + link(hostBId, hostBPortId, switchId, switchPorts[1]!.id), + link(hostCId, hostCPortId, switchId, switchPorts[2]!.id), + ], + switchConfigurationsByNodeId: new Map([[switchId, switchConfiguration('Classroom', 1_000)]]), + }, + 20, + ); + const macA = stableMacAddress(hostAPortId); + const macB = stableMacAddress(hostBPortId); + const payload: EthernetPayload = { + kind: 'arp', + packet: { + operation: 'request', + senderMacAddress: macA, + senderIPAddress: '192.0.2.1', + targetMacAddress: UNSPECIFIED_MAC_ADDRESS, + targetIPAddress: '192.0.2.200', + }, + }; + const frame = (sourceMacAddress: string, destinationMacAddress: string): EthernetFrame => ({ + identity: engine.allocateFrameIdentity(), + sourceMacAddress, + destinationMacAddress, + payload, + }); + const switchTraces = (detail: string) => + engine.state.packetTraces.filter((trace) => trace.nodeId === switchId && trace.detail === detail); + + engine.sendEthernetFrame(hostAId, hostAPortId, frame(macA, '02:00:00:00:00:FE')); + expect(switchTraces('switch unknown unicast flooding')).toHaveLength(2); + + engine.sendEthernetFrame(hostBId, hostBPortId, frame(macB, macA)); + expect(switchTraces('switch learned unicast forwarding')).toHaveLength(1); + + engine.sendEthernetFrame(hostAId, hostAPortId, frame(macA, macA)); + expect(switchTraces('switch filtered destination on incoming port').length).toBeGreaterThan(0); + expect(engine.switchSatEntries(switchId)).toHaveLength(2); + + const retention = 1_000; + const updateTimes = [...engine.state.switchForwardingUpdatedAtMillisecondsByNodeId.get(switchId)!.values()]; + const expirationDeadlines = updateTimes.map((time) => time + retention); + const firstExpiration = Math.min(...expirationDeadlines); + const lastExpiration = Math.max(...expirationDeadlines); + + engine.handle({ type: 'advance', toMilliseconds: firstExpiration - 1 }); + expect(engine.switchSatEntries(switchId)).toHaveLength(2); + engine.handle({ type: 'advance', toMilliseconds: lastExpiration }); + expect(engine.switchSatEntries(switchId)).toEqual([]); + }); +}); + +describe('firewall', () => { + it('accepts when inactive, and an active ICMP drop bypasses the ordered rules', () => { + const routerId = uuid(0x1801); + const portId = uuid(0x1811); + const router: NodeSnapshot = { id: routerId, kind: 'router', ports: [portSnapshot(portId, 'rt1')] }; + const packet: IPv4Packet = { + identity: 18, + senderIPAddress: '203.0.113.10', + receiverIPAddress: '10.0.0.1', + timeToLive: 64, + protocol: 'icmp', + payload: { kind: 'icmp', message: icmpMessage('echoRequest') }, + }; + const interfaces = new Map([ + [interfaceKey(routerId, portId), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }], + ]); + + const inactive = startedEngine( + { + nodes: [router], + links: [], + interfaceConfigurations: interfaces, + firewallConfigurationsByNodeId: new Map([[routerId, firewallConfiguration()]]), + }, + 18, + ); + expect(inactive.evaluateFirewall(packet, routerId).accepted).toBe(true); + + const active = startedEngine( + { + nodes: [router], + links: [], + interfaceConfigurations: interfaces, + firewallConfigurationsByNodeId: new Map([ + [ + routerId, + firewallConfiguration({ + isActive: true, + defaultPolicy: 'accept', + dropIcmp: true, + rules: [firewallRule({ protocol: 'icmp', action: 'accept' })], + }), + ], + ]), + }, + 18, + ); + expect(active.evaluateFirewall(packet, routerId).accepted).toBe(false); + expect(active.state.firewallDecisions.at(-1)?.ruleIndex).toBeUndefined(); + expect(active.state.packetTraces.at(-1)?.operation).toBe('dropped'); + }); + + it('lets the first matching TCP rule win, and established traffic bypasses SYN-only rules', () => { + const { engine, routerId } = firewallEngine( + firewallConfiguration({ + isActive: true, + defaultPolicy: 'drop', + filterSynSegmentsOnly: true, + rules: [ + firewallRule({ port: 443, protocol: 'tcp', action: 'accept' }), + firewallRule({ port: 443, protocol: 'tcp', action: 'drop' }), + ], + }), + ); + + const synDecision = engine.evaluateFirewall(tcpPacket(181, 443, TCP_FLAG.synchronize), routerId); + expect(synDecision.accepted).toBe(true); + expect(synDecision.ruleIndex).toBe(0); + expect(engine.evaluateFirewall(tcpPacket(182, 22, TCP_FLAG.acknowledgement), routerId).accepted).toBe(true); + }); + + it('matches a UDP response by its explicit source port and the direct-network marker', () => { + const { engine, routerId } = firewallEngine( + firewallConfiguration({ + isActive: true, + defaultPolicy: 'drop', + rules: [ + firewallRule({ + sourceIPAddress: DIRECTLY_CONNECTED_SOURCE_MARKER, + destinationIPAddress: '8.8.8.8', + destinationSubnetMask: '255.255.255.255', + port: 53, + protocol: 'udp', + action: 'accept', + }), + ], + }), + ); + const udp = (identity: number, sender: string, receiver: string, sourcePort: number, destinationPort: number): IPv4Packet => ({ + identity, + senderIPAddress: sender, + receiverIPAddress: receiver, + timeToLive: 64, + protocol: 'udp', + payload: { kind: 'udp', datagram: { sourcePort, destinationPort, payload: new Uint8Array() } }, + }); + + expect(engine.evaluateFirewall(udp(183, '10.0.0.20', '8.8.8.8', 50_001, 53), routerId).accepted).toBe(true); + expect(engine.evaluateFirewall(udp(184, '8.8.8.8', '10.0.0.20', 53, 50_001), routerId).accepted).toBe(true); + }); +}); + +describe('packet loss and trace retention', () => { + it('drops every physical delivery while global packet loss is on', () => { + const firstNodeId = uuid(0x101); + const firstPortId = uuid(0x102); + const secondNodeId = uuid(0x103); + const secondPortId = uuid(0x104); + const engine = startedEngine({ + nodes: [pc(firstNodeId, firstPortId), pc(secondNodeId, secondPortId)], + links: [link(firstNodeId, firstPortId, secondNodeId, secondPortId)], + deviceConfigurations: new Map([ + [firstNodeId, device('10.0.0.1')], + [secondNodeId, device('10.0.0.2')], + ]), + }); + const frame: EthernetFrame = { + identity: engine.allocateFrameIdentity(), + sourceMacAddress: stableMacAddress(firstPortId), + destinationMacAddress: ETHERNET_BROADCAST_MAC_ADDRESS, + payload: { + kind: 'arp', + packet: { + operation: 'request', + senderMacAddress: stableMacAddress(firstPortId), + senderIPAddress: '10.0.0.1', + targetMacAddress: UNSPECIFIED_MAC_ADDRESS, + targetIPAddress: '10.0.0.2', + }, + }, + }; + + engine.setGlobalPacketLossEnabled(true); + engine.sendEthernetFrame(firstNodeId, firstPortId, frame); + + expect(engine.state.globalPacketLossEnabled).toBe(true); + expect(engine.state.arpCachesByNodeId.get(secondNodeId)?.size ?? 0).toBe(0); + expect( + engine.state.packetTraces.some( + (trace) => + trace.frameIdentity === frame.identity && + trace.nodeId === secondNodeId && + trace.operation === 'dropped' && + trace.detail === 'global packet-loss simulation', + ), + ).toBe(true); + + engine.setGlobalPacketLossEnabled(false); + engine.sendEthernetFrame(firstNodeId, firstPortId, frame); + + expect(engine.state.globalPacketLossEnabled).toBe(false); + expect(engine.state.arpCachesByNodeId.get(secondNodeId)?.get('10.0.0.1')?.macAddress).toBe( + stableMacAddress(firstPortId), + ); + }); + + it('resets packet loss across stop and restart', () => { + const engine = new NetworkRuntimeEngine(42); + engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 }); + engine.setGlobalPacketLossEnabled(true); + expect(engine.state.globalPacketLossEnabled).toBe(true); + + engine.handle({ type: 'stop' }); + expect(engine.state.globalPacketLossEnabled).toBe(false); + + engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 }); + expect(engine.state.globalPacketLossEnabled).toBe(false); + }); + + it('evicts the oldest trace events in configured batches', () => { + const nodeId = uuid(0x2001); + const interfaceId = uuid(0x2002); + const engine = new NetworkRuntimeEngine(20, traceRetentionPolicy(3, 2)); + + for (let identity = 1; identity <= 6; identity += 1) { + engine.recordTrace({ + frameIdentity: identity, + nodeId, + interfaceId, + direction: 'outbound', + layer: 'dataLink', + operation: 'sent', + detail: `trace-${identity}`, + }); + } + + expect(engine.state.packetTraces.map((trace) => trace.id)).toEqual([5, 6]); + expect(engine.state.packetTraces.map((trace) => trace.detail)).toEqual(['trace-5', 'trace-6']); + expect(engine.state.discardedPacketTraceCount).toBe(4); + expect(engine.state.nextTraceIdentity).toBe(7); + }); +}); diff --git a/packages/core/test/fixtures.ts b/packages/core/test/fixtures.ts new file mode 100644 index 0000000..344e90d --- /dev/null +++ b/packages/core/test/fixtures.ts @@ -0,0 +1,50 @@ +// Test fixtures, ported from the private helpers of +// filius-ipad ios/FiliusPadTests/TopologyNetworkRuntimeEngineTests.swift. + +import { + deviceConfiguration, + NetworkRuntimeEngine, + portSnapshot, + topologySnapshot, + type DeviceConfiguration, + type Id, + type LinkSnapshot, + type NodeSnapshot, + type TopologySnapshotInput, +} from '../src/index.js'; + +let linkCounter = 0; + +/** Swift uses a fresh `UUID()` per link; a counter keeps runs reproducible. */ +export function link(sourceNodeId: Id, sourcePortId: Id, targetNodeId: Id, targetPortId: Id): LinkSnapshot { + linkCounter += 1; + return { + id: `ffffffff-0000-0000-0000-${linkCounter.toString(16).padStart(12, '0')}`, + sourceNodeId, + sourcePortId, + targetNodeId, + targetPortId, + }; +} + +export function pc(nodeId: Id, portId: Id): NodeSnapshot { + return { id: nodeId, kind: 'pc', ports: [portSnapshot(portId, 'eth0')] }; +} + +export function device(ipAddress: string, options: { mask?: string; gateway?: string } = {}): DeviceConfiguration { + return deviceConfiguration(ipAddress, options.mask ?? '255.255.255.0', options.gateway ?? ''); +} + +export function startedEngine( + input: TopologySnapshotInput, + seed: number = 14, +): NetworkRuntimeEngine { + const engine = new NetworkRuntimeEngine(seed); + engine.handle({ type: 'start', snapshot: topologySnapshot(input), seed, initialTimeMilliseconds: 0 }); + return engine; +} + +/** `00000000-0000-0000-0000-` followed by twelve hex digits. */ +export function uuid(suffix: number): Id { + return `00000000-0000-0000-0000-${suffix.toString(16).toUpperCase().padStart(12, '0')}`; +} diff --git a/packages/core/test/routeTable.test.ts b/packages/core/test/routeTable.test.ts new file mode 100644 index 0000000..5502914 --- /dev/null +++ b/packages/core/test/routeTable.test.ts @@ -0,0 +1,121 @@ +// Ported from filius-ipad ios/FiliusPadTests/TopologyJavaRouteTableTests.swift. +// Left out: column titles and geometry (editor), and the reducer tests +// (they move with the document layer, packages/doc). + +import { describe, expect, it } from 'vitest'; +import { + appendingBlankDraftIfNeeded, + bestMatchingManualRoute, + blankRouteDraft, + isValidJavaIPAddress, + isValidJavaSubnetMask, + manualRouteFromDraft, + routeTableRows, + visibleRouteRows, + type ManualRoute, +} from '../src/index.js'; + +function route(destinationNetwork: string, subnetMask: string, gateway: string, interfaceIPAddress: string): ManualRoute { + return { destinationNetwork, subnetMask, gateway, interfaceIPAddress }; +} + +describe('Java route table', () => { + it('projects multiple interfaces in Java order with Java values', () => { + const rows = routeTableRows( + [ + { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }, + { ipAddress: '192.168.0.1', subnetMask: '255.255.255.0' }, + ], + [ + route('172.16.0.0', '255.255.0.0', '10.0.0.2', '10.0.0.1'), + route('203.0.113.0', '255.255.255.0', '192.168.0.2', '192.168.0.1'), + ], + '10.0.0.254', + ); + + expect(rows.map((row) => row.destinationNetwork)).toEqual([ + '192.168.0.1', '10.0.0.1', + '192.168.0.0', '10.0.0.0', + '127.0.0.0', + '172.16.0.0', '203.0.113.0', + '0.0.0.0', + ]); + expect(rows.map((row) => row.origin)).toEqual([ + 'localHost', 'localHost', 'connected', 'connected', 'localhost', 'manual', 'manual', 'defaultGateway', + ]); + expect(rows.map((row) => row.isEditable)).toEqual([false, false, false, false, false, true, true, false]); + expect(rows[0]).toMatchObject({ subnetMask: '255.255.255.255', nextHop: '127.0.0.1', interfaceIPAddress: '127.0.0.1' }); + expect(rows[2]?.nextHop).toBe('192.168.0.1'); + expect(rows[4]?.nextHop).toBe('127.0.0.1'); + expect(rows.at(-1)).toMatchObject({ nextHop: '10.0.0.254', interfaceIPAddress: '10.0.0.1' }); + }); + + it('puts the default route on the last matching interface and falls back to the primary one', () => { + const interfaces = [ + { ipAddress: '10.0.0.1', subnetMask: '255.0.0.0' }, + { ipAddress: '10.1.0.1', subnetMask: '255.0.0.0' }, + ]; + + const matching = routeTableRows(interfaces, [], '10.2.0.1'); + expect(matching.at(-1)).toMatchObject({ origin: 'defaultGateway', interfaceIPAddress: '10.1.0.1' }); + + const fallback = routeTableRows(interfaces, [], '192.168.0.1'); + expect(fallback.at(-1)?.interfaceIPAddress).toBe('10.0.0.1'); + }); + + it('shows only manual rows when generated rows are hidden', () => { + const rows = routeTableRows( + [{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }], + [route('172.16.0.0', '255.255.0.0', '10.0.0.2', '10.0.0.1')], + '10.0.0.254', + ); + + expect(visibleRouteRows(rows, false).map((row) => row.origin)).toEqual(['manual']); + expect(visibleRouteRows(rows, true)).toEqual(rows); + }); + + it('accepts leading zeros and non-contiguous masks like Java', () => { + expect(isValidJavaIPAddress('001.002.003.004')).toBe(true); + expect(isValidJavaSubnetMask('255.0.255.0')).toBe(true); + expect(isValidJavaIPAddress('256.0.0.1')).toBe(false); + expect(isValidJavaSubnetMask('255.255.255')).toBe(false); + expect(isValidJavaIPAddress(' 10.0.0.1')).toBe(false); + }); + + it('commits a draft only when all four cells are valid', () => { + const draft = blankRouteDraft('00000000-0000-0000-0000-000000000013'); + draft.destinationNetwork = '10.0.0.0'; + draft.subnetMask = '255.0.255.0'; + draft.nextGateway = '10.0.0.2'; + + expect(manualRouteFromDraft(draft)).toBeUndefined(); + + draft.interfaceIPAddress = '10.0.0.1'; + expect(manualRouteFromDraft(draft)).toEqual(route('10.0.0.0', '255.0.255.0', '10.0.0.2', '10.0.0.1')); + }); + + it('keeps at most one pending blank draft', () => { + let counter = 0; + const newId = () => `draft-${(counter += 1)}`; + const first = appendingBlankDraftIfNeeded([], newId); + const second = appendingBlankDraftIfNeeded(first, newId); + + expect(first).toHaveLength(1); + expect(second).toEqual(first); + expect(second[0]?.isPendingInsertion).toBe(true); + }); + + it('picks the greatest numeric mask and keeps the first row on a tie', () => { + const broad = route('10.0.0.0', '255.0.0.0', '1.1.1.1', '10.0.0.1'); + const firstSpecific = route('10.1.0.0', '255.255.0.0', '2.2.2.2', '10.0.0.1'); + const tiedSpecific = route('10.1.0.0', '255.255.0.0', '3.3.3.3', '10.0.0.1'); + + expect(bestMatchingManualRoute('10.1.2.3', [broad, firstSpecific, tiedSpecific])).toBe(firstSpecific); + }); + + it('never includes learned RIP rows in the static projection', () => { + const rows = routeTableRows([{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }], [], undefined); + + expect(rows.some((row) => row.origin === 'rip')).toBe(false); + }); +}); diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 0000000..61638e5 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "types": [] + }, + "include": ["src", "test"] +} diff --git a/scripts/code_language_allow.txt b/scripts/code_language_allow.txt new file mode 100644 index 0000000..6eb6b2a --- /dev/null +++ b/scripts/code_language_allow.txt @@ -0,0 +1,15 @@ +# Words only this repository may use, in addition to the dashboard's +# scripts/code_language_allow.txt. Format: `path::word` (bound to one path or +# path prefix) or a bare word (anywhere). Each entry says why. +# +# The .fls format is Java's XMLEncoder output: its class and property names +# (filius.hardware.knoten.Vermittlungsrechner, GUIKnotenItem, ipAdresse …) +# are fields of a foreign API and keep their German names — in packages/fls +# only. +# +# Java FILIUS class and package names, cited in the provenance header of each +# ported file and in comments that point at the Java behaviour they copy. +vermittlungsrechner +verbindung +netzzugangsschicht +vermittlungsschicht diff --git a/scripts/hooks/pre-commit b/scripts/hooks/pre-commit new file mode 100755 index 0000000..98385ec --- /dev/null +++ b/scripts/hooks/pre-commit @@ -0,0 +1,22 @@ +#!/bin/sh +# Keeps German code out of this repository — the same rule as in the dashboard +# (its CLAUDE.md). The checker is borrowed from the dashboard this repository is +# a submodule of; CODE_LANGUAGE_ROOT points it at our files, and words only we +# may use (the Java class names of the .fls format) stand in +# scripts/code_language_allow.txt. +# +# Enable: npm run hooks +# Bypass: git commit --no-verify +top="$(git rev-parse --show-toplevel)" +super="$(git rev-parse --show-superproject-working-tree 2>/dev/null)" +checker="$super/scripts/check_code_language.py" +if [ -z "$super" ] || [ ! -f "$checker" ]; then + echo "pre-commit: not inside the dashboard checkout, language check skipped" + exit 0 +fi +CODE_LANGUAGE_ROOT="$top" python3 "$checker" --changed HEAD || { + echo + echo "German code in the commit. Glossary: knowledge/plans/CODE_ENGLISH_REFACTOR.md §3 (dashboard)" + echo "Commit anyway: git commit --no-verify" + exit 1 +} diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 0000000..169e476 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true, + "exactOptionalPropertyTypes": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "declaration": true, + "sourceMap": true, + "composite": true, + "skipLibCheck": true + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..0bc8463 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,4 @@ +{ + "files": [], + "references": [{ "path": "packages/core" }] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..6e6e3bc --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['packages/*/test/**/*.test.ts'], + }, +});