diff --git a/libs/@local/hashql/sdk/typescript-docs/.gitignore b/libs/@local/hashql/sdk/typescript-docs/.gitignore new file mode 100644 index 00000000000..7497a23afd3 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/.gitignore @@ -0,0 +1,4 @@ +.generated/ +.source/ +.twoslash/ +content/docs/reference/ diff --git a/libs/@local/hashql/sdk/typescript-docs/LICENSE.md b/libs/@local/hashql/sdk/typescript-docs/LICENSE.md new file mode 100644 index 00000000000..8ebfe728d7d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/LICENSE.md @@ -0,0 +1,606 @@ +# GNU Affero General Public License + +_Version 3, 19 November 2007_ +_Copyright © 2007 Free Software Foundation, Inc. <>_ + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +## Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: **(1)** assert copyright on the software, and **(2)** offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions + +“This License” refers to version 3 of the GNU Affero General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this +License. Each licensee is addressed as “you”. “Licensees” and +“recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a “modified version” of the +earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based +on the Program. + +To “propagate” a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” +to the extent that it includes a convenient and prominently visible +feature that **(1)** displays an appropriate copyright notice, and **(2)** +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code + +The “source code” for a work means the preferred form of the work +for making modifications to it. “Object code” means any non-source +form of a work. + +A “Standard Interface” means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other +than the work as a whole, that **(a)** is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and **(b)** serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +“Major Component”, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +### 2. Basic Permissions + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +### 4. Conveying Verbatim Copies + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + +- **a)** The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- **b)** The work must carry prominent notices stating that it is + released under this License and any conditions added under section 7. + This requirement modifies the requirement in section 4 to + “keep intact all notices”. +- **c)** You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- **d)** If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +“aggregate” if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + +- **a)** Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- **b)** Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either **(1)** a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or **(2)** access to copy the + Corresponding Source from a network server at no charge. +- **c)** Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- **d)** Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- **e)** Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A “User Product” is either **(1)** a “consumer product”, which means any +tangible personal property which is normally used for personal, family, +or household purposes, or **(2)** anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, “normally used” refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms + +“Additional permissions” are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + +- **a)** Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- **b)** Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- **c)** Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- **d)** Limiting the use for publicity purposes of names of licensors or + authors of the material; or +- **e)** Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- **f)** Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered “further +restrictions” within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +### 8. Termination + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated **(a)** +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and **(b)** permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents + +A “contributor” is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, “control” includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To “grant” such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either **(1)** cause the Corresponding Source to be so +available, or **(2)** arrange to deprive yourself of the benefit of the +patent license for this particular work, or **(3)** arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. “Knowingly relying” means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is “discriminatory” if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license **(a)** in connection with copies of the covered work +conveyed by you (or copies made from those copies), or **(b)** primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +### 13. Remote Network Interaction; Use with the GNU General Public License + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +### 14. Revised Versions of this License + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License “or any later version” applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +### 16. Limitation of Liability + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16 + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. diff --git a/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts b/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts new file mode 100644 index 00000000000..222bd15cb4e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts @@ -0,0 +1,5 @@ +import { createFromSource } from "fumadocs-core/search/server"; + +import { source } from "../../../lib/source"; + +export const { GET } = createFromSource(source, { language: "english" }); diff --git a/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx b/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx new file mode 100644 index 00000000000..d469bcf64c3 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx @@ -0,0 +1,56 @@ +import { + DocsBody, + DocsDescription, + DocsPage, + DocsTitle, +} from "fumadocs-ui/layouts/docs/page"; +import { createRelativeLink } from "fumadocs-ui/mdx"; +import { notFound } from "next/navigation"; + +import { getMDXComponents } from "../../../components/mdx"; +import { source } from "../../../lib/source"; + +import type { Metadata } from "next"; +import type { ReactNode } from "react"; + +interface PageProps { + params: Promise<{ slug?: string[] }>; +} + +export default async function Page({ params }: PageProps): Promise { + const { slug } = await params; + const page = source.getPage(slug); + if (page === undefined) { + notFound(); + } + const Content = page.data.body; + const components = getMDXComponents({ + // oxlint-disable-next-line id-length -- MDX uses HTML tag names as component keys. + a: createRelativeLink(source, page), + }); + return ( + + {page.data.title} + {page.data.description} + {/* Qualified type names may be longer than the mobile viewport. */} + {/* oxlint-disable-next-line react/forbid-component-props -- DocsBody exposes className for content layout. */} + + + + + ); +} + +export const generateStaticParams = (): { slug: string[] }[] => + source.generateParams(); + +export const generateMetadata = async ({ + params, +}: PageProps): Promise => { + const { slug } = await params; + const page = source.getPage(slug); + if (page === undefined) { + notFound(); + } + return { title: page.data.title, description: page.data.description }; +}; diff --git a/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx b/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx new file mode 100644 index 00000000000..432adfdef2f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx @@ -0,0 +1,19 @@ +import { DocsLayout } from "fumadocs-ui/layouts/docs"; + +import { source } from "../../lib/source"; + +import type { ReactNode } from "react"; + +const navigation = { title: "HashQL TypeScript", url: "/docs" }; + +export default function Layout({ + children, +}: { + children: ReactNode; +}): ReactNode { + return ( + + {children} + + ); +} diff --git a/libs/@local/hashql/sdk/typescript-docs/app/global.css b/libs/@local/hashql/sdk/typescript-docs/app/global.css new file mode 100644 index 00000000000..08609751b30 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/global.css @@ -0,0 +1,15 @@ +@import "tailwindcss"; +@import "fumadocs-ui/css/neutral.css"; +@import "fumadocs-ui/css/preset.css"; +@import "fumadocs-twoslash/twoslash.css"; + +/* A name that links to its documentation is underlined, whether or not Twoslash gives it a hover. */ +.twoslash a[href] { + text-decoration-line: underline; + text-decoration-color: color-mix(in oklab, currentColor 35%, transparent); + text-underline-offset: 0.25em; +} + +.twoslash a[href]:hover { + text-decoration-color: currentColor; +} diff --git a/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx b/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx new file mode 100644 index 00000000000..3efe419aa02 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx @@ -0,0 +1,21 @@ +import { RootProvider } from "fumadocs-ui/provider/next"; + +import type { Metadata } from "next"; +import type { ReactNode } from "react"; +import "./global.css"; + +export const metadata: Metadata = { title: "HashQL TypeScript" }; + +export default function Layout({ + children, +}: { + children: ReactNode; +}): ReactNode { + return ( + + + {children} + + + ); +} diff --git a/libs/@local/hashql/sdk/typescript-docs/app/page.tsx b/libs/@local/hashql/sdk/typescript-docs/app/page.tsx new file mode 100644 index 00000000000..03812238ab7 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/page.tsx @@ -0,0 +1,5 @@ +import { redirect } from "next/navigation"; + +export default function Home(): never { + redirect("/docs"); +} diff --git a/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx b/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx new file mode 100644 index 00000000000..e9880dc642c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx @@ -0,0 +1,30 @@ +import { Card } from "fumadocs-ui/components/card"; + +import type { ReactNode } from "react"; + +/** A link to a page or a folder, showing its name and size above the summary its module comment opens with. */ +export const IndexEntry = ({ + name, + count, + href, + children, +}: { + name: string; + count: string; + href: string; + children?: ReactNode; +}): ReactNode => ( + + {name} + + {count} + + + } + > + {children} + +); diff --git a/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx new file mode 100644 index 00000000000..ab114ff0f60 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx @@ -0,0 +1,18 @@ +import { Popup, PopupContent } from "fumadocs-twoslash/ui"; +import defaultComponents from "fumadocs-ui/mdx"; + +import { IndexEntry } from "./index-entry"; +import { ReferenceTrigger } from "./reference-trigger"; + +import type { MDXComponents } from "mdx/types"; + +export const getMDXComponents = ( + components?: MDXComponents, +): MDXComponents => ({ + ...defaultComponents, + IndexEntry, + Popup, + PopupContent, + PopupTrigger: ReferenceTrigger, + ...components, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx b/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx new file mode 100644 index 00000000000..c9e72bf392a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx @@ -0,0 +1,25 @@ +"use client"; + +import { PopupTrigger } from "fumadocs-twoslash/ui"; + +import type { ComponentProps, ReactNode } from "react"; + +export const ReferenceTrigger = ({ + href, + ...props +}: ComponentProps & { href?: string }): ReactNode => { + if (href === undefined) { + return ; + } + return ( + + {props.children} + + } + /> + ); +}; diff --git a/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx b/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx new file mode 100644 index 00000000000..8edc54b8495 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx @@ -0,0 +1,10 @@ +--- +title: HashQL TypeScript +description: Build typed HashQL expressions and programs in TypeScript. +--- + +## API reference + +The [Expression module](./reference/program/Expression) describes symbolic values, their semantic types and input requirements. + +The reference currently covers Expression. Examples construct and print J-Expr; they do not execute graph queries. diff --git a/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json b/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json new file mode 100644 index 00000000000..88a04097d86 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json @@ -0,0 +1,4 @@ +{ + "title": "HashQL TypeScript", + "pages": ["index", "reference"] +} diff --git a/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json new file mode 100644 index 00000000000..3a1f8960f0d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json @@ -0,0 +1,82 @@ +{ + "package": "@local/hashql-typescript-docs", + "dependencies": [ + "@local/hashql", + "@local/oxlint", + "@local/tsconfig" + ], + "tasks": { + "build": { + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ], + "env": [ + "NEXT_TELEMETRY_DISABLED" + ] + }, + "codegen": { + "dependsOn": [ + "doc:transform" + ] + }, + "dev": { + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ], + "cache": false, + "persistent": true, + "env": [ + "NEXT_TELEMETRY_DISABLED", + "PORT" + ] + }, + "doc:analyze": { + "dependsOn": [ + "doc:declarations" + ] + }, + "doc:declarations": { + "dependsOn": [] + }, + "doc:transform": { + "dependsOn": [ + "doc:analyze" + ] + }, + "lint:oxlint": { + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ] + }, + "lint:tsc": { + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ] + }, + "start": { + "dependsOn": [ + "build" + ], + "cache": false, + "persistent": true, + "env": [ + "NEXT_TELEMETRY_DISABLED", + "PORT" + ] + }, + "test:unit": { + "dependsOn": [], + "env": [ + "TEST_COVERAGE" + ] + } + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts b/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts new file mode 100644 index 00000000000..86ce5c31f11 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts @@ -0,0 +1,88 @@ +import { Array, Effect, Option, Struct, flow, pipe } from "effect"; +import { splitTokens } from "shiki/core"; + +import * as CodeBlock from "../src/CodeBlock.js"; + +import type { Element, ElementContent } from "hast"; +import type { ShikiTransformer } from "shiki"; + +const isElement = (node: ElementContent): node is Element => + node.type === "element"; + +// A popup's content is the hover text, which holds no names of the code. +const triggerIn = (node: Element): Option.Option => + pipe( + node.children, + Array.filter(isElement), + Array.filter(({ tagName }) => tagName !== "PopupContent"), + Array.findFirst((child) => + pipe( + child, + Option.liftPredicate(({ tagName }) => tagName === "PopupTrigger"), + Option.orElse(() => triggerIn(child)), + ), + ), + ); + +// Twoslash has replaced a hovered name's text with its popup by now, so its trigger becomes the link and the hover stays. +const link = (node: Element): void => { + for (const child of Array.filter(node.children, isElement)) { + const url = child.properties["data-reference"]; + + if (typeof url === "string") { + delete child.properties["data-reference"]; + Option.match(triggerIn(child), { + onNone: () => { + child.tagName = "a"; + child.properties.href = url; + }, + onSome: (trigger) => { + trigger.properties.href = url; + }, + }); + } else { + link(child); + } + } +}; + +/** Links the names a signature block's meta lists to the pages that document them. Place it after the Twoslash transformer. */ +export const referenceLinks = (): ShikiTransformer => ({ + name: "hashql:reference-links", + tokens(lines) { + const code = pipe( + lines, + Array.map(flow(Array.map(Struct.get("content")), Array.join(""))), + Array.join("\n"), + ); + // A transformer runs synchronously inside Shiki, and a block whose links do not fit its code fails the build. + const links = Effect.runSync( + CodeBlock.place(code, this.options.meta?.__raw ?? ""), + ); + const split = splitTokens( + lines, + Array.flatMap(links, ({ start, end }) => [start, end]), + ); + + // Shiki copies a token's attributes onto the element it renders. + for (const token of Array.flatten(split)) { + const found = Array.findFirst( + links, + ({ start, end }) => + start <= token.offset && token.offset + token.content.length <= end, + ); + + if (Option.isSome(found)) { + token.htmlAttrs = { + ...token.htmlAttrs, + "data-reference": found.value.url, + }; + } + } + + return split; + }, + code(code) { + link(code); + }, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/lib/source.ts b/libs/@local/hashql/sdk/typescript-docs/lib/source.ts new file mode 100644 index 00000000000..c0e7f60ee36 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/lib/source.ts @@ -0,0 +1,8 @@ +import { loader } from "fumadocs-core/source"; + +import { docs } from "../.source/server"; + +export const source = loader({ + baseUrl: "/docs", + source: docs.toFumadocsSource(), +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/next.config.mjs b/libs/@local/hashql/sdk/typescript-docs/next.config.mjs new file mode 100644 index 00000000000..1439b40dd5a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/next.config.mjs @@ -0,0 +1,10 @@ +import path from "node:path"; + +import { createMDX } from "fumadocs-mdx/next"; + +export default createMDX()({ + reactStrictMode: true, + serverExternalPackages: ["typescript"], + outputFileTracingRoot: path.resolve(import.meta.dirname, "../../../../.."), + devIndicators: false, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts new file mode 100644 index 00000000000..15650184fbc --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -0,0 +1,82 @@ +import { defineConfig } from "@local/oxlint"; + +export default defineConfig({ + runtime: "node", + frameworks: ["react", "next", "effect", "vitest"], + ignorePatterns: [".next/**", ".source/**", "next-env.d.ts"], + overrides: [ + { + files: ["src/cli.ts"], + rules: { + "vitest/require-hook": "allow", // The CLI entry point runs its command when imported; it is not a test file. + }, + }, + { + files: ["src/**/*.ts"], + rules: { + "unicorn/filename-case": [ + "deny", // filename casing follows Effect style + { cases: { pascalCase: true, kebabCase: true } }, + ], + }, + }, + { + files: ["*.config.mjs", "source.config.ts"], + rules: { + "effecttsgo/node-builtin-import": "allow", // Next.js and Fumadocs load these modules outside any Effect runtime that could provide FileSystem or Path. + "effecttsgo/schema-sync": "allow", // Next.js and Fumadocs evaluate a configuration module synchronously, and a malformed input should fail its load. + }, + }, + { + files: ["app/**/*.tsx", "*.config.mjs"], + rules: { + "import/no-default-export": "allow", // Next.js and PostCSS discover default exports. + }, + }, + { + files: ["app/**/*.tsx", "components/**/*.tsx"], + rules: { + "react/react-in-jsx-scope": "allow", // Next.js uses the automatic JSX runtime. + "react/jsx-filename-extension": ["deny", { extensions: [".tsx"] }], // This TypeScript app uses TSX. + "react/only-export-components": "allow", // Next.js discovers metadata and static parameter exports. + "oxc/no-async-await": "allow", // Server components await route parameters and syntax highlighting. + "effecttsgo/async-function": "allow", // Next.js calls server components and metadata functions as async functions. + }, + }, + { + files: ["components/**/*.tsx"], + rules: { + "react/function-component-definition": [ + "deny", // Match the repository's function-expression style. + { namedComponents: "arrow-function" }, + ], + }, + }, + { + files: ["components/reference-trigger.tsx"], + rules: { + "react/jsx-props-no-spreading": "allow", // Forward Base UI's trigger events, accessibility attributes and children. + "react-perf/jsx-no-jsx-as-prop": "allow", // Base UI's public render prop accepts the replacement element. + "jsx-a11y/no-redundant-roles": "allow", // The link role overrides Base UI's non-native button role. + }, + }, + { + files: ["components/index-entry.tsx"], + rules: { + "react-perf/jsx-no-jsx-as-prop": "allow", // Fumadocs' Card takes its title as a node, which carries the count beside the name. These server components render once. + }, + }, + { + files: ["lib/reference-links.ts"], + rules: { + "no-underscore-dangle": ["deny", { allow: ["__raw"] }], // Shiki exposes a code block's meta string under this public field name. + }, + }, + { + files: ["app/layout.tsx"], + rules: { + "import/no-unassigned-import": "allow", // The root layout loads global CSS. + }, + }, + ], +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json new file mode 100644 index 00000000000..68f8943c3cc --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -0,0 +1,68 @@ +{ + "name": "@local/hashql-typescript-docs", + "version": "0.0.0-private", + "private": true, + "description": "TypeScript SDK reference for HashQL", + "license": "AGPL-3", + "type": "module", + "scripts": { + "build": "next build --webpack", + "codegen": "fumadocs-mdx", + "dev": "next dev --webpack --hostname 127.0.0.1 --port ${PORT:-4398}", + "doc:analyze": "tsx src/cli.ts analyze --lib ../typescript --entry .=.generated/declarations/main.d.ts --entry ./draft=.generated/declarations/draft/index.d.ts", + "doc:declarations": "tsc --project tsconfig.api.json", + "doc:transform": "tsx src/cli.ts transform --lib ../typescript && oxfmt content/docs/reference", + "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", + "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", + "lint:tsc": "tsc --noEmit", + "start": "next start --hostname 127.0.0.1 --port ${PORT:-4398}", + "test:unit": "vitest run" + }, + "dependencies": { + "@fumadocs/satteri": "0.5.1", + "@local/hashql": "workspace:*", + "fumadocs-core": "16.16.2", + "fumadocs-mdx": "15.4.6", + "fumadocs-twoslash": "4.0.1", + "fumadocs-ui": "16.16.2", + "next": "16.3.8", + "react": "19.2.6", + "react-dom": "19.2.6", + "satteri": "0.10.5" + }, + "devDependencies": { + "@effect/platform-node": "4.0.3", + "@effect/vitest": "4.0.3", + "@local/oxlint": "workspace:*", + "@local/tsconfig": "workspace:*", + "@microsoft/api-extractor": "7.59.4", + "@microsoft/api-extractor-model": "7.33.15", + "@microsoft/tsdoc": "0.17.1", + "@microsoft/tsdoc-config": "0.18.3", + "@tailwindcss/postcss": "4.3.3", + "@tsconfig/bases": "catalog:", + "@types/hast": "3.0.5", + "@types/mdast": "4.0.4", + "@types/mdx": "2.0.14", + "@types/node": "catalog:", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "effect": "4.0.3", + "mdast-util-mdx-jsx": "3.1.3", + "oxc-parser": "0.152.0", + "oxc-resolver": "11.24.2", + "oxfmt": "0.71.0", + "oxlint": "catalog:", + "remark-frontmatter": "5.0.0", + "remark-mdx": "3.1.1", + "remark-stringify": "11.0.0", + "shiki": "4.5.0", + "tailwindcss": "4.3.3", + "tsx": "catalog:", + "typescript": "catalog:", + "unified": "11.0.5", + "vite": "catalog:", + "vitest": "catalog:", + "yaml": "2.9.1" + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs b/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs new file mode 100644 index 00000000000..d062fcdae9d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs @@ -0,0 +1,2 @@ +const config = { plugins: { "@tailwindcss/postcss": {} } }; +export default config; diff --git a/libs/@local/hashql/sdk/typescript-docs/source.config.ts b/libs/@local/hashql/sdk/typescript-docs/source.config.ts new file mode 100644 index 00000000000..a6732606197 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/source.config.ts @@ -0,0 +1,47 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { Schema } from "effect"; +import { rehypeCodeDefaultOptions } from "fumadocs-core/mdx-plugins"; +import { defineConfig, defineDocs } from "fumadocs-mdx/config"; +import { transformerTwoslash } from "fumadocs-twoslash"; + +import { referenceLinks } from "./lib/reference-links.js"; + +// Signature blocks compile against the declaration files `doc:declarations` emits, which they name through `#declarations/`. +const ApiConfig = Schema.fromJsonString( + Schema.Struct({ compilerOptions: Schema.Struct({ outDir: Schema.String }) }), +); +const declarations = path.resolve( + Schema.decodeSync(ApiConfig)(readFileSync("tsconfig.api.json", "utf8")) + .compilerOptions.outDir, +); + +export const docs = defineDocs({ + dir: "content/docs", + docs: { compiler: "satteri" }, +}); + +export default defineConfig({ + compiler: "satteri", + satteriOptions: { + rehypeCodeOptions: { + themes: { light: "github-light", dark: "github-dark" }, + langs: ["js", "jsx", "ts", "tsx"], + transformers: [ + ...(rehypeCodeDefaultOptions.transformers ?? []), + transformerTwoslash({ + twoslashOptions: { + compilerOptions: { + types: ["node"], + paths: { "#declarations/*": [`${declarations}/*`] }, + }, + }, + // Hovers show the compiler's types. The page beside them carries the documentation. + rendererRich: { jsdoc: false }, + }), + referenceLinks(), + ], + }, + }, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts new file mode 100644 index 00000000000..e7d25230ee6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts @@ -0,0 +1,282 @@ +import { ApiDeclaredItem, ApiModel } from "@microsoft/api-extractor-model"; +import { TSDocConfiguration, TSDocParser } from "@microsoft/tsdoc"; +import { TSDocConfigFile } from "@microsoft/tsdoc-config"; +import { + Array, + Cache, + Context, + Effect, + FileSystem, + Layer, + Option, + Path, + Schema, + Struct, + flow, + pipe, +} from "effect"; + +import { Sources } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +import type { ApiEntryPoint, ApiItem } from "@microsoft/api-extractor-model"; +import type { DocComment } from "@microsoft/tsdoc"; + +/** The part of a declaration map that names the source TypeScript emitted the file from. */ +const DeclarationMap = Schema.fromJsonString( + Schema.Struct({ + sources: Schema.NonEmptyArray(Schema.String), + sourceRoot: Schema.optionalKey(Schema.String), + }), +); + +// TypeScript's declaration emit renames each source extension this way. +const declarationExtensions: readonly (readonly [string, string])[] = [ + [".d.ts", ".d.ts"], + [".mts", ".d.mts"], + [".cts", ".d.cts"], + [".tsx", ".d.ts"], + [".ts", ".d.ts"], +]; + +/** A subpath that a package's `exports` names: `.` for the package itself, otherwise `./` followed by a path. A pattern with `*` names no single entry point. */ +export const Subpath = Schema.String.pipe( + Schema.check(Schema.isPattern(/^\.(?:\/[^/*]+)*$/u)), +); + +/** The file `analyze` writes beside the models, which names each entry point it analyzed. */ +export const manifestFile = "entry-points.json"; + +/** The entry points `analyze` analyzed, in the order it received them. Paths are relative to the manifest's directory. */ +export const Manifest = Schema.fromJsonString( + Schema.NonEmptyArray( + Schema.Struct({ + subpath: Subpath, + /** API Extractor's model of the entry point. */ + model: Schema.String, + /** The declaration file the model was extracted from. */ + declaration: Schema.String, + }), + ), + { space: 2 }, +); + +/** An entry point of the analyzed package. */ +export interface EntryPoint { + /** The subpath the package exports it at. */ + readonly subpath: string; + /** API Extractor's model of the entry point, whose members are its exports. */ + readonly model: ApiEntryPoint; + /** The source module TypeScript emitted the entry point's declaration file from. */ + readonly module: string; +} + +/** The output of the `analyze` command, with what the pages need to find their way back to the sources. */ +export class Analysis extends Context.Service< + Analysis, + { + /** The analyzed package's name. */ + readonly name: string; + /** The package's entry points, in the order `analyze` received them. */ + readonly entryPoints: Array.NonEmptyReadonlyArray; + /** The directory TypeScript emitted the declaration files into. The first entry point's file sits at its top, and the tree below mirrors the sources. */ + readonly declarationRoot: string; + /** The source file that declares an item. */ + readonly sourceOf: (item: ApiItem) => Option.Option; + /** The declaration file emitted from a source module. */ + readonly declarationOf: ( + source: string, + ) => Effect.Effect; + /** Parses a module's first JSDoc comment that carries `@module`, with the TSDoc configuration the analysis used. */ + readonly moduleComment: ( + source: string, + ) => Effect.Effect, TransformError>; + } +>()("@local/hashql-typescript-docs/Analysis") {} + +export interface Options { + /** The analyzed package's folder, which the model's file paths are relative to. */ + readonly lib: string; + /** The directory `analyze` wrote. */ + readonly analysis: string; +} + +const loadModel = Effect.fnUntraced(function* (file: string) { + const apiPackage = yield* Effect.try(() => + new ApiModel().loadPackage(file), + ).pipe( + Effect.mapError((cause) => TransformError.unreadableModel(file, cause)), + ); + + const entry = yield* pipe( + Array.head(apiPackage.entryPoints), + Effect.fromOption, + Effect.mapError(() => + TransformError.malformedAnalysis(`${file} has no entry point`), + ), + ); + + return { apiPackage, entry }; +}); + +// API Extractor reads `/tsdoc.json`, so comments outside the model parse with the same tags. +const loadParser = Effect.fnUntraced(function* (lib: string) { + const configFile = TSDocConfigFile.loadForFolder(lib); + + if (configFile.hasErrors) { + return yield* TransformError.malformedAnalysis( + configFile.getErrorSummary(), + ); + } + + const configuration = new TSDocConfiguration(); + configFile.configureParser(configuration); + + return new TSDocParser(configuration); +}); + +const sourceOfDeclaration = Effect.fnUntraced( + function* (declaration: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const mapPath = `${declaration}.map`; + const text = yield* fs.readFileString(mapPath); + + const map = yield* Schema.decodeEffect(DeclarationMap)(text).pipe( + Effect.mapError((cause) => + TransformError.malformedSourceMap(mapPath, cause), + ), + ); + + return path.resolve( + path.dirname(mapPath), + map.sourceRoot ?? "", + map.sources[0], + ); + }, + Effect.catchTag("PlatformError", TransformError.fileSystem), +); + +const loadManifest = Effect.fnUntraced( + function* (analysis: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const file = path.join(analysis, manifestFile); + const text = yield* fs.readFileString(file); + + const manifest = yield* Schema.decodeEffect(Manifest)(text).pipe( + Effect.mapError((cause) => TransformError.malformedManifest(file, cause)), + ); + + return Array.map(manifest, ({ subpath, model, declaration }) => ({ + subpath, + model: path.resolve(analysis, model), + declaration: path.resolve(analysis, declaration), + })); + }, + Effect.catchTag("PlatformError", TransformError.fileSystem), +); + +export const layer = ({ + lib, + analysis, +}: Options): Layer.Layer< + Analysis, + TransformError, + FileSystem.FileSystem | Path.Path | Sources +> => + Layer.effect( + Analysis, + Effect.gen(function* () { + const path = yield* Path.Path; + const sources = yield* Sources; + const services = yield* Effect.context< + FileSystem.FileSystem | Path.Path + >(); + + const parser = yield* loadParser(lib); + const manifest = yield* loadManifest(analysis); + const loaded = yield* Effect.forEach( + manifest, + Effect.fnUntraced(function* ({ subpath, model, declaration }) { + const { apiPackage, entry } = yield* loadModel(model); + const source = yield* sourceOfDeclaration(declaration); + + return { + name: apiPackage.name, + declaration, + entryPoint: { + subpath, + model: entry, + module: source, + } satisfies EntryPoint, + }; + }), + ); + const first = Array.headNonEmpty(loaded); + const rootSource = first.entryPoint.module; + const declarationRoot = path.dirname(first.declaration); + + // The emit mirrors the source tree, so the first entry point locates every other declaration file, and each one's map confirms it. + const declarations = yield* Cache.make({ + capacity: Number.POSITIVE_INFINITY, + lookup: Effect.fnUntraced(function* (source: string) { + const relative = path.relative(path.dirname(rootSource), source); + const [extension, emitted] = Array.findFirst( + declarationExtensions, + ([candidate]) => relative.endsWith(candidate), + ).pipe(Option.getOrElse(() => ["", ".d.ts"] as const)); + + const declaration = path.join( + declarationRoot, + `${relative.slice(0, relative.length - extension.length)}${emitted}`, + ); + + const declSource = yield* sourceOfDeclaration(declaration); + if (declSource !== source) { + return yield* TransformError.malformedAnalysis( + `${declaration} was not emitted from ${source}`, + ); + } + + return declaration; + }, Effect.provide(services)), + }); + + return Analysis.of({ + name: first.name, + entryPoints: Array.map(loaded, Struct.get("entryPoint")), + declarationRoot, + sourceOf: (item) => { + if (item instanceof ApiDeclaredItem) { + return Option.fromNullishOr(item.fileUrlPath).pipe( + Option.map((file) => path.resolve(lib, file)), + ); + } + + return Option.none(); + }, + declarationOf: (source) => Cache.get(declarations, source), + moduleComment: (source) => + sources.scope(source).pipe( + Effect.map(({ comments, text }) => + Array.findFirst( + comments, + flow( + Option.liftPredicate(({ value }) => value.startsWith("*")), + Option.map( + ({ start, end }) => + parser.parseString(text.slice(start, end)).docComment, + ), + Option.filter((parsed) => + parsed.modifierTagSet.hasTagName("@module"), + ), + ), + ), + ), + ), + }); + }), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts new file mode 100644 index 00000000000..6c45ec09465 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts @@ -0,0 +1,174 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable +import { + Extractor, + ExtractorConfig, + ExtractorLogLevel, +} from "@microsoft/api-extractor"; +import { + Array, + Data, + Effect, + FileSystem, + Option, + Path, + Record, + Schema, + flow, +} from "effect"; +import { Command, Flag } from "effect/cli"; + +import * as Analysis from "./Analysis.js"; + +import type { IConfigFile } from "@microsoft/api-extractor"; + +const makeExtractorConfig = ({ + lib, + entry, + model, +}: { + lib: string; + entry: string; + model: string; +}): IConfigFile => ({ + projectFolder: lib, + mainEntryPointFilePath: entry, + compiler: { + tsconfigFilePath: "/tsconfig.json", + }, + apiReport: { + enabled: false, + }, + docModel: { + enabled: true, + apiJsonFilePath: model, + }, + dtsRollup: { + enabled: false, + }, + tsdocMetadata: { + enabled: false, + }, + // `prepare` merges no defaults into a config object, which means we need to supply it manually + messages: { + compilerMessageReporting: { + default: { logLevel: ExtractorLogLevel.Warning }, + }, + extractorMessageReporting: { + default: { logLevel: ExtractorLogLevel.Warning }, + "ae-undocumented": { logLevel: ExtractorLogLevel.None }, + "ae-wrong-input-file-type": { logLevel: ExtractorLogLevel.Error }, + }, + tsdocMessageReporting: { + default: { logLevel: ExtractorLogLevel.Warning }, + }, + }, +}); + +/** API Extractor finished analyzing an entry point and reported errors. */ +export class ExtractionError extends Data.TaggedError("ExtractionError")<{ + readonly subpath: string; + readonly errorCount: number; + readonly warningCount: number; +}> {} + +export const command = Command.make("analyze", { + lib: Flag.Directory("lib"), + entry: Flag.KeyValuePair("entry").pipe( + Flag.withDescription( + "An export subpath and the declaration file TypeScript emitted for it, such as `./draft=`. The first entry's file sits at the top of the emit", + ), + // `KeyValuePair` requires a pair, though its type does not say so. + Flag.filterMap( + flow(Record.toEntries, Option.liftPredicate(Array.isArrayNonEmpty)), + () => "Expected at least one entry point", + ), + Flag.withSchema( + Schema.NonEmptyArray(Schema.Tuple([Analysis.Subpath, Schema.String])), + ), + ), + out: Flag.Directory("out").pipe( + Flag.withDefault( + Effect.suspend(() => + Path.Path.pipe( + Effect.map((path) => + path.resolve(import.meta.dirname, "..", ".generated"), + ), + ), + ), + ), + ), +}); + +// API Extractor analyzes a single entry point per run, and merging several into one module would collide where two of them export the same name. +const extract = Effect.fnUntraced(function* ({ + lib, + subpath, + entry, + model, +}: { + lib: string; + subpath: string; + entry: string; + model: string; +}) { + const path = yield* Path.Path; + + // May throw when `/tsdoc.json` is invalid, or when the entry is not a declaration file that exists. + const extractorConfig = yield* Effect.try(() => + ExtractorConfig.prepare({ + configObject: makeExtractorConfig({ lib, entry, model }), + configObjectFullPath: undefined, + packageJsonFullPath: path.join(lib, "package.json"), + }), + ); + + return yield* Effect.try(() => + Extractor.invoke(extractorConfig, { localBuild: true }), + ).pipe( + Effect.filterOrFail( + ({ succeeded }) => succeeded, + ({ errorCount, warningCount }) => + new ExtractionError({ subpath, errorCount, warningCount }), + ), + ); +}); + +export const handler = command.pipe( + Command.withHandler( + Effect.fnUntraced(function* ({ lib, entry, out }) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const libPath = path.resolve(lib); + const outPath = path.resolve(out); + + yield* fs.makeDirectory(outPath, { recursive: true }); + + const entryPoints = yield* Effect.forEach( + entry, + Effect.fnUntraced(function* ([subpath, file], index) { + const declaration = path.resolve(file); + const model = path.join(outPath, "api", `${index}.json`); + + yield* extract({ lib: libPath, subpath, entry: declaration, model }); + + return { + subpath, + model: path.relative(outPath, model), + declaration: path.relative(outPath, declaration), + }; + }), + ); + + const manifest = yield* Schema.encodeEffect(Analysis.Manifest)( + entryPoints, + ); + yield* fs.writeFileString( + path.join(outPath, Analysis.manifestFile), + manifest, + ); + + return "Ok"; + }), + ), +); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts new file mode 100644 index 00000000000..be41254e7c0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "@effect/vitest"; +import { Effect, Option } from "effect"; + +import * as CodeBlock from "./CodeBlock.js"; + +const urls: readonly Option.Option[] = [ + Option.some("/docs/reference/type/Type"), + Option.some('/docs/reference/type/Type#"quoted" and spaced'), + Option.none(), +]; + +describe("code_block", () => { + it.effect("urls_round_trip", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + + expect(yield* CodeBlock.urls(meta)).toStrictEqual(Option.some(urls)); + }), + ); + + // Fumadocs removes the attributes it knows and hands the rest to transformers. + it.effect("urls_beside_other_attributes", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + + expect( + yield* CodeBlock.urls(`title="Example" ${meta} lineNumbers`), + ).toStrictEqual(Option.some(urls)); + }), + ); + + it.effect("urls_absent", () => + Effect.gen(function* () { + expect(yield* CodeBlock.urls('twoslash title="Example"')).toStrictEqual( + Option.none(), + ); + }), + ); + + it.effect("urls_malformed", () => + Effect.gen(function* () { + const error = yield* Effect.flip(CodeBlock.urls('links="%5B%7B%7D%5D"')); + + expect(error.reason._tag).toBe("UnreadableCodeBlock"); + }), + ); + + // The formatter re-indents and wraps the code, and the names keep their order. + it.effect("place_after_formatting", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + const code = ["declare const value: Type.Any<", " Missing", ">;"].join( + "\n", + ); + + expect( + Array.from( + yield* CodeBlock.place(code, meta), + ({ start, end, url }) => [code.slice(start, end), url], + ), + ).toStrictEqual([ + ["Type", "/docs/reference/type/Type"], + ["Any", '/docs/reference/type/Type#"quoted" and spaced'], + ]); + }), + ); + + it.effect("place_misaligned", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + const error = yield* Effect.flip( + CodeBlock.place("declare const value: Type;", meta), + ); + + expect(error.reason).toMatchObject({ + _tag: "MisalignedCodeBlock", + references: 1, + links: 3, + }); + }), + ); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts new file mode 100644 index 00000000000..ee4eeca5017 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts @@ -0,0 +1,119 @@ +/** + * The code blocks that show a member's signature. + * + * Twoslash compiles each block whole, so the declarations its hovers need sit above a cut, and the page shows only the statements below it. The block's meta lists, for each name the statements refer to and in their order, the URL that documents it. The docs site formats the code before it highlights it, so it finds the names again in the formatted code and pairs them with that list. + * + * @module + */ +import { Array, Effect, Filter, Function, Option, Schema, pipe } from "effect"; +import { parseCodeBlockAttributes } from "fumadocs-core/mdx-plugins/codeblock-utils"; + +import * as References from "./References.js"; +import { parse } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +/** A span of the shown code that names a documented declaration, and the URL that documents it. */ +export interface Link { + readonly start: number; + readonly end: number; + readonly url: string; +} + +// `null` stands for a name that nothing on the site documents. +const Urls = Schema.fromJsonString( + Schema.Array(Schema.OptionFromNullOr(Schema.String)), +); + +const attribute = "links"; + +/** The line above which Twoslash compiles a block without showing it. */ +export const cut = "// ---cut---"; + +// Percent-encoding leaves the JSON without the quotes and spaces that would end the attribute. +/** A signature block's meta: Twoslash's trigger and, for each name the code refers to, its URL. */ +export const meta = ( + urls: readonly Option.Option[], +): Effect.Effect => + pipe( + urls, + Schema.encodeEffect(Urls), + Effect.map( + (encoded) => `twoslash ${attribute}="${encodeURIComponent(encoded)}"`, + ), + ); + +/** The URLs a code block's meta carries, `None` for a block that is not a signature. */ +export const urls = ( + blockMeta: string, +): Effect.Effect< + Option.Option[]>, + TransformError +> => + pipe( + parseCodeBlockAttributes(blockMeta, [attribute]).attributes[attribute], + Option.fromUndefinedOr, + Option.match({ + onNone: () => Effect.succeedNone, + onSome: (value) => + pipe( + value, + Schema.decodeUnknownEffect(Schema.String), + Effect.flatMap((encoded) => + Effect.try(() => decodeURIComponent(encoded)), + ), + Effect.flatMap(Schema.decodeEffect(Urls)), + Effect.mapError(TransformError.unreadableCodeBlock), + Effect.asSome, + ), + }), + ); + +const placeIn = ( + code: string, + blockMeta: string, +): Effect.Effect => + pipe( + blockMeta, + urls, + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed([]), + onSome: (listed) => + pipe( + code, + parse("signature.d.ts"), + Effect.map(({ program }) => References.of(program)), + Effect.filterOrFail( + (references) => references.length === listed.length, + (references) => + TransformError.misalignedCodeBlock( + references.length, + listed.length, + ), + ), + Effect.map((references) => + Array.filterMap( + Array.zip(references, listed), + Filter.fromPredicateOption(([{ start, end }, url]) => + Option.map( + url, + (found): Link => ({ start, end, url: found }), + ), + ), + ), + ), + ), + }), + ), + ); + +/** Pairs a signature block's URLs, from its meta, with the names its shown code refers to, and keeps the names that have one. */ +export const place: { + ( + blockMeta: string, + ): (code: string) => Effect.Effect; + ( + code: string, + blockMeta: string, + ): Effect.Effect; +} = Function.dual(2, placeIn); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts new file mode 100644 index 00000000000..275d7be27ab --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, layer } from "@effect/vitest"; +import { + StandardTags, + TSDocConfiguration, + TSDocParser, + TSDocTagDefinition, + TSDocTagSyntaxKind, +} from "@microsoft/tsdoc"; +import { Array, Effect, Layer, Option, pipe } from "effect"; + +import * as Comment from "./Comment.js"; + +import type { DocBlock, DocComment } from "@microsoft/tsdoc"; + +// The SDK's `tsdoc.json` defines `@since`, and the analysis parses with it. +const configuration = (): TSDocConfiguration => { + const result = new TSDocConfiguration(); + result.addTagDefinition( + new TSDocTagDefinition({ + tagName: "@since", + syntaxKind: TSDocTagSyntaxKind.BlockTag, + }), + ); + + return result; +}; + +const parse = (lines: readonly string[]): DocComment => + new TSDocParser(configuration()).parseString( + pipe( + ["/**", ...lines.map((line) => ` * ${line}`), " */"], + Array.join("\n"), + ), + ).docComment; + +const firstExample = (lines: readonly string[]): Effect.Effect => + pipe( + Comment.blocksTagged(parse(lines), StandardTags.example.tagName), + Array.head, + Effect.fromOption, + Effect.orDie, + ); + +// Only `Known` names something on a page. +const links: Layer.Layer = Layer.succeed( + Comment.Links, + Comment.Links.of({ + resolve: (reference) => + Effect.succeed( + Option.liftPredicate( + "/docs/known", + () => reference.emitAsTsdoc() === "Known", + ), + ), + }), +); + +describe("comment", () => { + layer(links)((it) => { + it.effect("summary_links", () => + Effect.gen(function* () { + const blocks = yield* Comment.section( + parse([ + "See {@link Known}, {@link Unknown} and {@link Known | this}.", + ]).summarySection, + ); + + expect(blocks).toStrictEqual([ + { + type: "paragraph", + children: [ + { type: "text", value: "See " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "inlineCode", value: "Known" }], + }, + { type: "text", value: ", " }, + { type: "inlineCode", value: "Unknown" }, + { type: "text", value: " and " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "text", value: "this" }], + }, + { type: "text", value: "." }, + ], + }, + ]); + }), + ); + + it.effect("summary_unparsed_syntax", () => + Effect.gen(function* () { + const blocks = yield* Comment.section( + parse(["Accepts {a: 1} and links {@link type}."]).summarySection, + ); + + expect(blocks).toStrictEqual([ + { + type: "paragraph", + children: [ + { type: "text", value: "Accepts " }, + { type: "text", value: "{" }, + { type: "text", value: "a: 1" }, + { type: "text", value: "}" }, + { type: "text", value: " and links " }, + { type: "inlineCode", value: "type" }, + { type: "text", value: "." }, + ], + }, + ]); + }), + ); + + it.effect("example_caption", () => + Effect.gen(function* () { + const example = yield* firstExample([ + "Summary.", + "", + "@example Build a {@link Known}.", + "```ts", + "const value = 1;", + "```", + ]); + + expect(yield* Comment.example(example)).toStrictEqual({ + caption: [ + { type: "text", value: "Build a " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "inlineCode", value: "Known" }], + }, + { type: "text", value: "." }, + ], + content: [{ type: "code", lang: "ts", value: "const value = 1;" }], + }); + }), + ); + + it.effect("example_without_caption", () => + Effect.gen(function* () { + const example = yield* firstExample([ + "@example", + "```", + "plain", + "```", + ]); + + expect(yield* Comment.example(example)).toStrictEqual({ + caption: [], + content: [{ type: "code", lang: null, value: "plain" }], + }); + }), + ); + + it("words", () => { + expect( + pipe( + Comment.blocksTagged(parse(["@since `4.0.0` beta"]), "@since"), + Array.head, + Option.map(({ content }) => Comment.words(content)), + ), + ).toStrictEqual(Option.some("4.0.0 beta")); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts new file mode 100644 index 00000000000..3e603737f62 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts @@ -0,0 +1,317 @@ +import { + DocCodeSpan, + DocErrorText, + DocEscapedText, + DocFencedCode, + DocHtmlEndTag, + DocHtmlStartTag, + DocInlineTag, + DocLinkTag, + DocNodeTransforms, + DocParagraph, + DocPlainText, + DocSoftBreak, + StandardTags, +} from "@microsoft/tsdoc"; +import { + Array, + Context, + Effect, + Filter, + Function, + Match, + Option, + String, + Tuple, + flow, + pipe, +} from "effect"; + +import { TransformError } from "./TransformError.js"; + +import type { + DocBlock, + DocComment, + DocDeclarationReference, + DocNode, + DocSection, +} from "@microsoft/tsdoc"; +import type { BlockContent, PhrasingContent } from "mdast"; + +/** Resolves declaration references in the comment under conversion, as its own module sees them. */ +export class Links extends Context.Service< + Links, + { + /** The URL of what a reference names, `None` when it names nothing on a page. */ + readonly resolve: ( + reference: DocDeclarationReference, + ) => Effect.Effect>; + } +>()("@local/hashql-typescript-docs/Comment/Links") {} + +/** An `@example` block split at its ``. The caption is empty when the block opens without one. */ +export interface Example { + readonly caption: readonly PhrasingContent[]; + readonly content: readonly BlockContent[]; +} + +const linkTagNames: ReadonlySet = new Set([ + StandardTags.link.tagName, + "@linkcode", + "@linkplain", +]); + +// TSDoc parses a link whose reference it cannot read as a generic inline tag. +const isUnparsedLink = (node: DocNode): node is DocInlineTag => + node instanceof DocInlineTag && linkTagNames.has(node.tagName); + +const isParagraph = (node: DocNode | undefined): node is DocParagraph => + node instanceof DocParagraph; + +const text = (value: string): PhrasingContent => ({ type: "text", value }); + +const inlineCode = (value: string): PhrasingContent => ({ + type: "inlineCode", + value, +}); + +const linkLabel = (tag: DocLinkTag): PhrasingContent => { + if (tag.linkText !== undefined) { + return text(tag.linkText); + } + + return inlineCode( + tag.codeDestination?.emitAsTsdoc() ?? tag.urlDestination ?? "", + ); +}; + +const destination = Effect.fnUntraced(function* (tag: DocLinkTag) { + const links = yield* Links; + + if (tag.urlDestination !== undefined) { + return Option.some(tag.urlDestination); + } + + if (tag.codeDestination !== undefined) { + return yield* links.resolve(tag.codeDestination); + } + + return Option.none(); +}); + +const link = (tag: DocLinkTag): Effect.Effect => + pipe( + tag, + destination, + Effect.map( + Option.match({ + onNone: () => linkLabel(tag), + onSome: (url): PhrasingContent => ({ + type: "link", + url, + children: [linkLabel(tag)], + }), + }), + ), + ); + +// TSDoc keeps the characters it could not parse as error text, and the analysis reports each at its source line. +const phrasing: ( + node: DocNode, +) => Effect.Effect = + Match.type().pipe( + Match.when(Match.instanceOf(DocPlainText), ({ text: value }) => + Effect.succeed(text(value)), + ), + Match.when(Match.instanceOf(DocSoftBreak), () => Effect.succeed(text(" "))), + Match.when(Match.instanceOf(DocCodeSpan), ({ code }) => + Effect.succeed(inlineCode(code)), + ), + Match.when(Match.instanceOf(DocEscapedText), ({ decodedText }) => + Effect.succeed(text(decodedText)), + ), + Match.when(Match.instanceOf(DocErrorText), ({ text: value }) => + Effect.succeed(text(value)), + ), + Match.when(Match.instanceOf(DocLinkTag), link), + Match.when(isUnparsedLink, ({ tagContent }) => + Effect.succeed(inlineCode(tagContent.trim())), + ), + Match.orElse(({ kind }) => + Effect.fail(TransformError.unsupportedComment(kind)), + ), + ); + +/** Converts a TSDoc paragraph to mdast phrasing content, with its spacing collapsed. */ +export const paragraph = ( + node: DocParagraph, +): Effect.Effect => + pipe( + DocNodeTransforms.trimSpacesInParagraph(node).getChildNodes(), + Effect.forEach(phrasing), + ); + +const block: ( + node: DocNode, +) => Effect.Effect = + Match.type().pipe( + Match.when(Match.instanceOf(DocParagraph), (child) => + paragraph(child).pipe( + Effect.map((children): BlockContent[] => { + if (Array.isReadonlyArrayNonEmpty(children)) { + return [{ type: "paragraph", children }]; + } + + return []; + }), + ), + ), + Match.when(Match.instanceOf(DocFencedCode), ({ language, code }) => + Effect.succeed([ + { + type: "code", + lang: Option.getOrNull( + Option.liftPredicate(language, String.isNonEmpty), + ), + value: code.trimEnd(), + }, + ]), + ), + Match.orElse(({ kind }) => + Effect.fail(TransformError.unsupportedComment(kind)), + ), + ); + +/** Converts block-level TSDoc nodes to mdast blocks. */ +export const blocks: ( + nodes: Iterable, +) => Effect.Effect = flow( + Effect.forEach(block), + Effect.map(Array.flatten), +); + +/** Converts a TSDoc section to mdast blocks. */ +export const section = ( + node: DocSection, +): Effect.Effect => + blocks(node.getChildNodes()); + +/** A comment's summary and remarks, the prose that introduces what it documents. */ +export const overview = ( + comment: DocComment, +): Effect.Effect => + pipe( + [ + section(comment.summarySection), + blocks(Array.fromNullishOr(comment.remarksBlock?.content)), + ], + Effect.all, + Effect.map(Array.flatten), + ); + +/** The first paragraph of a comment's summary, which stands for it in a list. */ +export const lead = ( + comment: DocComment, +): Effect.Effect => + pipe( + comment.summarySection.getChildNodes(), + Array.head, + Option.filter(isParagraph), + Option.match({ + onNone: () => Effect.succeed([]), + onSome: paragraph, + }), + ); + +/** The custom blocks of a comment that carry one tag, in source order. */ +export const blocksTagged: { + (tagName: string): (comment: DocComment) => readonly DocBlock[]; + (comment: DocComment, tagName: string): readonly DocBlock[]; +} = Function.dual( + 2, + (comment: DocComment, tagName: string): readonly DocBlock[] => + pipe( + comment.customBlocks, + Array.filter( + ({ blockTag }) => + blockTag.tagNameWithUpperCase === String.toUpperCase(tagName), + ), + ), +); + +/** The words of a section, for tags whose value is a name or a version rather than prose. */ +export const words = (node: DocSection): string => + pipe( + node.getChildNodes(), + Array.filterMap(Filter.instanceOf(DocParagraph)), + Array.flatMap((node) => + DocNodeTransforms.trimSpacesInParagraph(node).getChildNodes(), + ), + Array.map( + Match.type().pipe( + Match.when(Match.instanceOf(DocPlainText), ({ text: value }) => value), + Match.when(Match.instanceOf(DocCodeSpan), ({ code }) => code), + Match.orElse(() => " "), + ), + ), + Array.join(""), + String.trim, + ); + +// The space after a block tag and the line breaks before its content parse as text of their own. +const isBlank = (node: DocNode): boolean => + node instanceof DocSoftBreak || + (node instanceof DocPlainText && String.isEmpty(String.trim(node.text))); + +const paragraphOf = ( + configuration: DocParagraph["configuration"], + nodes: readonly DocNode[], +): DocParagraph => { + const result = new DocParagraph({ configuration }); + result.appendNodes(nodes); + + return result; +}; + +const isCaption = + (tag: typeof DocHtmlStartTag | typeof DocHtmlEndTag) => + (node: DocNode): boolean => + node instanceof tag && node.name === "caption"; + +// JSDoc's `` opens the first paragraph of an example. Everything after the caption is ordinary content. +export const example = ( + node: DocBlock, +): Effect.Effect => + Option.gen(function* () { + const [first, ...rest] = node.content.getChildNodes(); + + const opening = yield* Option.liftPredicate(first, isParagraph); + const nodes = opening.getChildNodes(); + + const start = yield* pipe( + nodes, + Array.findFirstWithIndex((node) => !isBlank(node)), + Option.filter(([node]) => isCaption(DocHtmlStartTag)(node)), + Option.map(Tuple.get(1)), + ); + const end = yield* Array.findFirstIndex(nodes, isCaption(DocHtmlEndTag)); + + return { + title: paragraphOf(opening.configuration, nodes.slice(start + 1, end)), + content: [ + paragraphOf(opening.configuration, nodes.slice(end + 1)), + ...rest, + ], + }; + }).pipe( + Option.match({ + onNone: () => + pipe( + node.content, + section, + Effect.map((content): Example => ({ caption: [], content })), + ), + onSome: ({ title, content }) => + Effect.all({ caption: paragraph(title), content: blocks(content) }), + }), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts b/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts new file mode 100644 index 00000000000..aabc67023e1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts @@ -0,0 +1,110 @@ +import { Array, Effect, Match, Option, Record, Struct, pipe } from "effect"; + +import { Analysis } from "./Analysis.js"; +import * as Comment from "./Comment.js"; +import { Site, withLinks } from "./Site.js"; + +import type { Page } from "./Site.js"; +import type { TransformError } from "./TransformError.js"; +import type { PhrasingContent } from "mdast"; +import type { MdxJsxFlowElement } from "mdast-util-mdx-jsx"; + +// A JSX element whose attributes are all strings, rendered by one of the site's MDX components. +const element = ( + name: string, + attributes: Record.ReadonlyRecord, + children: MdxJsxFlowElement["children"], +): MdxJsxFlowElement => ({ + type: "mdxJsxFlowElement", + name, + attributes: pipe( + attributes, + Record.toEntries, + Array.map(([key, value]) => ({ + type: "mdxJsxAttribute", + name: key, + value, + })), + ), + children, +}); + +const counted = (count: number, noun: string): string => { + if (count === 1) { + return `${count} ${noun}`; + } + + return `${count} ${noun}s`; +}; + +// An entry is a link, and a reader could not follow a link inside it, so the entry keeps a link's label alone. +const unlinked: (node: PhrasingContent) => PhrasingContent[] = + Match.type().pipe( + Match.discriminators("type")({ + link: ({ children }) => Array.flatMap(children, unlinked), + linkReference: ({ children }) => Array.flatMap(children, unlinked), + emphasis: (node) => [ + { ...node, children: Array.flatMap(node.children, unlinked) }, + ], + strong: (node) => [ + { ...node, children: Array.flatMap(node.children, unlinked) }, + ], + delete: (node) => [ + { ...node, children: Array.flatMap(node.children, unlinked) }, + ], + }), + Match.orElse((node) => [node]), + ); + +// A page's entry counts the names the page documents and carries the first paragraph of its module's comment. +const pageEntry = Effect.fnUntraced(function* (page: Page) { + const analysis = yield* Analysis; + const site = yield* Site; + + const file = Array.headNonEmpty(page.modules); + const comment = yield* analysis.moduleComment(file); + const lead = yield* Option.match(comment, { + onNone: () => Effect.succeed([]), + onSome: (found) => + withLinks( + { module: file, container: page.container }, + Comment.lead(found), + ), + }); + const names = pipe( + page.container.members, + Array.map(Struct.get("displayName")), + Array.dedupe, + ); + + return element( + "IndexEntry", + { + name: page.title, + count: counted(names.length, "member"), + href: site.url(page), + }, + pipe( + Array.flatMap(lead, unlinked), + Option.liftPredicate(Array.isArrayNonEmpty), + Option.match({ + onNone: () => [], + onSome: (children) => [{ type: "paragraph", children }], + }), + ), + ); +}); + +/** Entries for a page's namespace pages, as one grid of cards. */ +export const namespaces = ( + children: readonly Page[], +): Effect.Effect => + pipe( + Effect.forEach(children, pageEntry), + Effect.map((found) => + Array.match(found, { + onEmpty: () => [], + onNonEmpty: (entries) => [element("Cards", {}, [...entries])], + }), + ), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts new file mode 100644 index 00000000000..75bea3c378f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts @@ -0,0 +1,33 @@ +import { Function, String } from "effect"; +import remarkFrontmatter from "remark-frontmatter"; +import remarkMdx from "remark-mdx"; +import remarkStringify from "remark-stringify"; +import { unified } from "unified"; +import * as Yaml from "yaml"; + +import type { Root } from "mdast"; + +// remark-mdx escapes the characters MDX would read as JSX or expressions. +const processor = unified() + .use(remarkStringify, { bullet: "-", fences: true }) + .use(remarkFrontmatter) + .use(remarkMdx); + +/** A page's frontmatter, which Fumadocs reads its title from. */ +export interface Frontmatter { + readonly title: string; +} + +/** Serializes a page's mdast as MDX, under its frontmatter. */ +export const stringify: { + (frontmatter: Frontmatter): (tree: Root) => string; + (tree: Root, frontmatter: Frontmatter): string; +} = Function.dual(2, (tree: Root, frontmatter: Frontmatter): string => + processor.stringify({ + ...tree, + children: [ + { type: "yaml", value: String.trimEnd(Yaml.stringify(frontmatter)) }, + ...tree.children, + ], + }), +); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Member.ts b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts new file mode 100644 index 00000000000..37ba54fc1ea --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts @@ -0,0 +1,343 @@ +import { ApiDocumentedItem, ApiItemKind } from "@microsoft/api-extractor-model"; +import { StandardTags } from "@microsoft/tsdoc"; +import { + Array, + Effect, + Filter, + Option, + Order, + String, + Struct, + Tuple, + pipe, +} from "effect"; + +import * as CodeBlock from "./CodeBlock.js"; +import * as Comment from "./Comment.js"; + +import type { TransformError } from "./TransformError.js"; +import type { ApiItem } from "@microsoft/api-extractor-model"; +import type { + DocBlock, + DocComment, + DocParamCollection, + DocSection, +} from "@microsoft/tsdoc"; +import type { BlockContent, Heading, ListItem, PhrasingContent } from "mdast"; + +/** The statements declaring a member, as its code block shows them. */ +export interface Signature { + /** The statements, as TypeScript. */ + readonly code: string; + /** The rest of their declaration file, which the code block compiles them in and hides. */ + readonly context: string; + /** For each name the code refers to, in order, the URL that documents it. */ + readonly urls: readonly Option.Option[]; +} + +/** The declarations sharing one name in a container, with their source. */ +export interface Member { + /** Overloads in declaration order, or a merged interface and namespace. */ + readonly items: Array.NonEmptyReadonlyArray; + readonly signature: Signature; + /** The anchor that links to an item on its page. */ + readonly anchor: (item: ApiItem) => string; +} + +const memberDepth: Heading["depth"] = 3; +const nestedDepth: Heading["depth"] = 4; + +const strong = (value: string): PhrasingContent => ({ + type: "strong", + children: [{ type: "text", value }], +}); + +const heading = (depth: Heading["depth"], anchor: string): BlockContent => ({ + type: "heading", + depth, + children: [{ type: "text", value: `${anchor} [#${anchor}]` }], +}); + +// Twoslash compiles the whole block for its hovers, and shows only what follows the cut. +const code = ({ + code: shown, + context, + urls, +}: Signature): Effect.Effect => + pipe( + CodeBlock.meta(urls), + // Encoding values of the schema's own type cannot fail. + Effect.orDie, + Effect.map( + (meta): BlockContent => ({ + type: "code", + lang: "ts", + meta, + value: `${context}\n${CodeBlock.cut}\n${shown}`, + }), + ), + ); + +// A label opens the first paragraph of the content it introduces, or stands alone before a code block. +const labelled = ( + label: PhrasingContent, + content: readonly BlockContent[], +): BlockContent[] => { + const [first, ...rest] = content; + + if (first?.type === "paragraph") { + return [ + { + type: "paragraph", + children: [label, { type: "text", value: " " }, ...first.children], + }, + ...rest, + ]; + } + + return [{ type: "paragraph", children: [label] }, ...content]; +}; + +const comments = (items: readonly ApiItem[]): DocComment[] => + pipe( + items, + Array.filterMap(Filter.instanceOf(ApiDocumentedItem)), + Array.filterMap( + Filter.fromPredicateOption(({ tsdocComment }) => + Option.fromNullishOr(tsdocComment), + ), + ), + ); + +const kindLabels: readonly (readonly [ApiItemKind, string])[] = [ + [ApiItemKind.Function, "Functions"], + [ApiItemKind.Variable, "Variables"], + [ApiItemKind.Class, "Classes"], + [ApiItemKind.Interface, "Interfaces"], + [ApiItemKind.TypeAlias, "Type aliases"], + [ApiItemKind.Enum, "Enumerations"], + [ApiItemKind.Namespace, "Namespaces"], +]; + +/** The heading that lists a member, which is its authored `@category` or else its kind. */ +export const group = (items: Array.NonEmptyReadonlyArray): string => + pipe( + comments(items), + Array.findFirst((comment) => + Array.head(Comment.blocksTagged(comment, "@category")), + ), + Option.map((block) => Comment.words(block.content)), + Option.orElse(() => + pipe( + kindLabels, + Array.findFirst(([kind]) => kind === Array.headNonEmpty(items).kind), + Option.map(Tuple.get(1)), + ), + ), + Option.getOrElse(() => "Other"), + ); + +// An authored category ranks before every kind, so categories sort among themselves by name. +const kindRank = (label: string): number => + pipe( + kindLabels, + Array.findFirstIndex(([, kind]) => kind === label), + Option.getOrElse(() => -1), + ); + +const groupOrder: Order.Order = Order.combine( + Order.mapInput(Order.Number, kindRank), + String.Order, +); + +/** Orders groups by their heading: authored categories alphabetically, then kinds in a fixed order. */ +export const sortGroups = ( + groups: Iterable, +): (readonly [string, A])[] => Array.sortWith(groups, Tuple.get(0), groupOrder); + +// Stability, version and internal status, each only where the comment states it. +const markers = (comment: DocComment): BlockContent[] => { + const tagged = ( + tagName: string, + label: string, + ): Option.Option => + pipe( + Comment.blocksTagged(comment, tagName), + Array.head, + Option.map((block) => [ + strong(label), + { type: "text", value: ` ${Comment.words(block.content)}` }, + ]), + ); + + return pipe( + Array.getSomes([ + tagged("@stability", "Stability"), + tagged("@since", "Since"), + Option.liftPredicate([strong("Internal")], () => + comment.modifierTagSet.isInternal(), + ), + ]), + Array.match({ + onEmpty: () => [], + onNonEmpty: (facts) => [ + { + type: "paragraph", + children: pipe( + facts, + Array.intersperse([ + { type: "text", value: " · " }, + ]), + Array.flatten, + ), + }, + ], + }), + ); +}; + +const parameters = ( + label: string, + collection: DocParamCollection, +): Effect.Effect => + pipe( + collection.blocks, + Effect.forEach((block) => + pipe( + block.content, + Comment.section, + Effect.map( + (content): ListItem => ({ + type: "listItem", + spread: false, + children: labelled( + { type: "inlineCode", value: block.parameterName }, + content, + ), + }), + ), + ), + ), + Effect.map( + Array.match({ + onEmpty: (): BlockContent[] => [], + onNonEmpty: (items): BlockContent[] => [ + { type: "paragraph", children: [strong(label)] }, + { type: "list", ordered: false, spread: false, children: [...items] }, + ], + }), + ), + ); + +const labelledSections = ( + label: string, + sections: readonly DocSection[], +): Effect.Effect => + pipe( + sections, + Effect.forEach((content) => + pipe( + content, + Comment.section, + Effect.map((blocks) => labelled(strong(label), blocks)), + ), + ), + Effect.map(Array.flatten), + ); + +const exampleBlocks = ({ + caption, + content, +}: Comment.Example): BlockContent[] => { + const label = Array.match(caption, { + onEmpty: (): PhrasingContent[] => [strong("Example")], + onNonEmpty: (phrasing): PhrasingContent[] => [ + strong("Example"), + { type: "text", value: " (" }, + ...phrasing, + { type: "text", value: ")" }, + ], + }); + + return [{ type: "paragraph", children: label }, ...content]; +}; + +const contentOf = (block: DocBlock | undefined): DocSection[] => + Array.fromNullishOr(block?.content); + +const documentation = ( + comment: DocComment, +): Effect.Effect => + pipe( + [ + labelledSections("Deprecated", contentOf(comment.deprecatedBlock)), + Effect.succeed(markers(comment)), + Comment.overview(comment), + parameters("Type parameters", comment.typeParams), + parameters("Parameters", comment.params), + labelledSections("Returns", contentOf(comment.returnsBlock)), + labelledSections( + "Throws", + Array.map( + Comment.blocksTagged(comment, StandardTags.throws.tagName), + Struct.get("content"), + ), + ), + labelledSections( + "See", + Array.map(comment.seeBlocks, Struct.get("content")), + ), + pipe( + Comment.blocksTagged(comment, StandardTags.example.tagName), + Effect.forEach(Comment.example), + Effect.map(Array.flatMap(exampleBlocks)), + ), + ], + Effect.all, + Effect.map(Array.flatten), + ); + +const descendants = (items: readonly ApiItem[]): ApiItem[] => + Array.flatMap(items, (item) => [item, ...descendants(item.members)]); + +/** Renders a member as its heading and declarations, followed by the documentation of each declaration and of every documented nested member. */ +export const render = ({ + items, + signature, + anchor, +}: Member): Effect.Effect => + pipe( + [ + pipe( + signature, + code, + Effect.map((block) => [ + heading(memberDepth, anchor(Array.headNonEmpty(items))), + block, + ]), + ), + pipe( + comments(items), + Effect.forEach(documentation), + Effect.map(Array.flatten), + ), + pipe( + items, + Array.flatMap(Struct.get("members")), + descendants, + Array.flatMap((nested) => + Array.map(comments([nested]), (comment) => ({ nested, comment })), + ), + Effect.forEach(({ nested, comment }) => + pipe( + comment, + documentation, + Effect.map(Array.prepend(heading(nestedDepth, anchor(nested)))), + ), + ), + Effect.map(Array.flatten), + ), + ], + Effect.all, + Effect.map(Array.flatten), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Page.ts b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts new file mode 100644 index 00000000000..23c53918494 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts @@ -0,0 +1,145 @@ +import { Array, Effect, Option, Record, Result, Struct, pipe } from "effect"; + +import { Analysis } from "./Analysis.js"; +import * as Comment from "./Comment.js"; +import * as Listing from "./Listing.js"; +import * as Member from "./Member.js"; +import * as Signature from "./Signature.js"; +import { Site, withLinks } from "./Site.js"; +import { TransformError } from "./TransformError.js"; + +import type { Page } from "./Site.js"; +import type { ApiItem } from "@microsoft/api-extractor-model"; +import type { BlockContent, Root } from "mdast"; + +// The modules' own comments open the page, each linking from its module. +const overview = Effect.fnUntraced(function* (page: Page) { + const analysis = yield* Analysis; + + return yield* pipe( + page.modules, + Effect.forEach((file) => + pipe( + file, + analysis.moduleComment, + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed([]), + onSome: (comment) => + withLinks( + { module: file, container: page.container }, + Comment.overview(comment), + ), + }), + ), + ), + ), + Effect.map(Array.flatten), + ); +}); + +const member = Effect.fnUntraced(function* ( + page: Page, + items: Array.NonEmptyReadonlyArray, +) { + const analysis = yield* Analysis; + const site = yield* Site; + + const first = Array.headNonEmpty(items); + const origin = yield* pipe( + first, + site.origin, + Effect.fromOption, + Effect.mapError(() => + TransformError.malformedAnalysis( + `${first.getScopedNameWithinPackage()} has no source module on a page`, + ), + ), + ); + const declaration = yield* analysis.declarationOf(origin.module); + const signature = yield* Signature.make({ + name: first.displayName, + source: origin.module, + declaration, + root: analysis.declarationRoot, + exporters: [origin.module, ...page.modules], + }); + const resolve = yield* site.declarationLinks(origin, declaration); + const blocks = yield* withLinks( + origin, + Member.render({ + items, + signature: { + code: signature.code, + context: signature.context, + urls: Array.map(signature.references, ({ path }) => resolve(path)), + }, + anchor: site.anchor, + }), + ); + + return { label: Member.group(items), blocks }; +}); + +const heading = (value: string): BlockContent => ({ + type: "heading", + depth: 2, + children: [{ type: "text", value }], +}); + +const namespaces = ( + children: readonly Page[], +): Effect.Effect => + pipe( + Listing.namespaces(children), + Effect.map( + Array.match({ + onEmpty: (): BlockContent[] => [], + onNonEmpty: (found): BlockContent[] => [ + heading("Namespaces"), + ...found, + ], + }), + ), + ); + +// Rendered members under their group headings, in the groups' order. +const sections = ( + rendered: readonly { + readonly label: string; + readonly blocks: BlockContent[]; + }[], +): BlockContent[] => + pipe( + rendered, + Array.groupBy(Struct.get("label")), + Record.toEntries, + Member.sortGroups, + Array.flatMap(([label, group]) => [ + heading(label), + ...Array.flatMap(group, Struct.get("blocks")), + ]), + ); + +/** Builds a page from its modules' overviews and the pages of its namespaces, followed by its members grouped by category or kind. */ +export const render = Effect.fnUntraced(function* (page: Page) { + const site = yield* Site; + + const [children, items] = Array.partition(page.container.members, (item) => + Result.fromOption(site.pageOf(item), () => item), + ); + // Members sharing a name render as one: overloads, or an interface merged with a namespace. + const body = yield* Effect.all([ + overview(page), + namespaces(children), + pipe( + items, + Array.groupBy(Struct.get("displayName")), + Record.values, + Effect.forEach((group) => member(page, group)), + Effect.map(sections), + ), + ]); + + return { type: "root", children: Array.flatten(body) } satisfies Root; +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/References.ts b/libs/@local/hashql/sdk/typescript-docs/src/References.ts new file mode 100644 index 00000000000..42eaa80eff0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/References.ts @@ -0,0 +1,288 @@ +/** + * The names TypeScript code refers to, each at the identifier that writes it. + * + * A reference is a chain of identifiers in a type reference, a `typeof` query or a heritage clause, whose first name no type parameter, parameter, `infer` or mapped-type key of the code binds. Formatting the code moves the references without changing their order, which is how a code block pairs them with links the transform chose before the formatter ran. + * + * @module + */ +import { + Array, + Filter, + Match, + Option, + Order, + Predicate, + Struct, + pipe, +} from "effect"; +import { Visitor } from "oxc-parser"; + +import type { + BindingPattern, + BindingProperty, + BindingRestElement, + Expression, + IdentifierName, + ParamPattern, + Program, + Span, + TSConditionalType, + TSInferType, + TSTypeName, + TSTypeParameterDeclaration, +} from "oxc-parser"; + +/** A name the statements refer to, at one of its identifiers. */ +export interface Reference { + readonly start: number; + readonly end: number; + /** The names up to and including this identifier, outermost first: `Type`, then `Type.Any`. */ + readonly path: Array.NonEmptyReadonlyArray; +} + +/** A name in an entity name or a member expression, at its identifier. */ +interface Segment { + readonly name: string; + readonly start: number; + readonly end: number; +} + +const segment = ({ name, start, end }: IdentifierName): Segment => ({ + name, + start, + end, +}); + +// `this.x` names no declaration, so a qualifier that bottoms out at `this` yields nothing. +const typeNameSegments = (name: TSTypeName): readonly Segment[] => { + if (name.type === "Identifier") { + return [segment(name)]; + } + + if (name.type === "TSQualifiedName") { + return Array.match(typeNameSegments(name.left), { + onEmpty: () => [], + onNonEmpty: Array.append(segment(name.right)), + }); + } + + return []; +}; + +// Heritage clauses and `extends` name their base as an expression, which refers to a declaration only as a chain of identifiers. +const expressionSegments = (expression: Expression): readonly Segment[] => { + if (expression.type === "Identifier") { + return [segment(expression)]; + } + + if ( + expression.type === "MemberExpression" && + !expression.computed && + expression.property.type === "Identifier" + ) { + const { property } = expression; + + return Array.match(expressionSegments(expression.object), { + onEmpty: () => [], + onNonEmpty: Array.append(segment(property)), + }); + } + + return []; +}; + +const patternNames: ( + pattern: BindingPattern | ParamPattern, +) => readonly string[] = Match.type().pipe( + Match.discriminatorsExhaustive("type")({ + Identifier: ({ name }) => [name], + AssignmentPattern: ({ left }) => patternNames(left), + RestElement: ({ argument }) => patternNames(argument), + TSParameterProperty: ({ parameter }) => patternNames(parameter), + ObjectPattern: ({ properties }) => + Array.flatMap( + properties, + Match.type().pipe( + Match.discriminatorsExhaustive("type")({ + Property: ({ value }) => patternNames(value), + RestElement: ({ argument }) => patternNames(argument), + }), + ), + ), + ArrayPattern: ({ elements }) => + pipe( + elements, + Array.filter(Predicate.isNotNull), + Array.flatMap((element) => patternNames(element)), + ), + }), +); + +/** Names a declaration binds over a range of the code: type parameters, `infer` and mapped-type keys as types, parameters as values. */ +interface Binder { + readonly start: number; + readonly end: number; + readonly types: readonly string[]; + readonly values: readonly string[]; +} + +/** A chain of identifiers that refers to a declaration, and the space TypeScript looks its first name up in. */ +interface Candidate { + readonly segments: Array.NonEmptyReadonlyArray; + readonly space: "types" | "values"; +} + +/** Where the syntax binds names, and the chains of identifiers that may refer to declarations. */ +interface Collected { + readonly binders: readonly Binder[]; + readonly candidates: readonly Candidate[]; + readonly conditionals: readonly TSConditionalType[]; + readonly infers: readonly TSInferType[]; +} + +const typeParameterNames = ( + declaration: TSTypeParameterDeclaration | null | undefined, +): readonly string[] => + Array.map(declaration?.params ?? [], ({ name }) => name.name); + +const collect = (program: Program): Collected => { + const binders: Binder[] = []; + const candidates: Candidate[] = []; + const conditionals: TSConditionalType[] = []; + const infers: TSInferType[] = []; + + const binds = (node: { + readonly start: number; + readonly end: number; + readonly typeParameters?: TSTypeParameterDeclaration | null; + readonly params?: readonly ParamPattern[]; + }): void => { + binders.push({ + start: node.start, + end: node.end, + types: typeParameterNames(node.typeParameters), + values: Array.flatMap(node.params ?? [], patternNames), + }); + }; + const refers = ( + segments: readonly Segment[], + space: Candidate["space"], + ): void => { + if (Array.isReadonlyArrayNonEmpty(segments)) { + candidates.push({ segments, space }); + } + }; + + new Visitor({ + TSTypeAliasDeclaration: binds, + TSInterfaceDeclaration: binds, + ClassDeclaration: (node): void => { + binds(node); + + if (node.superClass !== null) { + refers(expressionSegments(node.superClass), "values"); + } + }, + FunctionDeclaration: binds, + FunctionExpression: binds, + TSDeclareFunction: binds, + ArrowFunctionExpression: binds, + TSFunctionType: binds, + TSConstructorType: binds, + TSMethodSignature: binds, + TSCallSignatureDeclaration: binds, + TSConstructSignatureDeclaration: binds, + // The key binds in the name and value types, which follow the constraint. + TSMappedType: ({ key, constraint, end }): void => { + binders.push({ + start: constraint.end, + end, + types: [key.name], + values: [], + }); + }, + TSConditionalType: (node): void => { + conditionals.push(node); + }, + TSInferType: (node): void => { + infers.push(node); + }, + TSTypeReference: ({ typeName }): void => { + refers(typeNameSegments(typeName), "types"); + }, + TSTypeQuery: ({ exprName }): void => { + if (exprName.type !== "TSImportType") { + refers(typeNameSegments(exprName), "values"); + } + }, + TSInterfaceHeritage: ({ expression }): void => { + refers(expressionSegments(expression), "types"); + }, + TSClassImplements: ({ expression }): void => { + refers(expressionSegments(expression), "types"); + }, + }).visit(program); + + return { binders, candidates, conditionals, infers }; +}; + +const contains = (outer: Span, inner: Span): boolean => + outer.start <= inner.start && inner.end <= outer.end; + +// An `infer` belongs to the innermost conditional whose `extends` clause holds it, and binds over that clause and the true branch. +const inferBinders = ({ conditionals, infers }: Collected): readonly Binder[] => + Array.filterMap( + infers, + Filter.fromPredicateOption((infer) => + pipe( + conditionals, + Array.filter(({ extendsType }) => contains(extendsType, infer)), + Array.sortWith( + ({ extendsType }) => extendsType.end - extendsType.start, + Order.Number, + ), + Array.head, + Option.map( + ({ extendsType, trueType }): Binder => ({ + start: extendsType.start, + end: trueType.end, + types: [infer.typeParameter.name.name], + values: [], + }), + ), + ), + ), + ); + +// Every identifier of a chain is a reference: `Type.Any` refers to `Type` at its first identifier and to `Type.Any` at its second. +const referencesAlong = ( + segments: Array.NonEmptyReadonlyArray, +): readonly Reference[] => + Array.map( + segments, + ({ start, end }, index): Reference => ({ + start, + end, + path: [ + Array.headNonEmpty(segments).name, + ...Array.map(segments.slice(1, index + 1), Struct.get("name")), + ], + }), + ); + +/** The names a program refers to, in source order. A name bound by a type parameter, a parameter or `infer` is not a declaration a page documents, so it yields no reference. */ +export const of = (program: Program): readonly Reference[] => { + const collected = collect(program); + const binders = [...collected.binders, ...inferBinders(collected)]; + const isBound = ({ segments: [head], space }: Candidate): boolean => + Array.some( + binders, + (binder) => contains(binder, head) && binder[space].includes(head.name), + ); + + return pipe( + collected.candidates, + Array.filter((candidate) => !isBound(candidate)), + Array.flatMap(({ segments }) => referencesAlong(segments)), + ); +}; diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts new file mode 100644 index 00000000000..640e8188cc7 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, layer } from "@effect/vitest"; +import { Array, Effect, FileSystem, Layer, Path, Record } from "effect"; + +import * as Signature from "./Signature.js"; +import * as Sources from "./Sources.js"; + +import type { TransformError } from "./TransformError.js"; + +const declaration = "/declarations/Program/Module.d.ts"; + +const files: Record.ReadonlyRecord = { + "/src/Program/Module.ts": [ + "declare function conditional(): void;", + "export { conditional as if };", + ].join("\n"), + [declaration]: [ + 'import * as Type from "../Type/index.js";', + 'import type { Other } from "./Other.js";', + 'import type { Types } from "effect";', + "/** Not exported, so it has no page. */", + "interface Hidden {", + " readonly value: T;", + "}", + "/** Picks a value. */", + "export declare function pick(value: T, other: Other): Hidden;", + "/** Picks every key. */", + "export declare function pick(key: K): {", + " [P in keyof K]: K[P] extends infer U ? U : Other;", + "};", + "declare function conditional(): Types.Invariant;", + "export { conditional as if };", + ].join("\n"), +}; + +// A read of a file the fixtures do not name is a defect in the test. +const fixtures: Layer.Layer = Layer.mergeAll( + Sources.layer.pipe( + Layer.provide( + FileSystem.layerNoop({ + readFileString: (path) => + Effect.fromOption(Record.get(files, path)).pipe(Effect.orDie), + }), + ), + ), + Path.layer, +); + +const make = ( + name: string, +): Effect.Effect< + Signature.Signature, + TransformError, + Sources.Sources | Path.Path +> => + Signature.make({ + name, + source: "/src/Program/Module.ts", + declaration, + root: "/declarations", + exporters: ["/src/Program/Module.ts"], + }); + +// A reference reads as the text it spans and the path it resolves. +const shown = ({ + code, + references, +}: Signature.Signature): readonly (readonly [string, string])[] => + Array.map( + references, + ({ start, end, path }) => + [code.slice(start, end), Array.join(path, ".")] as const, + ); + +describe("signature", () => { + layer(fixtures)((it) => { + it.effect("overloads_code", () => + Effect.gen(function* () { + const { code } = yield* make("pick"); + + expect(code).toBe( + [ + "export declare function pick(value: T, other: Other): Hidden;", + "export declare function pick(key: K): {", + " [P in keyof K]: K[P] extends infer U ? U : Other;", + "};", + ].join("\n"), + ); + }), + ); + + // Type parameters, the mapped key and the `infer` binding name no declaration. + it.effect("references_skip_bound_names", () => + Effect.gen(function* () { + const signature = yield* make("pick"); + + expect(shown(signature)).toStrictEqual([ + ["Type", "Type"], + ["Any", "Type.Any"], + ["Other", "Other"], + ["Hidden", "Hidden"], + ["Other", "Other"], + ]); + }), + ); + + it.effect("context_excludes_shown", () => + Effect.gen(function* () { + const { context } = yield* make("pick"); + + expect(context).toBe( + [ + 'import * as Type from "#declarations/Type/index.js";', + 'import type { Other } from "#declarations/Program/Other.js";', + 'import type { Types } from "effect";', + "interface Hidden {\n readonly value: T;\n}", + "declare function conditional(): Types.Invariant;", + ].join("\n"), + ); + }), + ); + + it.effect("alias_export", () => + Effect.gen(function* () { + const signature = yield* make("if"); + + expect(signature.code).toBe( + [ + "declare function conditional(): Types.Invariant;", + "export { conditional as if };", + ].join("\n"), + ); + expect(shown(signature)).toStrictEqual([ + ["Types", "Types"], + ["Invariant", "Types.Invariant"], + ["Other", "Other"], + ]); + }), + ); + + it.effect("undeclared_name", () => + Effect.gen(function* () { + const error = yield* Effect.flip(make("missing")); + + expect(error.reason).toMatchObject({ _tag: "MalformedAnalysis" }); + }), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts new file mode 100644 index 00000000000..18418ba6d42 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts @@ -0,0 +1,176 @@ +import { + Array, + Effect, + Option, + Path, + Record, + String, + Struct, + flow, + pipe, +} from "effect"; + +import * as References from "./References.js"; +import { Sources, parse } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +import type { ScopeStatement } from "./Statements.js"; + +/** The statements declaring a member, with the declaration file they compile in. */ +export interface Signature { + /** The statements, without comments. */ + readonly code: string; + /** The declaration file's other imports and declarations. Each relative module specifier starts with `#declarations/` instead, which names the directory TypeScript emitted the declaration files into. */ + readonly context: string; + /** The names the statements refer to, in order. */ + readonly references: readonly References.Reference[]; +} + +/** Where an aliased name comes from: the module declaring it and its name there. */ +interface Alias { + readonly module: string; + readonly local: string; +} + +// `export { local as name }` takes the name from another module when it re-exports, from an import when the local is one, and from the exporter's own declarations otherwise. +const aliasOf = Effect.fnUntraced(function* (exporter: string, name: string) { + const sources = yield* Sources; + const { reexports, imports } = yield* sources.scope(exporter); + + return pipe( + reexports, + Record.get(name), + Option.flatMap(({ local, specifier }) => + Option.match(specifier, { + onSome: (from) => + pipe( + sources.resolve(exporter, from), + Option.map((module): Alias => ({ module, local })), + ), + onNone: () => + pipe( + imports, + Record.get(local), + Option.flatMap( + (binding): Option.Option => + Option.all({ + module: sources.resolve(exporter, binding.specifier), + local: binding.imported, + }), + ), + Option.orElseSome((): Alias => ({ module: exporter, local })), + ), + }), + ), + ); +}); + +const statementsText = (statements: readonly ScopeStatement[]): string => + pipe(statements, Array.map(Struct.get("text")), Array.join("\n")); + +// Each relative specifier keeps naming its module wherever Twoslash compiles the context, through the path the docs site maps `#declarations/` to. +const rewriteSpecifiers = ( + { text, specifiers }: ScopeStatement, + rewrite: (specifier: string) => string, +): string => { + const [cursor, pieces] = Array.mapAccum( + specifiers, + 0, + (position, { start, end, value }) => [ + end, + `${text.slice(position, start)}${JSON.stringify(rewrite(value))}`, + ], + ); + + return `${Array.join(pieces, "")}${text.slice(cursor)}`; +}; + +export interface Options { + /** The name the member's module exports it under. */ + readonly name: string; + /** The source module declaring it. */ + readonly source: string; + /** The declaration file TypeScript emitted from the source module. */ + readonly declaration: string; + /** The directory TypeScript emitted the declaration files into, which `#declarations/` names. */ + readonly root: string; + /** Modules that may publish it under another name: the declaring module, then the page's. */ + readonly exporters: readonly string[]; +} + +/** + * The statements declaring a member, without comments, and the rest of their declaration file. + * + * A member exported under an alias keeps its local declaration, and an export specifier that publishes the alias follows it. The SDK exports `conditional` as `if` this way, because `if` cannot name a function. + */ +export const make = Effect.fnUntraced(function* ({ + name, + source, + declaration, + root, + exporters, +}: Options) { + const sources = yield* Sources; + const path = yield* Path.Path; + + const { local, statements } = yield* sources.declarations(declaration); + + const shown = yield* Option.match(Record.get(local, name), { + onSome: (declared) => + Effect.succeed({ declared, exported: Option.none() }), + onNone: () => + pipe( + exporters, + Effect.forEach((exporter) => aliasOf(exporter, name)), + Effect.map( + flow( + Array.getSomes, + Array.findFirst((alias) => + pipe( + alias, + Option.liftPredicate(({ module }) => module === source), + Option.flatMap(() => Record.get(local, alias.local)), + Option.map((declared) => ({ + declared, + exported: Option.some( + `export { ${alias.local} as ${name} };`, + ), + })), + ), + ), + ), + ), + Effect.flatMap(Effect.fromOption), + Effect.mapError(() => + TransformError.malformedAnalysis(`${source} declares no ${name}`), + ), + ), + }); + + const code = pipe( + [statementsText(shown.declared), ...Array.fromOption(shown.exported)], + Array.join("\n"), + ); + const { program } = yield* parse(code, declaration); + + const directory = path.relative(root, path.dirname(declaration)); + const rewrite = (specifier: string): string => { + if (!String.startsWith(".")(specifier)) { + return specifier; + } + + return `#declarations/${pipe(path.join(directory, specifier), String.split(path.sep), Array.join("/"))}`; + }; + const context = pipe( + statements, + Array.filter((statement) => !shown.declared.includes(statement)), + Array.map((statement) => rewriteSpecifiers(statement, rewrite)), + Array.join("\n"), + ); + + return { + code, + context, + references: References.of(program), + } satisfies Signature; +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts new file mode 100644 index 00000000000..7d90621b318 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts @@ -0,0 +1,478 @@ +import { + ApiItemContainerMixin, + ApiItemKind, +} from "@microsoft/api-extractor-model"; +import { + Array, + Context, + Effect, + Layer, + Option, + Path, + Record, + String, + Struct, + flow, + pipe, +} from "effect"; + +import { Analysis } from "./Analysis.js"; +import { Links } from "./Comment.js"; +import { Sources } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +import type { Scope } from "./Sources.js"; +import type { ApiItem } from "@microsoft/api-extractor-model"; +import type { DocDeclarationReference } from "@microsoft/tsdoc"; + +/** A reference page for one of the package's entry points, or for a namespace that a module re-exports with `export * as`. */ +export interface Page { + /** Path segments below the output directory, empty for the package page and the subpath's for another entry point's. */ + readonly path: readonly string[]; + readonly title: string; + /** The model item whose members the page documents. */ + readonly container: ApiItem; + /** The modules whose `@module` comments open the page. */ + readonly modules: Array.NonEmptyReadonlyArray; +} + +/** The module a comment comes from, whose imports its links see, and the item that stands for that module's declarations. */ +export interface Origin { + readonly module: string; + readonly container: ApiItem; +} + +/** Resolves a name path, `Type` or `Type.Any`, to the URL of what it names, `None` when it names nothing on a page. */ +export type Resolve = ( + path: Array.NonEmptyReadonlyArray, +) => Option.Option; + +/** The pages of the reference and the links between them. */ +export class Site extends Context.Service< + Site, + { + readonly pages: Array.NonEmptyReadonlyArray; + /** The entry points' pages, in the order `analyze` received them. */ + readonly roots: Array.NonEmptyReadonlyArray; + /** The page documenting a container's members, if it has one. */ + readonly pageOf: (container: ApiItem) => Option.Option; + readonly url: (page: Page) => string; + /** An item's anchor on its page: its name, qualified up to the page's container. */ + readonly anchor: (item: ApiItem) => string; + readonly origin: (item: ApiItem) => Option.Option; + /** Resolves the links of comments written at an origin. */ + readonly links: ( + origin: Origin, + ) => Effect.Effect; + /** Resolves names written in the declaration file emitted from an origin's module, as TypeScript resolves them there: the module's declarations, then its imports. */ + readonly declarationLinks: ( + origin: Origin, + declaration: string, + ) => Effect.Effect; + } +>()("@local/hashql-typescript-docs/Site") {} + +/** Runs a comment's conversion with its links resolved from the comment's origin. */ +export const withLinks = Effect.fnUntraced(function* ( + origin: Origin, + effect: Effect.Effect, +) { + const site = yield* Site; + const links = yield* site.links(origin); + + return yield* Effect.provideService(effect, Links, links); +}); + +// Every declaration sharing the name, since an interface and a namespace merge under one. +const members = (container: ApiItem, name: string): readonly ApiItem[] => { + if (ApiItemContainerMixin.isBaseClassOf(container)) { + return container.findMembersByName(name); + } + + return []; +}; + +const ancestors = (item: ApiItem): ApiItem[] => + Array.unfold(item.parent, (parent) => + pipe( + parent, + Option.fromNullishOr, + Option.map((found) => [found, found.parent] as const), + ), + ); + +// A namespace that a module re-exports with `export * as` gets a page below its parent's, so the URL nests as the names do. A `namespace` declaration renders among its siblings. +const pageOfNamespace = Effect.fnUntraced(function* ( + parent: Page, + item: ApiItem, +) { + const analysis = yield* Analysis; + const sources = yield* Sources; + + const file = analysis.sourceOf(item); + if (item.kind !== ApiItemKind.Namespace || Option.isNone(file)) { + return Option.none(); + } + + const { namespaces } = yield* sources.scope(file.value); + const specifier = Record.get(namespaces, item.displayName); + if (Option.isNone(specifier)) { + return Option.none(); + } + + const target = yield* pipe( + sources.resolve(file.value, specifier.value), + Effect.fromOption, + Effect.mapError(() => + TransformError.malformedAnalysis( + `${file.value} re-exports ${specifier.value}, which does not exist`, + ), + ), + ); + + return Option.some({ + path: [...parent.path, item.displayName], + title: item.displayName, + container: item, + modules: [target], + }); +}); + +const discover = ( + parent: Page, +): Effect.Effect => + pipe( + parent.container.members, + Effect.forEach((item) => + pipe( + pageOfNamespace(parent, item), + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(Array.empty()), + onSome: (page) => + pipe(page, discover, Effect.map(Array.prepend(page))), + }), + ), + ), + ), + Effect.map(Array.flatten), + ); + +interface Index { + readonly pageOf: (container: ApiItem) => Option.Option; + readonly pageOfModule: (file: string) => Option.Option; + readonly url: (page: Page) => string; + readonly anchor: (item: ApiItem) => string; + readonly itemUrl: (item: ApiItem) => Option.Option; + /** The nearest ancestor of an item that has a page. */ + readonly enclosing: (item: ApiItem) => Option.Option; +} + +const makeIndex = (pages: readonly Page[], url: string): Index => { + const byContainer = new Map( + Array.map(pages, (page) => [page.container, page] as const), + ); + const byModule = pipe( + pages, + Array.flatMap((page) => + Array.map(page.modules, (file) => [file, page] as const), + ), + Record.fromEntries, + ); + const hasPage = (item: ApiItem): boolean => byContainer.has(item); + + const pageOf = (container: ApiItem): Option.Option => + Option.fromNullishOr(byContainer.get(container)); + const pageUrl = (page: Page): string => Array.join([url, ...page.path], "/"); + const enclosing = (item: ApiItem): Option.Option => + pipe(item, ancestors, Array.findFirst(hasPage)); + + const anchor = (item: ApiItem): string => + pipe( + item, + ancestors, + Array.takeWhile((parent) => !hasPage(parent)), + Array.reverse, + Array.map(Struct.get("displayName")), + Array.append(item.displayName), + Array.join("."), + ); + + return { + pageOf, + pageOfModule: (file) => Record.get(byModule, file), + url: pageUrl, + anchor, + enclosing, + itemUrl: (item) => + pipe( + item, + pageOf, + Option.map(pageUrl), + Option.orElse(() => + pipe( + item, + enclosing, + Option.flatMap(pageOf), + Option.map((page) => `${pageUrl(page)}#${anchor(item)}`), + ), + ), + ), + }; +}; + +interface Resolution { + readonly index: Index; + readonly origin: Origin; + readonly scope: Scope; +} + +/** The declarations a name may refer to in one scope, empty when the scope has none. */ +type Lookup = (name: string) => readonly ApiItem[]; + +// The module's declarations, including those it publishes under another name with `export { local as name }`. +const declared = + ({ origin, scope }: Resolution): Lookup => + (name) => [ + ...members(origin.container, name), + ...pipe( + scope.reexports, + Record.toEntries, + Array.filter( + ([, { local, specifier }]) => + local === name && Option.isNone(specifier), + ), + Array.flatMap(([exported]) => members(origin.container, exported)), + ), + ]; + +// Specifiers resolve from the origin's module, which the emitted declaration files mirror. +const imported = + (sources: Sources["Service"], { index, origin, scope }: Resolution): Lookup => + (name) => + pipe( + scope.imports, + Record.get(name), + Option.flatMap(({ specifier, imported: exported }) => + pipe( + sources.resolve(origin.module, specifier), + Option.flatMap(index.pageOfModule), + Option.map(({ container }) => + Option.match(exported, { + onNone: () => [container], + onSome: (member) => members(container, member), + }), + ), + ), + ), + Option.getOrElse(Array.empty), + ); + +// A symbol reference such as `[Symbol.iterator]` names no member a page lists. +const namesOf = ( + reference: DocDeclarationReference, +): Option.Option> => + pipe( + reference.memberReferences, + Array.map((part) => + Option.fromNullishOr(part.memberIdentifier?.identifier), + ), + Option.all, + Option.filter(Array.isReadonlyArrayNonEmpty), + ); + +// The first scope that declares the leading name decides it, and the remaining names walk the members of every declaration found there. +const resolveIn = + (lookups: readonly Lookup[]) => + ([ + head, + ...tail + ]: Array.NonEmptyReadonlyArray): Option.Option => + pipe( + lookups, + Array.findFirst((lookup) => + Option.liftPredicate( + lookup(head), + Array.isReadonlyArrayNonEmpty, + ), + ), + Option.map((found: readonly ApiItem[]) => + Array.reduce(tail, found, (candidates, name) => + Array.flatMap(candidates, (parent) => members(parent, name)), + ), + ), + Option.flatMap(Array.head), + ); + +const makeLinks = Effect.fnUntraced(function* (index: Index, origin: Origin) { + const analysis = yield* Analysis; + const sources = yield* Sources; + const path = yield* Path.Path; + + const scope = yield* sources.scope(origin.module); + const resolution: Resolution = { index, origin, scope }; + + // A reference's import path selects an entry point, `/draft` the one at `./draft`. Without one, it names the entry point the comment's page belongs to. + const entryPointOf = ( + reference: DocDeclarationReference, + ): Option.Option => + Option.match(Option.fromNullishOr(reference.importPath), { + onNone: () => + pipe( + Array.prepend(ancestors(origin.container), origin.container), + Array.findFirst((item) => item.kind === ApiItemKind.EntryPoint), + ), + onSome: (importPath) => + pipe( + analysis.entryPoints, + Array.findFirst(({ subpath }) => subpath === `.${importPath}`), + Option.map(Struct.get("model")), + ), + }); + + // Links resolve the way TypeScript resolves them in the comment's module. A reference qualified from the package resolves last. + const fromPackage = + (reference: DocDeclarationReference): Lookup => + (name) => + pipe( + entryPointOf(reference), + Option.map((entryPoint) => members(entryPoint, name)), + Option.getOrElse(Array.empty), + ); + const target = (reference: DocDeclarationReference): Option.Option => + pipe( + reference, + namesOf, + Option.flatMap( + resolveIn([ + declared(resolution), + imported(sources, resolution), + fromPackage(reference), + ]), + ), + ); + + const shown = path.relative( + path.dirname(Array.headNonEmpty(analysis.entryPoints).module), + origin.module, + ); + + return Links.of({ + resolve: (reference) => + pipe( + reference, + Option.liftPredicate( + ({ packageName }) => + packageName === undefined || packageName === analysis.name, + ), + Option.flatMap(target), + Option.flatMap(index.itemUrl), + Option.match({ + onNone: () => + pipe( + Effect.logWarning( + `Unresolved link ${reference.emitAsTsdoc()} in ${shown}`, + ), + Effect.as(Option.none()), + ), + onSome: flow(Option.some, Effect.succeed), + }), + ), + }); +}); + +const makeDeclarationLinks = Effect.fnUntraced(function* ( + index: Index, + origin: Origin, + declaration: string, +) { + const sources = yield* Sources; + + const scope = yield* sources.scope(declaration); + const resolution: Resolution = { index, origin, scope }; + + return flow( + resolveIn([declared(resolution), imported(sources, resolution)]), + Option.flatMap(index.itemUrl), + ) satisfies Resolve; +}); + +export interface Options { + /** The URL of the package page, which every other page's URL extends. */ + readonly url: string; +} + +export const layer = ({ + url, +}: Options): Layer.Layer< + Site, + TransformError, + Analysis | Sources | Path.Path +> => + Layer.effect( + Site, + Effect.gen(function* () { + const analysis = yield* Analysis; + const services = yield* Effect.context(); + + // `./draft` is the page at `draft`, below the package's own. + const roots = Array.map( + analysis.entryPoints, + ({ subpath, model, module }): Page => ({ + path: Array.drop(String.split(subpath, "/"), 1), + title: `${analysis.name}${subpath.slice(1)}`, + container: model, + modules: [module], + }), + ); + const pages = yield* pipe( + roots, + Effect.forEach((root) => + pipe(root, discover, Effect.map(Array.prepend(root))), + ), + Effect.map(Array.flatten), + ); + const duplicate = pipe( + pages, + Array.groupBy((page) => Array.join(page.path, "/")), + Record.toEntries, + Array.findFirst(([, group]) => group.length > 1), + ); + + if (Option.isSome(duplicate)) { + return yield* TransformError.malformedAnalysis( + `Two namespaces render to ${duplicate.value[0]}`, + ); + } + + const index = makeIndex(pages, url); + + return Site.of({ + pages, + roots, + pageOf: index.pageOf, + url: index.url, + anchor: index.anchor, + origin: (item) => + pipe( + item, + analysis.sourceOf, + Option.flatMap((module) => + pipe( + module, + index.pageOfModule, + Option.map(Struct.get("container")), + Option.orElse(() => index.enclosing(item)), + Option.map((container) => ({ module, container })), + ), + ), + ), + links: (origin) => Effect.provide(makeLinks(index, origin), services), + declarationLinks: (origin, declaration) => + Effect.provide( + makeDeclarationLinks(index, origin, declaration), + services, + ), + }); + }), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts new file mode 100644 index 00000000000..a1bf80da674 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, layer } from "@effect/vitest"; +import { + Array, + Effect, + FileSystem, + Layer, + Option, + Record, + Struct, + pipe, +} from "effect"; + +import * as Sources from "./Sources.js"; + +const files: Record.ReadonlyRecord = { + "/scope.ts": [ + 'import * as Whole from "./whole.js";', + 'import { named as renamed } from "./named.js";', + 'import fallback from "./fallback.js";', + 'export * from "./everything.js";', + 'export * as Space from "./space.js";', + 'export { remote as published } from "./remote.js";', + "const local = 1;", + "export { local as alias };", + ].join("\n"), + "/overloads.d.ts": [ + "/** First overload. */", + "export declare function pick(value: string): string;", + "/** Second overload. */", + "export declare function pick(value: number): number;", + "export interface Shape {", + " /** The side length. */", + " readonly side: number; // trailing", + " readonly name: string;", + "}", + ].join("\n"), + "/statements.d.ts": [ + 'import type { Thing } from "./thing.js";', + 'import * as Space from "../space.js";', + "/** Documented. */", + 'export declare const value: import("./other.js").Other; // trailing', + "export { value as alias };", + 'export * from "./everything.js";', + ].join("\n"), + "/broken.ts": "export const = ;", +}; + +// A read of a file the fixtures do not name is a defect in the test. +const fixtures: Layer.Layer = Sources.layer.pipe( + Layer.provide( + FileSystem.layerNoop({ + readFileString: (path) => + Effect.fromOption(Record.get(files, path)).pipe(Effect.orDie), + }), + ), +); + +describe("sources", () => { + layer(fixtures)((it) => { + it.effect("scope_bindings", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const scope = yield* sources.scope("/scope.ts"); + + expect(scope.imports).toStrictEqual({ + Whole: { specifier: "./whole.js", imported: Option.none() }, + renamed: { specifier: "./named.js", imported: Option.some("named") }, + fallback: { + specifier: "./fallback.js", + imported: Option.some("default"), + }, + }); + expect(scope.wildcards).toStrictEqual(["./everything.js"]); + expect(scope.namespaces).toStrictEqual({ Space: "./space.js" }); + expect(scope.reexports).toStrictEqual({ + published: { local: "remote", specifier: Option.some("./remote.js") }, + alias: { local: "local", specifier: Option.none() }, + }); + }), + ); + + it.effect("declarations_overloads", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const { local } = yield* sources.declarations("/overloads.d.ts"); + + const texts = (name: string): Option.Option => + pipe( + local, + Record.get(name), + Option.map(Array.map(Struct.get("text"))), + ); + + expect(texts("pick")).toStrictEqual( + Option.some([ + "export declare function pick(value: string): string;", + "export declare function pick(value: number): number;", + ]), + ); + expect(texts("Shape")).toStrictEqual( + Option.some([ + [ + "export interface Shape {", + " readonly side: number; ", + " readonly name: string;", + "}", + ].join("\n"), + ]), + ); + }), + ); + + it.effect("declarations_scope_statements", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const { statements } = yield* sources.declarations("/statements.d.ts"); + + // Each specifier's offsets point at its quoted literal in the comment-free text. + expect( + Array.map(statements, ({ names, text, specifiers }) => ({ + names, + text, + specifiers: Array.map(specifiers, ({ start, end, value }) => [ + text.slice(start, end), + value, + ]), + })), + ).toStrictEqual([ + { + names: ["Thing"], + text: 'import type { Thing } from "./thing.js";', + specifiers: [['"./thing.js"', "./thing.js"]], + }, + { + names: ["Space"], + text: 'import * as Space from "../space.js";', + specifiers: [['"../space.js"', "../space.js"]], + }, + { + names: ["value"], + text: 'export declare const value: import("./other.js").Other;', + specifiers: [['"./other.js"', "./other.js"]], + }, + ]); + }), + ); + + it.effect("syntax_error", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const error = yield* Effect.flip(sources.scope("/broken.ts")); + + expect(error.reason).toMatchObject({ + _tag: "SourceSyntax", + file: "/broken.ts", + }); + }), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts new file mode 100644 index 00000000000..bdd76188041 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts @@ -0,0 +1,294 @@ +import { + Array, + Cache, + Context, + Effect, + FileSystem, + Filter, + Function, + Layer, + Option, + Record, + Struct, + Tuple, + flow, + pipe, +} from "effect"; +import { parseSync } from "oxc-parser"; +import { ResolverFactory } from "oxc-resolver"; + +import { + boundNames, + declarationOf, + declaredNames, + isExportAll, + isExportNamed, + isImport, + specifierLiterals, + statementText, +} from "./Statements.js"; +import { TransformError } from "./TransformError.js"; + +import type { File, ScopeStatement } from "./Statements.js"; +import type { + Comment, + ImportDeclarationSpecifier, + ModuleExportName, + Program, + Statement, +} from "oxc-parser"; + +/** A name an import declaration brings into a module's scope. */ +export interface Binding { + readonly specifier: string; + /** The imported export, `None` for a namespace import. */ + readonly imported: Option.Option; +} + +/** A name an export specifier publishes. */ +export interface Reexport { + readonly local: string; + /** The module it is re-exported from, `None` for a binding of the exporting module. */ + readonly specifier: Option.Option; +} + +/** The names a module imports and exports, and its block comments. */ +export interface Scope { + readonly text: string; + readonly imports: Record.ReadonlyRecord; + /** Specifiers of `export * from`, in source order. */ + readonly wildcards: readonly string[]; + /** Specifiers of `export * as`, by exported name. */ + readonly namespaces: Record.ReadonlyRecord; + /** Export specifiers, by exported name. */ + readonly reexports: Record.ReadonlyRecord; + readonly comments: readonly Comment[]; +} + +/** The statements of a declaration file that bring names into its scope. */ +export interface Declarations { + /** The statements declaring each top-level name, without comments. Overloads share an entry. */ + readonly local: Record.ReadonlyRecord< + string, + Array.NonEmptyReadonlyArray + >; + /** Every import and declaration, in source order. */ + readonly statements: readonly ScopeStatement[]; +} + +/** A module's syntax tree and comments. */ +export type Parsed = Pick, "program" | "comments">; + +/** Parses TypeScript with oxc, failing with every syntax error it reports. The file's name selects the dialect, such as a declaration file's. */ +export const parse: { + (file: string): (text: string) => Effect.Effect; + (text: string, file: string): Effect.Effect; +} = Function.dual( + 2, + (text: string, file: string): Effect.Effect => { + const { program, comments, errors } = parseSync(file, text); + + return Array.match(errors, { + onEmpty: () => Effect.succeed({ program, comments }), + onNonEmpty: (failures) => + Effect.fail( + TransformError.sourceSyntax( + file, + Array.map(failures, Struct.get("message")), + ), + ), + }); + }, +); + +const exportName = (name: ModuleExportName): string => { + if (name.type === "Literal") { + return name.value; + } + + return name.name; +}; + +const importedName = ( + specifier: ImportDeclarationSpecifier, +): Option.Option => { + if (specifier.type === "ImportSpecifier") { + return Option.some(exportName(specifier.imported)); + } + + if (specifier.type === "ImportDefaultSpecifier") { + return Option.some("default"); + } + + return Option.none(); +}; + +const collectScope = (program: Program): Omit => { + const exportsAll = Array.filter(program.body, isExportAll); + + return { + imports: pipe( + program.body, + Array.filter(isImport), + Array.flatMap((statement) => + Array.map( + statement.specifiers, + (specifier) => + [ + specifier.local.name, + { + specifier: statement.source.value, + imported: importedName(specifier), + }, + ] as const, + ), + ), + Record.fromEntries, + ), + wildcards: pipe( + exportsAll, + Array.filter(({ exported }) => exported === null), + Array.map(({ source }) => source.value), + ), + namespaces: pipe( + exportsAll, + Array.filterMap( + Filter.fromPredicateOption(({ exported, source }) => + pipe( + exported, + Option.fromNullishOr, + Option.map((name) => [exportName(name), source.value] as const), + ), + ), + ), + Record.fromEntries, + ), + reexports: pipe( + program.body, + Array.filter(isExportNamed), + Array.flatMap((statement) => + Array.map( + statement.specifiers, + (specifier) => + [ + exportName(specifier.exported), + { + local: exportName(specifier.local), + specifier: Option.fromNullishOr(statement.source?.value), + }, + ] as const, + ), + ), + Record.fromEntries, + ), + }; +}; + +const collectDeclarations = ( + text: string, + { program, comments }: Parsed, +): Declarations => { + const file: File = { text, comments, literals: specifierLiterals(program) }; + const scoped = Array.filterMap( + program.body, + Filter.fromPredicateOption((statement) => + pipe( + statement, + boundNames, + Option.map((names): readonly [Statement, ScopeStatement] => [ + statement, + { names, ...statementText(statement, file) }, + ]), + ), + ), + ); + + return { + local: pipe( + scoped, + Array.flatMap(([statement, scope]) => + pipe( + declarationOf(statement), + Array.fromOption, + Array.flatMap(declaredNames), + Array.map((name) => ({ name, scope })), + ), + ), + Array.groupBy(Struct.get("name")), + Record.map(Array.map(Struct.get("scope"))), + ), + statements: Array.map(scoped, Tuple.get(1)), + }; +}; + +/** Reads TypeScript modules with oxc, each file once per run, and resolves their specifiers. */ +export class Sources extends Context.Service< + Sources, + { + /** The imports, re-exports and comments of a module. */ + readonly scope: (file: string) => Effect.Effect; + /** The imports and declarations of a declaration file. */ + readonly declarations: ( + file: string, + ) => Effect.Effect; + /** The file a module specifier written in `file` names, `None` when it names nothing on disk. */ + readonly resolve: ( + file: string, + specifier: string, + ) => Option.Option; + } +>()("@local/hashql-typescript-docs/Sources") {} + +// The SDK's specifiers name the emitted `.js`, while its sources and declarations end in `.ts` and `.d.ts`. +const resolver = new ResolverFactory({ + extensionAlias: { ".js": [".ts", ".d.ts", ".js"] }, +}); + +export const layer: Layer.Layer = + Layer.effect( + Sources, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + + const read = Effect.fnUntraced( + function* (file: string) { + const text = yield* fs.readFileString(file); + const parsed = yield* parse(text, file); + + return { ...parsed, text }; + }, + Effect.catchTag("PlatformError", TransformError.fileSystem), + ); + + const scopes = yield* Cache.make({ + capacity: Number.POSITIVE_INFINITY, + lookup: flow( + read, + Effect.map( + ({ text, program, comments }): Scope => ({ + ...collectScope(program), + text, + comments: Array.filter(comments, ({ type }) => type === "Block"), + }), + ), + ), + }); + + const declarations = yield* Cache.make({ + capacity: Number.POSITIVE_INFINITY, + lookup: flow( + read, + Effect.map(({ text, ...parsed }) => + collectDeclarations(text, parsed), + ), + ), + }); + + return Sources.of({ + scope: (file) => Cache.get(scopes, file), + declarations: (file) => Cache.get(declarations, file), + resolve: (file, specifier) => + Option.fromNullishOr(resolver.resolveFileSync(file, specifier).path), + }); + }), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts b/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts new file mode 100644 index 00000000000..206e438cfba --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts @@ -0,0 +1,251 @@ +/** + * The top-level statements of a TypeScript module: which names each brings into scope, and its text without comments. + * + * @module + */ +import { Array, Filter, Function, Option, Order, String, pipe } from "effect"; +import { Visitor } from "oxc-parser"; + +import type { + BindingPattern, + Comment, + Declaration, + ExportAllDeclaration, + ExportNamedDeclaration, + ImportDeclaration, + Program, + Statement, + StringLiteral, + TSImportEqualsDeclaration, + TSQualifiedName, +} from "oxc-parser"; + +/** A module specifier in a statement's text. */ +export interface Specifier { + /** Where its string literal starts in the text, quotes included. */ + readonly start: number; + readonly end: number; + readonly value: string; +} + +/** A top-level statement of a declaration file that brings names into its scope: an import or a declaration. */ +export interface ScopeStatement { + /** The names it binds. */ + readonly names: readonly string[]; + /** Its text without comments. */ + readonly text: string; + /** The module specifiers its text names, in order. */ + readonly specifiers: readonly Specifier[]; +} + +export const isImport = ( + statement: Statement, +): statement is ImportDeclaration => statement.type === "ImportDeclaration"; + +const isImportEquals = ( + statement: Statement, +): statement is TSImportEqualsDeclaration => + statement.type === "TSImportEqualsDeclaration"; + +export const isExportAll = ( + statement: Statement, +): statement is ExportAllDeclaration => + statement.type === "ExportAllDeclaration"; + +export const isExportNamed = ( + statement: Statement, +): statement is ExportNamedDeclaration => + statement.type === "ExportNamedDeclaration"; + +const declarationTypes: ReadonlySet = new Set([ + "VariableDeclaration", + "FunctionDeclaration", + "TSDeclareFunction", + "ClassDeclaration", + "TSTypeAliasDeclaration", + "TSInterfaceDeclaration", + "TSEnumDeclaration", + "TSModuleDeclaration", +] satisfies Declaration["type"][]); + +const isDeclaration = (statement: Statement): statement is Declaration => + declarationTypes.has(statement.type); + +export const declarationOf = ( + statement: Statement, +): Option.Option => { + if (statement.type === "ExportNamedDeclaration") { + return Option.fromNullishOr(statement.declaration); + } + + return Option.liftPredicate(statement, isDeclaration); +}; + +// Destructuring patterns and string-named modules declare no name a member can have. +const identifierName = ( + node: BindingPattern | StringLiteral | TSQualifiedName | null, +): Option.Option => { + if (node?.type === "Identifier") { + return Option.some(node.name); + } + + return Option.none(); +}; + +export const declaredNames = (declaration: Declaration): readonly string[] => { + if (declaration.type === "VariableDeclaration") { + return Array.filterMap( + declaration.declarations, + Filter.fromPredicateOption(({ id }) => identifierName(id)), + ); + } + + return Array.fromOption(identifierName(declaration.id)); +}; + +// The names a statement brings into the file's scope, `None` for a statement that binds none, such as an export specifier. +export const boundNames = ( + statement: Statement, +): Option.Option => { + if (isImport(statement)) { + return Option.some( + Array.map(statement.specifiers, ({ local }) => local.name), + ); + } + + if (isImportEquals(statement)) { + return Option.some([statement.id.name]); + } + + return Option.map(declarationOf(statement), declaredNames); +}; + +// The module specifiers a statement names: its own source, and those of `import("…")` types and `require("…")` references inside it. +export const specifierLiterals = ( + program: Program, +): readonly StringLiteral[] => { + const literals: StringLiteral[] = []; + const collect = (literal: StringLiteral): void => { + literals.push(literal); + }; + + new Visitor({ + ImportDeclaration: ({ source }): void => { + collect(source); + }, + TSImportType: ({ source }): void => { + collect(source); + }, + TSExternalModuleReference: ({ expression }): void => { + collect(expression); + }, + }).visit(program); + + return literals; +}; + +/** A range of a file's text that a statement's text leaves out or names as a specifier. */ +interface Cut { + readonly start: number; + readonly end: number; + readonly specifier: Option.Option; +} + +// A comment alone on its lines leaves with those lines, so removing it leaves no blank line behind. +const commentRange = ( + text: string, + comment: Comment, +): { readonly start: number; readonly end: number } => { + const lineStart = text.lastIndexOf("\n", comment.start - 1) + 1; + const lineEnd = text.indexOf("\n", comment.end); + + if ( + lineEnd !== -1 && + String.isEmpty(String.trim(text.slice(lineStart, comment.start))) && + String.isEmpty(String.trim(text.slice(comment.end, lineEnd))) + ) { + return { start: lineStart, end: lineEnd + 1 }; + } + + return { start: comment.start, end: comment.end }; +}; + +/** A declaration file's text and the parts of it that statements cut out or name. */ +export interface File { + readonly text: string; + readonly comments: readonly Comment[]; + readonly literals: readonly StringLiteral[]; +} + +const textOf = ( + statement: Statement, + { text, comments, literals }: File, +): Omit => { + const within = ({ start, end }: { start: number; end: number }): boolean => + start >= statement.start && end <= statement.end; + const cuts = pipe( + [ + ...pipe( + comments, + Array.filter(within), + Array.map( + (comment): Cut => ({ + ...commentRange(text, comment), + specifier: Option.none(), + }), + ), + ), + ...pipe( + literals, + Array.filter(within), + Array.map( + ({ start, end, value }): Cut => ({ + start, + end, + specifier: Option.some(value), + }), + ), + ), + ], + Array.sortWith((cut: Cut) => cut.start, Order.Number), + ); + const result = Array.reduce( + cuts, + { + position: statement.start, + text: "", + specifiers: Array.empty(), + }, + ({ position, text: written, specifiers }, { start, end, specifier }) => { + const before = `${written}${text.slice(position, Math.max(position, start))}`; + + return Option.match(specifier, { + onNone: () => ({ + position: Math.max(position, end), + text: before, + specifiers, + }), + onSome: (value) => ({ + position: end, + text: `${before}${text.slice(start, end)}`, + specifiers: Array.append(specifiers, { + start: before.length, + end: before.length + end - start, + value, + }), + }), + }); + }, + ); + + return { + text: `${result.text}${text.slice(result.position, statement.end)}`, + specifiers: result.specifiers, + }; +}; + +/** A statement's text without the comments inside it, with the offsets of its specifiers in that text. */ +export const statementText: { + (file: File): (statement: Statement) => Omit; + (statement: Statement, file: File): Omit; +} = Function.dual(2, textOf); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts new file mode 100644 index 00000000000..8ea482a471a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts @@ -0,0 +1,126 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable +import { + Array, + Effect, + FileSystem, + Layer, + Option, + Path, + Schema, + pipe, +} from "effect"; +import { Command, Flag } from "effect/cli"; + +import * as Analysis from "./Analysis.js"; +import * as Mdx from "./Mdx.js"; +import * as Page from "./Page.js"; +import * as Site from "./Site.js"; +import * as Sources from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +// The reference folder lists the package page first, then its namespaces, then the other entry points in the order `analyze` received them. +const Meta = Schema.fromJsonString( + Schema.Struct({ title: Schema.String, pages: Schema.Array(Schema.String) }), + { space: 2 }, +); + +const packageDirectory = ( + ...segments: string[] +): Effect.Effect => + Effect.map(Path.Path, (path) => + path.resolve(import.meta.dirname, "..", ...segments), + ); + +export const command = Command.make("transform", { + lib: Flag.Directory("lib", { mustExist: true }).pipe( + Flag.withDescription("The analyzed package's folder"), + ), + analysis: Flag.Directory("analysis", { mustExist: true }).pipe( + Flag.withDescription("The directory `analyze` wrote"), + Flag.withDefault(packageDirectory(".generated")), + ), + out: Flag.Directory("out").pipe( + Flag.withDescription( + "The directory the reference pages are written to; its previous contents are removed", + ), + Flag.withDefault(packageDirectory("content", "docs", "reference")), + ), + url: Flag.String("url").pipe( + Flag.withDescription("The URL the package page is served at"), + Flag.withDefault("/docs/reference"), + ), +}); + +// Fumadocs lists a directory's pages under its index page, so a page with namespace pages below it, the package page among them, is its directory's index. +const segmentsOf = ( + site: Site.Site["Service"], + page: Site.Page, +): readonly string[] => { + const isDirectory = + Array.isReadonlyArrayEmpty(page.path) || + Array.some(page.container.members, (item) => + Option.isSome(site.pageOf(item)), + ); + + if (isDirectory) { + return [...page.path, "index"]; + } + + return page.path; +}; + +const write = Effect.fnUntraced( + function* (out: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const site = yield* Site.Site; + + // Encoding a value of the schema's own type cannot fail. + const meta = yield* Schema.encodeEffect(Meta)({ + title: "API reference", + pages: [ + "index", + "...", + ...pipe( + site.roots, + Array.flatMap(({ path: segments }) => Array.take(segments, 1)), + Array.dedupe, + ), + ], + }).pipe(Effect.orDie); + + yield* fs.remove(out, { recursive: true, force: true }); + const writeMdx = Effect.fnUntraced(function* ( + segments: readonly string[], + content: string, + ) { + const file = `${path.join(out, ...segments)}.mdx`; + + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, content); + }); + + yield* Effect.forEach(site.pages, (page) => + pipe( + Page.render(page), + Effect.map(Mdx.stringify({ title: page.title })), + Effect.flatMap((content) => writeMdx(segmentsOf(site, page), content)), + ), + ); + yield* fs.writeFileString(path.join(out, "meta.json"), meta); + yield* Effect.log(`Wrote ${site.pages.length} pages to ${out}`); + }, + Effect.catchTag("PlatformError", TransformError.fileSystem), +); + +export const handler = command.pipe( + Command.withHandler(({ out }) => + Effect.flatMap(Path.Path, (path) => write(path.resolve(out))), + ), + Command.provide(({ lib, analysis, url }) => + Site.layer({ url }).pipe( + Layer.provideMerge(Analysis.layer({ lib, analysis })), + Layer.provideMerge(Sources.layer), + ), + ), +); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts new file mode 100644 index 00000000000..2df23f6871e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts @@ -0,0 +1,114 @@ +import { Data } from "effect"; + +import type { Cause, Schema } from "effect"; +import type { PlatformError } from "effect/PlatformError"; + +/** Why building the reference pages failed. */ +export type Reason = Data.TaggedEnum<{ + /** Reading or writing a file failed. */ + FileSystem: { readonly cause: PlatformError }; + /** Oxc rejected a module that a page draws on. */ + SourceSyntax: { readonly file: string; readonly messages: readonly string[] }; + /** A declaration map does not name the source TypeScript emitted its file from. */ + MalformedSourceMap: { + readonly file: string; + readonly cause: Schema.SchemaError; + }; + /** The manifest `analyze` writes beside its models does not decode. */ + MalformedManifest: { + readonly file: string; + readonly cause: Schema.SchemaError; + }; + /** API Extractor could not load the API model the analysis wrote. */ + UnreadableModel: { + readonly file: string; + readonly cause: Cause.UnknownError; + }; + /** The analysis output lacks something a page needs. */ + MalformedAnalysis: { readonly detail: string }; + /** A documentation comment uses TSDoc syntax the pages have no rendering for. */ + UnsupportedComment: { readonly kind: string }; + /** A signature block's meta holds a `links` attribute that the transform did not write. */ + UnreadableCodeBlock: { + readonly cause: Schema.SchemaError | Cause.UnknownError; + }; + /** A signature block's code refers to a different number of names than its links cover. */ + MisalignedCodeBlock: { readonly references: number; readonly links: number }; +}>; + +/** Constructors and matching helpers for the tagged {@link Reason} variants. */ +export const Reason: Data.TaggedEnum.Constructor = + Data.taggedEnum(); + +const TransformErrorBase: ReturnType< + typeof Data.TaggedError<"TransformError"> +> = Data.TaggedError("TransformError"); + +/** Failure to build the reference pages from an analysis. `reason` names the input at fault. */ +export class TransformError extends TransformErrorBase<{ + readonly reason: Reason; +}> { + static readonly fileSystem = (cause: PlatformError): TransformError => + new TransformError({ reason: Reason.FileSystem({ cause }) }); + + static readonly sourceSyntax = ( + file: string, + messages: readonly string[], + ): TransformError => + new TransformError({ reason: Reason.SourceSyntax({ file, messages }) }); + + static readonly malformedSourceMap = ( + file: string, + cause: Schema.SchemaError, + ): TransformError => + new TransformError({ reason: Reason.MalformedSourceMap({ file, cause }) }); + + static readonly malformedManifest = ( + file: string, + cause: Schema.SchemaError, + ): TransformError => + new TransformError({ reason: Reason.MalformedManifest({ file, cause }) }); + + static readonly unreadableModel = ( + file: string, + cause: Cause.UnknownError, + ): TransformError => + new TransformError({ reason: Reason.UnreadableModel({ file, cause }) }); + + static readonly malformedAnalysis = (detail: string): TransformError => + new TransformError({ reason: Reason.MalformedAnalysis({ detail }) }); + + static readonly unsupportedComment = (kind: string): TransformError => + new TransformError({ reason: Reason.UnsupportedComment({ kind }) }); + + static readonly unreadableCodeBlock = ( + cause: Schema.SchemaError | Cause.UnknownError, + ): TransformError => + new TransformError({ reason: Reason.UnreadableCodeBlock({ cause }) }); + + static readonly misalignedCodeBlock = ( + references: number, + links: number, + ): TransformError => + new TransformError({ + reason: Reason.MisalignedCodeBlock({ references, links }), + }); + + override get message(): string { + return Reason.$match(this.reason, { + FileSystem: ({ cause }) => cause.message, + SourceSyntax: ({ file, messages }) => + `${file} does not parse: ${messages.join("; ")}`, + MalformedSourceMap: ({ file, cause }) => `${file}: ${cause.message}`, + MalformedManifest: ({ file, cause }) => `${file}: ${cause.message}`, + UnreadableModel: ({ file, cause }) => `${file}: ${cause.message}`, + MalformedAnalysis: ({ detail }) => detail, + UnsupportedComment: ({ kind }) => + `Documentation comments use ${kind}, which the reference pages cannot render`, + UnreadableCodeBlock: ({ cause }) => + `A signature block's links do not decode: ${cause.message}`, + MisalignedCodeBlock: ({ references, links }) => + `A signature block's code refers to ${references} names, but its links cover ${links}`, + }); + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/src/cli.ts b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts new file mode 100644 index 00000000000..252c5f10912 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts @@ -0,0 +1,18 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable +import { NodeRuntime, NodeServices } from "@effect/platform-node"; +import { Effect } from "effect"; +import { Command } from "effect/cli"; + +import * as Analyze from "./Analyze.js"; +import * as Transform from "./Transform.js"; + +const command = Command.make("docs").pipe( + Command.withSubcommands([Analyze.handler, Transform.handler]), +); + +Command.run(command, { version: "0.0.1" }).pipe( + // oxlint-disable-next-line effecttsgo/strict-effect-provide -- entrypoint + Effect.provide(NodeServices.layer), + // oxlint-disable-next-line typescript/strict-void-return -- false positive + NodeRuntime.runMain, +); diff --git a/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json b/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json new file mode 100644 index 00000000000..cac41c44891 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json @@ -0,0 +1,17 @@ +{ + "extends": "../typescript/tsconfig.json", + "compilerOptions": { + "noEmit": false, + "emitDeclarationOnly": true, + "declaration": true, + "declarationMap": true, + "outDir": ".generated/declarations", + "rootDir": "../typescript/src", + "incremental": false + }, + "include": ["../typescript/src"], + "exclude": [ + "../typescript/src/**/*.test.ts", + "../typescript/src/**/*.test-d.ts" + ] +} diff --git a/libs/@local/hashql/sdk/typescript-docs/tsconfig.json b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json new file mode 100644 index 00000000000..434ec35d288 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": ["@tsconfig/bases/next", "@local/tsconfig/policy.json"], + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + "**/*.mts", + "**/*.mjs", + ".next/types/**/*.ts", + ".next/dev/types/**/*.ts" + ], + "exclude": ["node_modules", ".generated", ".twoslash"] +} diff --git a/libs/@local/hashql/sdk/typescript-docs/turbo.json b/libs/@local/hashql/sdk/typescript-docs/turbo.json new file mode 100644 index 00000000000..3de78d0fc11 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/turbo.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://turborepo.org/schema.json", + "extends": ["//"], + "tasks": { + // TypeScript 7 emits a declaration file per module, which keeps each `export * as` a namespace API Extractor reads members from. + "doc:declarations": { + "dependsOn": ["^manifest"], + "outputs": [".generated/declarations/**"] + }, + "doc:analyze": { + "dependsOn": ["doc:declarations"], + "outputs": [".generated/entry-points.json", ".generated/api/**"] + }, + "doc:transform": { + "dependsOn": ["doc:analyze"], + "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/oxfmt.config.ts"], + "outputs": ["content/docs/reference/**"] + }, + "codegen": { + "dependsOn": ["doc:transform"], + "outputs": [".source/**"] + }, + // Twoslash type-checks the examples against the SDK's built declarations. + "build": { + "dependsOn": ["codegen", "^build"], + "env": ["NEXT_TELEMETRY_DISABLED"], + "outputs": [".next/**", "!.next/cache/**"] + }, + "dev": { + "dependsOn": ["codegen", "^build"], + "cache": false, + "persistent": true, + "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] + }, + "start": { + "dependsOn": ["build"], + "cache": false, + "persistent": true, + "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] + } + } +} diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 2d836a0eb64..966bf7981da 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -1,3 +1,3 @@ # HashQL TypeScript SDK -TypeScript SDK for HashQL. +Write HashQL programs in TypeScript. The guide and the API reference are in [`@local/hashql-typescript-docs`](../typescript-docs). diff --git a/libs/@local/hashql/sdk/typescript/docs/index.md b/libs/@local/hashql/sdk/typescript/docs/index.md new file mode 100644 index 00000000000..2f49d7f6a62 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/docs/index.md @@ -0,0 +1,45 @@ +# HashQL TypeScript SDK + +- What is HashQL? +- Create your first Program +- The two different notations + +HashQL is a query language designed for interacting with the HASH graph, a bi-temporal knowledge graph database which is able to represent complex relationships through the use of strongly typed ontologies. Through HashQL, users can perform advanced graph traversals, data analysis, or retrieve entities from the graph. Unlike traditional query languages, HashQL is a fully specified programming language and enables the expression of complete programs with embedded logic. It allows for chaining of multiple operations and access to different data sources transparently to the user. Similar to the HASH graph, it is strongly typed. A notable property of HashQL is that it does not prescribe a single canonical syntax; instead, it is built to be syntax-independent, with the explicit goal of allowing different ways of interacting with the underlying graph, through different languages and thereby bindings. This lets HashQL use existing tooling instead of requiring a custom toolchain, making development easier, particularly for new users. + +> HashQL programs are full programs; they are type-checked, compiled and executed by the HASH graph. + +The TypeScript SDK is such a binding that allows you to write HashQL programs in TypeScript. + +HashQL is functional and side-effect free; what does that mean? + +**Everything is an expression.** JavaScript differentiates between expressions and statements. Expressions produce values, and statements are used to bind values to names. For example, `2 + 3` is an expression that produces the value `5`, while `let x = 2 + 3` is a statement that binds the value `5` to the name `x`. + +**Fully Functional.** HashQL does not have the notion of operators, instead everything is a function call. User-defined functions? Functions. Arithmetic operations? Functions. Control flow? Functions. Binding values to names? Functions. To make this possible, HashQL has special-form functions: functions that are special in how they are evaluated; they have a reserved interpretation and cannot be created outside of the compiler. To put it another way, in Rust terms, special forms are like Rust intrinsics; like macros, they expand at compile time early in the pipeline. + +**Side-effect free.** The language is side-effect free, what does that mean? First: the language is immutable; once a value has been bound to a name, it cannot be changed. Second: an action inside the language cannot have any observable side-effects; a side-effect is something that happens outside of the language, such as I/O or modifying the environment. + +This means that HashQL only has two constructs to work with, on top of which everything else is built: function calls and values. That's it, and this, in conjunction with everything else, has some profound consequences. Let's take a look at a program that takes an input, adds 5 to it, and returns the result: + +``` +let(x, input(in, Integer), + let(y, 5, + +(x, y) + ) +) +``` + +Not very readable, is it? That's why the specification uses a special syntax to make programs easier to read and write. The same program can be written as: + +``` +let x = input(in, Integer) in +let y = 5 in +x + y +``` + +This makes it clearer what is happening; we can see the following interesting observations: + +1. `let` bindings create a new item in their scope (everything that is behind the `in` is evaluated in the new scope) +2. `let` bindings return a value: the value of the expression that it is surrounding +3. an expression **must** return a value + +Supported operators: diff --git a/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap new file mode 100644 index 00000000000..899b8519029 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap @@ -0,0 +1,393 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`draft_filters > frontend_selection: 5. Frontend: look up a published entity 1`] = ` +[ + "::kernel::special_form::let", + "webId", + [ + "::kernel::special_form::input", + "web_id", + "::graph::types::principal::actor_group::web::WebId", + ], + [ + "::kernel::special_form::let", + "entityUuid", + [ + "::kernel::special_form::input", + "entity_uuid", + "::graph::types::knowledge::entity::EntityUuid", + ], + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::bool::and", + [ + "::core::bool::and", + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "web_id", + ], + "webId", + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "entity_uuid", + ], + "entityUuid", + ], + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "draft_id", + ], + [ + "::core::option::None", + ], + ], + ], + ], + ], + ], + ], +] +`; + +exports[`draft_filters > frontend_selection: 6. Frontend: the sidebar's web and arch… 1`] = ` +[ + "::kernel::special_form::let", + "webId", + [ + "::kernel::special_form::input", + "web_id", + "::graph::types::principal::actor_group::web::WebId", + ], + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "web_id", + ], + "webId", + ], + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::bool::and", + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "archived", + ], + { + "#literal": false, + }, + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "draft_id", + ], + [ + "::core::option::None", + ], + ], + ], + ], + ], + ], +] +`; + +exports[`draft_filters > frontend_selection: 7. Frontend: match any supplied entity … 1`] = ` +[ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::bool::or", + [ + "::core::bool::or", + { + "#literal": false, + }, + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "entity_uuid", + ], + [ + "::graph::types::knowledge::entity::EntityUuid", + [ + "::core::uuid::Uuid", + { + "#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f", + }, + ], + ], + ], + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "entity_uuid", + ], + [ + "::graph::types::knowledge::entity::EntityUuid", + [ + "::core::uuid::Uuid", + { + "#literal": "926b2d9b-c099-4cc4-9b0b-906b0c27bc70", + }, + ], + ], + ], + ], + ], + ], +] +`; + +exports[`draft_filters > frontend_selection: 8. Frontend: make draft inclusion a que… 1`] = ` +[ + "::kernel::special_form::let", + "includeDrafts", + [ + "::kernel::special_form::input", + "include_drafts", + "::kernel::type::Boolean", + { + "#literal": false, + }, + ], + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::kernel::special_form::if", + "includeDrafts", + { + "#literal": true, + }, + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "draft_id", + ], + [ + "::core::option::None", + ], + ], + ], + ], + ], + ], +] +`; diff --git a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts new file mode 100644 index 00000000000..82c95986a66 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts @@ -0,0 +1,493 @@ +/** + * A checked tour of the HashQL TypeScript SDK. + * + * Each test pairs code you can write and the type TypeScript infers for it with a limitation and its supported workaround. `tsc` and `vitest --typecheck` check this file. Neither of them runs it. A rejected line carries `@ts-expect-error`, so the check fails both when an inference changes and when an expected rejection disappears. + * + * Type checking covers the authoring API. It does not execute HashQL. The SDK constructs syntax, and the HashQL compiler resolves names, checks scopes and type-checks the emitted program. Construction failures, such as an invalid binding name, arrive as a `Result` failure at run time and do not appear in these types. + * + * @module + */ +// oxlint-disable hash/naming-conventions -- HashQL type and constructor names keep their PascalCase spelling in callback arguments +// oxlint-disable vitest/prefer-expect-assertions -- type tests run through the compiler, not the runtime assertion counter +// oxlint-disable eslint/no-magic-numbers -- literal values demonstrate the numeric types +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { + Type as Alias, + Import, + Let, + Newtype, + withPrelude, +} from "../src/do/index.js"; +import { Expression, Module, Program } from "../src/main.js"; +import * as Operators from "../src/Program/Operators.js"; + +import type { + Inputs, + ProgramError, + Type, + TypeExpression, +} from "../src/main.js"; + +// Declarations bind TypeScript descriptions of HashQL types to absolute paths. The SDK trusts these annotations and includes no standard-library bundle, so the fixtures below describe only what the tour uses. Application code yields each `Result` inside `Result.gen`. The tour unwraps them with `getOrThrow`. + +type NullableString = Type.Union< + readonly [Type.PrimitiveString, Type.PrimitiveNull] +>; + +type Person = Type.Struct<{ + readonly name: Type.PrimitiveString; + readonly archived: Type.PrimitiveBoolean; + readonly scores: Type.List; + readonly labels: Type.Dict; + readonly location: Type.Tuple< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger] + >; + readonly then: Type.PrimitiveString; +}>; + +// The query helpers recognize a graph by this opaque shape. Its marker field names the vertex type. +type PersonGraph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Person }> +>; +type TemporalAxes = Type.Opaque< + "::graph::temporal::QueryTemporalAxes", + Type.Unknown +>; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + String: Module.type(), + Boolean: Module.type(), + }, + }), +); + +const profile = Result.getOrThrow( + Module.define("::example::profile", { + values: { + greet: + Module.value< + Type.Function + >(), + length: + Module.value< + Type.Function + >(), + }, + }), +); + +const head = Result.getOrThrow( + Module.define("::graph::head", { + values: { + entities: + Module.value>(), + }, + }), +); + +const temporal = Result.getOrThrow( + Module.define("::graph::tmp", { + values: { + decision_time_now: + Module.value>(), + }, + }), +); + +// A prelude seeds the environments without emitting imports. `$.query` offers `entities` because the value environment holds a graph-returning `entities`. +const { Do } = withPrelude({ + modules: { kernel, profile }, + values: { + entities: head.values.entities, + now: temporal.values.decision_time_now, + }, +}); + +type Closed = Expression.Expression; +type Built = Result.Result< + Expression.Expression, + ProgramError.Construction +>; + +declare const person: Closed; +declare const text: Closed; + +describe("reusable_expressions", () => { + test("inputs_and_defaults", () => { + // An expression is a value you can store and reuse. Its second type parameter records the host inputs it needs. + const count = Expression.input("count", kernel.types.Integer); + const nonzero = Operators.ne(count, 0n); + expectTypeOf(nonzero).toEqualTypeOf< + Operators.Predicate<{ readonly count: Type.PrimitiveInteger }> + >(); + + // A default makes the input optional for the host. + const page = Expression.input("page", kernel.types.Integer, 1n); + expectTypeOf>().toEqualTypeOf<{ + readonly page?: Type.PrimitiveInteger; + }>(); + + // A program that reuses `nonzero` inherits its requirement. + const root = Result.getOrThrow( + Do(($) => + Operators.and(nonzero, $.input("enabled", kernel.types.Boolean, true)), + ), + ); + const program = Program.program(root); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly enabled?: Type.PrimitiveBoolean; + }>(); + + // Limitation: an annotation cannot hide a requirement. + // @ts-expect-error A closed expression type has no room for `count`. + const hidden: Closed = nonzero; + expectTypeOf(hidden); + // Workaround: let TypeScript infer the type, or name the requirement. + const named: Expression.Expression< + Type.PrimitiveBoolean, + Expression.Inputs + > = nonzero; + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); + + // @ts-expect-error The default for an Integer input cannot be a Boolean. + Expression.input("count", kernel.types.Integer, true); + }); + + test("conflicting_input_names", () => { + // Uses of one input name intersect their types. A required use makes the name required. + const asInteger = Expression.input("shared", kernel.types.Integer); + const asString = Expression.input("shared", kernel.types.String); + const both = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- the conditional names its branches `then` and `else` + then: asInteger, + else: asString, + }); + + // Limitation: incompatible primitives produce `Never` in the record rather than a compile error at the use site. + expectTypeOf>().toEqualTypeOf<{ + readonly shared: Type.Never; + }>(); + + // Workaround: give inputs of different types different names. + const renamed = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- the conditional names its branches `then` and `else` + then: asInteger, + else: Expression.input("label", kernel.types.String), + }); + expectTypeOf>().toEqualTypeOf<{ + readonly shared: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + }>(); + }); +}); + +const userId: unique symbol = Symbol("UserId"); +const accountId: unique symbol = Symbol("AccountId"); +type UserId = Type.Opaque; + +describe("declarations", () => { + test("imports_and_aliases", () => { + const built = Do( + // Select names, and rename some of them. An alias of `"_"` keeps the original name. + Import((_, { kernel }) => kernel, { Integer: "Int", String: "_" }), + // A type alias preserves the underlying semantic type. + Alias("Count", (_, { Int }) => Int), + ($, _values, { Count, String }) => { + expectTypeOf(Count).toEqualTypeOf(); + expectTypeOf(String).toEqualTypeOf(); + // `$.ref` reaches module members without importing them. + return $.ref.profile.values.length($.input("name", String)); + }, + ); + expectTypeOf(built).toEqualTypeOf< + Built + >(); + + // Limitation: a selection must name an export of the declared module. + // @ts-expect-error This kernel declaration exports no `Missing`. + Import(() => kernel, ["Missing"]); + // Workaround: add the export to the module declaration, then import it. + }); + + test("nominal_types", () => { + Do( + Import((_, { kernel }) => kernel), + // A newtype introduces a nominal type and its constructor under one name. The unique symbol supplies TypeScript's identity and is not emitted. + Newtype("UserId", userId, (_, { Integer }) => Integer), + Let("owner", (_, { UserId }) => UserId(1n)), + ($, { owner, UserId }, types) => { + expectTypeOf(owner).toEqualTypeOf>(); + expectTypeOf(types.UserId).toEqualTypeOf< + TypeExpression.TypeExpression + >(); + + // Limitation: the representation does not have the nominal type. + // @ts-expect-error An Integer default does not have type UserId. + $.input("id", types.UserId, 2n); + // Workaround: wrap the representation with the constructor. + return $.input("id", types.UserId, UserId(2n)); + }, + ); + + // oxlint-disable-next-line typescript/no-inferrable-types -- shows the rejection after widening drops the unique symbol type + const widened: symbol = Symbol("UserId"); + // @ts-expect-error A widened `symbol` cannot tell declarations apart. + Newtype("UserId", widened, () => kernel.types.Integer); + }); + + test("shadowing", () => { + Do( + Import((_, { kernel }) => kernel), + Newtype("Id", userId, (_, { Integer }) => Integer), + Let("first", (_, { Id }) => Id(1n)), + // A later declaration shadows a name for the steps after it. + Newtype("Id", accountId, (_, { Integer }) => Integer), + // Values and types live in separate environments. This value named `Integer` leaves the type `Integer` untouched. + Let("Integer", ($) => $.literal("not a type")), + (_, { first, Id, Integer }, types) => { + expectTypeOf(first).toEqualTypeOf>(); + expectTypeOf(Integer).toEqualTypeOf>(); + expectTypeOf(types.Integer).toEqualTypeOf< + typeof kernel.types.Integer + >(); + + // Limitation: the same HashQL spelling does not make two nominal types equal. + // @ts-expect-error The shadowed `Id` built `first`. + const mixed: typeof first = Id(2n); + expectTypeOf(mixed); + // Workaround: a binding keeps its declared type, so keep using `first`. + return first; + }, + ); + }); +}); + +describe("expressions", () => { + test("projections", () => { + // Struct fields and tuple positions become typed properties. + expectTypeOf(person.name).toEqualTypeOf>(); + expectTypeOf(person.location[0]).toEqualTypeOf< + Closed + >(); + // `$project` spells the same projection explicitly. + expectTypeOf(person.$project("archived")).toEqualTypeOf< + typeof person.archived + >(); + + expectTypeOf(person.then).toEqualTypeOf>(); + expectTypeOf(person.$project("then")).toEqualTypeOf< + Closed + >(); + + // @ts-expect-error A struct has only its declared fields. + expectTypeOf(person.email); + }); + + test("indexing", () => { + // Indexing a list or dictionary may find nothing, so the result includes `Null`. + type MaybeInteger = Type.Union< + readonly [Type.PrimitiveInteger, Type.PrimitiveNull] + >; + expectTypeOf(person.scores.$index(0n)).toEqualTypeOf< + Closed + >(); + expectTypeOf(person.labels.$index(text)).toEqualTypeOf< + Closed + >(); + + // Limitation: the key must have the declared key type. + // @ts-expect-error List positions are Integer expressions. + person.scores.$index(text); + // Workaround: supply an Integer-producing expression or a bigint. + expectTypeOf( + person.scores.$index(profile.values.length(text)), + ).toEqualTypeOf>(); + }); + + test("calls", () => { + // A declared function value is callable with typed arguments. + const length = profile.values.length(person.name); + expectTypeOf(length).toEqualTypeOf>(); + // Arguments contribute their inputs to the call. + const typed = profile.values.length( + Expression.input("name", kernel.types.String), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly name: Type.PrimitiveString; + }>(); + + // @ts-expect-error `length` takes a String. + profile.values.length(person.archived); + // @ts-expect-error `length` takes exactly one argument. + profile.values.length(text, text); + }); + + test("query_composition", () => { + // Keep a predicate as an ordinary function and reuse it across queries. + const active = (vertex: Closed): Closed => + Operators.isFalse(vertex.archived); + + const built = Do(($, { now }) => + $.query + .entities(now()) + .filter("person", active) + .filter("person", (vertex) => + Operators.eq(vertex.name, $.input("name", kernel.types.String)), + ) + .collect(), + ); + // The query's vertex type comes from the `entities` declaration, and inputs from every filter accumulate in the result. + expectTypeOf(built).toEqualTypeOf< + Built, { readonly name: Type.PrimitiveString }> + >(); + + Do(($, { now }) => { + // @ts-expect-error A filter predicate must return a Boolean. + $.query.entities(now()).filter("person", (vertex) => vertex.name); + return $.literal(true); + }); + }); +}); + +describe("subtyping", () => { + test("numeric_host_types", () => { + // Numeric typing follows the host type, not whether the value has a fraction. + const number = Expression.literal(1); + const integer = Expression.literal(1n); + expectTypeOf(number).toEqualTypeOf>(); + expectTypeOf(integer).toEqualTypeOf>(); + + const acceptsNumber = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("accepts_number"); + expectTypeOf(acceptsNumber(1)).toEqualTypeOf< + Closed + >(); + // @ts-expect-error Integer does not implicitly widen to Number. + acceptsNumber(integer); + // @ts-expect-error A primitive bigint has the same restriction. + acceptsNumber(1n); + const assumed = Expression.assume()(integer); + expectTypeOf(acceptsNumber(assumed)).toEqualTypeOf< + Closed + >(); + }); + + test("explicit_widening", () => { + // HashQL accepts a String where a function expects `String | Null`. The SDK compares semantic types exactly and does not model subtyping. Limitation: the SDK rejects a semantic subtype. + // @ts-expect-error `greet` declares `String | Null`, and `text` is a String. + profile.values.greet(text); + + // Workaround: state the wider type with `Expression.assume`. It changes only the SDK annotation. It emits no conversion and no HashQL type assertion, and the compiler still checks the program. + const widened = Expression.assume()(text); + expectTypeOf(profile.values.greet(widened)).toEqualTypeOf< + Closed + >(); + }); + + test("assumed_inputs", () => { + const name = Expression.input("name", kernel.types.String); + const widened = Expression.assume()(name); + // The input keeps its declared type. Only the expression's annotation changes. + expectTypeOf(widened).toEqualTypeOf< + Expression.Expression< + NullableString, + { readonly name: Type.PrimitiveString } + > + >(); + + // Limitation: `assume` cannot discard a requirement. + // @ts-expect-error The assumed expression still needs `name`. + const closed: Closed = widened; + expectTypeOf(closed); + // Workaround: supply a default to make the input optional for the host. + const defaulted = Expression.assume()( + Expression.input("name", kernel.types.String, ""), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly name?: Type.PrimitiveString; + }>(); + }); +}); + +describe("lexical_scope", () => { + test("callback_scope", () => { + Do( + Let("outer", ($) => $.integer(1)), + ($, { outer }) => + $.if( + $.literal(true), + () => $.Let("inner", () => outer).Expr((_, { inner }) => inner), + () => + $.Expr((_, values) => { + // TypeScript types each callback environment as a record, which gives completion and catches misspelt names while you write. + // @ts-expect-error The sibling branch's binding is absent here. + expectTypeOf(values.inner); + return values.outer; + }), + ), + ); + }); + + test("escaped_reference", () => { + // Limitation: a handle is a reference to a HashQL name. JavaScript can carry it out of the block that binds the name, and TypeScript accepts the result. + let escaped: Closed = Expression.integer(0); + Do( + Let("local", ($) => $.integer(1)), + (_, { local }) => { + escaped = local; + return local; + }, + ); + const outside = Do(() => escaped); + expectTypeOf(outside).toEqualTypeOf< + Built + >(); + + // The SDK neither resolves names nor checks scopes. The HashQL compiler reports `local` as an unresolved variable when it checks the emitted program. Workaround: take handles from the callback arguments of the block that uses them, and leave free-reference checks to the compiler. + }); +}); + +describe("queries_and_let", () => { + test("bound_query", () => { + Do( + Let("people", ($, { now }) => $.query.entities(now())), + (_, { people }) => { + // `Let` gives its binding the plain expression type of the value. + expectTypeOf(people).toEqualTypeOf>(); + + // The binding loses the query methods. This is an unfinished SDK convenience. + // @ts-expect-error `filter` exists only on the query chain. + expectTypeOf(people.filter); + return people; + }, + ); + }); + + test("bind_after_collect", () => { + // Workaround: build the whole chain in one expression, and bind its collected result or the values the query depends on. + const built = Do( + Let("axes", (_, { now }) => now()), + Let("people", ($, { axes }) => + $.query + .entities(axes) + .filter("person", (vertex) => Operators.isFalse(vertex.archived)) + .collect(), + ), + (_, { people }) => people.$index(0n), + ); + expectTypeOf(built).toEqualTypeOf< + Built, Inputs.Empty> + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts new file mode 100644 index 00000000000..902edad8d3c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts @@ -0,0 +1,142 @@ +/** + * Minimal graph declarations for the Draft filter examples. + * + * These declarations cover only the entity fields and standard-library exports used by the examples. Generated bindings can supply these declarations without changing the query bodies. + * + * @module + */ +import { Result } from "effect"; + +import { Module } from "../src/main.js"; + +import type { Expression, Inputs, Type, TypeExpression } from "../src/main.js"; + +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +type ActorGroupEntityUuid = Type.Opaque< + "::graph::types::principal::actor_group::ActorGroupEntityUuid", + Uuid +>; +export type WebId = Type.Opaque< + "::graph::types::principal::actor_group::web::WebId", + ActorGroupEntityUuid +>; +type EntityType = Type.Opaque< + `::graph::types::knowledge::entity::${Name}`, + Value +>; +export type EntityUuid = EntityType<"EntityUuid", Uuid>; +type DraftId = EntityType<"DraftId", Uuid>; +type None = Type.Opaque<"::core::option::None", Type.PrimitiveNull>; +type Draft = Type.Union< + readonly [None, Type.Opaque<"::core::option::Some", DraftId>] +>; +type EntityId = EntityType< + "EntityId", + Type.Struct<{ + readonly web_id: WebId; + readonly entity_uuid: EntityUuid; + readonly draft_id: Draft; + }> +>; +export type Entity = EntityType< + "Entity", + Type.Struct<{ + readonly metadata: EntityType< + "EntityMetadata", + Type.Struct<{ + readonly record_id: EntityType< + "RecordId", + Type.Struct<{ readonly entity_id: EntityId }> + >; + readonly archived: Type.PrimitiveBoolean; + }> + >; + }> +>; +type EntityGraph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Entity }> +>; +export type TemporalAxes = Type.Union< + readonly [ + Type.Opaque< + "::graph::temporal::PinnedTransactionTimeTemporalAxes", + Type.Unknown + >, + Type.Opaque< + "::graph::temporal::PinnedDecisionTimeTemporalAxes", + Type.Unknown + >, + ] +>; +type CreateUuid = Type.Function; +type CreateEntityUuid = Type.Function; +type Entities = Type.Function; +type Now = Type.Function; +type Value = Expression.Expression; + +export const uuid: Module.Module<{ + readonly values: { readonly Uuid: Value }; +}> = Result.getOrThrow( + Module.define("::core::uuid", { + values: { + Uuid: Module.value(), + }, + }), +); +export const entity: Module.Module<{ + readonly types: { + readonly EntityUuid: TypeExpression.TypeExpression; + }; + readonly values: { readonly EntityUuid: Value }; +}> = Result.getOrThrow( + Module.define("::graph::types::knowledge::entity", { + types: { EntityUuid: Module.type() }, + values: { + EntityUuid: Module.value(), + }, + }), +); +export const web: Module.Module<{ + readonly types: { readonly WebId: TypeExpression.TypeExpression }; +}> = Result.getOrThrow( + Module.define("::graph::types::principal::actor_group::web", { + types: { WebId: Module.type() }, + }), +); +export const temporal: Module.Module<{ + readonly types: { + readonly QueryTemporalAxes: TypeExpression.TypeExpression; + }; +}> = Result.getOrThrow( + Module.define("::graph::temporal", { + types: { QueryTemporalAxes: Module.type() }, + }), +); +export const kernel: Module.Module<{ + readonly types: { + readonly Boolean: TypeExpression.TypeExpression; + }; +}> = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Boolean: Module.type() }, + }), +); +export const head: Module.Module<{ + readonly values: { readonly entities: Value }; +}> = Result.getOrThrow( + Module.define("::graph::head", { + values: { + entities: Module.value(), + }, + }), +); +export const temporary: Module.Module<{ + readonly values: { readonly decision_time_now: Value }; +}> = Result.getOrThrow( + Module.define("::graph::tmp", { + values: { + decision_time_now: Module.value(), + }, + }), +); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts new file mode 100644 index 00000000000..2807d4f8e5d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts @@ -0,0 +1,260 @@ +/** Construction and input typing for the Draft filter gallery. @module */ +import { Array, Record, Result, Schema, flow, pipe } from "effect"; +import { describe, expect, expectTypeOf, test } from "vitest"; + +import { isReadonlyArray } from "../src/internal/array.js"; +import { Expression, JExpr } from "../src/main.js"; +import { examples } from "./filters-draft.js"; +import { originals } from "./filters-originals.js"; + +import type { Type } from "../src/main.js"; +import type * as ProgramError from "../src/Program/ProgramError.js"; +import type { + Entity, + EntityUuid, + TemporalAxes, + WebId, +} from "./filters-declarations.js"; + +const aliases = new Map([ + ["::core::cmp::eq", "=="], + ["::core::bool::and", "&&"], + ["::core::bool::or", "||"], +]); + +const parseJson = flow( + Schema.decodeResult(Schema.fromJsonString(Schema.Json)), + Result.getOrThrow, +); +const parseImport = flow( + Schema.decodeUnknownResult( + Schema.Tuple([ + Schema.Literal("::kernel::special_form::use"), + Schema.String, + Schema.Union([ + Schema.Struct({ "#tuple": Schema.Array(Schema.String) }), + Schema.Struct({ + "#struct": Schema.Record(Schema.String, Schema.String), + }), + ]), + Schema.Json, + ]), + ), + Result.getOrThrow, +); + +const resolveImport = ( + value: Schema.JsonArray, + imports: ReadonlyMap, +): { + readonly body: Schema.Json; + readonly imports: ReadonlyMap; +} => { + const [, path, selection, body] = parseImport(value); + const imported = new Map(imports); + if ("#tuple" in selection) { + for (const name of selection["#tuple"]) { + imported.set(name, `${path}::${name}`); + } + } else { + for (const [name, alias] of Record.toEntries(selection["#struct"])) { + let binding = alias; + if (alias === "_") { + binding = name; + } + imported.set(binding, `${path}::${name}`); + } + } + return { body, imports: imported }; +}; + +// Only spelling differs: qualified exports, explicit projections and the inferred temporal type. +const normalize = ( + value: Schema.Json, + imports: ReadonlyMap = new Map(), +): Schema.Json => { + if (typeof value === "string") { + return imports.get(value) ?? value; + } + if (isReadonlyArray(value)) { + if (value[0] === "::kernel::special_form::use") { + const imported = resolveImport(value, imports); + return normalize(imported.body, imported.imports); + } + const nodes = pipe( + value, + Array.map((node) => normalize(node, imports)), + ); + const [operation, input, field] = nodes; + if (typeof operation !== "string") { + return nodes; + } + const callee = operation.replace("::kernel::special_form::", ""); + if ( + callee === "access" && + typeof input === "string" && + typeof field === "string" + ) { + return `${input}.${field}`; + } + if ( + callee === "input" && + input === "axis" && + field === "::graph::temporal::QueryTemporalAxes" + ) { + return [callee, input, "_"]; + } + return [aliases.get(callee) ?? callee, ...Array.drop(nodes, 1)]; + } + if (value !== null && typeof value === "object") { + if ("#literal" in value) { + return value; + } + return pipe( + value, + Record.map((member) => normalize(member, imports)), + ); + } + return value; +}; + +const compile = ( + result: Result.Result, +): string => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +const publishedSelection = 4; +const draftSelection = 7; +const allEntities = examples[0]; +const suppliedTimeAxis = examples[2]; +const publishedEntityById = examples[publishedSelection]; +const optionalDrafts = examples[draftSelection]; + +const gallery = pipe( + Array.zip(examples, originals), + Array.map(([program, { title, source, before }]) => ({ + program, + title, + source, + before, + })), +); +const jexprExamples = pipe( + gallery, + Array.filter(({ source }) => source.endsWith(".jsonc")), +); +const frontendExamples = pipe( + gallery, + Array.filter( + ({ source }) => source.endsWith(".ts") || source.endsWith(".tsx"), + ), +); + +describe("query_normalization", () => { + test("import_aliases", () => { + expect.hasAssertions(); + expect( + normalize([ + "::kernel::special_form::use", + "::example", + { "#struct": { left: "binding", right: "_" } }, + ["binding", "right", { "#literal": "binding" }], + ]), + ).toStrictEqual([ + "::example::left", + "::example::right", + { "#literal": "binding" }, + ]); + }); + + test("import_shadowing", () => { + expect.hasAssertions(); + expect( + normalize([ + "::kernel::special_form::use", + "::outer", + { "#tuple": ["value"] }, + [ + "pair", + "value", + [ + "::kernel::special_form::use", + "::inner", + { "#tuple": ["value"] }, + "value", + ], + "value", + ], + ]), + ).toStrictEqual([ + "pair", + "::outer::value", + "::inner::value", + "::outer::value", + ]); + }); + + test("literal_values", () => { + expect.hasAssertions(); + expect(normalize(["==", "field", { "#literal": false }])).not.toStrictEqual( + normalize(["==", "field", { "#literal": true }]), + ); + }); +}); + +describe("draft_filters", () => { + test("query_with_import", () => { + expect.hasAssertions(); + expect(examples).toHaveLength(originals.length); + expect(compile(allEntities)).toBe( + '["::kernel::special_form::use","::graph::tmp",{"#struct":{"decision_time_now":"now"}},["::graph::tail::collect",["::graph::head::entities",["now"]]]]', + ); + }); + + test.each(gallery)("valid_construction: $title", ({ program }) => { + expect.hasAssertions(); + expect(() => + JExpr.make( + pipe(program, Result.flatMap(Expression.toJExpr), Result.getOrThrow), + ), + ).not.toThrow(); + }); + + test.each(jexprExamples)("original_query: $title", ({ program, before }) => { + expect.hasAssertions(); + expect(normalize(parseJson(compile(program)))).toStrictEqual( + normalize(parseJson(before)), + ); + }); + + test.each(frontendExamples)("frontend_selection: $title", ({ program }) => { + expect.hasAssertions(); + expect(parseJson(compile(program))).toMatchSnapshot(); + }); + + test("declared_inputs", () => { + expect.hasAssertions(); + const axis = Result.getOrThrow(suppliedTimeAxis); + const selected = Result.getOrThrow(publishedEntityById); + const flag = Result.getOrThrow(optionalDrafts); + expectTypeOf>().toEqualTypeOf< + Type.List + >(); + expectTypeOf>().toEqualTypeOf<{ + readonly axis: TemporalAxes; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly web_id: WebId; + readonly entity_uuid: EntityUuid; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly include_drafts: Type.PrimitiveBoolean; + }>(); + expect(compile(optionalDrafts)).toContain('"include_drafts"'); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts new file mode 100644 index 00000000000..45d28b30d88 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts @@ -0,0 +1,202 @@ +/** + * The filter gallery written with synchronous Draft callbacks. + * + * These programs reproduce, in order, the existing queries in `filters-originals.ts`. Each schema supplies the callback's second argument, and $.let introduces a named HashQL binding. Native loops and functions run during construction. $.if emits a query-time branch. + * + * The shared declarations cover only the graph exports used here. Construction emits J-Expr without executing against a graph service. + * + * @module + */ +import { Array, pipe } from "effect"; + +import { withPrelude } from "../src/draft/index.js"; +import { + entity, + head, + kernel, + temporal, + temporary, + uuid, + web, +} from "./filters-declarations.js"; + +import type { Expression, Inputs, Type } from "../src/main.js"; +import type * as ProgramError from "../src/Program/ProgramError.js"; +import type { + Entity, + EntityUuid, + TemporalAxes, + WebId, +} from "./filters-declarations.js"; +import type { Result } from "effect"; + +const { program } = withPrelude({ + values: { + createUuid: uuid.values.Uuid, + createEntityUuid: entity.values.EntityUuid, + ...head.values, + now: temporary.values.decision_time_now, + }, +}); + +const allEntities = program({}, ($) => { + const { now } = $.import(temporary, { decision_time_now: "now" }); + return $.query.entities(now()).collect(); +}); + +const entityByUuid = program({}, ($) => { + const { now, createEntityUuid, createUuid } = $.prelude(); + return $.query + .entities(now()) + .filter("vertex", (_, vertex) => + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, + createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ), + ) + .collect(); +}); + +const suppliedTimeAxis = program( + { axis: temporal.types.QueryTemporalAxes }, + ($, { axis }) => { + const { createEntityUuid, createUuid } = $.prelude(); + + return $.query + .entities(axis) + .filter("vertex", (_, vertex) => + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, + createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ), + ) + .collect(); + }, +); + +const predicateLocalBinding = program({}, ($) => { + const { now } = $.prelude(); + return $.query + .entities(now()) + .filter("vertex", ($) => { + const foo = $.let("foo", false); + + return $.and(true, $.or(true, foo)); + }) + .collect(); +}); + +const publishedEntityById = program( + { web_id: web.types.WebId, entity_uuid: entity.types.EntityUuid }, + ($, inputs) => { + const { now } = $.prelude(); + const webId = $.let("webId", inputs.web_id); + const entityUuid = $.let("entityUuid", inputs.entity_uuid); + + return $.query + .entities(now()) + .filter("vertex", (_, vertex) => { + const id = vertex.metadata.record_id.entity_id; + return $.eq(id.web_id, webId) + .and($.eq(id.entity_uuid, entityUuid)) + .and($.isNone(id.draft_id)); + }) + .collect(); + }, +); + +const sidebarSelection = program({ web_id: web.types.WebId }, ($, inputs) => { + const { now } = $.prelude(); + const webId = $.let("webId", inputs.web_id); + + return $.query + .entities(now()) + .filter("vertex", (_, vertex) => + $.eq(vertex.metadata.record_id.entity_id.web_id, webId), + ) + .filter("vertex", (_, vertex) => + $.isFalse(vertex.metadata.archived).and( + $.isNone(vertex.metadata.record_id.entity_id.draft_id), + ), + ) + .collect(); +}); + +const selectedIds = [ + "e2851dbb-7376-4959-9bca-f72cafc4448f", + "926b2d9b-c099-4cc4-9b0b-906b0c27bc70", +] as const; + +const anyOfEntityIds = program({}, ($) => { + const { now, createEntityUuid, createUuid } = $.prelude(); + return $.query + .entities(now()) + .filter("vertex", ($, vertex) => + pipe( + selectedIds, + // oxlint-disable-next-line unicorn/no-array-reduce -- this is Effect's typed fold, not a native array method + Array.reduce($.literal(false), (matches, entityUuid) => + $.or( + matches, + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, + createEntityUuid(createUuid(entityUuid)), + ), + ), + ), + ), + ) + .collect(); +}); + +// Draft retains the declared input as required, even though the emitted input supplies a default. +const optionalDrafts = program( + { include_drafts: kernel.types.Boolean }, + ($) => { + const { now } = $.prelude(); + const includeDrafts = $.let( + "includeDrafts", + $.input("include_drafts", kernel.types.Boolean, false), + ); + + return $.query + .entities(now()) + .filter("vertex", ($, vertex) => + $.if( + includeDrafts, + () => true, + () => $.isNone(vertex.metadata.record_id.entity_id.draft_id), + ), + ) + .collect(); + }, +); + +type Query = Result.Result< + Expression.Expression, I>, + ProgramError.Construction +>; + +/** The gallery's programs, in the order of `filters-originals.ts`, retaining each Draft schema in its result type. */ +export const examples: readonly [ + allEntities: Query, + entityByUuid: Query, + suppliedTimeAxis: Query<{ readonly axis: TemporalAxes }>, + predicateLocalBinding: Query, + publishedEntityById: Query<{ + readonly web_id: WebId; + readonly entity_uuid: EntityUuid; + }>, + sidebarSelection: Query<{ readonly web_id: WebId }>, + anyOfEntityIds: Query, + optionalDrafts: Query<{ readonly include_drafts: Type.PrimitiveBoolean }>, +] = [ + allEntities, + entityByUuid, + suppliedTimeAxis, + predicateLocalBinding, + publishedEntityById, + sidebarSelection, + anyOfEntityIds, + optionalDrafts, +]; diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts b/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts new file mode 100644 index 00000000000..34603fed0b1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts @@ -0,0 +1,100 @@ +/** + * The existing queries that the Draft filter gallery reproduces, in the gallery's order. + * + * A J-Expr original comes from a HashQL compiler test, and the gallery's program must match it up to spelling. A frontend original is the selection predicate of a frontend request. It has no J-Expr form, so a snapshot pins the gallery's translation instead. Source paths are relative to the repository root. + * + * @module + */ + +/** One existing query and where it comes from. */ +export interface Original { + readonly title: string; + readonly source: string; + readonly before: string; +} + +export const originals: readonly Original[] = [ + { + title: "1. Start a graph query", + source: + "libs/@local/hashql/hir/tests/ui/lower/checking/minimal-graph.jsonc", + before: `["::graph::tail::collect", ["::graph::head::entities", ["::graph::tmp::decision_time_now"]]]`, + }, + { + title: "2. Filter by UUID, then collect", + source: + "libs/@local/hashql/hir/tests/ui/lower/checking/collect-filter-graph.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["==", "vertex.metadata.record_id.entity_id.entity_uuid", + ["::graph::types::knowledge::entity::EntityUuid", + ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, + }, + { + title: "3. Supply the temporal axes as a query input", + source: "libs/@local/hashql/mir/tests/ui/reify/graph-read.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["input", "axis", "_"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["==", "vertex.metadata.record_id.entity_id.entity_uuid", + ["::graph::types::knowledge::entity::EntityUuid", + ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, + }, + { + title: "4. Bind a value inside the predicate", + source: + "libs/@local/hashql/hir/tests/ui/lower/graph-hoisting/nested-boolean-expression-outer-let.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["let", "foo", {"#literal": false}, + ["&&", {"#literal": true}, ["||", {"#literal": true}, "foo"]]]]]]`, + }, + // The gallery's inputs stand in for these requests' parameters. + { + title: "5. Frontend: look up a published entity", + source: "apps/hash-frontend/src/components/hooks/use-entity-by-id.ts", + before: `// The branch where the supplied entity ID has no draft ID. +{ + filter: { all: [ + { equal: [{ path: ["webId"] }, { parameter: webId }] }, + { equal: [{ path: ["uuid"] }, { parameter: entityUuid }] } + ] }, + includeDrafts: false +}`, + }, + { + title: "6. Frontend: the sidebar's web and archive predicates", + source: + "apps/hash-frontend/src/shared/generate-sidebar-entities-query-variables.tsx", + before: `// Predicate excerpt: the separate noisy-system-type exclusion is omitted. +{ + filter: { all: [ + { notEqual: [{ path: ["archived"] }, { parameter: true }] }, + { equal: [{ path: ["webId"] }, { parameter: webId }] } + ] }, + includeDrafts: false +}`, + }, + { + title: "7. Frontend: match any supplied entity UUID", + source: "apps/hash-frontend/src/components/hooks/use-users-with-links.ts", + before: `// The ID-list predicate only; the user-type filter and avatar traversal are omitted. +{ any: userAccountIds.map((actorId) => ({ + equal: [{ path: ["uuid"] }, { parameter: actorId }] +})) }`, + }, + { + title: "8. Frontend: make draft inclusion a query-time choice", + source: "apps/hash-frontend/src/pages/shared/entity-selector.tsx", + before: `// The request flag only; the selector's later deduplication is omitted. +{ includeDrafts }`, + }, +]; diff --git a/libs/@local/hashql/sdk/typescript/package.json b/libs/@local/hashql/sdk/typescript/package.json index 02acf0b5561..2bc9e437bb6 100644 --- a/libs/@local/hashql/sdk/typescript/package.json +++ b/libs/@local/hashql/sdk/typescript/package.json @@ -12,6 +12,10 @@ ".": { "types": "./dist/main.d.ts", "default": "./dist/main.js" + }, + "./draft": { + "types": "./dist/draft/index.d.ts", + "default": "./dist/draft/index.js" } }, "scripts": { @@ -19,7 +23,10 @@ "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", "lint:tsc": "tsc --noEmit", - "test:unit": "vitest run --typecheck --passWithNoTests" + "test:unit": "vitest run --typecheck" + }, + "dependencies": { + "effect": "4.0.3" }, "devDependencies": { "@local/oxlint": "workspace:*", diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts new file mode 100644 index 00000000000..25bec4dc600 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Call} values. */ +export const Schema: typeof Defs.Call = Defs.Call; + +/** + * A function expression followed by positional or labeled arguments. + * + * The array contains at least the function expression. A function with no arguments is a one-element array. + */ +export type Call = Defs.CallType; +/** The schema-encoded representation of {@link Call}. */ +export type Encoded = Defs.CallEncoded; + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a call's structure and every nested expression. + * + * The array needs at least the function expression, and each later element must be an expression or a labeled argument. The result is a new array. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Call = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts new file mode 100644 index 00000000000..7e3da238452 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts @@ -0,0 +1,57 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Dict} values. */ +export const Schema: typeof Defs.Dict = Defs.Dict; + +/** + * A dictionary constructor with string keys or expression-keyed entries. + * + * Record keys are literal strings. In an array of pairs, both the key and the value are expressions, so the string key `"user.name"` below is a field access rather than literal text. + * + * @example Compare a literal key with a computed key. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * + * const literalKey = JExpr.dict({ "user.name": JExpr.literal("Alice") }); + * assert.equal(JExpr.compile(literalKey), '{"#dict":{"user.name":{"#literal":"Alice"}}}'); + * + * const computedKey = JExpr.dict([["user.name", JExpr.literal("Alice")]]); + * assert.equal(JExpr.compile(computedKey), '{"#dict":[["user.name",{"#literal":"Alice"}]]}'); + * ``` + */ +export interface Dict extends Defs.DictType {} +/** The schema-encoded representation of {@link Dict}. */ +export interface Encoded extends Defs.DictEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks dictionary entries and an optional type annotation. + * + * Record keys can be any string, and `#type` can be any text. Each value, and each key in the pair form, must be an expression. The result is a new dictionary. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Dict = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts new file mode 100644 index 00000000000..7d7d430ede3 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Float} values. */ +export const Schema: typeof Defs.Float = Defs.Float; + +/** + * A float's source text, including a fraction or exponent. + * + * `value` uses JSON number syntax, such as `"1.0"` or `"1e3"`. Keeping the text preserves the distinction between an integer and an integral float. + */ +export interface Float extends Defs.FloatType {} +/** The schema-encoded representation of {@link Float}. */ +export interface Encoded extends Defs.FloatEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks that `value` is a float in JSON number syntax, such as `1.0` or `1e3`. + * + * The text needs a fraction or exponent, so `1` and `1.` fail. `_tag` may be omitted, and the result supplies it. `options.disableChecks` skips the spelling check and keeps only the object's shape. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Float = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts new file mode 100644 index 00000000000..fcb5a4721e9 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts @@ -0,0 +1,90 @@ +import { Record } from "effect"; +import { pipe } from "effect/Function"; + +import { isReadonlyArray } from "../internal/array.js"; +import * as Type from "./Type/index.js"; + +import type * as Defs from "./schema.js"; + +/** The `_` placeholder, which asks the HashQL compiler to infer a type in a {@link fn} signature. */ +const inferred = "_" as const; + +export { inferred as infer }; + +/** An explicit type or {@link inferred | infer}, accepted by {@link fn} for parameter and return types. */ +export type TypeArgument = Type.Type | typeof inferred; + +/** Renders a type argument, preserving the inference placeholder. */ +const compileType = (type: TypeArgument): Defs.ExpressionType => { + if (type === inferred) { + return inferred; + } + + return Type.toExpression(type); +}; + +/** A closure's signature and body, accepted by {@link fn}. */ +export interface FnOptions { + /** + * Type parameter names, or a record mapping each name to its bound. + * + * An array becomes a `#tuple` of unbounded names. In a record, use {@link inferred | infer} for an unbounded parameter. Defaults to no generic parameters. + */ + readonly generics?: + | readonly string[] + | Record.ReadonlyRecord; + /** Parameter names and types, in argument order. Names must be identifiers. Use {@link inferred | infer} for an inferred type. */ + readonly params: Record.ReadonlyRecord; + /** The return type. Defaults to {@link inferred | infer}. */ + readonly returns?: TypeArgument; + /** The expression that computes the closure's result. */ + readonly body: Defs.ExpressionType; +} + +/** Renders named types as a struct of type expressions. */ +const compileTypes = ( + types: Record.ReadonlyRecord, +): Defs.StructType => ({ "#struct": pipe(types, Record.map(compileType)) }); + +/** Renders unbounded names as a tuple and named bounds as a struct. */ +const compileGenerics = ( + generics: FnOptions["generics"], +): Defs.TupleType | Defs.StructType => { + if (generics === undefined) { + return { "#tuple": [] }; + } + + if (isReadonlyArray(generics)) { + return { "#tuple": generics }; + } + + return compileTypes(generics); +}; + +/** + * Defines a closure with named parameters. + * + * The result is the call `["fn", generics, params, returns, body]`. Parameter names are in scope in the body, and their record order determines the argument order. The return type defaults to {@link inferred | infer}. Types are written as constructor syntax, as in `JExpr.as`. The builder checks neither the body nor its use of the parameters. Call the closure with `JExpr.call` or bind it with `JExpr.let`. + * + * @example Define a predicate with an inferred parameter type. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * + * const isDraft = JExpr.fn({ + * params: { entity: JExpr.infer }, + * body: JExpr.call("==", "entity.draft_id", JExpr.literal(null)), + * }); + * assert.equal( + * JExpr.compile(isDraft), + * '["fn",{"#tuple":[]},{"#struct":{"entity":"_"}},"_",["==","entity.draft_id",{"#literal":null}]]', + * ); + * ``` + */ +export const fn = (options: FnOptions): Defs.CallType => [ + "fn", + compileGenerics(options.generics), + compileTypes(options.params), + compileType(options.returns ?? inferred), + options.body, +]; diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts new file mode 100644 index 00000000000..4ff9b302838 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts @@ -0,0 +1,160 @@ +/** + * Single HashQL identifiers and their source spelling. + * + * An {@link Ident} stores its kind and its value without backticks, like `Ident` in `hashql-core`. Use {@link decodeResult} to read source syntax such as `foo`, `+`, `` `+` `` or `` `https://example.com/` ``, and {@link compile} to write it back. Paths, field access and the `_` placeholder are wider string expressions rather than identifiers. + * + * @module + */ +import { Schema as $Schema, Option, SchemaGetter, SchemaParser } from "effect"; +import { compose } from "effect/Function"; + +import * as Scan from "../internal/scan.js"; +import { characterClass, exactly } from "../internal/schema-arbitrary.js"; + +import type { Effect, SchemaIssue } from "effect"; +import type { Result } from "effect/Result"; +import type { ParseOptions } from "effect/SchemaAST"; + +const lexicalStart = new RegExp(Scan.lexicalStartPattern, "u"); +const lexicalContinue = new RegExp(Scan.lexicalContinuePattern, "u"); +const symbolCharacter = new RegExp(Scan.symbolCharacterPattern, "u"); + +const LexicalSchema: $Schema.TaggedStruct< + "Lexical", + { value: $Schema.String } +> = $Schema.TaggedStruct("Lexical", { + value: exactly(Scan.lexicalPattern, () => + Scan.lexicalPattern + .replaceAll(Scan.lexicalStartPattern, characterClass(lexicalStart)) + .replaceAll(Scan.lexicalContinuePattern, characterClass(lexicalContinue)), + ), +}); + +const SymbolSchema: $Schema.TaggedStruct<"Symbol", { value: $Schema.String }> = + $Schema.TaggedStruct("Symbol", { + value: exactly(Scan.symbolPattern, () => + Scan.symbolPattern.replace( + Scan.symbolCharacterPattern, + characterClass(symbolCharacter), + ), + ), + }); + +const BaseUrlSchema: $Schema.TaggedStruct< + "BaseUrl", + { value: $Schema.String } +> = $Schema.TaggedStruct("BaseUrl", { value: exactly(Scan.baseUrlPattern) }); + +/** + * Schema for identifier objects with unquoted values. + * + * `Arbitrary.schema(SchemaFromSelf)` generates every identifier kind. Derivation computes and caches character ranges from the runtime's Unicode tables on first use. + */ +export const SchemaFromSelf: $Schema.toTaggedUnion< + "_tag", + readonly [typeof LexicalSchema, typeof SymbolSchema, typeof BaseUrlSchema] +> = $Schema + .Union([LexicalSchema, SymbolSchema, BaseUrlSchema]) + .pipe($Schema.toTaggedUnion("_tag")); + +/** + * Codec between source syntax and an identifier object. + * + * Decoding accepts exactly one identifier. Encoding quotes symbol and base-URL identifiers. {@link make} validates the decoded object rather than source text. Arbitrary generation uses the decoded {@link SchemaFromSelf}. + */ +export const Schema: $Schema.decodeTo< + typeof SchemaFromSelf, + typeof $Schema.NonEmptyString +> = $Schema.NonEmptyString.pipe( + $Schema.decodeTo(SchemaFromSelf, { + decode: SchemaGetter.transformOptional( + compose( + Option.andThen(Scan.scanIdentExact), + // oxlint-disable-next-line no-use-before-define -- lazy evaluation that is otherwise circular + Option.map((value) => fromScanned(value)), + ), + ), + // oxlint-disable-next-line no-use-before-define -- lazy evaluation that is otherwise circular + encode: SchemaGetter.transform((value) => compile(value)), + }), +); + +/** + * The decoded form of an identifier, with its kind in `_tag` and its value without backticks. + * + * A `Lexical` value is a Unicode identifier, either `XID_Start XID_Continue*` or `_` followed by at least one `XID_Continue` character. A `Symbol` value is one or more ASCII operator characters, `!#$%&*+-./<=>?@\^|~[]`, or non-ASCII punctuation and symbols, such as `+` or `==`. A `BaseUrl` value is an `http` or `https` URL ending in `/`, checked for spelling rather than validity. An object written directly is unchecked until {@link make} validates it. + */ +export type Ident = (typeof Schema)["Type"]; + +/** Identifier source text, with backticks around a quoted symbol or base URL. */ +export type Encoded = (typeof Schema)["Encoded"]; + +/** Input accepted by {@link make} before validation: an identifier object, not source text. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks an identifier object, such as `{ _tag: "Symbol", value: "+" }`, against its kind's pattern. + * + * Use {@link decodeResult} for source text. When `_tag` is omitted, the result takes the kind whose pattern matches `value`. + * + * @throws {Error} If `value` is not valid for the given kind. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Ident = + SchemaParser.make(Schema); + +/** Checks an identifier object like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks an identifier object like {@link make}, returning `None` if validation fails. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +/** @internal */ +export const fromScanned = (scanned: Scan.ScanIdent): Ident => ({ + _tag: scanned.kind, + value: scanned.value, +}); + +/** + * Decodes exactly one identifier from source text. + * + * A symbol can be bare or backticked. A base URL must be backticked. Any other text, including surrounding whitespace or a `::` separator, fails with a {@link SchemaIssue.Issue} in the returned `Result`. + * + * @example Decode an operator and print it back. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * import { Result } from "effect"; + * + * const plus = Result.getOrThrow(JExpr.Ident.decodeResult("+")); + * assert.deepEqual(plus, { _tag: "Symbol", value: "+" }); + * assert.equal(JExpr.Ident.compile(plus), "`+`"); + * assert.ok(Result.isFailure(JExpr.Ident.decodeResult("user.name"))); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const decodeResult: ( + input: string, + options?: ParseOptions, +) => Result = SchemaParser.decodeResult(Schema); + +/** + * Writes an identifier as source text. + * + * A lexical value is written as is. A symbol or base URL is wrapped in backticks, so the bare `+` decodes and compiles to `` `+` ``. The value is not validated. + */ +export const compile = (ident: Ident): string => { + if (ident._tag === "Lexical") { + return ident.value; + } + + return `\`${ident.value}\``; +}; diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts new file mode 100644 index 00000000000..0eac28462fa --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts @@ -0,0 +1,48 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Identifier} values. */ +export const Schema: typeof Defs.Identifier = Defs.Identifier; + +/** + * Source text interpreted as a path, type or argument shorthand. + * + * The schema accepts any string, including the empty string. HashQL parses it according to its position in the expression. In an expression position, `"user"` is a path, `"user.name"` and `"items[0]"` access a field and an element, and `"_"` is a placeholder. In a call argument, `":user"` is shorthand for the labeled argument `{":user": "user"}`. A type position reads the text as type syntax. For a single identifier object, see `JExpr.Ident`. + */ +export type Identifier = Defs.IdentifierType; +/** The schema-encoded representation of {@link Identifier}. */ +export type Encoded = Defs.IdentifierEncoded; + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Accepts any string as a string expression. + * + * The schema has no checks, so this confirms only that the input is a string. HashQL parses the text when it compiles the program. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Identifier = SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts new file mode 100644 index 00000000000..d2eca78c7d0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts @@ -0,0 +1,55 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Integer} values. */ +export const Schema: typeof Defs.Integer = Defs.Integer; + +/** + * An arbitrary-precision integer's decimal source text, stored in a literal's `#literal` field. + * + * `value` uses JSON integer syntax, such as `"-42"`. It has no fraction or exponent. Keeping the text avoids JavaScript's numeric precision limit, but a `number` loses precision before `JExpr.integer` reads it. Pass a `bigint` for integers beyond `Number.MAX_SAFE_INTEGER`. + * + * @example Keep an integer beyond JavaScript's safe range. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * + * assert.equal(JExpr.compile(JExpr.integer(2n ** 64n)), '{"#literal":18446744073709551616}'); + * assert.equal(JExpr.compile(JExpr.integer(2 ** 53 + 1)), '{"#literal":9007199254740992}'); + * ``` + */ +export interface Integer extends Defs.IntegerType {} +/** The schema-encoded representation of {@link Integer}. */ +export interface Encoded extends Defs.IntegerEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks that `value` is an integer in JSON number syntax, such as `-42`. + * + * Leading zeros, a fraction and an exponent fail. `_tag` may be omitted, and the result supplies it. `options.disableChecks` skips the spelling check and keeps only the object's shape. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Integer = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts new file mode 100644 index 00000000000..d9476a7b8e5 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts @@ -0,0 +1,48 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link LabeledArgument} values. */ +export const Schema: typeof Defs.LabeledArgument = Defs.LabeledArgument; + +/** + * A call argument labeled with a parameter name. + * + * The object has exactly one key: `:` followed by an identifier. The value is an expression. It can appear anywhere after the function in a call array, and HashQL's parser gathers it into the call's labeled arguments rather than its positional ones. + */ +export interface LabeledArgument extends Defs.LabeledArgumentType {} +/** The schema-encoded representation of {@link LabeledArgument}. */ +export interface Encoded extends Defs.LabeledArgumentEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a labeled argument's single key and its value. + * + * The object needs exactly one key, `:` followed by an identifier, and an expression as its value. `options.disableChecks` skips the key checks along with the checks inside the value. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => LabeledArgument = SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/List.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/List.ts new file mode 100644 index 00000000000..add1db5c2b7 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/List.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link List} values. */ +export const Schema: typeof Defs.List = Defs.List; + +/** + * A list constructor whose elements are expressions. + * + * The schema checks each expression. HashQL determines their common element type. + */ +export interface List extends Defs.ListType {} +/** The schema-encoded representation of {@link List}. */ +export interface Encoded extends Defs.ListEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks list elements and an optional type annotation. + * + * Each element must be an expression, and `#type` can be any text. The result is a new list. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => List = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Literal.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Literal.ts new file mode 100644 index 00000000000..bf2b94d41de --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Literal.ts @@ -0,0 +1,46 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Literal} values. */ +export const Schema: typeof Defs.Literal = Defs.Literal; + +/** + * A primitive value in a `#literal` constructor. + * + * Numeric values are tagged `JExpr.Integer` or `JExpr.Float` objects that preserve their source text. Strings, booleans and `null` appear directly under `#literal`, and a string here is a string value rather than a name. `#type` holds optional annotation text. + */ +export interface Literal extends Defs.LiteralType {} +/** The schema-encoded representation of {@link Literal}. */ +export interface Encoded extends Defs.LiteralEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a literal's value and an optional type annotation. + * + * A string, boolean or `null` value is accepted as is. A numeric value must be a tagged integer or float object with valid spelling, and its `_tag` may be omitted. `#type` can be any text. `options.disableChecks` skips the numeric spelling check. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Literal = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts new file mode 100644 index 00000000000..e3144de4ae2 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts @@ -0,0 +1,135 @@ +/** + * HashQL paths with an optional root and a nonempty sequence of identifiers. + * + * {@link SchemaFromSelf} validates path objects and supports schema-derived arbitrary generation. {@link Schema} and {@link decodeResult} decode source text without treating `::` inside a quoted identifier as a separator, and {@link compile} writes it back. Path text is narrower than a string expression, which can also hold field access, index access or generic arguments. + * + * @module + */ +import { + Schema as $Schema, + Array, + Option, + SchemaGetter, + SchemaParser, + Struct, +} from "effect"; +import { compose } from "effect/Function"; + +import * as Scan from "../internal/scan.js"; +import * as Ident from "./Ident.js"; + +import type { Effect, SchemaIssue } from "effect"; +import type { Result } from "effect/Result"; +import type { ParseOptions } from "effect/SchemaAST"; + +/** + * Schema for path objects containing decoded identifiers. + * + * `Arbitrary.schema(SchemaFromSelf)` generates rooted and relative paths with at least one segment. + */ +export const SchemaFromSelf: $Schema.Struct<{ + rooted: $Schema.Boolean; + segments: $Schema.NonEmptyArray; +}> = $Schema.Struct({ + rooted: $Schema.Boolean, + segments: $Schema.NonEmptyArray(Ident.SchemaFromSelf), +}); + +/** Codec between path source text and a {@link Path} object. */ +export const Schema: $Schema.decodeTo< + typeof SchemaFromSelf, + typeof $Schema.NonEmptyString +> = $Schema.NonEmptyString.pipe( + $Schema.decodeTo(SchemaFromSelf, { + decode: SchemaGetter.transformOptional( + compose( + Option.andThen(Scan.scanPath), + Option.map( + Struct.evolve({ + segments: Array.map(Ident.fromScanned), + }), + ), + ), + ), + // oxlint-disable-next-line no-use-before-define -- circular evaluation + encode: SchemaGetter.transform((path) => compile(path)), + }), +); + +/** + * The decoded form of a path, with its root flag and its identifier segments in order. + * + * `rooted` is `true` for a leading `::`, as in `::core::math`. `segments` holds at least one identifier object from `JExpr.Ident`. An object written directly is unchecked until {@link make} validates it. + */ +export interface Path extends $Schema.Schema.Type {} + +/** Source text representing a {@link Path}, including quotes and separators. */ +export type Encoded = $Schema.Codec.Encoded; + +/** Input accepted by {@link make} before validation: a path object, not source text. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a path object, requiring at least one segment and a valid identifier in each. + * + * Use {@link decodeResult} for source text. + * + * @throws {Error} If a segment is not a valid identifier or `segments` is empty. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Path = + SchemaParser.make(Schema); + +/** Checks a path object like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks a path object like {@link make}, returning `None` if validation fails. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +/** + * Writes a path as source text. + * + * Segments are joined by `::`, with a leading `::` for a rooted path, and each segment is written like `JExpr.Ident.compile`, with backticks around a symbol or base URL. Whitespace that decoding accepted around separators is not kept. The segments are not validated. + */ +export const compile = (path: Path): string => { + const segments = path.segments + .map((segment) => Ident.compile(segment)) + .join("::"); + + if (path.rooted) { + return `::${segments}`; + } + + return segments; +}; + +/** + * Decodes path text into a {@link Path}. + * + * The text is an optional leading `::` followed by `::`-separated identifiers, with whitespace allowed around each separator. A backticked base URL, such as `` `https://example.com/a::b/` ``, can contain `::`. Surrounding whitespace, an empty segment, generic arguments such as `List` and field access such as `user.name` fail with a {@link SchemaIssue.Issue} in the returned `Result`. + * + * @example Decode a rooted operator path. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * import { Result } from "effect"; + * + * const add = Result.getOrThrow(JExpr.Path.decodeResult("::core :: math::+")); + * assert.ok(add.rooted); + * assert.equal(JExpr.Path.compile(add), "::core::math::`+`"); + * assert.ok(Result.isFailure(JExpr.Path.decodeResult("List"))); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const decodeResult: ( + input: string, + options?: ParseOptions, +) => Result = SchemaParser.decodeResult(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Struct.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Struct.ts new file mode 100644 index 00000000000..9a6ef5251ba --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Struct.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for `Struct` values. */ +export const Schema: typeof Defs.Struct = Defs.Struct; + +/** + * A data constructor with identifier-named fields. + * + * Each field contains an expression. The schema checks the field names as well as their values. + */ +export interface Struct extends Defs.StructType {} +/** The schema-encoded representation of `Struct`. */ +export interface Encoded extends Defs.StructEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks field names, field expressions and an optional type annotation. + * + * Field names must be identifiers, such as `name` or `` `+` ``. Field values must be expressions. `#type` can be any text. The result is a new struct. `options.disableChecks` skips the field-name check and the checks inside nested values. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Struct = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Tuple.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Tuple.ts new file mode 100644 index 00000000000..09c23d5688e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Tuple.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for `Tuple` values. */ +export const Schema: typeof Defs.Tuple = Defs.Tuple; + +/** + * A fixed-length sequence of expressions with a type for each position. + * + * An empty tuple is valid. HashQL determines each element's type. + */ +export interface Tuple extends Defs.TupleType {} +/** The schema-encoded representation of `Tuple`. */ +export interface Encoded extends Defs.TupleEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks tuple elements and an optional type annotation. + * + * Each element must be an expression, and `#type` can be any text. The result is a new tuple. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Tuple = + SchemaParser.make(Schema); + +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Expression.test.ts new file mode 100644 index 00000000000..b93de225a73 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Expression.test.ts @@ -0,0 +1,80 @@ +import { Option } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../index.js"; +import * as Type from "./index.js"; + +const integer = Option.getOrThrow(Type.reference("::kernel::type::Integer")); +const text = Option.getOrThrow(Type.reference("::kernel::type::String")); +const tuple = Type.tuple(integer); +const record = Option.getOrThrow(Type.struct({ value: tuple })); +const cases: readonly (readonly [string, Type.Type, JExpr.Expression])[] = [ + ["reference", integer, "::kernel::type::Integer"], + ["tuple", tuple, { "#tuple": ["::kernel::type::Integer"] }], + ["empty_tuple", Type.tuple(), { "#tuple": [] }], + [ + "struct", + record, + { "#struct": { value: { "#tuple": ["::kernel::type::Integer"] } } }, + ], + ["empty_struct", Option.getOrThrow(Type.struct({})), { "#struct": {} }], + [ + "union", + Type.union(integer, text), + [ + "::kernel::type::Union", + "::kernel::type::Integer", + "::kernel::type::String", + ], + ], + [ + "intersection", + Type.intersection(integer, text), + [ + "::kernel::type::Intersection", + "::kernel::type::Integer", + "::kernel::type::String", + ], + ], + [ + "generic_argument", + Option.getOrThrow(Type.reference("List", tuple)), + "List<(::kernel::type::Integer,)>", + ], +]; + +describe("type_expressions", () => { + test.each(cases)("%s", (_, type, expression) => { + expect.hasAssertions(); + expect(Type.toExpression(type)).toStrictEqual(expression); + expect([ + JExpr.type("Local", type, "_")[2], + JExpr.newtype("Local", type, "_")[2], + JExpr.input("value", type)[2], + JExpr.input("value", type, "default")[2], + JExpr.as("value", type)[2], + ]).toStrictEqual([ + expression, + expression, + expression, + expression, + expression, + ]); + expect( + JExpr.fn({ params: { argument: type }, returns: type, body: "argument" }), + ).toStrictEqual([ + "fn", + { "#tuple": [] }, + { "#struct": { argument: expression } }, + expression, + "argument", + ]); + }); + + test("annotation_string", () => { + expect.hasAssertions(); + expect(JExpr.typed(JExpr.tuple(JExpr.integer(1)), tuple)["#type"]).toBe( + "(::kernel::type::Integer,)", + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Generic.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Generic.ts new file mode 100644 index 00000000000..fc23c97f03e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Generic.ts @@ -0,0 +1,59 @@ +import { Option, Result, SchemaParser } from "effect"; + +import * as Ident from "../Ident.js"; +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Generic = Defs.Generic; + +export type Generic = Defs.GenericType; +export type Encoded = Defs.GenericEncoded; + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Generic = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +/** + * Creates a generic argument: the `Integer` in `List`. + */ +export const argument = (type: Defs.Type): Defs.GenericArgumentType => ({ + _tag: "GenericArgument", + bound: type, +}); + +/** + * Creates a named generic constraint: the `T: Integer` in `Foo`. + * + * Returns `None` if `name` is not a valid identifier according to `Ident.decodeResult`. Without a bound, it compiles to the bare name, which HashQL parses as a generic argument. A declaration name such as `Pair` reads that bare name as an unbounded parameter. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const bound = ( + name: string, + type?: Defs.Type, +): Option.Option => + Option.map( + Ident.decodeResult(name).pipe(Result.getSuccess), + (ident): Defs.GenericBoundType => { + if (type === undefined) { + return { _tag: "GenericBound", name: ident }; + } + + return { _tag: "GenericBound", name: ident, bound: type }; + }, + ); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericArgument.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericArgument.ts new file mode 100644 index 00000000000..f5f97833ed6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericArgument.ts @@ -0,0 +1,31 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.GenericArgument = Defs.GenericArgument; + +export interface GenericArgument extends Defs.GenericArgumentType {} +export interface Encoded extends Defs.GenericArgumentEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => GenericArgument = SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericBound.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericBound.ts new file mode 100644 index 00000000000..ef80290d7c2 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericBound.ts @@ -0,0 +1,31 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.GenericBound = Defs.GenericBound; + +export interface GenericBound extends Defs.GenericBoundType {} +export interface Encoded extends Defs.GenericBoundEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => GenericBound = SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Intersection.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Intersection.ts new file mode 100644 index 00000000000..0d52534c024 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Intersection.ts @@ -0,0 +1,31 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Intersection = Defs.Intersection; + +export interface Intersection extends Defs.IntersectionType {} +export interface Encoded extends Defs.IntersectionEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Intersection = SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Reference.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Reference.ts new file mode 100644 index 00000000000..f48b728cccd --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Reference.ts @@ -0,0 +1,34 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Reference = Defs.Reference; + +/** + * Type syntax naming a type by its decoded path, with its generic entries in order. + * + * `JExpr.type` and `JExpr.newtype` also accept a reference as a declaration name. There its generic list declares parameters: a bare name such as `T` is an unbounded parameter and `T: Integer` a bounded one. + */ +export interface Reference extends Defs.ReferenceType {} +export interface Encoded extends Defs.ReferenceEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Reference = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Struct.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Struct.ts new file mode 100644 index 00000000000..1451ac28a12 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Struct.ts @@ -0,0 +1,28 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Struct = Defs.Struct; + +export interface Struct extends Defs.StructType {} +export interface Encoded extends Defs.StructEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Struct = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Tuple.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Tuple.ts new file mode 100644 index 00000000000..c9844864406 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Tuple.ts @@ -0,0 +1,28 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Tuple = Defs.Tuple; + +export interface Tuple extends Defs.TupleType {} +export interface Encoded extends Defs.TupleEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Tuple = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Union.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Union.ts new file mode 100644 index 00000000000..09f8bf72aa6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Union.ts @@ -0,0 +1,28 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Union = Defs.Union; + +export interface Union extends Defs.UnionType {} +export interface Encoded extends Defs.UnionEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Union = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/index.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/index.ts new file mode 100644 index 00000000000..1c769224a27 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/index.ts @@ -0,0 +1,462 @@ +/** + * Builds HashQL type syntax for J-Expr queries. + * + * A {@link Type} is tagged type syntax. Use {@link reference} for a named type and {@link struct}, {@link tuple}, {@link union} or {@link intersection} to compose types. The syntax has two J-Expr spellings. {@link compile} writes annotation text for a `#type` field, and {@link toExpression} writes the constructor syntax that `as`, `input`, `fn`, `type` and `newtype` emit. + * + * {@link reference} and {@link struct} return an {@link Option.Option}: an invalid name produces `None`. The other builders accept their members without checks. Name resolution and type checking belong to the HashQL compiler. + * + * @module + */ +import { Array, Option, Record, Result, SchemaParser, Tuple } from "effect"; +import { compose, dual, pipe } from "effect/Function"; + +import * as Ident from "../Ident.js"; +import * as Path from "../Path.js"; +import * as Defs from "./schema.js"; + +import type { Identifier } from "../Identifier.js"; +import type { ExpressionType } from "../schema.js"; +import type { Schema as $Schema, Effect, SchemaIssue } from "effect"; +import type { NonEmptyReadonlyArray } from "effect/Array"; + +export * as Generic from "./Generic.js"; +export * as GenericArgument from "./GenericArgument.js"; +export * as GenericBound from "./GenericBound.js"; +export * as Intersection from "./Intersection.js"; +export * as Reference from "./Reference.js"; +export * as Struct from "./Struct.js"; +export * as Tuple from "./Tuple.js"; +export * as Union from "./Union.js"; + +/** + * Schema for validating and encoding {@link Type} values. + * + * Use {@link make} to construct a value or {@link compile} to render type syntax. Schema encoding produces the tagged object representation described by {@link Encoded}. + */ +export const Schema: typeof Defs.Type = Defs.Type; + +/** + * Tagged HashQL type syntax, as accepted by `JExpr.input`, `JExpr.as`, `JExpr.typed` and the other builders that take a type. + * + * The `_tag` discriminant selects the form. `Reference` names a type by path with optional generics, `Struct` and `Tuple` list named or positional members, and `Union` and `Intersection` combine member types. Paths and member names are decoded identifier objects. `TypeExpression.toType` extracts this syntax from a declared type expression. Nothing validates an object written directly until {@link make} checks its names, and the HashQL compiler resolves those names and checks the type. + */ +export type Type = Defs.Type; + +/** + * The schema-encoded form of a {@link Type}, which writes each path and member name as source text. + * + * A reference's path becomes text such as `"::core::List"`, and a struct member name becomes text such as `` "`+`" ``. The rest keeps its tagged objects. {@link Schema} encodes and decodes this form, and neither form is J-Expr. Use {@link compile} or {@link toExpression} for J-Expr. + */ +export type Encoded = Defs.TypeEncoded; + +/** Constructor input accepted by {@link Schema} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a tagged type object, including its decoded paths and names, and returns a new value. + * + * Validates the input against {@link Schema} by default. `options.disableChecks` skips the identifier checks but still requires the tagged structure. {@link makeOption} returns `None` for validation failures, and {@link makeEffect} preserves the issue in its error channel. + * + * @throws {Error} If construction fails. A schema-validation error carries a {@link SchemaIssue.Issue} in its `cause`. + * + * @example Construct and check tagged type syntax. + * ```ts + * import { Effect, Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Type.make({ + * _tag: "Reference", + * path: { rooted: false, segments: [{ _tag: "Lexical", value: "Integer" }] }, + * generics: [], + * }); + * Type.compile(integer); // => "Integer" + * + * const invalid = { + * _tag: "Reference", + * path: { rooted: false, segments: [{ _tag: "Lexical", value: "" }] }, + * generics: [], + * } as const; + * Option.isNone(Type.makeOption(invalid)); // => true + * + * const empty = Effect.runSync(Type.makeEffect({ _tag: "Tuple", members: [] })); + * Type.compile(empty); // => "()" + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Type = + SchemaParser.make(Schema); + +/** + * Constructs a type with schema failures in the effect's error channel. + * + * Uses the construction options described by {@link make}. Fails with a {@link SchemaIssue.Issue} if the input fails schema validation. + * + * @see {@link make} for construction examples. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** + * Constructs a type, returning `None` if schema validation fails. + * + * Uses the construction options described by {@link make}. Use {@link makeEffect} when you need the validation issue. + * + * @see {@link make} for construction examples. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +/** + * Creates a type whose values satisfy at least one member type. + * + * Preserves member order, duplicates and nested unions. Use {@link or} to combine types while flattening union operands. + * + * @example Build a union without flattening. + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const string = Option.getOrThrow(Type.reference("String")); + * Type.compile(Type.union(integer, string)); // => "(Integer | String)" + * Type.compile(Type.union(integer)); // => "Integer" + * ``` + */ +export const union = ( + ...members: NonEmptyReadonlyArray +): Defs.UnionType => ({ _tag: "Union", members }); + +/** + * Creates a type whose values satisfy every member type. + * + * Preserves member order, duplicates and nested intersections. Use {@link and} to combine types while flattening intersection operands. + * + * @example Build an intersection. + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const named = Option.getOrThrow(Type.reference("Named")); + * const aged = Option.getOrThrow(Type.reference("Aged")); + * Type.compile(Type.intersection(named, aged)); // => "(Named & Aged)" + * ``` + */ +export const intersection = ( + ...members: NonEmptyReadonlyArray +): Defs.IntersectionType => ({ _tag: "Intersection", members }); + +/** Exposes a readonly view of a value without copying or freezing it. */ +const asReadonlyUnsafe = (input: T): Readonly => input; + +/** + * Creates a type with named fields. + * + * Returns `None` if any field name is not a valid identifier according to `Ident.decodeResult`. Symbol names accept bare (`+`) or backticked (`` `+` ``) spelling. Fields follow the record's own enumerable string-key order. An empty record produces an empty struct, which {@link compile} renders as `(:)`. + * + * @example Build a struct type and reject an invalid field name. + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const string = Option.getOrThrow(Type.reference("String")); + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const person = Option.getOrThrow(Type.struct({ name: string, age: integer })); + * Type.compile(person); // => "(name: String, age: Integer)" + * Option.isNone(Type.struct({ "": string })); // => true + * Type.compile(Option.getOrThrow(Type.struct({}))); // => "(:)" + * ``` + */ +export const struct = ( + fields: Record.ReadonlyRecord, +): Option.Option => + pipe( + Record.toEntries(fields), + Array.map( + compose( + Tuple.evolve([ + compose(Ident.decodeResult, Result.getSuccess), + Option.some, + ]), + Option.all, + ), + ), + Option.all, + Option.map(asReadonlyUnsafe), + Option.map((members) => ({ + _tag: "Struct", + members, + })), + ); + +/** + * Creates a type with positional fields. + * + * An empty tuple compiles to `()`. A single-member tuple keeps a trailing comma to distinguish it from a parenthesized type. + * + * @example Build empty, single-member and pair tuples. + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * Type.compile(Type.tuple()); // => "()" + * Type.compile(Type.tuple(integer)); // => "(Integer,)" + * Type.compile(Type.tuple(integer, integer)); // => "(Integer, Integer)" + * ``` + */ +export const tuple = (...members: readonly Type[]): Defs.TupleType => ({ + _tag: "Tuple", + members, +}); + +/** + * Refers to a named type with optional generic arguments or bounds. + * + * `path` uses path syntax, such as `Integer`, `core::math::add` or `::core::math::+`. Returns `None` if `Path.decodeResult` rejects it, including text with generic arguments such as `List`. Validation checks syntax only. The HashQL compiler resolves the name and checks its generic arguments. + * + * A plain {@link Type} supplies a positional generic argument. An explicit `GenericArgument` or `GenericBound` object from the `Generic` module keeps its form. Generic order follows the argument list. + * + * @example Refer to generic, bounded and rooted types. + * ```ts + * import { Option } from "effect"; + * import * as Generic from "./Generic.js"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const list = Option.getOrThrow(Type.reference("List", integer)); + * Type.compile(list); // => "List" + * + * const bounded = Option.getOrThrow( + * Type.reference("List", Option.getOrThrow(Generic.bound("T", integer))), + * ); + * Type.compile(bounded); // => "List" + * + * const rooted = Option.getOrThrow(Type.reference("::core::math::+", integer)); + * Type.compile(rooted); // => "::core::math::`+`" + * Option.isNone(Type.reference("")); // => true + * ``` + */ +export const reference = ( + path: string, + ...generics: readonly (Type | Defs.GenericType)[] +): Option.Option => + Option.all({ + _tag: Option.some("Reference" as const), + path: Path.decodeResult(path).pipe(Result.getSuccess), + generics: Option.some( + generics.map((generic): Defs.GenericType => { + if ( + generic._tag === "GenericArgument" || + generic._tag === "GenericBound" + ) { + return generic; + } + + return { _tag: "GenericArgument", bound: generic }; + }), + ), + }); + +/** Treats a non-union type as a single union member. */ +const unionMembers = (type: Type): NonEmptyReadonlyArray => { + if (type._tag === "Union") { + return type.members; + } + + return [type]; +}; + +/** Treats a non-intersection type as a single intersection member. */ +const intersectionMembers = (type: Type): NonEmptyReadonlyArray => { + if (type._tag === "Intersection") { + return type.members; + } + + return [type]; +}; + +/** + * Combines types into a union, flattening union operands by one level. + * + * Members of `self` precede members of `that`. Duplicates remain. Chained calls produce a flat union when the initial operands have no nested unions. Use {@link union} to preserve nesting. + * + * @example Chain unions with flattening. + * ```ts + * import { Option } from "effect"; + * import { pipe } from "effect/Function"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const string = Option.getOrThrow(Type.reference("String")); + * const boolean = Option.getOrThrow(Type.reference("Boolean")); + * const value = pipe(integer, Type.or(string), Type.or(boolean)); + * Type.compile(value); // => "(Integer | String | Boolean)" + * Type.compile(Type.or(integer, string)); // => "(Integer | String)" + * ``` + */ +export const or: { + (that: Type): (self: Type) => Defs.UnionType; + (self: Type, that: Type): Defs.UnionType; +} = dual( + 2, + (self: Type, that: Type): Defs.UnionType => ({ + _tag: "Union", + members: [...unionMembers(self), ...unionMembers(that)], + }), +); + +/** + * Combines types into an intersection, flattening its operands once. + * + * An intersection operand contributes its immediate members. Members of `self` precede members of `that`. Duplicates remain. Chained calls produce a flat intersection when the initial operands have no nested intersections. Use {@link intersection} to preserve nesting. + * + * @example Chain intersections with flattening. + * ```ts + * import { Option } from "effect"; + * import { pipe } from "effect/Function"; + * import * as Type from "./index.js"; + * + * const named = Option.getOrThrow(Type.reference("Named")); + * const aged = Option.getOrThrow(Type.reference("Aged")); + * const located = Option.getOrThrow(Type.reference("Located")); + * const person = pipe(named, Type.and(aged), Type.and(located)); + * Type.compile(person); // => "(Named & Aged & Located)" + * Type.compile(Type.and(named, aged)); // => "(Named & Aged)" + * ``` + */ +export const and: { + (that: Type): (self: Type) => Defs.IntersectionType; + (self: Type, that: Type): Defs.IntersectionType; +} = dual( + 2, + (self: Type, that: Type): Defs.IntersectionType => ({ + _tag: "Intersection", + members: [...intersectionMembers(self), ...intersectionMembers(that)], + }), +); + +/** Delimits a compound type expression to preserve its grouping. */ +const parenthesize = ( + members: readonly Type[], + separator: string, +): Identifier => + // oxlint-disable-next-line no-use-before-define -- recursive printer + `(${members.map((member) => compile(member)).join(separator)})`; + +/** Renders a positional argument or named bound within a generic argument list. */ +const compileGeneric: (generic: Defs.GenericType) => Identifier = + Defs.Generic.match({ + // oxlint-disable-next-line no-use-before-define -- recursive printer + GenericArgument: ({ bound }) => compile(bound), + GenericBound: ({ name, bound }) => { + if (bound === undefined) { + return Ident.compile(name); + } + + // oxlint-disable-next-line no-use-before-define -- recursive printer + return `${Ident.compile(name)}: ${compile(bound)}`; + }, + }); + +/** + * Compiles a type into J-Expr type syntax. + * + * Unions and intersections with more than one member always retain parentheses to preserve grouping in nested expressions. A single-member union or intersection compiles as its member. Empty structs use `(:)`, empty tuples use `()`, and single-member tuples retain a trailing comma. + * + * @example Compile a nested type. + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const string = Option.getOrThrow(Type.reference("String")); + * const list = Option.getOrThrow( + * Type.reference("List", Type.union(integer, string)), + * ); + * Type.compile(list); // => "List<(Integer | String)>" + * ``` + */ +export const compile: (type: Type) => Identifier = Defs.Type.match({ + Union: ({ members }) => { + const [first, ...rest] = members; + + if (rest.length === 0) { + return compile(first); + } + + return parenthesize(members, " | "); + }, + Intersection: ({ members }) => { + const [first, ...rest] = members; + + if (rest.length === 0) { + return compile(first); + } + + return parenthesize(members, " & "); + }, + Struct: ({ members }) => { + if (members.length === 0) { + return "(:)"; + } + + const fields = members.map( + ([name, member]) => `${Ident.compile(name)}: ${compile(member)}`, + ); + + return `(${fields.join(", ")})`; + }, + Tuple: ({ members }) => { + const [only, ...rest] = members; + + if (only === undefined) { + return "()"; + } + + if (rest.length === 0) { + return `(${compile(only)},)`; + } + + return parenthesize(members, ", "); + }, + Reference: ({ path, generics }) => { + if (generics.length === 0) { + return Path.compile(path); + } + + const args = generics.map((generic) => compileGeneric(generic)); + return `${Path.compile(path)}<${args.join(", ")}>`; + }, +}); + +/** + * Encodes a type in an expression position, such as a type definition or closure parameter. + * + * Compound types use constructors here. Only annotation positions accept their type-syntax strings. + */ +export const toExpression: (type: Type) => ExpressionType = Defs.Type.match({ + Reference: compile, + Tuple: ({ members }) => ({ "#tuple": members.map(toExpression) }), + Struct: ({ members }) => ({ + "#struct": Object.fromEntries( + members.map(([name, member]) => [ + Ident.compile(name), + toExpression(member), + ]), + ), + }), + Union: ({ members }): ExpressionType => [ + "::kernel::type::Union", + ...members.map(toExpression), + ], + Intersection: ({ members }): ExpressionType => [ + "::kernel::type::Intersection", + ...members.map(toExpression), + ], +}); diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Type/schema.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/schema.ts new file mode 100644 index 00000000000..bb8700ccb20 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/schema.ts @@ -0,0 +1,152 @@ +import { Schema } from "effect"; + +import * as Ident from "../Ident.js"; +import * as Path from "../Path.js"; + +type TypeRef = Schema.suspend>; +const TypeRef: TypeRef = Schema.suspend( + // oxlint-disable-next-line no-use-before-define -- recursive schema + (): Schema.Codec => Type, +); + +export const Union: Schema.TaggedStruct< + "Union", + { members: Schema.NonEmptyArray } +> = Schema.TaggedStruct("Union", { + members: Schema.NonEmptyArray(TypeRef), +}); + +/** Type syntax for a value of at least one member type, with annotation text `(A | B)`. */ +export interface UnionType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link UnionType}, with nested paths and names as source text. */ +export interface UnionEncoded extends Schema.Codec.Encoded {} + +export const Intersection: Schema.TaggedStruct< + "Intersection", + { members: Schema.NonEmptyArray } +> = Schema.TaggedStruct("Intersection", { + members: Schema.NonEmptyArray(TypeRef), +}); + +/** Type syntax for a value of every member type, with annotation text `(A & B)`. */ +export interface IntersectionType extends Schema.Schema.Type< + typeof Intersection +> {} +/** The schema-encoded form of {@link IntersectionType}, with nested paths and names as source text. */ +export interface IntersectionEncoded extends Schema.Codec.Encoded< + typeof Intersection +> {} + +export const Struct: Schema.TaggedStruct< + "Struct", + { members: Schema.$Array> } +> = Schema.TaggedStruct("Struct", { + members: Schema.Array(Schema.Tuple([Ident.Schema, TypeRef])), +}); + +/** Type syntax for named fields, holding decoded name and type pairs in order. Its annotation text is `(name: T)`, or `(:)` when empty. */ +export interface StructType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link StructType}, with field names, paths and nested names as source text. */ +export interface StructEncoded extends Schema.Codec.Encoded {} + +export const Tuple: Schema.TaggedStruct< + "Tuple", + { members: Schema.$Array } +> = Schema.TaggedStruct("Tuple", { + members: Schema.Array(TypeRef), +}); + +/** Type syntax for positional members, with annotation text `(A, B)`, `(A,)` or `()`. */ +export interface TupleType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link TupleType}, with nested paths and names as source text. */ +export interface TupleEncoded extends Schema.Codec.Encoded {} + +export const GenericArgument: Schema.TaggedStruct< + "GenericArgument", + { bound: TypeRef } +> = Schema.TaggedStruct("GenericArgument", { + bound: TypeRef, +}); + +/** A positional generic argument, such as the `Integer` in `List`. */ +export interface GenericArgumentType extends Schema.Schema.Type< + typeof GenericArgument +> {} +/** The schema-encoded form of {@link GenericArgumentType}, with nested paths and names as source text. */ +export interface GenericArgumentEncoded extends Schema.Codec.Encoded< + typeof GenericArgument +> {} + +export const GenericBound: Schema.TaggedStruct< + "GenericBound", + { + name: typeof Ident.Schema; + bound: Schema.optionalKey; + } +> = Schema.TaggedStruct("GenericBound", { + name: Ident.Schema, + bound: TypeRef.pipe(Schema.optionalKey), +}); + +/** A named generic parameter with an optional bound, such as the `T: Integer` in `List`. */ +export interface GenericBoundType extends Schema.Schema.Type< + typeof GenericBound +> {} +/** The schema-encoded form of {@link GenericBoundType}, with its name, paths and nested names as source text. */ +export interface GenericBoundEncoded extends Schema.Codec.Encoded< + typeof GenericBound +> {} + +export const Generic: Schema.toTaggedUnion< + "_tag", + readonly [typeof GenericArgument, typeof GenericBound] +> = Schema.Union([GenericArgument, GenericBound]).pipe( + Schema.toTaggedUnion("_tag"), +); +/** An entry in a reference's generic list: a positional argument or a named bound. */ +export type GenericType = (typeof Generic)["Type"]; +/** The schema-encoded form of {@link GenericType}. */ +export type GenericEncoded = (typeof Generic)["Encoded"]; + +export const Reference: Schema.TaggedStruct< + "Reference", + { path: typeof Path.Schema; generics: Schema.$Array } +> = Schema.TaggedStruct("Reference", { + path: Path.Schema, + generics: Schema.Array(Generic), +}); + +/** Type syntax naming a type by its decoded path, with its generic entries in order. */ +export interface ReferenceType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link ReferenceType}, with its path and nested names as source text. */ +export interface ReferenceEncoded extends Schema.Codec.Encoded< + typeof Reference +> {} + +export const Type: Schema.toTaggedUnion< + "_tag", + readonly [ + typeof Union, + typeof Intersection, + typeof Struct, + typeof Tuple, + typeof Reference, + ] +> = Schema.Union([Union, Intersection, Struct, Tuple, Reference]).pipe( + Schema.toTaggedUnion("_tag"), +); + +/** Tagged type syntax: a union, intersection, struct, tuple or reference. */ +export type Type = + | UnionType + | IntersectionType + | StructType + | TupleType + | ReferenceType; +/** The schema-encoded form of {@link Type}, with paths and names as source text. */ +export type TypeEncoded = + | UnionEncoded + | IntersectionEncoded + | StructEncoded + | TupleEncoded + | ReferenceEncoded; diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/compile.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/compile.ts new file mode 100644 index 00000000000..3cadd26e580 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/compile.ts @@ -0,0 +1,155 @@ +/** + * Writes J-Expr JSON while preserving numeric literal spellings. + * + * @internal + */ +import { Record } from "effect"; + +import { isReadonlyArray } from "../internal/array.js"; + +import type * as Defs from "./schema.js"; + +/** An SDK expression tree to render. */ +type Expression = Defs.ExpressionType; + +/** Quotes object keys and joins already-rendered values. */ +const compileObject = ( + entries: readonly (readonly [string, string])[], +): string => + `{${entries.map(([key, value]) => `${JSON.stringify(key)}:${value}`).join(",")}}`; + +/** Joins already-rendered elements into a JSON array. */ +const compileArray = (items: readonly string[]): string => + `[${items.join(",")}]`; + +/** Adds an optional type annotation to a rendered data constructor. */ +const compileAnnotated = ( + key: string, + value: string, + type: string | undefined, +): string => { + if (type === undefined) { + return compileObject([[key, value]]); + } + + return compileObject([ + [key, value], + ["#type", JSON.stringify(type)], + ]); +}; + +/** Emits numeric source text directly and JSON-encodes other primitive values. */ +const compileLiteral = (value: Defs.LiteralType["#literal"]): string => { + if (value !== null && typeof value === "object") { + return value.value; + } + + return JSON.stringify(value); +}; + +/** Distinguishes a standalone expression from a labeled-argument object. */ +const isPositional = ( + argument: Expression | Defs.LabeledArgumentType, +): argument is Expression => + typeof argument === "string" || + isReadonlyArray(argument) || + !Object.keys(argument).every((key) => key.startsWith(":")); + +/** + * Writes an expression tree as compact J-Expr JSON text. + * + * Each numeric literal is written from its stored text, so an integer keeps every digit and a float keeps its fraction or exponent. `JSON.stringify` would write the SDK's tagged numeric objects instead, which HashQL rejects because a `#literal` value must be a JSON primitive. Strings are JSON-escaped, and object keys follow each object's own enumerable string-key order. A call argument whose keys all start with `:` is written as a labeled argument. + * + * Serialization does not validate. A literal that `JExpr.make` would reject keeps its stored text, so the output can contain non-JSON text such as `NaN`. An object without a constructor key throws a `TypeError`. Check a tree from an untrusted source with `JExpr.make` before compiling it. + * + * @example Serialize exact numbers, unlike JSON.stringify. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * + * const values = JExpr.tuple(JExpr.integer(2n ** 64n), JExpr.float(1), JExpr.float(2.5)); + * assert.equal(JExpr.compile(values), '{"#tuple":[{"#literal":18446744073709551616},{"#literal":1.0},{"#literal":2.5}]}'); + * assert.equal(JSON.stringify(JExpr.integer(1)), '{"#literal":{"_tag":"Integer","value":"1"}}'); + * ``` + */ +export const compile = (expression: Expression): string => { + if (typeof expression === "string") { + return JSON.stringify(expression); + } + + if (isReadonlyArray(expression)) { + return compileArray( + expression.map((argument) => { + if (isPositional(argument)) { + return compile(argument); + } + + return compileObject( + Record.toEntries(argument).map(([key, value]) => [ + key, + compile(value), + ]), + ); + }), + ); + } + + if ("#literal" in expression) { + return compileAnnotated( + "#literal", + compileLiteral(expression["#literal"]), + expression["#type"], + ); + } + + if ("#struct" in expression) { + return compileAnnotated( + "#struct", + compileObject( + Record.toEntries(expression["#struct"]).map(([key, value]) => [ + key, + compile(value), + ]), + ), + expression["#type"], + ); + } + + if ("#tuple" in expression) { + return compileAnnotated( + "#tuple", + compileArray(expression["#tuple"].map(compile)), + expression["#type"], + ); + } + + if ("#list" in expression) { + return compileAnnotated( + "#list", + compileArray(expression["#list"].map(compile)), + expression["#type"], + ); + } + + const entries = expression["#dict"]; + + if (isReadonlyArray(entries)) { + return compileAnnotated( + "#dict", + compileArray( + entries.map(([key, value]) => + compileArray([compile(key), compile(value)]), + ), + ), + expression["#type"], + ); + } + + return compileAnnotated( + "#dict", + compileObject( + Record.toEntries(entries).map(([key, value]) => [key, compile(value)]), + ), + expression["#type"], + ); +}; diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/index.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/index.ts new file mode 100644 index 00000000000..19ff4c6a073 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/index.ts @@ -0,0 +1,465 @@ +/** + * Builds, checks and serializes raw HashQL J-Expr syntax. + * + * J-Expr is HashQL's JSON notation. Arrays are calls, objects keyed by `#literal`, `#struct`, `#tuple`, `#list` or `#dict` construct data, and strings are source text that HashQL parses as a name, path or type. The string `"user"` therefore refers to a value by name. Use {@link literal} for data: `literal("user")` is the string value `"user"`. + * + * The builders return the SDK's {@link Expression} tree, not J-Expr text. The tree stores each numeric literal as tagged source text, such as `{ _tag: "Integer", value: "42" }`, to keep integers beyond JavaScript's precision and the distinction between `1` and `1.0`. {@link compile} writes the tree as J-Expr JSON, where those literals become bare JSON numbers. `JSON.stringify` and {@link Schema} encoding keep the tagged objects, so neither produces J-Expr. + * + * Builders such as {@link literal}, {@link struct} and {@link call} assemble syntax without validating it, and nothing in this module executes a query. {@link make} checks a finished tree against {@link Schema} and throws on failure. {@link makeEffect} keeps the issue in an Effect, and {@link makeOption} returns `None`. The schema checks structure, identifier-named fields and labels, and numeric spelling. It does not parse string expressions or `#type` annotations, resolve names or check types. The HashQL compiler does that when it receives the program. + * + * Builders that take a type, such as {@link input} and {@link typed}, accept type syntax, which `TypeExpression.toType` extracts from a declared type expression. `Ident` and `Path` decode and print single identifiers and paths. Each constructor also has a namespace, such as `Literal` or `Call`, holding its schema, value type and checked `make` functions. + * + * @example Bind a value, check the tree and serialize it. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * + * const query = JExpr.make(JExpr.let("name", JExpr.literal("Alice"), "name")); + * assert.equal(JExpr.compile(query), '["::kernel::special_form::let","name",{"#literal":"Alice"},"name"]'); + * ``` + * + * @module + */ +import { SchemaParser } from "effect"; +import { dual } from "effect/Function"; + +import { isReadonlyArray } from "../internal/array.js"; +import * as Defs from "./schema.js"; +import * as Type from "./Type/index.js"; + +import type * as Reference from "./Type/Reference.js"; +import type { + Schema as $Schema, + Effect, + Option, + Record, + SchemaIssue, +} from "effect"; + +export * as Call from "./Call.js"; +export * as Dict from "./Dict.js"; +export * as Float from "./Float.js"; +export * as Identifier from "./Identifier.js"; +export * as Integer from "./Integer.js"; +export * as LabeledArgument from "./LabeledArgument.js"; +export * as List from "./List.js"; +export * as Literal from "./Literal.js"; +export * as Struct from "./Struct.js"; +export * as Tuple from "./Tuple.js"; +export * as Ident from "./Ident.js"; +export * as Path from "./Path.js"; +export { compile } from "./compile.js"; + +/** + * Effect schema for the SDK's {@link Expression} tree. + * + * Decoding and {@link make} check the tree's structure, identifier-named struct fields and labels, and numeric literal spelling. They accept any string expression and any `#type` text. The encoded form, {@link Encoded}, keeps the tagged numeric literals, so use {@link compile} to produce J-Expr JSON text. + */ +export const Schema: typeof Defs.Expression = Defs.Expression; + +/** + * An SDK expression tree: a call array, a data constructor object or a string expression. + * + * A string is source text that HashQL parses, such as `"user"`, `"entity.properties"` or the placeholder `"_"`, rather than a string value. Numeric literals hold tagged source text, so serialize a tree with {@link compile} rather than `JSON.stringify`. + */ +export type Expression = Defs.ExpressionType; + +/** The schema-encoded tree, with the same tagged numeric literals as {@link Expression}. */ +export type Encoded = Defs.ExpressionEncoded; + +/** Constructor input accepted by {@link Schema} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks an expression tree against {@link Schema} and returns the checked tree. + * + * The result is a new tree without keys outside the matched constructor. Numeric literal objects may omit `_tag`, which the result supplies. `options.disableChecks` skips the identifier, label and numeric-spelling checks but still requires the tree's structure. `options.parseOptions` passes Effect parse options, such as `onExcessProperty: "error"` to reject unknown keys. Use {@link makeOption} when only validity matters, or {@link makeEffect} to inspect a {@link SchemaIssue.Issue} with the failing node's location. + * + * @throws {Error} If validation fails. The error carries a {@link SchemaIssue.Issue} in its `cause`. + * + * @example Check a struct and detect an invalid field name. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * import { Option } from "effect"; + * + * const person = JExpr.make(JExpr.struct({ name: JExpr.literal("Alice") })); + * assert.equal(JExpr.compile(person), '{"#struct":{"name":{"#literal":"Alice"}}}'); + * + * const invalid = JExpr.struct({ "not an ident": JExpr.literal("x") }); + * assert.ok(Option.isNone(JExpr.makeOption(invalid))); + * assert.throws(() => JExpr.make(invalid), { message: "Schema validation failed" }); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Expression = SchemaParser.make(Schema); + +/** Checks a tree like {@link make}, failing the synchronous effect with the {@link SchemaIssue.Issue} instead of throwing. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Checks a tree like {@link make}, returning `None` instead of throwing for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +export { fn, infer } from "./Function.js"; +export type { FnOptions, TypeArgument } from "./Function.js"; + +/** Data constructors that accept a `#type` annotation through {@link typed}. */ +export type Annotatable = + | Defs.StructType + | Defs.TupleType + | Defs.DictType + | Defs.ListType + | Defs.LiteralType; + +/** + * Creates an integer literal from a value's exact decimal digits. + * + * A `bigint` keeps every digit. A `number` is converted from its double value, so an integer beyond `Number.MAX_SAFE_INTEGER` may already have lost precision before this call, and `-0` becomes `0`. A non-integral or non-finite number is stored as its JavaScript text without an error. {@link make} rejects that literal, while {@link compile} emits the text, such as `1.5` or `NaN`. See `JExpr.Integer.Integer` for a precision example. + */ +export const integer = (value: number | bigint): Defs.LiteralType => { + if (typeof value === "number" && Number.isInteger(value)) { + return { "#literal": { _tag: "Integer", value: BigInt(value).toString() } }; + } + + return { "#literal": { _tag: "Integer", value: String(value) } }; +}; + +/** + * Creates a numeric literal that HashQL parses as a float. + * + * The text is JavaScript's shortest decimal for the double, so `float(0.1 + 0.2)` compiles to `0.30000000000000004`. HashQL reads a number as a float only when its text has a fraction or exponent. Integral values therefore gain a fraction: `float(1)` compiles to `1.0` and `-0` to `-0.0`. Magnitudes that JavaScript writes in exponent form keep it, such as `1e+21`. `NaN` and infinities are stored without an error. {@link make} rejects them, and {@link compile} emits text that is not JSON. See {@link compile} for float examples. + */ +export const float = (value: number): Defs.LiteralType => { + if (Object.is(value, -0)) { + return { "#literal": { _tag: "Float", value: "-0.0" } }; + } + + const text = String(value); + + if (Number.isInteger(value) && !text.includes("e")) { + return { "#literal": { _tag: "Float", value: `${text}.0` } }; + } + + return { "#literal": { _tag: "Float", value: text } }; +}; + +/** + * Creates a literal from a primitive value. + * + * A string becomes a string value, unlike a bare string expression. Every `bigint` and every integral number, including `1.0`, `-0` and `1e21`, becomes an {@link integer} literal. Other numbers become {@link float} literals. Use {@link float} explicitly to keep `1` as `1.0` or preserve negative zero. See {@link make} for a string literal example. + */ +export const literal = ( + value: string | number | bigint | boolean | null, +): Defs.LiteralType => { + if (typeof value === "bigint") { + return integer(value); + } + + if (typeof value === "number") { + if (Number.isInteger(value)) { + return integer(value); + } + + return float(value); + } + + return { "#literal": value }; +}; + +/** + * Creates a list whose elements share a type. + * + * HashQL infers the element type. Use {@link tuple} when each position needs its own type. + */ +export const list = (...items: readonly Expression[]): Defs.ListType => ({ + "#list": items, +}); + +/** Creates a fixed-length sequence with a type for each position. */ +export const tuple = (...items: readonly Expression[]): Defs.TupleType => ({ + "#tuple": items, +}); + +/** + * Creates a struct with named fields. + * + * Field names must be identifiers, such as `name`, `+` or `` `+` ``, which {@link make} checks and this builder does not. Each field has its own type. Use {@link dict} for arbitrary string keys. Fields follow the record's own enumerable string-key order. The tree holds the given record object rather than a copy. See {@link make} for a struct example. + */ +export const struct = ( + fields: Record.ReadonlyRecord, +): Defs.StructType => ({ "#struct": fields }); + +/** + * Creates a dictionary from string keys or key expressions. + * + * Record keys are literal strings, even when they look like paths. JavaScript puts integer-like record keys first in ascending order, and {@link compile} keeps that order. Use `[key, value]` pairs to compute keys from expressions or to control their order. The tree holds the given record or array rather than a copy. See `JExpr.Dict.Dict` for examples of both key forms. + */ +export const dict = ( + entries: + | Record.ReadonlyRecord + | readonly (readonly [Expression, Expression])[], +): Defs.DictType => ({ "#dict": entries }); + +/** + * Sets a data constructor's type annotation. + * + * Returns a shallow copy with `#type` set, replacing any existing annotation, and leaves `self` unchanged. The annotation is the type's annotation text, such as `(name: String)`, which HashQL parses and checks. Calls and paths cannot carry this field. Use {@link asType | as} to assert their types. Call it data-first as `typed(self, type)` or data-last in a pipeline. + * + * @example Annotate a literal with a declared type. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr, Prelude, TypeExpression } from "@local/hashql"; + * import { Result, pipe } from "effect"; + * + * const number = Result.getOrThrow(TypeExpression.toType(Prelude.builtin.types.Number)); + * const annotated = pipe(JExpr.literal(3.14), JExpr.typed(number)); + * assert.equal(JExpr.compile(annotated), '{"#literal":3.14,"#type":"::kernel::type::Number"}'); + * ``` + */ +export const typed: { + (type: Type.Type): (self: E) => E; + (self: E, type: Type.Type): E; +} = dual( + 2, + (self: E, type: Type.Type): E => ({ + ...self, + "#type": Type.compile(type), + }), +); + +/** + * Creates a labeled argument for {@link call}, such as `{":name": value}`. + * + * Give `name` without the leading `:`. It must be an identifier, which {@link make} checks and this builder does not. The object keeps its place in the call array. HashQL's parser gathers labeled arguments into their own list, so this one takes no positional slot. See {@link call} for a labeled call example. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const label = ( + name: string, + value: Expression, +): Defs.LabeledArgumentType => ({ [`:${name}`]: value }); + +/** + * Builds a call to a function expression. + * + * `fn` can be a path or an expression that produces a function, including a closure from {@link fn}. Arguments keep their supplied order in the array, including those created with {@link label}. Neither this builder nor {@link make} checks the function's arity or argument types. + * + * @example Call a function with a positional and a labeled argument. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * + * const greeting = JExpr.call("greet", "user", JExpr.label("style", JExpr.literal("formal"))); + * assert.equal(JExpr.compile(greeting), '["greet","user",{":style":{"#literal":"formal"}}]'); + * ``` + */ +export const call = ( + fn: Expression, + ...args: readonly (Expression | Defs.LabeledArgumentType)[] +): Defs.CallType => [fn, ...args]; + +/** + * Selects a branch according to a Boolean expression. + * + * Both branches are already built syntax, so this call runs no host code for either of them. HashQL evaluates only the selected branch when the query runs. Without `otherwise`, or with `otherwise` set to `undefined`, the expression produces HashQL's `Some(then)` when the condition is true and `None` when it is false. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const conditional = ( + condition: Expression, + then: Expression, + otherwise?: Expression, +): Defs.CallType => { + if (otherwise === undefined) { + return ["::kernel::special_form::if", condition, then]; + } + + return ["::kernel::special_form::if", condition, then, otherwise]; +}; + +export { conditional as if }; + +/** + * Binds `value` to `name` within `body`. + * + * `name` is emitted as given, and the HashQL compiler checks that it is an identifier. Use {@link asType | as} on `value` to give it an explicit type. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const binding = ( + name: string, + value: Expression, + body: Expression, +): Defs.CallType => ["::kernel::special_form::let", name, value, body]; + +export { binding as let }; + +/** + * Asserts an expression's type for the HashQL type checker. + * + * The assertion constrains the expression's type without converting its value. A compound type is emitted as constructor syntax, such as a `::kernel::type::Union` call or a `#struct` of types, rather than annotation text. Use {@link typed} to put an annotation directly on a data constructor. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const asType = (value: Expression, type: Type.Type): Defs.CallType => [ + "as", + value, + Type.toExpression(type), +]; + +export { asType as as }; + +/** + * Items to import into the body of {@link use}. + * + * Use `"*"` for all items or an array for named imports. For aliases, supply a record from original name to local name: `{ entities: "allEntities" }` imports `entities` as `allEntities`. The alias `"_"` keeps the original name. An array becomes a `#tuple` of names and a record becomes a `#struct`, whose keys {@link make} checks as identifiers. + */ +export type Imports = + | "*" + | readonly string[] + | Record.ReadonlyRecord; + +/** Renders an import selection as a wildcard, tuple or alias record. */ +const compileImports = (imports: Imports): Expression => { + if (imports === "*") { + return imports; + } + + if (isReadonlyArray(imports)) { + return { "#tuple": imports }; + } + + return { "#struct": imports }; +}; + +/** + * Imports items from the module at `path` into `body`. + * + * `path` is path text, such as `::core::math`, which the HashQL compiler resolves. {@link Imports} describes wildcard imports, named imports and aliases. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const use = ( + path: string, + imports: Imports, + body: Expression, +): Defs.CallType => [ + "::kernel::special_form::use", + path, + compileImports(imports), + body, +]; + +/** + * Reads a named query input supplied by the host. + * + * Without `defaultValue`, or with `defaultValue` set to `undefined`, the host must supply the input. Otherwise, HashQL evaluates `defaultValue`, asserted as `type`, when the input is absent. Obtain `type` from a declared type expression with `TypeExpression.toType`. + * + * @example Read an optional page size. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr, Prelude, TypeExpression } from "@local/hashql"; + * import { Result } from "effect"; + * + * const integer = Result.getOrThrow(TypeExpression.toType(Prelude.builtin.types.Integer)); + * const pageSize = JExpr.input("page_size", integer, JExpr.integer(10)); + * assert.equal(JExpr.compile(pageSize), '["::kernel::special_form::input","page_size","::kernel::type::Integer",{"#literal":10}]'); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const input = ( + name: string, + type: Type.Type, + defaultValue?: Expression, +): Defs.CallType => { + if (defaultValue === undefined) { + return ["::kernel::special_form::input", name, Type.toExpression(type)]; + } + + return [ + "::kernel::special_form::input", + name, + Type.toExpression(type), + defaultValue, + ]; +}; + +/** + * Selects a named field or a tuple position. + * + * Give a field identifier as a string or a zero-based tuple position as a number. A number becomes an {@link integer} literal, so a non-integral position fails {@link make}. Use {@link index} when the selector is an expression. A string expression such as `"entity.properties"` is HashQL shorthand for the same named field access. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const access = ( + value: Expression, + field: string | number, +): Defs.CallType => { + if (typeof field === "number") { + return ["::kernel::special_form::access", value, integer(field)]; + } + + return ["::kernel::special_form::access", value, field]; +}; + +/** + * Looks up a collection element using an index expression. + * + * Use {@link literal} for a fixed index. A string such as `"offset"` refers to a value in scope. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const index = ( + value: Expression, + position: Expression, +): Defs.CallType => ["::kernel::special_form::index", value, position]; + +/** Renders a declaration name, including any generic parameters. */ +const compileName = (name: string | Reference.Reference): string => { + if (typeof name === "string") { + return name; + } + + return Type.compile(name); +}; + +/** + * Introduces a type alias in `body`. + * + * The alias denotes the same type as `type`. Use {@link newtype} for a distinct nominal type with a constructor. `name` is text emitted as given, such as `"Pair"`, or reference type syntax, which compiles to the same form. Its generic list declares the alias's parameters, such as `T` or `T: Integer`. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const typeAlias = ( + name: string | Reference.Reference, + type: Type.Type, + body: Expression, +): Defs.CallType => [ + "::kernel::special_form::type", + compileName(name), + Type.toExpression(type), + body, +]; + +export { typeAlias as type }; + +/** + * Introduces a distinct type and its constructor in `body`. + * + * The constructor has the same name as the type. `name` accepts generic parameters as described by {@link typeAlias | type}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const newtype = ( + name: string | Reference.Reference, + type: Type.Type, + body: Expression, +): Defs.CallType => [ + "::kernel::special_form::newtype", + compileName(name), + Type.toExpression(type), + body, +]; diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/schema.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/schema.ts new file mode 100644 index 00000000000..547b3b5c7fc --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/schema.ts @@ -0,0 +1,262 @@ +import { Option, Schema } from "effect"; + +import * as Scan from "../internal/scan.js"; + +import type { SchemaAST } from "effect"; +import type { ReadonlyRecord } from "effect/Record"; + +/** A deferred reference that permits expressions to contain other expressions. */ +type ExpressionRef = Schema.suspend< + Schema.Codec +>; +const ExpressionRef: ExpressionRef = Schema.suspend( + // oxlint-disable-next-line no-use-before-define -- recursive schema + (): Schema.Codec => Expression, +); + +/** Whether `input` is a single identifier in source form, such as `name`, `+` or `` `+` ``. */ +const isIdentSource = (input: string): boolean => + Option.isSome(Scan.scanIdentExact(input)); + +/** + * A path, a type expression or a labeled-argument shorthand. + * + * The schema accepts any string. HashQL parses it according to its position in the expression. + */ +export const Identifier: Schema.String = Schema.String.pipe( + Schema.brand("~hashql/Identifier"), +); + +/** The value described by {@link Identifier}. */ +export type IdentifierType = typeof Identifier.Type; +/** The schema-encoded form of {@link Identifier}. */ +export type IdentifierEncoded = Schema.Codec.Encoded; + +/** + * Requires every key to start with `prefix` followed by a complete identifier. + * + * Checking the whole record rejects invalid keys that `Schema.Record` would otherwise skip when matching a key schema. + */ +const hasIdentKeys = ( + prefix: string, + expected: string, +): SchemaAST.Filter> => + Schema.makeFilter( + (record: ReadonlyRecord) => + Object.keys(record) + .filter( + (key) => + !key.startsWith(prefix) || !isIdentSource(key.slice(prefix.length)), + ) + .map((key) => ({ path: [key], issue: `Expected ${expected}` })), + { expected }, + ); + +/** Colon-prefixed key text, before {@link hasIdentKeys} validates the identifier. */ +const LabelKey: Schema.TemplateLiteral = + Schema.TemplateLiteral([":", Schema.String]); + +/** + * A labeled call argument, such as `{":name": value}`. + * + * It can appear anywhere after the function in a call array. HashQL's parser gathers labeled arguments into their own list, so a labeled argument takes no positional slot. + */ +export const LabeledArgument: Schema.$Record = + Schema.Record(LabelKey, ExpressionRef).check( + hasIdentKeys(":", "`:` followed by an identifier"), + Schema.isMinProperties(1), + Schema.isMaxProperties(1), + ); + +/** The value described by {@link LabeledArgument}. */ +export interface LabeledArgumentType extends Schema.Schema.Type< + typeof LabeledArgument +> {} +/** The schema-encoded form of {@link LabeledArgument}. */ +export interface LabeledArgumentEncoded extends Schema.Codec.Encoded< + typeof LabeledArgument +> {} + +/** A nonempty call array, starting with the function expression. */ +export const Call: Schema.TupleWithRest< + Schema.Tuple, + readonly [Schema.Union] +> = Schema.TupleWithRest(Schema.Tuple([ExpressionRef]), [ + Schema.Union([ExpressionRef, LabeledArgument]), +]); + +/** The value described by {@link Call}. */ +export type CallType = readonly [ + ExpressionType, + ...(ExpressionType | LabeledArgumentType)[], +]; +/** The schema-encoded form of {@link Call}. */ +export type CallEncoded = readonly [ + ExpressionEncoded, + ...(ExpressionEncoded | LabeledArgumentEncoded)[], +]; + +/** A data constructor with identifier-named fields and an optional type annotation. */ +export const Struct: Schema.Struct<{ + "#struct": Schema.$Record; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#struct": Schema.Record(Schema.String, ExpressionRef).check( + hasIdentKeys("", "an identifier"), + ), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Struct}. */ +export interface StructType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Struct}. */ +export interface StructEncoded extends Schema.Codec.Encoded {} + +/** A fixed-length sequence of expressions and an optional type annotation. */ +export const Tuple: Schema.Struct<{ + "#tuple": Schema.$Array; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#tuple": Schema.Array(ExpressionRef), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Tuple}. */ +export interface TupleType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Tuple}. */ +export interface TupleEncoded extends Schema.Codec.Encoded {} + +/** A dictionary of string-keyed values or expression pairs, with an optional type annotation. */ +export const Dict: Schema.Struct<{ + "#dict": Schema.Union< + readonly [ + Schema.$Record, + Schema.$Array>, + ] + >; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#dict": Schema.Union([ + Schema.Record(Schema.String, ExpressionRef), + Schema.Array(Schema.Tuple([ExpressionRef, ExpressionRef])), + ]), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Dict}. */ +export interface DictType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Dict}. */ +export interface DictEncoded extends Schema.Codec.Encoded {} + +/** A list of expressions and an optional type annotation. */ +export const List: Schema.Struct<{ + "#list": Schema.$Array; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#list": Schema.Array(ExpressionRef), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link List}. */ +export interface ListType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link List}. */ +export interface ListEncoded extends Schema.Codec.Encoded {} + +/** + * An integer literal in JSON number syntax, such as `-42`. + * + * Keeping the text preserves integers beyond JavaScript's numeric precision limit. + */ +export const Integer: Schema.TaggedStruct<"Integer", { value: Schema.String }> = + Schema.TaggedStruct("Integer", { + value: Schema.String.check( + Schema.isPattern(/^-?(?:0|[1-9]\d*)$/u, { + expected: "an integer in JSON number syntax", + }), + ), + }); + +/** The value described by {@link Integer}. */ +export interface IntegerType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Integer}. */ +export interface IntegerEncoded extends Schema.Codec.Encoded {} + +/** + * A float literal in JSON number syntax with a fraction or exponent, such as `1.0` or `1e3`. + * + * HashQL reads a number as a float only if its text contains a fraction or exponent. The stored text preserves that distinction. + */ +export const Float: Schema.TaggedStruct<"Float", { value: Schema.String }> = + Schema.TaggedStruct("Float", { + value: Schema.String.check( + Schema.isPattern( + /^-?(?:0|[1-9]\d*)(?:\.\d+(?:[eE][+-]?\d+)?|[eE][+-]?\d+)$/u, + { expected: "a float in JSON number syntax" }, + ), + ), + }); + +/** The value described by {@link Float}. */ +export interface FloatType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Float}. */ +export interface FloatEncoded extends Schema.Codec.Encoded {} + +/** A primitive value, with tagged source text for numbers and an optional type annotation. */ +export const Literal: Schema.Struct<{ + "#literal": Schema.Union< + readonly [ + Schema.String, + typeof Integer, + typeof Float, + Schema.Boolean, + Schema.Null, + ] + >; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#literal": Schema.Union([ + Schema.String, + Integer, + Float, + Schema.Boolean, + Schema.Null, + ]), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Literal}. */ +export interface LiteralType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Literal}. */ +export interface LiteralEncoded extends Schema.Codec.Encoded {} + +/** The recursive union of calls, data constructors and string expressions. */ +export const Expression: Schema.Union< + readonly [ + typeof Call, + typeof Struct, + typeof Tuple, + typeof Dict, + typeof List, + typeof Literal, + typeof Identifier, + ] +> = Schema.Union([Call, Struct, Tuple, Dict, List, Literal, Identifier]); + +/** The value described by {@link Expression}. */ +export type ExpressionType = + | CallType + | StructType + | TupleType + | DictType + | ListType + | LiteralType + | IdentifierType; +/** The schema-encoded form of {@link Expression}. */ +export type ExpressionEncoded = + | CallEncoded + | StructEncoded + | TupleEncoded + | DictEncoded + | ListEncoded + | LiteralEncoded + | IdentifierEncoded; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/Binding.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Binding.ts new file mode 100644 index 00000000000..661a8491001 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Binding.ts @@ -0,0 +1,24 @@ +import { Result } from "effect"; + +import * as Ident from "../../JExpr/Ident.js"; +import * as ProgramError from "../ProgramError.js"; + +export interface Binding { + readonly name: Ident.Ident; + readonly value: Value; +} + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a named binding +export const make = ( + name: string, + value: Value, +): Result.Result, ProgramError.Construction> => + Ident.decodeResult(name).pipe( + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidBindingName({ name, cause }), + }), + ), + Result.map((name) => ({ name, value })), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/Expr.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Expr.ts new file mode 100644 index 00000000000..71c88addbc0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Expr.ts @@ -0,0 +1,14 @@ +import type * as JExpr from "../../JExpr/index.js"; +import type { Node } from "./Node.js"; + +export class Expr implements Node { + readonly expression: JExpr.Expression; + + constructor(expression: JExpr.Expression) { + this.expression = expression; + } + + compile(): JExpr.Expression { + return this.expression; + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/If.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/If.ts new file mode 100644 index 00000000000..4f5f455d631 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/If.ts @@ -0,0 +1,23 @@ +import * as JExpr from "../../JExpr/index.js"; + +import type { Node } from "./Node.js"; + +export class If implements Node { + readonly condition: Node; + readonly consequent: Then; + readonly alternate: Else; + + constructor(condition: Node, consequent: Then, alternate: Else) { + this.condition = condition; + this.consequent = consequent; + this.alternate = alternate; + } + + compile(): JExpr.Expression { + return JExpr.if( + this.condition.compile(), + this.consequent.compile(), + this.alternate.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/Import.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Import.ts new file mode 100644 index 00000000000..a4252f8af81 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Import.ts @@ -0,0 +1,24 @@ +import * as JExpr from "../../JExpr/index.js"; +import * as Path from "../../JExpr/Path.js"; + +import type { Node } from "./Node.js"; + +export class Import implements Node { + readonly path: Path.Path; + readonly imports: JExpr.Imports; + readonly child: Child; + + constructor(path: Path.Path, imports: JExpr.Imports, child: Child) { + this.path = path; + this.imports = imports; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.use( + Path.compile(this.path), + this.imports, + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/Let.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Let.ts new file mode 100644 index 00000000000..bfbcce0fdf1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Let.ts @@ -0,0 +1,23 @@ +import * as Ident from "../../JExpr/Ident.js"; +import * as JExpr from "../../JExpr/index.js"; + +import type { Binding } from "./Binding.js"; +import type { Node } from "./Node.js"; + +export class Let implements Node { + readonly binding: Binding; + readonly child: Child; + + constructor(binding: Binding, child: Child) { + this.binding = binding; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.let( + Ident.compile(this.binding.name), + this.binding.value.compile(), + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Newtype.ts new file mode 100644 index 00000000000..d473fe65b1f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Newtype.ts @@ -0,0 +1,24 @@ +import * as Ident from "../../JExpr/Ident.js"; +import * as JExpr from "../../JExpr/index.js"; + +import type * as Syntax from "../../JExpr/Type/index.js"; +import type { Binding } from "./Binding.js"; +import type { Node } from "./Node.js"; + +export class Newtype implements Node { + readonly binding: Binding; + readonly child: Child; + + constructor(binding: Binding, child: Child) { + this.binding = binding; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.newtype( + Ident.compile(this.binding.name), + this.binding.value, + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/Node.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Node.ts new file mode 100644 index 00000000000..d4ee40bef58 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Node.ts @@ -0,0 +1,7 @@ +import type * as JExpr from "../../JExpr/index.js"; + +/** A builder node that emits J-Expr syntax during expression serialization. */ +export interface Node { + /** Returns syntax without executing the represented HashQL expression. */ + readonly compile: () => JExpr.Expression; +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/Type.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Type.ts new file mode 100644 index 00000000000..2766ff1699b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Type.ts @@ -0,0 +1,24 @@ +import * as Ident from "../../JExpr/Ident.js"; +import * as JExpr from "../../JExpr/index.js"; + +import type * as Syntax from "../../JExpr/Type/index.js"; +import type { Binding } from "./Binding.js"; +import type { Node } from "./Node.js"; + +export class Type implements Node { + readonly binding: Binding; + readonly child: Child; + + constructor(binding: Binding, child: Child) { + this.binding = binding; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.type( + Ident.compile(this.binding.name), + this.binding.value, + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/AST/index.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/index.ts new file mode 100644 index 00000000000..7c4d651947d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/index.ts @@ -0,0 +1,8 @@ +export * from "./Binding.js"; +export * from "./Expr.js"; +export * from "./If.js"; +export * from "./Import.js"; +export * from "./Let.js"; +export * from "./Newtype.js"; +export type * from "./Node.js"; +export * from "./Type.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Expression.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test-d.ts new file mode 100644 index 00000000000..13cb4dc6fa4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test-d.ts @@ -0,0 +1,434 @@ +/** + * Static checks for symbolic calls, field projections and input requirements. + * + * @module + */ +import { describe, expectTypeOf, test } from "vitest"; + +import type * as Type from "../Type/index.js"; +import type { Expression } from "./Expression.js"; +import type * as Inputs from "./Inputs.js"; + +type Left = Type.Struct<{ + readonly shared: Type.List; + readonly left: Type.PrimitiveBoolean; +}>; +type Right = Type.Struct<{ + readonly shared: Type.List; + readonly right: Type.PrimitiveInteger; +}>; + +interface Recursive extends Type.Struct<{ + readonly next: Recursive; + readonly value: Type.PrimitiveString; +}> {} + +const outOfBoundsPosition = 2; + +declare const left: Expression; +declare const position: Expression; +declare const text: Expression; +declare const union: Expression< + Type.Union, + Inputs.Empty +>; +declare const intersection: Expression< + Type.Intersection, + Inputs.Empty +>; +declare const recursive: Expression; + +const preserve = ( + expression: Expression, +): Expression => expression; + +describe("binding", () => { + test("primitive_identity", () => { + expectTypeOf< + Expression + >().not.toBeNever(); + expectTypeOf(text).not.toHaveProperty("$project"); + expectTypeOf(text).not.toHaveProperty("$index"); + expectTypeOf(text).not.toExtend< + Expression + >(); + // @ts-expect-error A non-function expression has no call signature. + text(); + }); + + test("generic_preservation", () => { + expectTypeOf(preserve(left)).toEqualTypeOf< + Expression + >(); + expectTypeOf(preserve(left).shared).toEqualTypeOf< + Expression, Inputs.Empty> + >(); + }); + + test("recursive_projection", () => { + expectTypeOf(recursive.next.next.value).toEqualTypeOf< + Expression + >(); + expectTypeOf(recursive.$project("next").$project("value")).toEqualTypeOf< + Expression + >(); + }); + + test("opaque_forwarding", () => { + type Wrapped = Expression, Inputs.Empty>; + expectTypeOf().toEqualTypeOf< + Expression, Inputs.Empty> + >(); + expectTypeOf().not.toExtend>(); + expectTypeOf().not.toExtend< + Expression, Inputs.Empty> + >(); + }); +}); + +describe("projection", () => { + test("union_common_fields", () => { + expectTypeOf(union).not.toHaveProperty("left"); + expectTypeOf(union).not.toHaveProperty("right"); + expectTypeOf(union.shared).toEqualTypeOf< + Expression< + Type.Union< + readonly [Type.List, Type.List] + >, + Inputs.Empty + > + >(); + expectTypeOf(union.$project("shared")).toEqualTypeOf(); + // @ts-expect-error Every alternative must support the requested field. + union.$project("left"); + }); + + test("intersection_common_fields", () => { + expectTypeOf(intersection).not.toHaveProperty("left"); + expectTypeOf(intersection).not.toHaveProperty("right"); + expectTypeOf(intersection.shared).toEqualTypeOf< + Expression< + Type.Intersection< + readonly [Type.List, Type.List] + >, + Inputs.Empty + > + >(); + expectTypeOf(intersection.$project("shared")).toEqualTypeOf< + typeof intersection.shared + >(); + // @ts-expect-error An intersection projection must be valid on every member. + intersection.$project("right"); + }); + + test("nullable_receiver", () => { + type Nullable = Expression< + Type.Union, + Inputs.Empty + >; + expectTypeOf().not.toHaveProperty("shared"); + expectTypeOf().not.toHaveProperty("$project"); + expectTypeOf().not.toBeNever(); + }); + + test("tuple_positions", () => { + type Pair = Expression< + Type.Tuple, + Inputs.Empty + >; + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().not.toHaveProperty("length"); + expectTypeOf().not.toHaveProperty("map"); + expectTypeOf().not.toHaveProperty(outOfBoundsPosition); + }); +}); + +declare const pair: Expression< + Type.Tuple, + Inputs.Empty +>; + +describe("tuple_projection", () => { + test("explicit_position", () => { + expectTypeOf(pair.$project(0)).toEqualTypeOf<(typeof pair)[0]>(); + // @ts-expect-error The tuple has no third position. + pair.$project(2); + // @ts-expect-error The number type does not identify one fixed tuple field. + pair.$project(Number("0")); + // @ts-expect-error Direct access also rejects nonexistent tuple positions. + expectTypeOf(pair[outOfBoundsPosition]); + }); + + test("empty_tuple", () => { + type Empty = Expression, Inputs.Empty>; + expectTypeOf().not.toBeNever(); + expectTypeOf().not.toHaveProperty(0); + expectTypeOf().not.toHaveProperty("$project"); + }); +}); + +type Overlap = Type.Intersection< + readonly [ + Type.Union, + Type.Union, + ] +>; + +type Algebra = Expression< + Type.Struct<{ + readonly overlap: Overlap; + readonly duplicate: Type.Union< + readonly [ + Type.PrimitiveString, + Type.Union, + ] + >; + readonly top: Type.Union; + readonly narrow: Type.Intersection< + readonly [Type.Unknown, Type.PrimitiveString] + >; + readonly impossible: Type.Intersection< + readonly [Type.PrimitiveString, Type.PrimitiveInteger] + >; + readonly emptyUnion: Type.Union; + readonly emptyIntersection: Type.Intersection; + }>, + Inputs.Empty +>; + +describe("composition", () => { + test("distributive_narrowing", () => { + type Narrowed = Expression< + Type.Intersection< + readonly [ + Type.Struct<{ readonly shared: Overlap["types"][0] }>, + Type.Struct<{ readonly shared: Overlap["types"][1] }>, + ] + >, + Inputs.Empty + >; + + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("union_identities", () => { + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("intersection_identities", () => { + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("numeric_intersection", () => { + type Numeric = Type.Intersection< + readonly [Type.PrimitiveInteger, Type.PrimitiveNumber] + >; + type Fields = Expression< + Type.Struct<{ readonly value: Numeric }>, + Inputs.Empty + >; + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("neutral_members", () => { + type WithNever = Expression< + Type.Union, + Inputs.Empty + >; + type WithUnknown = Expression< + Type.Intersection, + Inputs.Empty + >; + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().not.toEqualTypeOf< + Expression + >(); + }); +}); + +declare const dictionary: Expression< + Type.Dict, + Inputs.Empty +>; +declare const opaqueList: Expression< + Type.Opaque<"Names", Type.List>, + Inputs.Empty +>; + +describe("indexing", () => { + test("list_nullable", () => { + expectTypeOf(left.shared.$index(position)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + // @ts-expect-error List indices are integer expressions. + left.shared.$index(text); + }); + + test("dictionary_nullable", () => { + expectTypeOf(dictionary.$index(text)).toEqualTypeOf< + Expression, Inputs.Empty> + >(); + expectTypeOf(dictionary.$index(text)).not.toHaveProperty("shared"); + // @ts-expect-error The dictionary declares a string key. + dictionary.$index(position); + }); + + test("opaque_collection", () => { + expectTypeOf(opaqueList.$index(position)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + }); + + test("composed_values", () => { + expectTypeOf(union.shared.$index(position)).toEqualTypeOf< + Expression + >(); + expectTypeOf(intersection.shared.$index(position)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + }); + + test("incompatible_keys", () => { + type MixedKeys = readonly [ + Type.Dict, + Type.Dict, + ]; + expectTypeOf< + Expression, Inputs.Empty> + >().not.toHaveProperty("$index"); + expectTypeOf< + Expression, Inputs.Empty> + >().not.toHaveProperty("$index"); + expectTypeOf< + Expression< + Type.Union, Type.PrimitiveNull]>, + Inputs.Empty + > + >().not.toHaveProperty("$index"); + }); +}); + +type Key = Type.Struct<{ readonly id: Type.PrimitiveInteger }>; +declare const keyed: Expression< + Type.Dict, + Inputs.Empty +>; +declare const key: Expression; +declare const narrowerKey: Expression< + Type.Struct<{ + readonly id: Type.PrimitiveInteger; + readonly name: Type.PrimitiveString; + }>, + Inputs.Empty +>; +declare const unionKeyed: Expression< + Type.Dict, Left>, + Inputs.Empty +>; +declare const unionKey: Expression< + Type.Union<[Type.PrimitiveString, Type.PrimitiveNull]>, + Inputs.Empty +>; + +declare const reserved: Expression< + Type.Struct<{ + readonly $project: Type.PrimitiveString; + readonly $index: Type.PrimitiveInteger; + readonly get: Type.PrimitiveBoolean; + readonly then: Type.PrimitiveString; + }>, + Inputs.Empty +>; +declare const incompatibleValues: Expression< + Type.Intersection< + readonly [ + Type.Dict, + Type.Dict, + ] + >, + Inputs.Empty +>; + +describe("operation_names", () => { + test("explicit_reserved_field", () => { + expectTypeOf(reserved.$project("$project")).toEqualTypeOf< + Expression + >(); + expectTypeOf(reserved.$project("$index")).toEqualTypeOf< + Expression + >(); + expectTypeOf(reserved).not.toHaveProperty("$index"); + expectTypeOf(reserved.get).toEqualTypeOf< + Expression + >(); + expectTypeOf(reserved.then).toEqualTypeOf< + Expression + >(); + expectTypeOf(reserved.$project("then")).toEqualTypeOf< + Expression + >(); + }); + + test("uninhabited_value_lookup", () => { + expectTypeOf(incompatibleValues.$index(text)).toEqualTypeOf< + Expression + >(); + }); +}); + +describe("key_identity", () => { + test("invariant_key", () => { + expectTypeOf(keyed.$index(key)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + // @ts-expect-error A narrower struct is not the declared key type. + keyed.$index(narrowerKey); + }); + + test("declared_union_key", () => { + expectTypeOf(unionKeyed.$index(unionKey)).toEqualTypeOf< + Expression, Inputs.Empty> + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts new file mode 100644 index 00000000000..a1f12ece31e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts @@ -0,0 +1,157 @@ +/** + * Runtime checks for symbolic calls and property projections. + * + * @module + */ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../JExpr/index.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; + +import type * as Type from "../Type/index.js"; +import type * as Inputs from "./Inputs.js"; + +type Vertex = Type.Struct<{ readonly name: Type.PrimitiveString }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": T }> +>; +type VertexOf = T extends Graph ? VertexType : never; + +interface Filter extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer Input, Type.Any] + ? Type.Function< + readonly [ + Graph>, + Type.Function], Type.PrimitiveBoolean>, + ], + Graph> + > + : Type.Function; +} + +const compile = (expression: Expression.Any): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(expression))); + +// This handwritten declaration targets the standard-library function. +const body = Result.getOrThrow( + Module.define("::graph::body", { + values: { filter: Module.value>() }, + }), +); + +describe("expression", () => { + test("generic_filter_call", () => { + expect.hasAssertions(); + const vertices = Expression.fromJExpr, Inputs.Empty>( + "vertices", + ); + const predicate = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >([ + "::kernel::special_form::fn", + { "#tuple": [] }, + { "#struct": { vertex: "_" } }, + "_", + [ + "::core::cmp::eq", + ["::kernel::special_form::access", "vertex", "name"], + { "#literal": "Ada" }, + ], + ]); + const prelude = { select: body.values.filter }; + expect(compile(prelude.select(vertices, predicate))).toBe( + '["::graph::body::filter","vertices",["::kernel::special_form::fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",["::core::cmp::eq",["::kernel::special_form::access","vertex","name"],{"#literal":"Ada"}]]]', + ); + }); + + test("returned_function", () => { + expect.hasAssertions(); + type Unary = Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + >; + const outer = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("outer"); + const operand = Expression.fromJExpr( + JExpr.integer(2), + ); + expect(compile(outer()(operand))).toBe('[["outer"],{"#literal":2}]'); + }); + + test("projected_function", () => { + expect.hasAssertions(); + type Unary = Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + >; + const record = Expression.fromJExpr< + Type.Struct<{ readonly increment: Unary }>, + Inputs.Empty + >("record"); + const operand = Expression.fromJExpr( + JExpr.integer(2), + ); + expect(compile(record.increment(operand))).toBe( + '[["::kernel::special_form::access","record","increment"],{"#literal":2}]', + ); + }); + + test("projection_and_index", () => { + expect.hasAssertions(); + const record = Expression.fromJExpr< + Type.Struct<{ readonly users: Type.List }>, + Inputs.Empty + >("record"); + const index = Expression.fromJExpr( + JExpr.integer(0), + ); + expect(compile(record.users.$index(index))).toBe( + '["::kernel::special_form::index",["::kernel::special_form::access","record","users"],{"#literal":0}]', + ); + expect(compile(record.$project("users"))).toBe( + '["::kernel::special_form::access","record","users"]', + ); + }); + + test("reserved_projection", () => { + expect.hasAssertions(); + const record = Expression.fromJExpr< + Type.Struct<{ readonly $: Type.PrimitiveBoolean }>, + Inputs.Empty + >("record"); + expect(compile(record.$project("$"))).toBe( + '["::kernel::special_form::access","record","$"]', + ); + }); + + test("callable_properties", () => { + expect.hasAssertions(); + const record = Expression.fromJExpr< + Type.Struct<{ + readonly name: Type.PrimitiveString; + readonly length: Type.PrimitiveInteger; + readonly then: Type.Function; + }>, + Inputs.Empty + >("record"); + expect(compile(record.name)).toBe( + '["::kernel::special_form::access","record","name"]', + ); + expect(compile(record.length)).toBe( + '["::kernel::special_form::access","record","length"]', + ); + expect(compile(record.$project("then")())).toBe( + '[["::kernel::special_form::access","record","then"]]', + ); + const thenField = record.then; + expect(compile(thenField())).toBe( + '[["::kernel::special_form::access","record","then"]]', + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Expression.ts b/libs/@local/hashql/sdk/typescript/src/Program/Expression.ts new file mode 100644 index 00000000000..989391982ad --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Expression.ts @@ -0,0 +1,547 @@ +/** + * Symbolic HashQL values with semantic types and input requirements. + * + * Handles build syntax rather than executing queries. Their descriptors select the available calls and projections. Rebinding retains those descriptors while replacing the referenced path, and construction failures remain attached to the handle. + * + * A projected field named `then` retains its HashQL meaning. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. + * + * @module + */ +// oxlint-disable max-lines -- expression constructors and their API examples belong with the private handle metadata and proxy machinery +// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods +import { Function, Predicate, Result, Schema, identity, pipe } from "effect"; + +import { Relocate } from "../internal/relocation.js"; +import * as JExpr from "../JExpr/index.js"; +import * as AST from "./AST/index.js"; +import * as ProgramError from "./ProgramError.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type * as Type from "../Type/index.js"; +import type { Accessors, Callable, Conditional } from "./ExpressionType.js"; +import type * as Input from "./Inputs.js"; +import type { Types } from "effect"; + +export type { Conditional } from "./ExpressionType.js"; + +const TypeId = "~hashql/Expression"; +const Binding: unique symbol = Symbol("~hashql/Expression"); + +interface Variance { + readonly _T: Types.Invariant; + readonly _Inputs: Types.Contravariant; +} + +/** Host literals accepted without an explicit expression wrapper: strings, numbers, bigints, booleans and null. */ +export type Primitive = Type.Primitive["value"]; + +type InputAlternatives = E extends Primitive + ? Input.Empty + : E extends { + readonly [TypeId]: { + readonly _Inputs: Types.Contravariant; + }; + } + ? [Requirements] extends [never] + ? Input.Erased + : // oxlint-disable-next-line typescript/no-restricted-types -- detects the top type in a caller annotation without erasing a value + unknown extends Requirements + ? Input.Erased + : { readonly [Key in keyof Requirements]: Requirements[Key] } + : Input.Erased; + +/** The semantic input descriptors required by every host-side alternative, with defaults marked optional. */ +export type Inputs = Input.Conservative>; + +/** An expression with its semantic type erased, for syntax-only operations. */ +export interface Any extends Relocatable { + readonly [Binding]: Result.Result; +} + +/** Semantic metadata and stored construction result shared by expressions and adapted callables. */ +export interface Handle extends Any { + readonly [TypeId]: Variance; + readonly [Relocate]: Relocatable>[typeof Relocate]; +} + +/** An expression or host literal accepted by syntax-only operations such as {@link toJExpr}. */ +export type AnyValue = Any | Primitive; + +/** + * An exactly typed handle or the host primitive corresponding to its semantic descriptor. + * + * Argument compatibility uses the semantic metadata that adapted callables retain. Integer operands accept bigint and Integer handles. TypeScript rejects a host number at that position rather than widening its descriptor. + */ +export type Value = + | (Any & Pick, typeof TypeId | typeof Binding>) + | (T extends Type.Primitive ? T["value"] : never); + +/** + * Reads semantic metadata without constraining an adapted callable to its original host signature. + * + * Host numbers remain Number regardless of their emitted literal syntax. + */ +export type TypeOf = V extends { + readonly [TypeId]: { readonly _T: Types.Invariant }; +} + ? T + : V extends string + ? Type.PrimitiveString + : V extends boolean + ? Type.PrimitiveBoolean + : V extends bigint + ? Type.PrimitiveInteger + : V extends number + ? Type.PrimitiveNumber + : V extends null + ? Type.PrimitiveNull + : never; + +class ExpressionImpl { + readonly [TypeId]: Variance; + + readonly #expr: Result.Result; + + constructor(expr: Result.Result) { + this.#expr = expr; + this[TypeId] = { + _T: identity, + // oxlint-disable-next-line typescript/strict-void-return -- only used for type variance + _Inputs: identity, + }; + } + + get [Binding](): Result.Result { + return this.#expr; + } +} + +/** + * A symbolic HashQL value with type-directed projection, indexing and calls. + * + * `T` describes the represented value, not its host wrapper. `Inputs` records the inputs needed to evaluate it. Fields and tuple positions project to new expressions. Use `$project` for fields whose names collide with SDK operations. Lists and dictionaries expose `$index`, whose result includes Null for a missing entry. Callable descriptors expose a host call that constructs HashQL call syntax. + * + * Property access and calls construct syntax without reading data or executing the represented function. Extract that syntax or its retained construction failure with {@link toJExpr}. + * + * @example Project a field from a typed input. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Structural } from "@local/hashql"; + * import { Result } from "effect"; + * + * const account = Expression.input("account", Structural.type({ active: Boolean })); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(account.active)), + * Result.getOrThrow(Expression.toJExpr(account.$project("active"))), + * ); + * ``` + */ +export type Expression = Handle & + Accessors & + Callable; + +/** + * Recognizes the private expression marker without checking the stored result or semantic type. + * + * Use this to distinguish SDK handles from host literals, not to validate untrusted objects. + */ +// oxlint-disable-next-line typescript/no-restricted-types -- the guard accepts unchecked host values +export const isExpression = (value: unknown): value is Any => + Predicate.hasProperty(value, Binding); + +const jexprParser = Schema.decodeResult(Schema.toType(JExpr.Schema)); + +const parseNode = ( + expression: JExpr.Expression, +): Result.Result => + Result.mapBoth(jexprParser(expression), { + onSuccess: (syntax) => new AST.Expr(syntax), + onFailure: (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExpression({ cause }), + }), + }); + +/** + * Extracts a handle's stored AST result or validates a host literal into an AST node. + * + * Existing construction failures pass through unchanged. Invalid primitive syntax, including non-finite numbers, returns an `InvalidExpression` failure. Prefer {@link toJExpr} when consuming J-Expr syntax rather than builder nodes. + */ +export const toNode = ( + value: AnyValue, +): Result.Result => { + if (isExpression(value)) { + return value[Binding]; + } + return parseNode(JExpr.literal(value)); +}; + +/** + * Extracts J-Expr syntax without evaluating the represented value. + * + * A failed handle returns its stored construction error. Host literals undergo the same syntax validation as {@link literal}. Serialize the resulting structured syntax with `JExpr.compile`, or wrap the expression with `Program.program` and use `Program.compile`. + */ +export const toJExpr = ( + value: AnyValue, +): Result.Result => + Result.map(toNode(value), (node) => node.compile()); + +const make = ( + impl: ExpressionImpl, +): Expression => { + const target = Object.assign( + (...args: readonly AnyValue[]) => + make( + new ExpressionImpl( + Result.map( + Result.all({ + callee: impl[Binding], + arguments: Result.all(args.map(toJExpr)), + }), + ({ callee, arguments: arguments_ }) => + new AST.Expr(JExpr.call(callee.compile(), ...arguments_)), + ), + ), + ), + { + [TypeId]: impl[TypeId], + [Binding]: impl[Binding], + [Relocate]: ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + impl[Binding], + Result.map(() => + make( + new ExpressionImpl( + parseNode(JExpr.Path.compile(path)), + ), + ), + ), + ), + }, + ); + + const proxy = new Proxy(target, { + get( + target, + property, + receiver, + ): // oxlint-disable-next-line typescript/no-restricted-types -- proxy property reads may return arbitrary host values + unknown { + if (property === "$index") { + return (key: AnyValue) => { + const expr = Result.map( + Result.all({ value: target[Binding], key: toJExpr(key) }), + ({ value, key }) => new AST.Expr(JExpr.index(value.compile(), key)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + }; + } + + if (property === "$project") { + return (key: string | number) => { + const expr = Result.map( + target[Binding], + (node) => new AST.Expr(JExpr.access(node.compile(), key)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + }; + } + + if (property === Binding) { + return target[Binding]; + } + + if (property === TypeId) { + return target[TypeId]; + } + + if (typeof property === "string" && /^\d+$/u.test(property)) { + const index = Number(property); + const expr = Result.map( + target[Binding], + (node) => new AST.Expr(JExpr.access(node.compile(), index)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + } + + if (typeof property === "string") { + const expr = Result.map( + target[Binding], + (node) => new AST.Expr(JExpr.access(node.compile(), property)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + } + + return Reflect.get(target, property, receiver); + }, + }); + + const handle: Handle = proxy; + + // SAFETY: the handle retains T and Inputs. The traps supply their type-directed operations. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- TypeScript cannot derive conditional accessors and call signatures from proxy traps + return handle as Expression; +}; + +/** + * Wraps an AST construction result while retaining either its node or its failure. + * + * This low-level builder operation trusts the caller to establish `T`, `Inputs` and the node's validity. Use {@link fromJExpr} when syntax needs validation. + */ +export const fromResult = ( + node: Result.Result, +): Expression => make(new ExpressionImpl(node)); + +/** + * Ascribes a semantic type to syntax supplied by a declaration or another trusted builder. + * + * The caller supplies the semantic type and input requirements. This operation validates syntax only and stores an `InvalidExpression` construction failure if validation fails. Extract it with {@link toJExpr}. It does not resolve names or infer requirements from the syntax. + */ +export const fromJExpr = ( + expression: JExpr.Expression, +): Expression => fromResult(parseNode(expression)); + +/** Wraps an already constructed AST node without validation, using caller-supplied semantic metadata as in {@link fromResult}. */ +export const fromNode = ( + node: AST.Node, +): Expression => fromResult(Result.succeed(node)); + +/** A replacement call signature with the source expression's semantic metadata. */ +export type Adapted = C & + Pick, typeof TypeId | typeof Binding> & + Relocatable>; + +/** + * Adapts host arguments while preserving expression metadata and rebinding. + * + * The adapter must retain the represented function's meaning. It may accept additional host shorthand and normalize it before emitting a call. The factory runs immediately and again with the new source expression on each relocation. Build the returned callable from that argument rather than capturing an older expression. Exceptions from the factory or returned callable propagate to their caller. + * + * Both `adaptCallable(source, factory)` and `adaptCallable(factory)(source)` preserve the source's semantic type and input metadata. The replacement host signature comes from the factory. + * + * @example Accept trimmed host text when constructing a lookup call. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression } from "@local/hashql"; + * import type { Inputs, Type } from "@local/hashql"; + * import { Result, pipe } from "effect"; + * + * const lookup = Expression.fromJExpr< + * Type.Function, + * Inputs.Empty + * >("lookup"); + * const trimmedLookup = Expression.adaptCallable(lookup, (source) => + * (name: string) => source(name.trim()), + * ); + * const pipedLookup = pipe(lookup, Expression.adaptCallable((source) => + * (name: string) => source(name.trim()), + * )); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(trimmedLookup(" Ada "))), + * ["lookup", { "#literal": "Ada" }], + * ); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(pipedLookup(" Ada "))), + * Result.getOrThrow(Expression.toJExpr(trimmedLookup(" Ada "))), + * ); + * ``` + */ +export const adaptCallable: { + Any>( + adapt: (self: Expression) => C, + ): (self: Expression) => Adapted; + Any>( + self: Expression, + adapt: (self: Expression) => C, + ): Adapted; +} = Function.dual( + 2, + Any>( + self: Expression, + adapt: (self: Expression) => C, + ): Adapted => + Object.assign(adapt(self), { + [TypeId]: self[TypeId], + [Binding]: self[Binding], + [Relocate]: ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + self[Relocate](path), + Result.map((moved) => adaptCallable(moved, adapt)), + ), + }), +); + +/** + * Changes an expression's semantic type assumption while preserving its syntax and input requirements. + * + * The caller establishes the semantic type `T` through a trusted declaration or other knowledge outside the SDK. The returned function accepts an expression or host primitive without validating that semantic type at runtime or converting the value. It emits no HashQL type assertion. The HashQL compiler still checks the resulting program. + * + * @example Annotate an identifier whose meaning the application establishes. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Prelude } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * type UserId = Type.Opaque<"example::UserId", Type.PrimitiveString>; + * const text = Expression.input("userId", Prelude.builtin.types.String); + * const userId = Expression.assume()(text); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(userId)), + * Result.getOrThrow(Expression.toJExpr(text)), + * ); + * ``` + */ +export const assume = + () => + (expression: E): Expression> => + fromResult>(toNode(expression)); + +/** + * Constructs a typed host literal with no input requirements. + * + * Use a string to construct a string literal rather than a name reference. A host number has the Number descriptor even when its emitted syntax is integral. Bigints have the Integer descriptor. Non-finite numbers produce an `InvalidExpression` failure retained until {@link toJExpr}. Objects and arrays need structural construction instead. + */ +export const literal = ( + value: V, +): Expression, Input.Empty> => fromJExpr(JExpr.literal(value)); + +/** + * Constructs an Integer literal from a bigint or integral host number. + * + * Fractions and non-finite numbers produce an `InvalidExpression` construction failure. Use bigint when the original integer exceeds the safe number range, because a number has already undergone JavaScript rounding. See {@link toJExpr} to inspect success or failure. + */ +export const integer = ( + value: number | bigint, +): Expression => + fromJExpr(JExpr.integer(value)); + +/** Constructs a Number literal, retaining non-finite values as construction failures as in {@link literal}. */ +export const number = ( + value: number, +): Expression => + fromJExpr(JExpr.literal(value)); + +/** + * References a program input, optionally supplying its default expression. + * + * The inferred {@link Inputs} record requires the input when you omit the default or pass `undefined`. A definitely present default makes this occurrence optional, but another required use of the same name takes precedence. If the default's type includes `undefined`, the input remains required. Requirements of the default expression also contribute to the result. + * + * @param name - The input name emitted into the program. + * @param type - The input's HashQL type, which also constrains the default. + * @param defaultValue - The value or expression used when the input is absent at query execution. + * @returns A symbolic reference. Use {@link toJExpr} to extract the syntax or its construction failure. + * + * @example Supply a default page size. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { Result } from "effect"; + * + * const pageSize = Expression.input("pageSize", Prelude.builtin.types.Integer, 10n); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(pageSize))), + * '["::kernel::special_form::input","pageSize","::kernel::type::Integer",{"#literal":10}]', + * ); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs an input from its name and type +export function input( + name: Name, + type: TypeExpression.TypeExpression, + defaultValue?: undefined, +): Expression>>; +export function input< + const Name extends string, + T extends Type.Any, + const Default extends Value>, +>( + name: Name, + type: TypeExpression.TypeExpression, + defaultValue: Default, +): Expression< + T, + Input.Merge>>, Inputs> +>; +export function input< + const Name extends string, + T extends Type.Any, + const Default extends Value>, +>( + name: Name, + type: TypeExpression.TypeExpression, + defaultValue: Default | undefined, +): Expression>, Inputs>>; +export function input( + name: string, + type: TypeExpression.TypeExpression, + defaultValue?: AnyValue, +): Expression { + return Result.gen(function* () { + const syntax = yield* TypeExpression.toType(type); + if (defaultValue === undefined) { + return yield* toNode(fromJExpr(JExpr.input(name, syntax))); + } + + const value = yield* toJExpr(defaultValue); + return yield* toNode(fromJExpr(JExpr.input(name, syntax, value))); + }).pipe(fromResult); +} + +/** + * Constructs a conditional whose result type combines its branch types. + * + * The caller constructs all three operands before this call, without host short-circuiting. The result retains the condition's requirements and those of both branches, even for a literal condition. Either branch can contribute a construction failure. Equal branch descriptors remain equal, while distinct descriptors form a normalized union. + * + * @example Select a label in the represented program. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Program } from "@local/hashql"; + * import { Result } from "effect"; + * + * const label = Expression.ifElse(true, { then: "enabled", else: "disabled" }); + * assert.equal( + * Result.getOrThrow(Program.compile(Program.program(label))), + * '["::kernel::special_form::if",{"#literal":true},{"#literal":"enabled"},{"#literal":"disabled"}]', + * ); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the condition and branches construct a new expression +export const ifElse = < + const Condition extends Value, + const Then extends AnyValue, + const Else extends AnyValue, +>( + condition: Condition, + branches: { + readonly then: Then; + readonly else: Else; + }, +): Expression< + Conditional, TypeOf>, + Input.Merge, Input.Merge, Inputs>> +> => + pipe( + { + condition: toNode(condition), + consequent: toNode(branches.then), + alternate: toNode(branches.else), + }, + Result.all, + Result.map( + ({ condition, consequent, alternate }) => + new AST.If(condition, consequent, alternate), + ), + fromResult< + Conditional, TypeOf>, + Input.Merge, Input.Merge, Inputs>> + >, + ); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/ExpressionType.ts b/libs/@local/hashql/sdk/typescript/src/Program/ExpressionType.ts new file mode 100644 index 00000000000..883c6c1b8eb --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/ExpressionType.ts @@ -0,0 +1,381 @@ +/** + * Type-level normalization, calls and projections for symbolic values. + * + * Union projections require the field in every alternative. Intersections combine field descriptors, while index access includes Null for an absent element. These calculations retain the source expression's input requirements. + * + * @module + */ +import type * as Type from "../Type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Input from "./Inputs.js"; + +type Composition = "Union" | "Intersection"; +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- the empty intersection contributes no accessor members +type EmptyAccessors = Record; + +type Same = [Left] extends [Right] + ? [Right] extends [Left] + ? true + : false + : false; + +type Includes< + Members extends readonly Type.Any[], + Member extends Type.Any, +> = Members extends readonly [ + infer Head extends Type.Any, + ...infer Tail extends readonly Type.Any[], +] + ? Same extends true + ? true + : Includes + : false; + +type Unique< + Members extends readonly Type.Any[], + Result extends readonly Type.Any[], +> = number extends Members["length"] + ? Members + : Members extends readonly [ + infer Head extends Type.Any, + ...infer Tail extends readonly Type.Any[], + ] + ? Includes extends true + ? Unique + : Unique + : Result; + +type MembersOf = T extends { + readonly _tag: Kind; + readonly types: infer Members extends readonly Type.Any[]; +} + ? Members + : readonly [T]; + +type Compose< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Members extends readonly [] + ? Kind extends "Union" + ? Type.Never + : Type.Unknown + : Members extends readonly [infer Member extends Type.Any] + ? Member + : Kind extends "Union" + ? Type.Union + : Type.Intersection; + +type Join< + Left extends Type.Any, + Right extends Type.Any, +> = Left extends Type.Never + ? Right + : Right extends Type.Never + ? Left + : Left extends Type.Unknown + ? Type.Unknown + : Right extends Type.Unknown + ? Type.Unknown + : Compose< + "Union", + Unique< + readonly [ + ...MembersOf, + ...MembersOf, + ], + readonly [] + > + >; + +type PrimitiveConflict = + Left extends Type.Intersection + ? true extends { + [Index in keyof Members]: PrimitiveConflict; + }[number] + ? true + : false + : Right extends Type.Intersection + ? true extends { + [Index in keyof Members]: PrimitiveConflict; + }[number] + ? true + : false + : Left extends Type.Primitive + ? Right extends Type.Primitive + ? [Left | Right] extends [ + Type.PrimitiveInteger | Type.PrimitiveNumber, + ] + ? false + : Same extends true + ? false + : true + : false + : false; + +type MeetMembers< + Members extends readonly Type.Any[], + Other extends Type.Any, +> = { + readonly [Index in keyof Members]: Meet; +}; + +type Meet< + Left extends Type.Any, + Right extends Type.Any, +> = Left extends Type.Never + ? Type.Never + : Right extends Type.Never + ? Type.Never + : Left extends Type.Unknown + ? Right + : Right extends Type.Unknown + ? Left + : Same extends true + ? Left + : Left extends Type.Union + ? Reduce<"Union", MeetMembers, Type.Never> + : Right extends Type.Union + ? Reduce<"Union", MeetMembers, Type.Never> + : PrimitiveConflict extends true + ? Type.Never + : Compose< + "Intersection", + Unique< + readonly [ + ...MembersOf, + ...MembersOf, + ], + readonly [] + > + >; + +type Reduce< + Kind extends Composition, + Members extends readonly Type.Any[], + Result extends Type.Any, +> = number extends Members["length"] + ? Kind extends "Union" + ? Type.Union + : Type.Intersection + : Members extends readonly [ + infer Head extends Type.Any, + ...infer Tail extends readonly Type.Any[], + ] + ? Reduce< + Kind, + Tail, + Kind extends "Union" + ? Join> + : Meet> + > + : Result; + +/** Simplifies explicit unions and intersections without widening the parent expression's type. */ +export type Normalize = [T] extends [never] + ? Type.Never + : [T] extends [Type.Union] + ? Reduce<"Union", Members, Type.Never> + : [T] extends [Type.Intersection] + ? Reduce<"Intersection", Members, Type.Unknown> + : T; + +type Combine< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Reduce; + +type FieldMaps = { + readonly [Index in keyof Members]: FieldsOf>; +}; + +type ProjectMembers< + Members extends readonly Type.Any[], + Key extends PropertyKey, +> = { + readonly [Index in keyof Members]: Key extends keyof FieldsOf< + Normalize + > + ? FieldsOf>[Key] extends infer Field extends + Type.Any + ? Field + : never + : never; +}; + +/** A projection is available only when every member supports it. */ +type CombinedFields< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Members extends readonly [] + ? EmptyAccessors + : { + readonly [Key in keyof FieldMaps[number]]: Combine< + Kind, + ProjectMembers + >; + }; + +type FieldsOf = [T] extends [Type.Struct] + ? { + readonly [Field in Extract]: Fields[Field]; + } + : [T] extends [Type.Tuple.Any] + ? { + readonly [Index in Extract< + keyof T["fields"], + `${number}` + > as Index extends `${infer Position extends number}` + ? Position + : never]: T["fields"][Index]; + } + : [T] extends [Type.Opaque] + ? FieldsOf> + : [T] extends [Type.Union] + ? CombinedFields<"Union", Members> + : [T] extends [Type.Intersection] + ? CombinedFields<"Intersection", Members> + : EmptyAccessors; + +interface IndexDescriptor { + readonly key: Type.Any; + readonly value: Type.Any; +} + +type IndexValues = { + readonly [Index in keyof Members]: IndexOf< + Normalize + > extends infer Descriptor extends IndexDescriptor + ? Descriptor["value"] + : never; +}; + +type IndexFailures< + Members extends readonly Type.Any[], + Key extends Type.Any, +> = { + readonly [Index in keyof Members]: IndexOf< + Normalize + > extends infer Descriptor + ? [Descriptor] extends [IndexDescriptor] + ? Same extends true + ? never + : Index + : Index + : Index; +}[number]; + +type CombinedIndex< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Members extends readonly [ + infer Head extends Type.Any, + ...(readonly Type.Any[]), +] + ? IndexOf> extends infer Descriptor + ? [Descriptor] extends [IndexDescriptor] + ? [IndexFailures] extends [never] + ? { + readonly key: Descriptor["key"]; + readonly value: Combine>; + } + : undefined + : undefined + : undefined + : undefined; + +type IndexOf = [T] extends [Type.List] + ? { readonly key: Type.PrimitiveInteger; readonly value: Value } + : [T] extends [Type.Dict] + ? { readonly key: Key; readonly value: Value } + : [T] extends [Type.Opaque] + ? IndexOf> + : [T] extends [Type.Union] + ? CombinedIndex<"Union", Members> + : [T] extends [Type.Intersection] + ? CombinedIndex<"Intersection", Members> + : undefined; + +type ProjectionAccessors = { + readonly [Key in Exclude< + keyof Fields, + "$project" | "$index" | "~hashql/Expression" + >]: Fields[Key] extends infer Field extends Type.Any + ? Expression.Expression, Inputs> + : never; +} & ([keyof Fields] extends [never] + ? EmptyAccessors + : { + readonly $project: ( + key: Key, + ) => Fields[Key] extends infer Field extends Type.Any + ? Expression.Expression, Inputs> + : never; + }); + +type IndexAccessor = [Descriptor] extends [IndexDescriptor] + ? { + readonly $index: >( + key: Key, + ) => Expression.Expression< + Join, Type.PrimitiveNull>, + Input.Merge> + >; + } + : EmptyAccessors; + +/** + * Projection and indexing operations selected by an expression's semantic descriptor. + * + * Struct fields and tuple positions support property access and `$project`. For unions and intersections, a projected field must exist in every member. `$project` also accepts operation names such as `$index` when they name actual fields. List and dictionary `$index` calls merge the key's inputs and include Null in the result for an absent element. Opaque descriptors expose the operations of their underlying type. + */ +export type Accessors = ProjectionAccessors< + FieldsOf>, + Inputs +> & + IndexAccessor>, Inputs>; + +/** Host arguments accepted at each semantic parameter position, including corresponding primitive shorthand. */ +export type Arguments = { + readonly [Index in keyof Parameters]: Expression.Value; +}; + +/** Combined input requirements of a call's argument tuple, retaining requirements from optional positions. */ +export type ArgumentInputs = + Input.All<{ + readonly [Index in keyof Values]: Expression.Inputs; + }>; + +type ArgumentTypes = { + readonly [Index in keyof Values]: Expression.TypeOf; +}; + +/** + * Host call signatures that construct calls to fixed or generic HashQL functions. + * + * Fixed signatures constrain each argument by its declared descriptor. Generic signatures apply the argument descriptors to the declared type-level function. Both forms merge the callee's input requirements with those of every argument. Non-function descriptors contribute no call signature. + */ +export type Callable = + T extends Type.Function + ? >( + ...args: Values + ) => Expression.Expression< + Returns, + Input.Merge> + > + : T extends Type.GenericFunction + ? ( + ...args: Values & + Arguments< + Type.Apply>["parameters"] + > + ) => Expression.Expression< + Type.Apply>["returns"], + Input.Merge> + > + : EmptyAccessors; + +/** The normalized union of two conditional branch descriptors, retaining a single descriptor when both are equal. */ +export type Conditional = Join< + Normalize, + Normalize +>; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Import.ts b/libs/@local/hashql/sdk/typescript/src/Program/Import.ts new file mode 100644 index 00000000000..b15a233b86b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Import.ts @@ -0,0 +1,258 @@ +/** + * Typed lexical imports shared by the authoring APIs. + * + * Selection changes local names, not the declared types or callable capabilities. Each selected producer rebinds itself before the namespace join. The compiler remains responsible for resolving the emitted import. + * + * @module + */ +import { Array, Result, SchemaParser, pipe } from "effect"; + +import { isReadonlyArray } from "../internal/array.js"; +import { relocate } from "../internal/relocation.js"; +import * as JExpr from "../JExpr/index.js"; +import * as AST from "./AST/index.js"; +import * as ProgramError from "./ProgramError.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type * as Module from "./Module.js"; +import type * as Namespace from "./Namespace.js"; +import type { ReadonlyRecord } from "effect/Record"; + +/** The string export names of a module across its three tables. */ +type Name = Extract< + keyof M["modules"] | keyof M["values"] | keyof M["types"], + string +>; + +/** + * The exports an import brings into scope and the local names they take. + * + * - `"*"` imports every own name in the module's three tables. + * - An array of export names imports those names unchanged. + * - A record maps export names to local aliases. The alias `"_"` keeps the export's own name. + * + * One name selects the module, type and value exports that share it. Each imported export emits its local name, and the import wraps the expression built in its scope in a `use` of the module's path. An alias that is not a HashQL identifier, or a symbol key in the record, fails construction with `InvalidImportName`. + * + * @example Import a built-in function under another name. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const { math } = Prelude.builtin.modules; + * const result = program({}, ($) => { + * const { plus } = $.import(math, { add: "plus" }); + * return plus(1n, 2n); + * }); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Result.flatMap(result, Expression.toJExpr))), + * '["::kernel::special_form::use","::core::math",{"#struct":{"add":"plus"}},["plus",{"#literal":1},{"#literal":2}]]', + * ); + * + * const invalid = program({}, ($) => { + * $.import(math, { add: "not an identifier" }); + * return $.literal(true); + * }); + * assert.ok(Result.isFailure(invalid)); + * assert.equal(invalid.failure.reason._tag, "InvalidImportName"); + * ``` + */ +export type Selection = + | "*" + | readonly Name[] + | Partial, string>>; + +/** Filters and renames one table according to a selection. */ +type Selected = I extends "*" + ? E + : I extends readonly string[] + ? Pick> + : { + readonly [K in keyof E as K extends keyof I + ? I[K] extends "_" + ? K + : I[K] extends string + ? I[K] + : never + : never]: E[K]; + }; + +/** The tables an import adds to a scope, keyed by local name and keeping each selected export's type. */ +export interface Imported { + readonly modules: Selected; + readonly values: Selected; + readonly types: Selected; +} + +interface Plan { + readonly names: ReadonlyMap< + string, + { readonly alias: string; readonly ident: JExpr.Ident.Ident } + >; + readonly syntax: JExpr.Imports; +} + +const decodeName = SchemaParser.decodeUnknownResult(JExpr.Ident.Schema); + +const importName = ( + name: string | undefined, +): Result.Result => + pipe( + decodeName(name), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidImportName({ + name: String(name), + cause, + }), + }), + ), + ); + +const requests = ( + module: Module.Any, + selection: Selection, +): readonly (readonly [string, string | undefined])[] => { + if (selection === "*") { + return Array.map( + [ + ...new Set([ + ...Object.getOwnPropertyNames(module.modules), + ...Object.getOwnPropertyNames(module.types), + ...Object.getOwnPropertyNames(module.values), + ]), + ], + (name) => [name, name] as const, + ); + } + + if (isReadonlyArray(selection)) { + return pipe( + selection, + Array.map((name) => [name, name] as const), + ); + } + + return pipe( + Object.getOwnPropertyNames(selection), + Array.map((name) => { + const alias = selection[name]; + if (alias === "_") { + return [name, name] as const; + } + + return [name, alias] as const; + }), + ); +}; + +const plan = ( + module: Module.Any, + selection: Selection, +): Result.Result => + Result.gen(function* () { + const names = new Map< + string, + { readonly alias: string; readonly ident: JExpr.Ident.Ident } + >(); + + const aliases: [string, string][] = []; + for (const [name, alias] of requests(module, selection)) { + const ident = yield* importName(alias); + names.set(name, { alias: String(alias), ident }); + aliases.push([name, JExpr.Ident.compile(ident)]); + } + + if (typeof selection === "object") { + for (const name of Object.getOwnPropertySymbols(selection)) { + yield* importName(String(name)); + } + } + + let syntax: JExpr.Imports = "*"; + if (isReadonlyArray(selection)) { + syntax = Object.freeze([...names.keys()]); + } else if (selection !== "*") { + syntax = Object.freeze(Object.fromEntries(aliases)); + } + + return { names, syntax }; + }); + +interface Capability extends Relocatable {} +type Rebindings = { readonly [K in keyof E]: Relocatable }; + +/** A module whose exports each rebind to their own type, as an import requires. */ +export interface Rebindable { + readonly modules: M["modules"] & Rebindings; + readonly types: M["types"] & Rebindings; + readonly values: M["values"] & Rebindings; +} + +/** Rebinds each value at its original E[K] type before asserting the renamed table. */ +const select = , I>( + entries: E & Rebindings, + names: Plan["names"], +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + const selected: Partial> = {}; + const sources: Rebindings = entries; + // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- K retains the original producer result E[K] before the alias changes its key + const member = ( + name: K, + { + alias, + ident, + }: { readonly alias: string; readonly ident: JExpr.Ident.Ident }, + ): Result.Result>, ProgramError.Construction> => + pipe( + relocate(sources[name], { rooted: false, segments: [ident] }), + Result.map((value) => + Object.defineProperty(selected, alias, { + value, + enumerable: true, + configurable: true, + }), + ), + ); + + for (const name of Object.getOwnPropertyNames(entries)) { + const ident = names.get(name); + if (ident !== undefined) { + yield* member(name, ident); + } + } + + // SAFETY: Plan selects the requested source names and aliases; member retains E[K] for each selected key, including non-enumerable own exports. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- TypeScript cannot express this key remapping through Object.defineProperty + return Object.freeze(selected) as Selected; + }); + +export interface Declaration { + readonly scope: Imported & Namespace.Rebindable>; + readonly wrap: (child: AST.Node) => AST.Node; +} + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the module and selection construct a declaration +export const bind = >( + module: M & Rebindable, + selection: I, +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + const selected = yield* plan(module, selection); + const scope: Imported = yield* Result.all({ + modules: select(module.modules, selected.names), + types: select(module.types, selected.names), + values: select(module.values, selected.names), + }); + + return { + // SAFETY: every selected member came from a producer checked by Rebindable, and its own relocation returns that same capability. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- mapped selections retain the producer bound that TypeScript cannot distribute through Selected + scope: scope as Imported & Namespace.Rebindable>, + wrap: (child: AST.Node): AST.Node => + new AST.Import(module.path, selected.syntax, child), + }; + }); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts new file mode 100644 index 00000000000..c000b02e686 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts @@ -0,0 +1,314 @@ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Program } from "../main.js"; +import * as Operators from "./Operators.js"; + +import type { Inputs, Type } from "../main.js"; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + Boolean: Module.type(), + String: Module.type(), + }, + }), +); +const integer = kernel.types.Integer; +const boolean = kernel.types.Boolean; +const string = kernel.types.String; + +interface Same extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.Function + : Type.Function; +} + +declare const optionalDefault: + | Expression.Expression< + Type.PrimitiveInteger, + { readonly fallback: Type.PrimitiveInteger } + > + | undefined; + +declare const hostAlternative: + | Expression.Expression< + Type.PrimitiveInteger, + { readonly first: Type.PrimitiveInteger } + > + | Expression.Expression< + Type.PrimitiveInteger, + { readonly second: Type.PrimitiveInteger } + >; +declare const possiblyClosed: + | Expression.Expression + | Expression.Expression< + Type.PrimitiveInteger, + { readonly first: Type.PrimitiveInteger } + >; + +describe("requirement_algebra", () => { + test("optional_tuple", () => { + expectTypeOf< + Inputs.All< + readonly [ + first?: { readonly count?: Type.PrimitiveInteger }, + second?: { + readonly count: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + }, + ] + > + >().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + }>(); + }); + + test("empty_and_variadic_tuple", () => { + // oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty tuple contributes no input names + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Inputs.All< + readonly [ + { readonly first: Type.PrimitiveInteger }, + ...{ readonly second: Type.PrimitiveString }[], + ] + > + >().toEqualTypeOf<{ + readonly first: Type.PrimitiveInteger; + readonly second: Type.PrimitiveString; + }>(); + }); + + test("required_conflict", () => { + expectTypeOf< + Inputs.Conservative< + | { readonly value?: Type.PrimitiveInteger } + | { readonly value: Type.PrimitiveString } + > + >().toEqualTypeOf<{ readonly value: Type.Never }>(); + expectTypeOf< + Inputs.Merge<{ readonly value?: Type.PrimitiveInteger }, Inputs.Empty> + >().toEqualTypeOf<{ readonly value?: Type.PrimitiveInteger }>(); + }); + + test("erased_metadata", () => { + expectTypeOf>().toEqualTypeOf(); + // oxlint-disable-next-line typescript/no-restricted-types -- exercises erasure of the requirement record + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Inputs.Merge + >().toEqualTypeOf(); + }); +}); + +describe("input_requirements", () => { + test("host_alternatives_keep_every_requirement", () => { + type Alternatives = + | { readonly first: Type.PrimitiveInteger } + | { readonly second: Type.PrimitiveString }; + expectTypeOf< + Inputs.Merge + >().toEqualTypeOf<{ + readonly first: Type.PrimitiveInteger; + readonly second: Type.PrimitiveString; + readonly third: Type.PrimitiveBoolean; + }>(); + expectTypeOf< + Inputs.Conservative< + Inputs.Empty | { readonly first: Type.PrimitiveInteger } + > + >().toEqualTypeOf<{ readonly first: Type.PrimitiveInteger }>(); + expectTypeOf< + Inputs.Conservative< + | { readonly same: Type.PrimitiveInteger } + | { readonly same: Type.PrimitiveString } + > + >().toEqualTypeOf<{ readonly same: Type.Never }>(); + const composed = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a query branch + then: hostAlternative, + else: 0n, + }); + // @ts-expect-error an empty annotation cannot hide host-side alternatives + const closed: Expression.Expression = + composed; + expectTypeOf(closed); + const combined = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a query branch + then: possiblyClosed, + else: 0n, + }); + // @ts-expect-error a closed alternative cannot make a required alternative disappear through contravariance + const hidden: Expression.Expression = + combined; + expectTypeOf(hidden); + }); + + test("required_and_default", () => { + const required = Expression.input("count", integer); + const optional = Expression.input("limit", integer, Expression.integer(10)); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly limit?: Type.PrimitiveInteger; + }>(); + // @ts-expect-error A closed-expression annotation cannot discard a required input. + const closed: Expression.Expression = + required; + expectTypeOf(closed); + // @ts-expect-error The default must have the input's declared semantic type. + Expression.input("count", integer, Expression.literal(false)); + }); + + test("uncertain_default", () => { + const value = Expression.input("count", integer, optionalDefault); + // oxlint-disable-next-line unicorn/no-useless-undefined -- checks an explicitly absent host default + const omitted = Expression.input("count", integer, undefined); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly fallback: Type.PrimitiveInteger; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + }); + + test("default_dependencies", () => { + const fallback = Expression.input("fallback", integer); + const value = Expression.input("count", integer, fallback); + expectTypeOf>().toEqualTypeOf<{ + readonly count?: Type.PrimitiveInteger; + readonly fallback: Type.PrimitiveInteger; + }>(); + }); + + test("repeated_name", () => { + const optional = Expression.input( + "enabled", + boolean, + Expression.literal(true), + ); + const required = Expression.input("enabled", boolean); + const both = Operators.and(optional, required); + expectTypeOf>().toEqualTypeOf<{ + readonly enabled: Type.PrimitiveBoolean; + }>(); + const defaults = Operators.or(optional, optional); + expectTypeOf>().toEqualTypeOf<{ + readonly enabled?: Type.PrimitiveBoolean; + }>(); + }); + + test("conflicting_name", () => { + const count = Expression.input("shared", integer); + const text = Expression.input("shared", string); + const value = Expression.ifElse(Expression.literal(true), { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a query branch + then: count, + else: text, + }); + expectTypeOf>().toEqualTypeOf<{ + readonly shared: Type.Never; + }>(); + }); +}); + +describe("operation_requirements", () => { + test("primitive_composition", () => { + const left = Expression.input("left", integer); + const right = Expression.input("right", integer); + const enabled = Expression.input("enabled", boolean); + const predicate = Operators.or( + Operators.and(Operators.eq(left, right), Operators.isTrue(enabled)), + Operators.isFalse(enabled), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly left: Type.PrimitiveInteger; + readonly right: Type.PrimitiveInteger; + readonly enabled: Type.PrimitiveBoolean; + }>(); + }); + + test("projection_and_index", () => { + const module = Result.getOrThrow( + Module.define("::example", { + types: { + Rows: Module.type< + Type.Struct<{ readonly values: Type.List }> + >(), + }, + }), + ); + const rows = Expression.input("rows", module.types.Rows); + const position = Expression.input("position", integer); + const projected = rows.$project("values"); + const selected = rows.values.$index(position); + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); + expectTypeOf>().toEqualTypeOf<{ + readonly rows: Type.Struct<{ + readonly values: Type.List; + }>; + readonly position: Type.PrimitiveInteger; + }>(); + }); + + test("function_and_generic_calls", () => { + const count = Expression.input("count", integer); + const callee = Expression.fromJExpr< + Type.Function, + { readonly receiver: Type.PrimitiveBoolean } + >("callee"); + const result = callee(count); + expectTypeOf>().toEqualTypeOf<{ + readonly receiver: Type.PrimitiveBoolean; + readonly count: Type.PrimitiveInteger; + }>(); + const generic = Expression.fromJExpr< + Type.GenericFunction, + Inputs.Empty + >("same"); + const identity = generic(count); + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); + // @ts-expect-error Input accumulation must not widen the call's parameter types. + callee(Expression.input("wrong", boolean)); + // @ts-expect-error A fixed signature still checks arity. + callee(count, count); + }); +}); + +describe("snippet_requirements", () => { + test("reusable_snippet", () => { + const count = Expression.input("count", integer); + const snippet = Operators.ne(count, Expression.integer(0)); + const combined = Operators.and( + snippet, + Expression.input("enabled", boolean), + ); + const program = Program.program(combined); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly enabled: Type.PrimitiveBoolean; + }>(); + }); +}); + +describe("builder_requirements", () => { + test("assumption_preservation", () => { + const source = Expression.input("source", integer); + const assumed = Expression.assume()(source); + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts new file mode 100644 index 00000000000..71405039d9b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts @@ -0,0 +1,40 @@ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, JExpr, Module } from "../main.js"; +import * as Operators from "./Operators.js"; + +import type { Type } from "../main.js"; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Integer: Module.type() }, + }), +); +const integer = kernel.types.Integer; +const compile = (expression: Expression.Any): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(expression))); + +describe("input_composition", () => { + test("snippet_reuse", () => { + expect.hasAssertions(); + const snippet = Expression.input("count", integer, Expression.integer(7)); + const comparison = Operators.eq( + snippet, + Expression.input("other", integer), + ); + expect(compile(snippet)).toBe( + '["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}]', + ); + expect(compile(comparison)).toBe( + '["::core::cmp::eq",["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}],["::kernel::special_form::input","other","::kernel::type::Integer"]]', + ); + }); + + test("assumption_syntax", () => { + expect.hasAssertions(); + const expression = Expression.input("count", integer); + const assumed = Expression.assume()(expression); + expect(compile(assumed)).toBe(compile(expression)); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Inputs.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.ts new file mode 100644 index 00000000000..5819a898ca6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.ts @@ -0,0 +1,146 @@ +/** + * Input requirements carried by expressions and programs. + * + * A required use makes a name required even when another use has a default. Shared names combine their semantic descriptors through an intersection, so incompatible uses produce Type.Never rather than a JavaScript intersection of descriptor objects. + * + * Host-side alternatives retain every possible requirement. The types here cannot know which expression the host will select, and an empty alternative must not hide a branch that needs an input. + * + * @module + */ +import type * as Type from "../Type/index.js"; +import type { Normalize } from "./ExpressionType.js"; +import type { Types } from "effect"; + +/** An expression with no input requirements. */ +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- a closed expression requires no input names +export type Empty = Record; + +declare const ErasedRequirement: unique symbol; + +/** + * Marks input requirements that TypeScript could not recover. + * + * Requirement inference produces this marker when an expression's requirement record is `never` or `unknown`, or when a value lacks the SDK's requirement metadata. No input schema has the marker key, so a Draft program schema cannot satisfy an erased requirement. Merging it with a named requirement gives `never`. + */ +export interface Erased { + readonly [ErasedRequirement]: Type.Unknown; +} + +type RequiredKeys = { + [K in keyof I]-?: Empty extends Pick ? never : K; +}[keyof I]; + +type At = K extends keyof I + ? Exclude + : never; + +type Combined = K extends keyof L + ? K extends keyof R + ? At extends infer A extends Type.Any + ? At extends infer B extends Type.Any + ? Normalize> + : never + : never + : At + : At; + +type MergeRecords = [keyof R] extends [never] + ? L + : [keyof L] extends [never] + ? R + : Types.Simplify< + { + readonly [K in RequiredKeys | RequiredKeys]: Combined; + } & { + readonly [K in Exclude< + keyof L | keyof R, + RequiredKeys | RequiredKeys + >]?: Combined; + } + >; + +// Intersecting call signatures selects one union member through the last overload. Each step removes whichever member inference selects. +type Last = Types.Covariant.Type< + Types.UnionToIntersection : never> +>; + +// Invariance keeps Empty from swallowing a required record during Exclude. A plain union of records would let the empty record remove every remaining alternative. +type Alternatives = I extends I ? Types.Invariant : never; + +type Collapse = [U] extends [never] + ? I + : Types.IsUnion extends false + ? MergeRecords> + : Collapse< + Exclude>, + MergeRecords>> + >; + +/** + * Requires every host-side alternative, preserving shared semantic constraints. + * + * A union of requirement records becomes one record that requires each name any alternative requires. `never` and `unknown` become {@link Erased}. + */ +export type Conservative = [I] extends [never] + ? Erased + : // oxlint-disable-next-line typescript/no-restricted-types -- this type-level check detects erased metadata rather than storing a runtime value + unknown extends I + ? Erased + : Collapse, Empty>; + +type MergeConservative = typeof ErasedRequirement extends + | keyof L + | keyof R + ? never + : MergeRecords; + +// An input-independent builder step preserves its unresolved left type parameter. Normalizing it again would change the step's generic result type. +type MergeRight = [keyof R] extends [never] + ? L + : MergeConservative, R>; + +/** + * Combines shared requirements, preserving the left type when the right side needs no inputs. + * + * A name stays optional in the result only when every side that mentions it marks it optional. Where both sides mention a name, the result takes the intersection of its descriptors. + * + * @example Type-only: combine a defaulted use with a required use. + * ```ts + * import type { Inputs, Type } from "@local/hashql"; + * + * type Equal = + * (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + * ? true + * : false; + * + * export const requiredWins: Equal< + * Inputs.Merge< + * { readonly limit?: Type.PrimitiveInteger }, + * { + * readonly limit: Type.PrimitiveInteger; + * readonly name: Type.PrimitiveString; + * } + * >, + * { + * readonly limit: Type.PrimitiveInteger; + * readonly name: Type.PrimitiveString; + * } + * > = true; + * export const conflictIsNever: Equal< + * Inputs.Merge< + * { readonly id: Type.PrimitiveInteger }, + * { readonly id: Type.PrimitiveString } + * >, + * { readonly id: Type.Never } + * > = true; + * ``` + */ +export type Merge = MergeRight>; + +/** Combines tuple members, retaining every possible requirement in arrays and optional positions. */ +// oxlint-disable-next-line typescript/no-restricted-types -- inferred metadata includes unknown and never; Conservative detects erasure instead of assuming a valid input record +export type All = T extends readonly [] + ? Empty + : T extends readonly [infer H, ...infer R] + ? Merge> + : Conservative; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Module.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.test-d.ts new file mode 100644 index 00000000000..51d654506d5 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.test-d.ts @@ -0,0 +1,290 @@ +/** + * Type-level module checks for named exports, generic aliases and optional namespaces. + * + * @module + */ +// oxlint-disable unicorn/no-array-method-this-argument -- filter is a HashQL function, not Array.filter +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import * as JExpr from "../JExpr/index.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; + +import type * as Type from "../Type/index.js"; +import type * as Inputs from "./Inputs.js"; +import type { TypeExpression } from "./TypeExpression.js"; + +type Vertex = Type.Struct<{ readonly name: Type.PrimitiveString }>; +type OtherVertex = Type.Struct<{ readonly age: Type.PrimitiveInteger }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": T }> +>; +type VertexOf = T extends Graph ? V : never; + +interface Filter extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer T, Type.Any] + ? Type.Function< + readonly [ + Graph>, + Type.Function], Type.PrimitiveBoolean>, + ], + Graph> + > + : Type.Function; +} + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : Type.Never; +} + +interface Equal extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [ + infer L extends Type.Any, + infer R extends Type.Any, + ] + ? Type.Function + : Type.Function; +} + +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +type Remainder = Type.Function< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + Type.PrimitiveInteger +>; + +const kernelTypes = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + String: Module.type(), + List: Module.genericType(1), + }, + }), +); +const math = Result.getOrThrow( + Module.define("::core::math", { + values: { rem: Module.value() }, + }), +); +const cmp = Result.getOrThrow( + Module.define("::core::cmp", { + values: { eq: Module.value>() }, + }), +); +const uuid = Result.getOrThrow( + Module.define("::core::uuid", { + types: { Uuid: Module.type() }, + values: { + Uuid: Module.value< + Type.Function + >(), + }, + }), +); +const body = Result.getOrThrow( + Module.define("::graph::body", { + values: { filter: Module.value>() }, + }), +); +const modules = Result.getOrThrow( + Module.root({ + kernel: Result.getOrThrow( + Module.define("::kernel", { modules: { type: kernelTypes } }), + ), + core: Result.getOrThrow( + Module.define("::core", { modules: { math, cmp, uuid } }), + ), + graph: Result.getOrThrow(Module.define("::graph", { modules: { body } })), + }), +); +const prelude = { + rem: modules.modules.core.modules.math.values.rem, + eq: modules.modules.core.modules.cmp.values.eq, + filter: modules.modules.graph.modules.body.values.filter, + Integer: modules.modules.kernel.modules.type.types.Integer, + List: modules.modules.kernel.modules.type.types.List, +}; +const aliases = Result.getOrThrow( + Module.define("::application", { + values: { select: prelude.filter }, + types: { Sequence: prelude.List }, + }), +); + +declare const integer: Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty +>; +declare const string: Expression.Expression; +declare const vertices: Expression.Expression, Inputs.Empty>; +declare const predicate: Expression.Expression< + Type.Function, + Inputs.Empty +>; +declare const otherPredicate: Expression.Expression< + Type.Function, + Inputs.Empty +>; +declare const wrongResult: Expression.Expression< + Type.Function, + Inputs.Empty +>; + +describe("module_types", () => { + test("module_call_types", () => { + expectTypeOf(prelude.rem(integer, integer)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(prelude.eq(integer, string)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(uuid.values.Uuid(string)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(uuid.types.Uuid).toEqualTypeOf>(); + // @ts-expect-error Remainder requires integers. + prelude.rem(integer, string); + // @ts-expect-error Remainder takes two operands. + prelude.rem(integer); + // @ts-expect-error Values and types occupy distinct namespaces. + uuid.types.Uuid(string); + // @ts-expect-error A newtype remains distinct from its representation. + prelude.rem(uuid.values.Uuid(string), integer); + }); + + test("generic_alias", () => { + expectTypeOf(body.values.filter(vertices, predicate)).toEqualTypeOf< + Expression.Expression, Inputs.Empty> + >(); + expectTypeOf(prelude.filter(vertices, predicate)).toEqualTypeOf< + Expression.Expression, Inputs.Empty> + >(); + expectTypeOf(aliases.values.select(vertices, predicate)).toEqualTypeOf< + Expression.Expression, Inputs.Empty> + >(); + // @ts-expect-error The predicate's vertex must match the graph's vertex. + prelude.filter(vertices, otherPredicate); + // @ts-expect-error A predicate returns Boolean. + prelude.filter(vertices, wrongResult); + // @ts-expect-error The source must be a graph. + prelude.filter(integer, predicate); + // @ts-expect-error Filter requires a predicate. + prelude.filter(vertices); + // @ts-expect-error Filter takes two operands. + prelude.filter(vertices, predicate, integer); + }); + + test("generic_type", () => { + expectTypeOf(prelude.List(prelude.Integer)).toEqualTypeOf< + TypeExpression> + >(); + expectTypeOf( + aliases.types.Sequence(kernelTypes.types.String), + ).toEqualTypeOf>>(); + expectTypeOf(prelude.List(prelude.List(prelude.Integer))).toEqualTypeOf< + TypeExpression>> + >(); + // @ts-expect-error List requires an element type. + prelude.List(); + // @ts-expect-error List has exactly one type parameter. + prelude.List(prelude.Integer, prelude.Integer); + // @ts-expect-error A value expression is not a type expression. + prelude.List(integer); + // @ts-expect-error The constructor's arity comes from its declaration. + Module.genericType(2); + }); + + test("optional_namespaces", () => { + const definition: { + readonly types?: { + readonly Integer: Module.Declaration< + TypeExpression + >; + }; + } = {}; + const optional = Result.getOrThrow(Module.define("::optional", definition)); + expectTypeOf(optional.types.Integer).toEqualTypeOf< + TypeExpression | undefined + >(); + // @ts-expect-error The entry is optional even though the namespace table always exists. + expectTypeOf(optional.types.Integer.syntax); + }); + + test("optional_declarations", () => { + const types: { + readonly Integer?: Module.Declaration< + TypeExpression + >; + } = {}; + const optional = Result.getOrThrow(Module.define("::optional", { types })); + expectTypeOf(optional.types.Integer).toEqualTypeOf< + TypeExpression | undefined + >(); + }); + + test("relocated_members", () => { + const local = Result.getOrThrow(JExpr.Path.decodeResult("local")); + const relocated = Result.getOrThrow( + Module.relocate(modules.modules.core, local), + ); + expectTypeOf(relocated.modules.math.values.rem).toEqualTypeOf< + typeof prelude.rem + >(); + expectTypeOf(relocated.modules.uuid.types.Uuid).toEqualTypeOf< + TypeExpression + >(); + expectTypeOf(relocated.modules.uuid.values.Uuid(string)).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error The relocated function retains its semantic parameter types. + relocated.modules.math.values.rem(string, integer); + // @ts-expect-error Relocation does not introduce undeclared names. + expectTypeOf(relocated.modules.missing); + + const input = Expression.input("count", prelude.Integer); + const source = Result.getOrThrow( + Module.define("::inputs", { values: { count: input } }), + ); + const moved = Result.getOrThrow(Module.relocate(source, local)); + expectTypeOf(moved.values.count).toEqualTypeOf(); + // @ts-expect-error An imported reference still carries its source input requirement. + const closed: Expression.Expression = + moved.values.count; + expectTypeOf(closed).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("unpreserved_extension", () => { + const extended = Object.assign(prelude.Integer, { annotation: "extra" }); + // @ts-expect-error The type's rebinding operation does not promise to retain caller-added properties. + expectTypeOf(Module.define("::extended", { types: { Integer: extended } })); + }); + + test("tree_members", () => { + expectTypeOf(modules.modules.core.modules.math.values.rem).toEqualTypeOf< + typeof prelude.rem + >(); + // @ts-expect-error Missing modules do not become arbitrary string lookups. + expectTypeOf(modules.modules.missing); + // @ts-expect-error Empty namespaces retain their exact keys. + expectTypeOf(math.types.Integer); + // @ts-expect-error A module record is readonly. + modules.modules.core = modules.modules.kernel; + // @ts-expect-error A value export is readonly. + math.values.rem = prelude.eq; + // @ts-expect-error A value declaration cannot enter the type namespace. + Module.define("::bad", { types: { value: Module.value() } }); + Result.getOrThrow( + Module.define("::bad", { + // @ts-expect-error A type declaration cannot enter the value namespace. + values: { Integer: Module.type() }, + }), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts new file mode 100644 index 00000000000..690d68cafe0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts @@ -0,0 +1,419 @@ +/** + * Runtime checks for module binding, alias identity and invalid export names. + * + * @module + */ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../JExpr/index.js"; +import * as TypeSyntax from "../JExpr/Type/index.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../Type/index.js"; +import type * as Inputs from "./Inputs.js"; + +type Remainder = Type.Function< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + Type.PrimitiveInteger +>; +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [ + infer Element extends Type.Any, + ] + ? Type.List + : Type.Never; +} + +const kernelTypes = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + List: Module.genericType(1), + }, + }), +); +const math = Result.getOrThrow( + Module.define("::core::math", { + values: { rem: Module.value() }, + }), +); +const uuid = Result.getOrThrow( + Module.define("::core::uuid", { + types: { Uuid: Module.type() }, + values: { + Uuid: Module.value< + Type.Function + >(), + }, + }), +); +const modules = Result.getOrThrow( + Module.root({ + kernel: Result.getOrThrow( + Module.define("::kernel", { modules: { type: kernelTypes } }), + ), + core: Result.getOrThrow( + Module.define("::core", { modules: { math, uuid } }), + ), + }), +); +const prelude = { + remainder: modules.modules.core.modules.math.values.rem, + Integer: modules.modules.kernel.modules.type.types.Integer, + List: modules.modules.kernel.modules.type.types.List, +}; +const integer = ( + value: number, +): Expression.Expression => + Expression.fromJExpr(JExpr.integer(value)); + +const dividendValue = 7; +const divisorValue = 3; +const dividend = integer(dividendValue); +const divisor = integer(divisorValue); + +const compile = (expression: Expression.Any): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(expression))); + +describe("module_exports", () => { + test("prototype_named_export", () => { + expect.hasAssertions(); + const name = "__proto__"; + const exports = Result.getOrThrow( + Module.define("::exports", { + types: { [name]: Module.type() }, + }), + ); + expect(Object.hasOwn(exports.types, name)).toBe(true); + expect(Object.getPrototypeOf(exports.types)).toBe(Object.prototype); + expect( + TypeSyntax.compile(Result.getOrThrow(exports.types[name].syntax)), + ).toBe("::exports::__proto__"); + }); + + test("nonenumerable_exports", () => { + expect.hasAssertions(); + const types = { Integer: Module.type() }; + const children = { math }; + Object.defineProperty(types, "Integer", { enumerable: false }); + Object.defineProperty(children, "math", { enumerable: false }); + const exports = Result.getOrThrow( + Module.define("::exports", { types, modules: children }), + ); + const tree = Result.getOrThrow(Module.root(children)); + expect(Object.keys(exports.types)).toStrictEqual(["Integer"]); + expect(exports.modules.math).toBe(math); + expect(tree.modules.math).toBe(math); + }); + + test("symbol_export", () => { + expect.hasAssertions(); + const name = Symbol("not a HashQL name"); + const results = [ + Module.define("::exports", { + types: { [name]: Module.type() }, + }), + Module.define("::exports", { + values: { [name]: Module.value() }, + }), + Module.define("::exports", { modules: { [name]: math } }), + Module.root({ [name]: math }), + ]; + for (const result of results) { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "SymbolExportName", name } }, + }); + } + }); + + test("optional_namespace", () => { + expect.hasAssertions(); + const definition: { + readonly types?: { + readonly Integer: Module.Declaration< + TypeExpression.TypeExpression + >; + }; + } = {}; + expect( + Result.getOrThrow(Module.define("::exports", definition)).types, + ).toStrictEqual({}); + }); + + test("qualified_call", () => { + expect.hasAssertions(); + expect(compile(prelude.remainder(dividend, divisor))).toBe( + '["::core::math::rem",{"#literal":7},{"#literal":3}]', + ); + }); + + test("alias_identity", () => { + expect.hasAssertions(); + const aliases = Result.getOrThrow( + Module.define("::application", { + modules: { arithmetic: math }, + types: { Whole: prelude.Integer, Sequence: prelude.List }, + values: { remainder: prelude.remainder }, + }), + ); + expect(aliases.values.remainder).toBe(math.values.rem); + expect(aliases.modules).toStrictEqual({ arithmetic: math }); + expect(aliases.types.Whole).toBe(kernelTypes.types.Integer); + expect(aliases.types.Sequence).toBe(kernelTypes.types.List); + expect( + TypeSyntax.compile( + Result.getOrThrow( + TypeExpression.toType(aliases.types.Sequence(aliases.types.Whole)), + ), + ), + ).toBe("::kernel::type::List<::kernel::type::Integer>"); + }); + + test("type_and_constructor", () => { + expect.hasAssertions(); + const text = Expression.fromJExpr( + JExpr.literal("6b118660-f68e-4f4f-a3ec-e79639ca16fd"), + ); + expect( + TypeSyntax.compile( + Result.getOrThrow(TypeExpression.toType(uuid.types.Uuid)), + ), + ).toBe("::core::uuid::Uuid"); + expect(compile(uuid.values.Uuid(text))).toBe( + '["::core::uuid::Uuid",{"#literal":"6b118660-f68e-4f4f-a3ec-e79639ca16fd"}]', + ); + }); + + test("nested_type_application", () => { + expect.hasAssertions(); + const nested = prelude.List(prelude.List(prelude.Integer)); + expect( + TypeSyntax.compile(Result.getOrThrow(TypeExpression.toType(nested))), + ).toBe( + "::kernel::type::List<::kernel::type::List<::kernel::type::Integer>>", + ); + expect(compile(Expression.input("values", nested))).toBe( + '["::kernel::special_form::input","values","::kernel::type::List<::kernel::type::List<::kernel::type::Integer>>"]', + ); + }); + + test("symbol_name", () => { + expect.hasAssertions(); + const operators = Result.getOrThrow( + Module.define("::core::math", { + values: { "%": Module.value() }, + }), + ); + expect(compile(operators.values["%"](dividend, divisor))).toBe( + '["::core::math::`%`",{"#literal":7},{"#literal":3}]', + ); + }); +}); + +describe("module_relocation", () => { + test("nested_exports", () => { + expect.hasAssertions(); + const root = Result.getOrThrow( + Module.define("::source", { + modules: { arithmetic: math }, + types: { Integer: prelude.Integer, Sequence: prelude.List }, + values: { Uuid: uuid.values.Uuid }, + }), + ); + const local = Result.getOrThrow( + Module.relocate( + root, + Result.getOrThrow(JExpr.Path.decodeResult("local")), + ), + ); + expect( + compile(local.modules.arithmetic.values.rem(dividend, divisor)), + ).toBe('["local::arithmetic::rem",{"#literal":7},{"#literal":3}]'); + expect( + TypeSyntax.compile( + Result.getOrThrow(local.types.Sequence(prelude.Integer).syntax), + ), + ).toBe("local::Sequence<::kernel::type::Integer>"); + expect( + TypeSyntax.compile(Result.getOrThrow(local.types.Integer.syntax)), + ).toBe("local::Integer"); + expect(compile(local.values.Uuid("id"))).toBe( + '["local::Uuid",{"#literal":"id"}]', + ); + }); + + test("repeated_relocation", () => { + expect.hasAssertions(); + const root = Result.getOrThrow( + Module.define("::source", { modules: { arithmetic: math } }), + ); + const local = Result.getOrThrow( + Module.relocate( + root, + Result.getOrThrow(JExpr.Path.decodeResult("local")), + ), + ); + const second = Result.getOrThrow( + Module.relocate( + local, + Result.getOrThrow(JExpr.Path.decodeResult("second")), + ), + ); + expect( + compile(second.modules.arithmetic.values.rem(dividend, divisor)), + ).toBe('["second::arithmetic::rem",{"#literal":7},{"#literal":3}]'); + expect(compile(math.values.rem(dividend, divisor))).toBe( + '["::core::math::rem",{"#literal":7},{"#literal":3}]', + ); + }); + + test("value_failure", () => { + expect.hasAssertions(); + const invalid = Expression.number(Infinity); + const source = Result.getOrThrow( + Module.define("::source", { values: { invalid } }), + ); + const result = Module.relocate( + source, + Result.getOrThrow(JExpr.Path.decodeResult("local")), + ); + expect( + Result.match(result, { + onFailure: (error) => error.reason._tag, + onSuccess: () => null, + }), + ).toBe("InvalidExpression"); + }); +}); + +describe("module_construction", () => { + test("record_snapshot", () => { + expect.hasAssertions(); + const definitions = { rem: math.values.rem }; + const children = { arithmetic: math }; + const snapshot = Result.getOrThrow( + Module.define("::application", { + values: definitions, + modules: children, + }), + ); + definitions.rem = Expression.fromJExpr( + "replacement", + ); + children.arithmetic = Result.getOrThrow( + Module.define("::other", { + values: { rem: Module.value() }, + }), + ); + expect(snapshot.values.rem).toBe(math.values.rem); + expect(snapshot.modules.arithmetic).toBe(math); + expect( + [ + snapshot, + snapshot.values, + snapshot.types, + snapshot.modules, + modules.modules, + ].every(Object.isFrozen), + ).toBe(true); + expect(Reflect.set(snapshot.values, "other", math.values.rem)).toBe(false); + }); + + test("prototype_names", () => { + expect.hasAssertions(); + const unusual = Result.getOrThrow( + Module.define("::example", { + values: { + ["__proto__"]: Module.value(), + constructor: Module.value(), + }, + }), + ); + const { __proto__: prototypeExport } = unusual.values; + expect(Object.hasOwn(unusual.values, "__proto__")).toBe(true); + expect(compile(prototypeExport)).toBe('"::example::__proto__"'); + expect(compile(unusual.values.constructor)).toBe( + '"::example::constructor"', + ); + }); + + test("invalid_names", () => { + expect.hasAssertions(); + expect(Module.define("core::math", {})).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { _tag: "RelativeModulePath", name: "core::math" }, + }, + }); + expect(Module.define("", {})).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidModulePath", name: "" } }, + }); + for (const result of [ + Module.define("::core::math", { + values: { "": Module.value() }, + }), + Module.define("::core", { modules: { "": math } }), + Module.root({ "": math }), + Module.define("::core::math", { values: { "": math.values.rem } }), + ]) { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidExportName", name: "" } }, + }); + } + }); + + test.each([-1, Number.NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])( + "invalid_type_arity: %s", + (arity) => { + expect.hasAssertions(); + const result = Module.define("::generic", { + types: { Invalid: Module.genericType(arity) }, + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { _tag: "InvalidTypeArity", arity }, + }, + }); + }, + ); +}); + +describe("type_application", () => { + test("runtime_type_arity", () => { + expect.hasAssertions(); + // @ts-expect-error The runtime call omits the required type argument. + const missing = prelude.List(); + // @ts-expect-error The runtime call supplies an extra type argument. + const extra = prelude.List(prelude.Integer, prelude.Integer); + expect(TypeExpression.toType(missing)).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "TypeArgumentCount", expected: 1, received: 0 }, + }, + }); + expect(TypeExpression.toType(extra)).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "TypeArgumentCount", expected: 1, received: 2 }, + }, + }); + expect(TypeExpression.toType(prelude.List(missing))).toStrictEqual( + TypeExpression.toType(missing), + ); + expect(Expression.toJExpr(Expression.input("values", extra))).toStrictEqual( + TypeExpression.toType(extra), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Module.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.ts new file mode 100644 index 00000000000..04bbfd5fae1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.ts @@ -0,0 +1,495 @@ +/** + * Typed declarations bound to absolute HashQL paths. + * + * A module record describes exports that the HashQL environment provides under one path. Defining it emits no syntax and creates nothing in HashQL. Its declarations emit references beneath that path for the HashQL compiler to resolve, and importing a module emits a `use` of its path. + * + * Modules keep type and value exports separate because a type and its constructor can share a name. Existing exports are aliases: selecting or regrouping one never changes its reference. Declarations supply trusted type information. The HashQL compiler checks the emitted query. + * + * Expected construction failures, such as an invalid path or export name, arrive in a `Result`. + * + * @module + */ +import { Predicate, Result, flow, pipe } from "effect"; + +import { + Relocate, + relocate as relocateHandle, +} from "../internal/relocation.js"; +import * as JExpr from "../JExpr/index.js"; +import * as Expression from "./Expression.js"; +import * as ProgramError from "./ProgramError.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type * as Type from "../Type/index.js"; +import type * as Inputs from "./Inputs.js"; +import type { ReadonlyRecord } from "effect/Record"; + +const Declare: unique symbol = Symbol("~hashql/ModuleDeclaration"); +const TypeId: unique symbol = Symbol("~hashql/Module"); + +/** + * A declaration waiting for the module to supply its absolute export path. + * + * {@link value}, {@link type} and {@link genericType} create declarations. {@link define} binds each one to the export `E` it describes. + */ +export interface Declaration { + readonly [Declare]: ( + path: JExpr.Path.Path, + ) => Result.Result; +} + +/** An inspectable export table without fixing its concrete key set. */ +interface Namespace extends ReadonlyRecord {} + +/** Reverse mapping lets each declaration retain the type of the export it creates. */ +type Declarations = { + readonly [K in keyof E]: Declaration | E[K]; +}; + +/** + * A module with its concrete export names erased. + * + * The type and value tables are separate namespaces, so one name can hold both a type and its value constructor. + */ +export interface Any extends Relocatable { + readonly [TypeId]: true; + /** The path under which the module binds its exports. */ + readonly path: JExpr.Path.Path; + /** Child modules by local name. */ + readonly modules: Namespace; + /** Type expressions and generic type constructors by export name. */ + readonly types: Namespace; + /** Value expressions by export name. */ + readonly values: Namespace; +} + +/** + * Named declarations and existing exports to assemble into a module. + * + * Each table is optional. The type and value tables accept declarations or existing exports, and the module table accepts modules that are already bound. + */ +export interface Definition { + readonly modules?: Namespace; + readonly types?: Namespace< + Declaration | TypeExpression.Export + >; + readonly values?: Namespace | Expression.Any>; +} + +/** A table with no names. */ +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an absent namespace intentionally has no known members +type Empty = Record; + +/** Models possible namespace omission as optional members of an always-present table. */ +type Entries = K extends keyof S + ? undefined extends S[K] + ? Partial> + : S[K] + : Empty; + +/** Distributes over alternatives so an optional declaration also unwraps when present. */ +type Export = D extends Declaration ? E : D; + +/** Replaces each declaration in a table with the export it binds to. */ +type Exports = { + readonly [K in keyof D]: Export; +}; + +/** Bound tables retain their key-to-export relationships independently of the source declarations. */ +interface Bound extends Relocatable> { + readonly [TypeId]: true; + /** The path under which the module binds its exports. */ + readonly path: JExpr.Path.Path; + /** Child modules by local name. */ + readonly modules: Readonly; + /** Type expressions and generic type constructors by export name. */ + readonly types: Readonly; + /** Value expressions by export name. */ + readonly values: Readonly; +} + +/** Each entry must retain its own rebinding result, not merely a common export type. */ +type Rebindings = { readonly [K in keyof E]: Relocatable }; + +/** A declared or existing export must preserve its promised capabilities when imported. */ +type Rebindable = + E extends Declaration + ? Declaration> + : E extends undefined + ? undefined + : E & Relocatable; + +/** Applies the rebinding requirement to every entry of a table. */ +type RebindableEntries = { readonly [K in keyof E]: Rebindable }; + +/** Requires every table of a module definition to hold rebindable entries. */ +type RebindableDefinition = { + readonly [K in keyof S]: K extends keyof Definition + ? RebindableEntries + : S[K]; +}; + +/** + * An immutable module record preserving each export's concrete type. + * + * An omitted table becomes an empty table, and the names of an optional table become optional exports. + */ +export interface Module extends Bound< + Entries, + Exports>, + Exports> +> {} + +/** + * Recognizes a module assembled by this SDK. + * + * The guard checks for the module marker property. A joined namespace name that includes a module also passes, while the record {@link root} returns does not. + */ +// oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries +export const isModule = (value: unknown): value is Any => + Predicate.hasProperty(value, TypeId); + +/** + * Declares a value with trusted semantic type information. + * + * The bound export emits its absolute path, such as `::core::math::rem`, and requires no inputs. `T` decides which calls, projections and indexing TypeScript accepts, and a function descriptor makes the export callable. Nothing checks that the HashQL value has this type. + */ +export const value = (): Declaration< + Expression.Expression +> => ({ + [Declare]: flow( + JExpr.Path.compile, + Expression.fromJExpr, + Result.succeed, + ), +}); + +/** + * Declares a named type without expanding it into its structural representation. + * + * Once bound, the export emits a reference to its absolute path, such as `::core::uuid::Uuid`. TypeScript takes its descriptor `T` on trust. + */ +export const type = (): Declaration< + TypeExpression.TypeExpression +> => ({ + [Declare]: flow(TypeExpression.reference, Result.succeed), +}); + +/** + * Declares a named generic type with a type-level operation for its result. + * + * TypeScript requires `arity` to equal `F["arity"]`. Binding returns an `InvalidTypeArity` failure for an arity that is not a non-negative safe integer. The bound constructor emits applications of the export's path and checks the argument count of each call. + */ +export const genericType = ( + arity: F["arity"], +): Declaration> => ({ + [Declare]: (path) => TypeExpression.constructor(path, arity), +}); + +const memberName = ( + name: string, +): Result.Result => + pipe( + JExpr.Ident.decodeResult(name), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExportName({ name, cause }), + }), + ), + ); + +/** Symbol keys cannot appear in HashQL paths and must not disappear during binding. */ +const requireStringKeys = ( + symbols: readonly symbol[], +): Result.Result => { + const [name] = symbols; + + if (name !== undefined) { + return Result.fail(ProgramError.Construction.symbolExportName(name)); + } + + return Result.void; +}; + +/** + * Maps each own name at its corresponding export type. + * + * The callback is generic in K: it must produce E[K] from S[K] for the same key. This preserves the relationship that a callback over an entry union would lose. The source may contain declarations, while the destination contains bound exports. + */ +const mapEntries = < + E extends Namespace, + S extends Declarations, +>( + entries: S, + resolve: ( + name: K, + entry: S[K], + ident: JExpr.Ident.Ident, + ) => Result.Result, +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + yield* pipe(entries, Object.getOwnPropertySymbols, requireStringKeys); + const exports: Partial = {}; + const member = ( + name: K, + ): Result.Result => + pipe( + memberName(name), + Result.flatMap((ident) => resolve(name, entries[name], ident)), + ); + + for (const name of Object.getOwnPropertyNames(entries)) { + const bound = yield* member(name); + // Defining the property also preserves the ordinary export name __proto__. + Object.defineProperty(exports, name, { value: bound, enumerable: true }); + } + + // SAFETY: the loop fills each own string key at its original E[K] type. TypeScript cannot prove that coverage. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- completes a per-key checked Partial, without changing any export type + return Object.freeze(exports as E); + }); + +const copyModules = >( + modules: M, +): Result.Result, ProgramError.Construction> => + mapEntries(modules, (_name, entry) => Result.succeed(entry)); + +const isDeclaration = (entry: Declaration | E): entry is Declaration => + Predicate.hasProperty(entry, Declare); + +/** Resolves each declaration without widening its semantic descriptor. */ +const bind = >( + parent: JExpr.Path.Path, + entries: Declarations | undefined, +): Result.Result | Empty, ProgramError.Construction> => { + if (entries === undefined) { + return Result.succeed(Object.freeze({})); + } + + const resolve = ( + _name: K, + entry: Declaration | E[K], + ident: JExpr.Ident.Ident, + ): Result.Result => { + if (isDeclaration(entry)) { + return entry[Declare]({ + rooted: parent.rooted, + segments: [...parent.segments, ident], + }); + } + + return Result.succeed(entry); + }; + + return mapEntries>(entries, resolve); +}; + +/** Rebinds each member using the result type retained by that member's producer. */ +const rebase = < + E extends Namespace & + Rebindings, +>( + path: JExpr.Path.Path, + entries: E, +): Result.Result, ProgramError.Construction> => { + const sources: Rebindings = entries; + const resolve = ( + name: K, + _entry: E[K], + ident: JExpr.Ident.Ident, + ): Result.Result => + relocateHandle(sources[name], { + rooted: path.rooted, + segments: [...path.segments, ident], + }); + + return mapEntries(entries, resolve); +}; + +/** Captures typed export tables so rebinding preserves each member's result type. */ +const bound = < + M extends Namespace & Rebindings, + T extends Namespace & Rebindings, + V extends Namespace & Rebindings, +>( + path: JExpr.Path.Path, + entries: { readonly modules: M; readonly types: T; readonly values: V }, +): Bound => + Object.freeze({ + [TypeId]: true as const, + path, + ...entries, + [Relocate]: ( + next: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + { + modules: rebase(next, entries.modules), + types: rebase(next, entries.types), + values: rebase(next, entries.values), + }, + Result.all, + Result.map((exports) => bound(next, exports)), + ), + }); + +/** + * Binds new declarations and retains existing exports by identity. + * + * `name` must be an absolute path such as `::core::math`. Each declaration binds to that path extended by its key, so a value declared as `rem` emits `::core::math::rem`. An existing type expression, expression or module keeps its identity and the syntax it already emits. Child modules retain their own paths, including when mounted under an alias. Copying and freezing the records prevents caller mutations from adding or replacing exports afterward. The caller's tables are not frozen. + * + * Every own string key becomes an export, including non-enumerable keys and `__proto__`. A key must be a HashQL identifier. Emitted paths quote an operator name such as `%`, as in `` ::core::math::`%` ``. + * + * Invalid paths, export names and generic arities return construction failures. A malformed path returns `InvalidModulePath`, a relative path `RelativeModulePath`, a key that is not an identifier `InvalidExportName`, a symbol key `SymbolExportName` and an invalid generic arity `InvalidTypeArity`. Binding stops at the first failure, checking the module, type and value tables in that order. + * + * TypeScript keeps the namespaces apart: a value declaration cannot enter `types`, and a type declaration cannot enter `values`. Each existing export must rebind to its own type. TypeScript rejects a handle extended through `Object.assign`, because rebinding would drop the added properties. + * + * @example Declare a type and its value constructor under one name. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Module } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; + * + * const uuid = Result.getOrThrow( + * Module.define("::core::uuid", { + * types: { Uuid: Module.type() }, + * values: { + * Uuid: Module.value< + * Type.Function + * >(), + * }, + * }), + * ); + * const id = Expression.input("id", uuid.types.Uuid, uuid.values.Uuid("fallback")); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(id))), + * '["::kernel::special_form::input","id","::core::uuid::Uuid",["::core::uuid::Uuid",{"#literal":"fallback"}]]', + * ); + * + * const relative = Module.define("core::uuid", {}); + * assert.ok(Result.isFailure(relative)); + * assert.equal(relative.failure.reason._tag, "RelativeModulePath"); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the module under construction +export function define( + name: string, + definition: S & RebindableDefinition, +): Result.Result, ProgramError.Construction>; +export function define< + M extends Namespace & Rebindings, + T extends Namespace & Rebindings, + V extends Namespace & Rebindings, +>( + name: string, + definition: { + readonly modules?: M; + readonly types?: Declarations; + readonly values?: Declarations; + }, +): Result.Result< + Bound, + ProgramError.Construction +> { + return Result.gen(function* () { + const path = yield* pipe( + JExpr.Path.decodeResult(name), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidModulePath({ name, cause }), + }), + ), + ); + + if (!path.rooted) { + return yield* Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.RelativeModulePath({ name }), + }), + ); + } + + let modules: Readonly | Empty = Object.freeze({}); + if (definition.modules !== undefined) { + modules = yield* copyModules(definition.modules); + } + + return bound(path, { + modules, + types: yield* bind(path, definition.types), + values: yield* bind(path, definition.values), + }); + }); +} + +/** + * Rebinds a module tree while preserving each export's declared type. + * + * Every export becomes a reference to its name under `path`, including aliases of exports from other modules. Child modules are rebound recursively beneath it. The path can be relative, as it is when an import binds a module under a local name. Each export keeps its descriptor and input requirements even though its syntax becomes a reference. The original module keeps its paths. The first export that cannot be rebound, such as a value whose construction failed, returns its failure. It accepts the module first or last. + * + * @example Rebind an alias and a child module. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Module } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * const compile = (value: Expression.Any): string => + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(value))); + * const config = Result.getOrThrow( + * Module.define("::core::config", { + * values: { limit: Module.value() }, + * }), + * ); + * const app = Result.getOrThrow( + * Module.define("::app", { + * modules: { settings: config }, + * values: { maximum: config.values.limit }, + * }), + * ); + * assert.equal(compile(app.values.maximum), '"::core::config::limit"'); + * + * const local = Result.getOrThrow( + * Module.relocate(app, Result.getOrThrow(JExpr.Path.decodeResult("local"))), + * ); + * assert.equal(compile(local.values.maximum), '"local::maximum"'); + * assert.equal( + * compile(local.modules.settings.values.limit), + * '"local::settings::limit"', + * ); + * ``` + */ +export const relocate: { + ( + path: JExpr.Path.Path, + ): ( + self: Any & Relocatable, + ) => Result.Result; + ( + self: Any & Relocatable, + path: JExpr.Path.Path, + ): Result.Result; +} = relocateHandle; + +/** + * Assembles already-bound modules without rebasing their references. + * + * The result is a frozen `{ modules }` record keyed by the supplied names. It is not a module: it has no path, and {@link isModule} rejects it. Each child keeps its identity and its own path. The record fits any parameter that takes a scope definition, such as a Draft prelude. Names follow the rules and failures of the module table of {@link define}. + */ +export const root = >( + modules: M, +): Result.Result< + { readonly modules: Readonly }, + ProgramError.Construction +> => + pipe( + modules, + copyModules, + Result.map((bound) => Object.freeze({ modules: bound })), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test-d.ts new file mode 100644 index 00000000000..2245b154f0a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test-d.ts @@ -0,0 +1,170 @@ +/** + * Static checks for joined capabilities, optional names and relocation. + * + * @module + */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { relocate } from "../internal/relocation.js"; +import * as JExpr from "../JExpr/index.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; +import * as Namespace from "./Namespace.js"; +import * as Structural from "./Structural.js"; + +import type { Inputs, Type, TypeExpression } from "../main.js"; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : Type.Never; +} + +const identity = Symbol("Item"); +type Item = Type.Opaque; +const child = Result.getOrThrow( + Module.define("::child", { + values: { + count: Module.value(), + // oxlint-disable-next-line unicorn/no-thenable -- this is a HashQL export name + then: Module.value(), + }, + }), +); +const source = Result.getOrThrow( + Module.define("::source", { + modules: { Item: child, List: child }, + types: { Item: Module.type(), List: Module.genericType(1) }, + values: { + Item: Module.value< + Type.Function + >(), + List: Module.value< + Type.Function + >(), + }, + }), +); +const flat = Namespace.flatten(source); +const path = Result.getOrThrow(JExpr.Path.decodeResult("local")); + +describe("namespace_types", () => { + test("joined_types", () => { + expectTypeOf(flat.Item(1n)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(flat.Item.count).toEqualTypeOf(); + expectTypeOf(flat.Item.then).toEqualTypeOf(); + expectTypeOf(Structural.type(flat.Item)).toEqualTypeOf< + TypeExpression.TypeExpression + >(); + expectTypeOf(flat.List(Structural.type(BigInt))).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + expectTypeOf(flat.List(1n)).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error The value constructor requires Integer. + flat.Item("wrong"); + // @ts-expect-error No namespace declared this name. + expectTypeOf(flat.missing); + // @ts-expect-error Empty type tables do not introduce arbitrary names. + expectTypeOf(flat.Item.types.missing); + }); + + test("joined_relocation", () => { + const moved = Result.getOrThrow(relocate(flat.List, path)); + expectTypeOf(moved).toEqualTypeOf(); + expectTypeOf(moved.count).toEqualTypeOf(); + expectTypeOf(moved(Structural.type(String))).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + expectTypeOf(moved(1n)).toEqualTypeOf< + Expression.Expression + >(); + const twice = Result.getOrThrow(relocate(moved, path)); + expectTypeOf(twice).toEqualTypeOf(); + }); + + test("optional_names", () => { + const types: { + readonly Maybe?: TypeExpression.TypeExpression; + } = {}; + const modules: { readonly child?: typeof child } = {}; + const optional = Namespace.flatten({ modules, types, values: {} }); + expectTypeOf(optional.Maybe).toEqualTypeOf< + TypeExpression.TypeExpression | undefined + >(); + expectTypeOf>().toEqualTypeOf< + typeof types + >(); + // @ts-expect-error Narrow the optional module before reading its members. + expectTypeOf(optional.child.count); + const explicit = Namespace.modules({ modules, types: {}, values: {} }); + // @ts-expect-error Explicit module views also preserve optional entries. + expectTypeOf(explicit.child.count); + const shared = Namespace.flatten({ + modules: {}, + types, + values: { Maybe: Expression.integer(1) }, + }); + expectTypeOf(shared.Maybe).not.toBeUndefined(); + }); + + test("projection_collision", () => { + const value = Structural.value< + Type.Struct<{ + readonly count: Type.PrimitiveString; + readonly own: Type.PrimitiveBoolean; + }> + >()({ count: "shadowed", own: true }); + const joined = Namespace.flatten({ + modules: { Both: child }, + types: { Both: Structural.type(BigInt) }, + values: { Both: value }, + }).Both; + expectTypeOf(joined.count).toEqualTypeOf(); + expectTypeOf(joined.own).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(joined.$project("count")).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Structural.type(joined)).toEqualTypeOf< + TypeExpression.TypeExpression + >(); + }); + + test("unpreserved_properties", () => { + const extended = Object.assign(Structural.type(BigInt), { note: "extra" }); + // @ts-expect-error Rebinding the producer would drop note. + Namespace.combine(extended, Expression.integer(1)); + Namespace.flatten({ + modules: {}, + // @ts-expect-error A joined namespace must preserve every promised property. + types: { Both: extended }, + values: { Both: Expression.integer(1) }, + }); + expectTypeOf(extended.note).toEqualTypeOf(); + const optional: { readonly Both?: typeof extended } = {}; + // @ts-expect-error Optional producers must preserve their properties when present. + Namespace.flatten({ modules: {}, types: optional, values: {} }); + }); + + test("input_requirements", () => { + const input = Expression.input("count", Structural.type(BigInt)); + const joined = Namespace.combine(input, Structural.type(BigInt)); + const moved = Result.getOrThrow(relocate(joined, path)); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + // @ts-expect-error Moving a reference does not erase its input requirement. + const closed: Expression.Expression = + moved; + expectTypeOf(closed).toEqualTypeOf< + Expression.Expression + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test.ts new file mode 100644 index 00000000000..6bad1688f36 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test.ts @@ -0,0 +1,232 @@ +/** + * Runtime checks for namespace forwarding and relocation of joined handles. + * + * @module + */ +import { Result, flow } from "effect"; +import { describe, expect, test } from "vitest"; + +import { relocate } from "../internal/relocation.js"; +import * as JExpr from "../JExpr/index.js"; +import * as TypeSyntax from "../JExpr/Type/index.js"; +import { Expression, Module, Structural, TypeExpression } from "../main.js"; +import * as Namespace from "./Namespace.js"; + +import type * as Type from "../Type/index.js"; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : Type.Never; +} + +const path = flow(JExpr.Path.decodeResult, Result.getOrThrow); +const valueSyntax = flow(Expression.toJExpr, Result.getOrThrow); +const typeSyntax = flow( + TypeExpression.toType, + Result.getOrThrow, + TypeSyntax.compile, +); +const child = Result.getOrThrow( + Module.define("::child", { + values: { + count: Module.value(), + // oxlint-disable-next-line unicorn/no-thenable -- this is a HashQL export name + then: Module.value(), + $: Module.value(), + name: Module.value(), + length: Module.value(), + prototype: Module.value(), + constructor: Module.value(), + toString: Module.value(), + syntax: Module.value(), + }, + }), +); +const source = Result.getOrThrow( + Module.define("::source", { + modules: { Both: child }, + types: { Both: Module.genericType(1) }, + values: { + Both: Module.value< + Type.Function + >(), + }, + }), +); + +describe("namespace", () => { + test("joined_dispatch", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + expect(joined).toSatisfy(TypeExpression.isConstructor); + expect(joined).toSatisfy(Expression.isExpression); + expect(joined).toSatisfy(Module.isModule); + expect(typeSyntax(joined(Structural.type(BigInt)))).toBe( + "::source::Both<::kernel::type::Integer>", + ); + expect(valueSyntax(joined(1n))).toStrictEqual([ + "::source::Both", + { "#literal": { _tag: "Integer", value: "1" } }, + ]); + }); + + test("joined_relocation", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + const moved = Result.getOrThrow(relocate(joined, path("local"))); + expect(typeSyntax(moved(Structural.type(String)))).toBe( + "local<::kernel::type::String>", + ); + expect(valueSyntax(moved(1n))).toStrictEqual([ + "local", + { "#literal": { _tag: "Integer", value: "1" } }, + ]); + expect(valueSyntax(moved.count)).toBe("local::count"); + }); + + test("repeated_relocation", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + const moved = Result.getOrThrow(relocate(joined, path("local"))); + const twice = Result.getOrThrow(relocate(moved, path("again"))); + expect(typeSyntax(twice(Structural.type(BigInt)))).toBe( + "again<::kernel::type::Integer>", + ); + expect(valueSyntax(twice.count)).toBe("again::count"); + expect(valueSyntax(joined.count)).toBe("::child::count"); + }); + + test("ordinary_then", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + expect(joined.then).toBe(child.values.then); + expect("then" in joined).toBe(true); + expect(Namespace.modules(source).Both.then).toBe(child.values.then); + expect(joined.values.$).toBe(child.values.$); + expect(joined.$).toBe(child.values.$); + }); + + test("function_intrinsics", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + expect(joined.name).toBe(child.values.name); + // oxlint-disable-next-line vitest/prefer-to-have-length -- length holds the declared HashQL export + expect(joined.length).toBe(child.values.length); + expect(joined.prototype).toBe(child.values.prototype); + expect(joined.constructor).toBe(child.values.constructor); + expect(joined.toString).toBe(child.values.toString); + }); + + test("projection_collision", () => { + expect.hasAssertions(); + const value = Structural.value< + Type.Struct<{ + readonly count: Type.PrimitiveString; + readonly own: Type.PrimitiveBoolean; + }> + >()({ count: "shadowed", own: true }); + const joined = Namespace.flatten({ + modules: { Both: child }, + types: { Both: Structural.type(BigInt) }, + values: { Both: value }, + }).Both; + expect(joined.count).toBe(child.values.count); + expect(typeSyntax(joined)).toBe("::kernel::type::Integer"); + expect(valueSyntax(joined.own)).toStrictEqual(valueSyntax(value.own)); + expect(valueSyntax(joined.$project("count"))).toStrictEqual( + valueSyntax(value.count), + ); + }); + + test("prototype_names", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + modules: { ["__proto__"]: child }, + types: { ["__proto__"]: Module.type() }, + values: { ["__proto__"]: Module.value() }, + }), + ); + // oxlint-disable-next-line eslint/no-proto -- this is an ordinary HashQL export + const joined = Namespace.flatten(custom).__proto__; + expect(joined).toSatisfy(Module.isModule); + expect(joined).toSatisfy(TypeExpression.isExport); + expect(joined).toSatisfy(Expression.isExpression); + expect(joined.count).toBe(child.values.count); + }); + + test("inherited_name", () => { + expect.hasAssertions(); + const typeOnly = Namespace.flatten({ + modules: {}, + types: { toString: Structural.type(BigInt) }, + values: {}, + }); + expect(typeOnly.toString).toSatisfy(TypeExpression.isExport); + expect(typeOnly.toString).not.toSatisfy(Expression.isExpression); + }); + + test("optional_absence", () => { + expect.hasAssertions(); + const modules: { readonly child?: typeof child } = {}; + const types: { + readonly Integer?: TypeExpression.TypeExpression; + } = {}; + expect( + Object.keys(Namespace.flatten({ modules, types, values: {} })), + ).toStrictEqual([]); + expect( + Object.keys(Namespace.modules({ modules, types, values: {} })), + ).toStrictEqual([]); + }); + + test("nonenumerable_names", () => { + expect.hasAssertions(); + const types = { Integer: Structural.type(BigInt) }; + Object.defineProperty(types, "Integer", { enumerable: false }); + const flat = Namespace.flatten({ modules: {}, types, values: {} }); + expect(flat.Integer).toBe(types.Integer); + expect(Object.keys(flat)).toStrictEqual(["Integer"]); + }); + + test("joined_failure", () => { + expect.hasAssertions(); + const failed = Expression.number(Number.NaN); + const joined = Namespace.combine(failed, Structural.type(BigInt)); + expect(relocate(joined, path("local"))).toMatchObject({ _tag: "Failure" }); + }); + + test("module_view_relocation", () => { + expect.hasAssertions(); + const tree = Result.getOrThrow( + Module.define("::tree", { modules: { nested: child } }), + ); + const view = Namespace.modules({ + modules: { tree }, + types: {}, + values: {}, + }).tree; + const moved = Result.getOrThrow(relocate(view, path("local"))); + expect(valueSyntax(moved.nested.count)).toBe("local::nested::count"); + expect(valueSyntax(moved.modules.nested.values.count)).toBe( + "local::nested::count", + ); + }); + + test("join_order", () => { + expect.hasAssertions(); + const module = Namespace.modules(source).Both; + const value = Structural.value< + Type.Struct<{ readonly count: Type.PrimitiveString }> + >()({ count: "shadowed" }); + const type = Structural.type(BigInt); + const joined = Namespace.combine(Namespace.combine(type, value), module); + expect(typeSyntax(joined)).toBe("::kernel::type::Integer"); + expect(joined.count).toBe(child.values.count); + expect(valueSyntax(joined.$project("count"))).toStrictEqual( + valueSyntax(value.count), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts new file mode 100644 index 00000000000..90f448c8a23 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts @@ -0,0 +1,508 @@ +/** + * Shared names with separate module, type and value capabilities. + * + * A flattened name can be a value, a type constructor and a module at once. Type metadata wins property collisions, followed by module exports and then value projections. Explicit projection and indexing remain available through `$project` and `$index`. Rebinding a joined name moves every capability, rather than following property-lookup precedence. + * + * Draft's `$.prelude()`, `$.modules()` and `$.import(...)` return these flattened views. A name that only optional entries supply is optional, and a module also exposes its child exports directly, beside its own `modules`, `types` and `values` tables. + * + * @module + */ +// oxlint-disable max-lines -- capability joining and scope flattening share producer tracking, export lookup and rebinding machinery +import { Function, Result, pipe } from "effect"; + +import { Relocate } from "../internal/relocation.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; +import * as Structural from "./Structural.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type { JExpr, Type } from "../main.js"; +import type { Accessors } from "./ExpressionType.js"; +import type * as ProgramError from "./ProgramError.js"; +import type * as Scope from "./Scope.js"; + +/** A producer that retains a rebinding operation in its result. */ +interface Capability extends Relocatable {} + +type RebindableEntry = E extends Capability ? Relocatable : E; + +/** + * Scope exports need string names and producers that preserve their properties during rebinding. + * + * Draft's `withPrelude` requires this of a custom prelude. An export extended through `Object.assign` fails it, because rebinding would drop the added properties. + */ +export type Rebindable = { + readonly [N in keyof S]: N extends keyof Scope.Scope + ? { + readonly [K in keyof S[N]]: K extends symbol + ? never + : RebindableEntry; + } + : S[N]; +}; +const Components: unique symbol = Symbol("~hashql/NamespaceComponents"); + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an absent capability contributes no properties +type Empty = Record; +type Present = E extends undefined ? Empty : E; +type Lookup = K extends keyof S ? S[K] : undefined; + +/** Keeps original producers available after repeated joins, including their generic call signatures. */ +type Part = E extends { + readonly [Components]: readonly [infer L, infer R]; +} + ? Part extends undefined + ? Part + : Part + : E extends C + ? E + : undefined; + +type Parts = Part extends undefined ? Part : Part; + +type Metadata = Omit< + Present, + keyof Present | (V extends Expression.Any ? ExpressionReserved : never) +> & + Present; + +type ExpressionReserved = "$project" | "$index" | "~hashql/Expression"; + +/** Removes shadowed projections without discarding generic call signatures. */ +type WithMetadata = V extends Expression.Any + ? M & + (Expression.TypeOf extends + | Type.Function.Any + | Type.GenericFunction.Any + | Type.Primitive + ? V + : Expression.Handle, Expression.Inputs> & + Omit< + Accessors, Expression.Inputs>, + Exclude + >) + : M & V; + +type Combined = WithMetadata< + Present>, + Metadata< + Parts, + Parts, + Parts + > +>; + +/** + * One name carrying the capabilities of two exports, such as a value constructor and the type it constructs. + * + * Property reads follow the precedence the module introduction states. A call with type arguments reaches the type constructor, and a call with value arguments reaches the value. The last relocation signature returns the whole joined capability set. + */ +export type Joined = Combined & { + readonly [Components]: readonly [L, R]; +} & Relocatable>; + +/** Distributes over optional entries instead of intersecting their undefined alternatives. */ +type Selected = L extends undefined + ? R + : R extends undefined + ? L + : Joined; + +type ModuleView = M & + Omit, keyof M> & + Relocatable>; + +type Viewed = M extends Module.Any ? ModuleView : undefined; + +type Member = Selected, V>, T>; + +type Keys = + | keyof S["modules"] + | keyof S["types"] + | keyof S["values"]; + +type RequiredKeys = { + [K in keyof S]-?: undefined extends S[K] ? never : K; +}[keyof S]; + +type RequiredNames = + | RequiredKeys + | RequiredKeys + | RequiredKeys; + +/** + * The single-object view of a scope, in which each name joins its module, type and value exports. + * + * A guaranteed export in any namespace makes the flattened name required. A name that only optional entries supply is optional. A module also exposes its child exports directly, beside its own `modules`, `types` and `values` tables. + */ +export type Flatten = { + readonly [K in Keys as K extends RequiredNames ? K : never]: Member< + Lookup, + Lookup, + Lookup + >; +} & { + readonly [K in Keys as K extends RequiredNames ? never : K]?: Exclude< + Member< + Lookup, + Lookup, + Lookup + >, + undefined + >; +}; + +interface ModuleScope { + readonly modules: S["modules"]; + readonly types: Empty; + readonly values: Empty; +} +/** The flattened view of a scope's modules alone, each exposing its child exports directly. */ +export type Modules = Flatten>; + +const combinedHandles = new WeakMap< + Capability, + readonly [] | readonly [Capability, Capability] +>(); + +/** Finds the original producer rather than mistaking a combined marker for a second producer. */ +const find = ( + candidate: Capability, + predicate: (candidate: Capability) => candidate is E, +): E | undefined => { + const components = combinedHandles.get(candidate); + if (components?.length === 2) { + return find(components[1], predicate) ?? find(components[0], predicate); + } + + if (predicate(candidate)) { + return candidate; + } + + return undefined; +}; + +// Function intrinsics are not declared namespace exports. Joined proxies check their sources. +const hasExport = (candidate: Capability, key: PropertyKey): boolean => { + if (combinedHandles.has(candidate)) { + return key in candidate; + } + + if (typeof candidate === "function") { + return Object.prototype.propertyIsEnumerable.call(candidate, key); + } + + return Object.hasOwn(candidate, key); +}; + +const expressionReserved = new Set([ + "$project", + "$index", + "~hashql/Expression", +]); + +/** + * Selects a callable capability from the runtime argument category. + * + * Proxy calls arrive without their generic argument tuple. The public intersection retains each source signature. This boundary invokes only the matching SDK callable. Its result is another SDK capability. + */ +const invoke = ( + candidate: Capability | undefined, + // oxlint-disable-next-line typescript/no-restricted-types -- a proxy call receives unchecked host arguments + args: readonly unknown[], +): Capability | undefined => { + if (typeof candidate !== "function") { + return undefined; + } + + const typeCall = + TypeExpression.isConstructor(candidate) && + args.every(Structural.isDefinition); + + const valueCall = + Expression.isExpression(candidate) && args.every(Structural.isValue); + + if (!typeCall && !valueCall) { + return undefined; + } + + // SAFETY: each matching SDK callable returns a type or value handle. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- invocation erases the argument tuple at the proxy boundary + return Reflect.apply(candidate, undefined, args) as Capability; +}; + +/** Joins concrete capability producers and rebinds both with their original result types. */ +export const combine: { + >( + right: R, + ): >(left: L) => Joined; + < + L extends Capability & Relocatable, + R extends Capability & Relocatable, + >( + left: L, + right: R, + ): Joined; +} = Function.dual( + 2, + < + L extends Capability & Relocatable, + R extends Capability & Relocatable, + >( + left: L, + right: R, + ): Joined => { + const leftSource: Relocatable = left; + const rightSource: Relocatable = right; + + const rebind = ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + Result.all({ + left: leftSource[Relocate](path), + right: rightSource[Relocate](path), + }), + Result.map((moved) => combine(moved.left, moved.right)), + ); + + const type = + find(right, TypeExpression.isExport) ?? + find(left, TypeExpression.isExport); + + const value = + find(right, Expression.isExpression) ?? + find(left, Expression.isExpression); + + const module = find(right, Module.isModule) ?? find(left, Module.isModule); + + // oxlint-disable-next-line typescript/no-restricted-types -- proxy invocation selects a callable from the host arguments + const callable = (...args: readonly unknown[]): Capability | undefined => { + const first = invoke(type, args); + const second = invoke(value, args); + + if (first === undefined) { + return second; + } + + if (second === undefined) { + return first; + } + + return combine(first, second); + }; + + const components: readonly [L, R] = [left, right]; + + let target: Relocatable> = { [Relocate]: rebind }; + if (typeof left === "function" || typeof right === "function") { + target = Object.assign(callable, target); + } + + const proxy = new Proxy(target, { + has: (_target, key): boolean => + key === Relocate || + key === Components || + hasExport(left, key) || + hasExport(right, key), + // oxlint-disable-next-line typescript/no-restricted-types -- a property trap returns heterogeneous host properties + get: (_target, key): unknown => { + if (key === Components) { + return components; + } + + if (key === Relocate) { + return rebind; + } + + if (expressionReserved.has(key) && value !== undefined) { + return Reflect.get(value, key); + } + + if (type !== undefined && hasExport(type, key)) { + return Reflect.get(type, key); + } + + if (module !== undefined && hasExport(module, key)) { + return Reflect.get(module, key); + } + + if (value !== undefined) { + return Reflect.get(value, key); + } + + return Reflect.get(_target, key); + }, + }); + + combinedHandles.set(proxy, components); + + // SAFETY: property forwarding implements Combined; rebind already returns Joined. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy cannot express forwarded properties or overloaded calls + return proxy as Joined; + }, +); + +function select< + L extends Capability | undefined, + R extends Capability | undefined, +>(left: L, right: R): Selected; +function select< + L extends Capability & Relocatable, + R extends Capability & Relocatable, +>(left: L | undefined, right: R | undefined): L | R | Joined | undefined { + if (left === undefined) { + return right; + } + + if (right === undefined) { + return left; + } + + return combine(left, right); +} + +/** A module view rebuilds its flattened children from the rebound module. */ +function viewModule(module: M): ModuleView; +function viewModule>( + module: M, +): ModuleView { + // oxlint-disable-next-line eslint/no-use-before-define -- module views and child flattening are mutually recursive + const children = flattenScope(module); + const source: Relocatable = module; + + const rebind = ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + source[Relocate](path), + Result.map((moved) => viewModule(moved)), + ); + + const target = { [Relocate]: rebind }; + const proxy = new Proxy(target, { + has: (_target, key): boolean => + key === Relocate || + hasExport(module, key) || + Object.hasOwn(children, key), + // oxlint-disable-next-line typescript/no-restricted-types -- a property trap returns heterogeneous host properties + get: (_target, key): unknown => { + if (key === Relocate) { + return rebind; + } + if (hasExport(module, key)) { + return Reflect.get(module, key); + } + return Reflect.get(children, key); + }, + }); + + combinedHandles.set(proxy, []); + + // SAFETY: module properties take precedence over children, exactly as ModuleView specifies. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy does not model forwarded properties + return proxy as ModuleView; +} + +function viewOptional(module: M): Viewed; +function viewOptional( + module: M | undefined, +): ModuleView | undefined { + if (module === undefined) { + return undefined; + } + return viewModule(module); +} + +/** Resolves one key while retaining all three source export types. */ +const member = < + M extends Module.Any | undefined, + T extends TypeExpression.Export | undefined, + V extends Expression.Any | undefined, +>( + module: M, + type: T, + value: V, +): Member => select(select(viewOptional(module), value), type); + +/** Reads own names to exclude inherited object properties from namespace declarations. */ +function lookup( + table: S, + name: K, +): Lookup; +function lookup( + table: Readonly>, + name: K, +): E | undefined { + if (Object.hasOwn(table, name)) { + return table[name]; + } + + return undefined; +} + +/** Per-key results before mapping absent alternatives to optional properties. */ +type Members = { + readonly [K in Keys]: Member< + Lookup, + Lookup, + Lookup + >; +}; + +/** Property definition preserves __proto__ without losing the key-to-value relationship. */ +const define = ( + table: Partial, + name: K, + value: O[K], +): void => { + Object.defineProperty(table, name, { value, enumerable: true }); +}; + +/** Copies each namespace key once without introducing names from missing tables. */ +const flattenScope = (scope: S): Flatten => { + const entries: Partial> = {}; + + // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- K ties three lookups to the same destination member + const resolve = & string>(name: K): void => { + const value = member( + lookup(scope.modules, name), + lookup(scope.types, name), + lookup(scope.values, name), + ); + + if (value !== undefined) { + define, K>(entries, name, value); + } + }; + + const names = new Set([ + ...Object.getOwnPropertyNames(scope.modules), + ...Object.getOwnPropertyNames(scope.types), + ...Object.getOwnPropertyNames(scope.values), + ]); + + for (const name of names) { + resolve(name); + } + + // SAFETY: the loop checks each own key at Members[K]. Absent alternatives become optional properties. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- completes the per-key mapped table after enumerating its names + return Object.freeze(entries) as Flatten; +}; + +/** Joins a checked scope. Module.define performs the same producer check for nested tables. */ +export const flatten = ( + scope: S & Rebindable, +): Flatten => flattenScope(scope); + +/** Keeps only module names, with their child exports available directly. */ +export const modules = ( + scope: S & Pick, "modules">, +): Modules => + flattenScope>({ + modules: scope.modules, + types: {}, + values: {}, + }); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Operators.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Operators.test-d.ts new file mode 100644 index 00000000000..1c56fe98aae --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Operators.test-d.ts @@ -0,0 +1,47 @@ +/** Operator domains and input inference in both argument orders. @module */ +import { pipe } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Operators, Prelude } from "../main.js"; + +import type { Inputs, Type } from "../main.js"; + +describe("operator_types", () => { + test("operator_domains", () => { + const count = Expression.input("count", Prelude.builtin.types.Integer); + const other = Expression.input("other", Prelude.builtin.types.Integer, 0n); + const first = Operators.eq(count, other); + const last = pipe(count, Operators.eq(other)); + expectTypeOf(first).toEqualTypeOf< + Operators.Predicate<{ + readonly count: Type.PrimitiveInteger; + readonly other?: Type.PrimitiveInteger; + }> + >(); + expectTypeOf(last).toEqualTypeOf(first); + expectTypeOf(count).not.toHaveProperty("$"); + expectTypeOf(Expression.literal(true)).not.toHaveProperty("and"); + // @ts-expect-error Integer and Number remain distinct in the data-last form. + pipe(count, Operators.eq(1)); + // @ts-expect-error Negation does not coerce numeric truthiness. + Operators.not(count); + // @ts-expect-error A conjunction requires a Boolean left operand. + pipe(count, Operators.and(true)); + // @ts-expect-error Only an option union admits None checking. + Operators.isNone(count); + const left = Symbol("Left"); + const right = Symbol("Right"); + const firstNominal = Expression.fromJExpr< + Type.Opaque, + Inputs.Empty + >("a"); + const secondNominal = Expression.fromJExpr< + Type.Opaque, + Inputs.Empty + >("b"); + // @ts-expect-error A pipe cannot equate distinct nominal identities. + pipe(firstNominal, Operators.eq(secondNominal)); + // @ts-expect-error A fluent predicate still requires Boolean operands. + first.and(count); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Operators.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Operators.test.ts new file mode 100644 index 00000000000..13e38af8859 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Operators.test.ts @@ -0,0 +1,117 @@ +/** Explicit operator composition and relocation. @module */ +// oxlint-disable unicorn/no-array-method-this-argument -- Result.flatMap is not an array method +import { Result, pipe } from "effect"; +import { describe, expect, expectTypeOf, test } from "vitest"; + +import * as Draft from "../draft/index.js"; +import { Relocate } from "../internal/relocation.js"; +import { Expression, JExpr, Operators, Prelude } from "../main.js"; + +import type { Type } from "../main.js"; + +const syntax = (expression: Expression.Any): JExpr.Expression => + Result.getOrThrow(Expression.toJExpr(expression)); + +describe("operators", () => { + test("composition_forms", () => { + expect.hasAssertions(); + const count = Expression.input("count", Prelude.builtin.types.Integer); + const enabled = Expression.input( + "enabled", + Prelude.builtin.types.Boolean, + true, + ); + const chained = Operators.eq(count, 1n).and(enabled).or(false).not(); + const piped = pipe( + count, + Operators.eq(1n), + Operators.and(enabled), + Operators.or(false), + Operators.not, + ); + const nested = Operators.not( + Operators.or(Operators.and(Operators.eq(count, 1n), enabled), false), + ); + expect(syntax(chained)).toStrictEqual(syntax(piped)); + expect(syntax(nested)).toStrictEqual(syntax(chained)); + expect(syntax(chained)).toStrictEqual([ + "::core::bool::not", + [ + "::core::bool::or", + [ + "::core::bool::and", + [ + "::core::cmp::eq", + [ + "::kernel::special_form::input", + "count", + "::kernel::type::Integer", + ], + JExpr.literal(1n), + ], + [ + "::kernel::special_form::input", + "enabled", + "::kernel::type::Boolean", + { "#literal": true }, + ], + ], + { "#literal": false }, + ], + ]); + expectTypeOf(chained).toEqualTypeOf< + Operators.Predicate<{ + readonly count: Type.PrimitiveInteger; + readonly enabled?: Type.PrimitiveBoolean; + }> + >(); + expectTypeOf(piped).toEqualTypeOf(chained); + expect(Expression.isExpression(chained)).toBe(true); + }); + + test("context_binding", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const composed = $.eq(1n, 1n).and($.not(false)); + const bound = $.let("selected", composed); + expectTypeOf(bound).not.toHaveProperty("and"); + return pipe(bound, $.or(false)); + }); + expect( + Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)), + ).toStrictEqual([ + "::kernel::special_form::let", + "selected", + [ + "::core::bool::and", + ["::core::cmp::eq", JExpr.literal(1n), JExpr.literal(1n)], + ["::core::bool::not", { "#literal": false }], + ], + ["::core::bool::or", "selected", { "#literal": false }], + ]); + }); + + test("relocated_chain", () => { + expect.hasAssertions(); + const original = Operators.eq(1n, 2n); + const first = Result.getOrThrow( + original[Relocate](Result.getOrThrow(JExpr.Path.decodeResult("first"))), + ); + const second = Result.getOrThrow( + first[Relocate](Result.getOrThrow(JExpr.Path.decodeResult("second"))), + ); + expect(syntax(second.and(false))).toStrictEqual([ + "::core::bool::and", + "second", + { "#literal": false }, + ]); + expect(syntax(second.not())).toStrictEqual(["::core::bool::not", "second"]); + expect(Expression.isExpression(second)).toBe(true); + }); + + test("construction_failure", () => { + expect.hasAssertions(); + const failure = Operators.eq(Number.POSITIVE_INFINITY, 1).and(true).not(); + expect(Result.isFailure(Expression.toNode(failure))).toBe(true); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts b/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts new file mode 100644 index 00000000000..af141f0fa87 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts @@ -0,0 +1,224 @@ +/** + * Explicit predicate construction with fluent and data-last composition. + * + * Ordinary expressions have no operator methods. These constructors return Boolean expressions with chaining methods. Binding one through let produces an ordinary expression again. Both composition forms emit HashQL calls, not host predicates, and preserve every operand's input requirements. + * + * @module + */ +import { Array, Function, Result, pipe } from "effect"; + +import { Relocate } from "../internal/relocation.js"; +import * as JExpr from "../JExpr/index.js"; +import * as AST from "./AST/index.js"; +import * as Expression from "./Expression.js"; + +import type * as Type from "../Type/index.js"; +import type { Normalize } from "./ExpressionType.js"; +import type * as Inputs from "./Inputs.js"; +import type * as ProgramError from "./ProgramError.js"; + +type BooleanValue = Expression.Value; +type Requirements = Inputs.Merge< + Expression.Inputs, + Expression.Inputs +>; + +/** + * A Boolean expression with fluent logical composition and a retained input record. + * + * Chaining constructs syntax rather than testing a host condition. Binding the result with a declaration gives an ordinary Boolean expression. Use the standalone operators to continue composing that binding. See {@link eq} for both fluent and pipe-based forms. + */ +export interface Predicate extends Expression.Expression< + Type.PrimitiveBoolean, + I +> { + /** Combines this predicate with another Boolean operand, retaining both sets of inputs. */ + readonly and: ( + other: R, + ) => Predicate>>; + /** Constructs a disjunction without short-circuiting host-side operand construction. */ + readonly or: ( + other: R, + ) => Predicate>>; + /** Negates the represented predicate without changing its input requirements. */ + readonly not: () => Predicate; + readonly [Relocate]: ( + path: JExpr.Path.Path, + ) => Result.Result, ProgramError.Construction>; +} + +const call = ( + path: string, + operands: readonly Expression.AnyValue[], +): Predicate => + // oxlint-disable-next-line eslint/no-use-before-define -- syntax construction and predicate decoration are mutually recursive + predicate( + pipe( + operands, + Array.map(Expression.toJExpr), + Result.all, + Result.map((arguments_) => new AST.Expr(JExpr.call(path, ...arguments_))), + ), + ); + +/** Copies metadata from a freshly constructed handle, whose marker properties are own and enumerable. */ +const predicate = ( + node: Result.Result, +): Predicate => { + const expression = Expression.fromResult(node); + return { + ...expression, + and: ( + other: R, + ): Predicate>> => + call("::core::bool::and", [expression, other]), + or: ( + other: R, + ): Predicate>> => + call("::core::bool::or", [expression, other]), + not: (): Predicate => call("::core::bool::not", [expression]), + [Relocate]: (path) => + pipe( + expression[Relocate](path), + Result.map((moved) => predicate(Expression.toNode(moved))), + ), + }; +}; + +/** Direct and data-last comparison forms, checking the second supplied operand against the first operand's semantic descriptor. */ +interface Comparison { + ( + right: R, + ): >>>( + left: L, + ) => Predicate>; + < + const L extends Expression.AnyValue, + const R extends Expression.Value>>, + >( + left: L, + right: R, + ): Predicate>; +} + +const comparison = (path: string): Comparison => + Function.dual( + 2, + < + const L extends Expression.AnyValue, + const R extends Expression.Value>>, + >( + left: L, + right: R, + ): Predicate> => call(path, [left, right]), + ); + +/** + * Constructs equality between operands with matching semantic descriptors. + * + * `eq(left, right)` checks the right descriptor against the left. `eq(right)(left)` fixes the right descriptor first. Host primitives use their SDK descriptors: use bigint with an Integer expression and number with a Number expression. The result retains both operands' inputs and construction failures. + * + * @example Compose the same predicate with chaining or a pipe. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Operators, Prelude } from "@local/hashql"; + * import { Result, pipe } from "effect"; + * + * const count = Expression.input("count", Prelude.builtin.types.Integer); + * const chained = Operators.eq(count, 1n).and(true).not(); + * const piped = pipe(count, Operators.eq(1n), Operators.and(true), Operators.not); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(chained)), + * Result.getOrThrow(Expression.toJExpr(piped)), + * ); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the curried form fixes the right descriptor and checks the left; both argument orders have exact-type tests +export const eq: Comparison = comparison("::core::cmp::eq"); +/** Constructs inequality with the same operand constraints and composition forms as {@link eq}. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the curried form fixes the right descriptor and checks the left; both argument orders have exact-type tests +export const ne: Comparison = comparison("::core::cmp::ne"); + +/** Direct and data-last forms that combine two Boolean operands and their input requirements. */ +interface BooleanCombination { + ( + right: R, + ): (left: L) => Predicate>; + ( + left: L, + right: R, + ): Predicate>; +} + +const combination = (path: string): BooleanCombination => + Function.dual( + 2, + ( + left: L, + right: R, + ): Predicate> => call(path, [left, right]), + ); + +/** Constructs a Boolean conjunction, directly or as `and(right)(left)`, without short-circuiting host construction. */ +export const and: BooleanCombination = combination("::core::bool::and"); +/** Constructs a Boolean disjunction, directly or as `or(right)(left)`, without short-circuiting host construction. */ +export const or: BooleanCombination = combination("::core::bool::or"); +/** Constructs Boolean negation while retaining the operand's inputs and construction failures. */ +export const not = ( + expression: E, +): Predicate> => call("::core::bool::not", [expression]); +/** Constructs an equality comparison with true, returning a chainable {@link Predicate}. */ +export const isTrue = ( + expression: E, +): Predicate> => + call("::core::cmp::eq", [expression, true]); +/** Constructs an equality comparison with false, returning a chainable {@link Predicate}. */ +export const isFalse = ( + expression: E, +): Predicate> => + call("::core::cmp::eq", [expression, false]); + +type Optional = + Normalize> extends Type.Union + ? Extract< + M[number], + Type.Opaque<"::core::option::None", Type.Any> + > extends never + ? never + : E + : never; + +/** + * Compares an optional value with the HashQL `::core::option::None` constructor. + * + * The operand's normalized descriptor must be a union containing that nominal type. Null is a different value and does not satisfy this constraint. The resulting equality expression retains the operand's TypeScript descriptor without narrowing it. + */ +export const isNone = ( + expression: E & Optional, +): Predicate> => + pipe( + Expression.toJExpr(expression), + Result.map( + (value) => + new AST.Expr( + JExpr.call( + "::core::cmp::eq", + value, + JExpr.call("::core::option::None"), + ), + ), + ), + predicate>, + ); + +/** The same constructors are available on authoring contexts and as standalone functions. */ +export interface Operations { + readonly eq: typeof eq; + readonly ne: typeof ne; + readonly and: typeof and; + readonly or: typeof or; + readonly not: typeof not; + readonly isTrue: typeof isTrue; + readonly isFalse: typeof isFalse; + readonly isNone: typeof isNone; +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts b/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts new file mode 100644 index 00000000000..e93730e3ef6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts @@ -0,0 +1,194 @@ +/** + * A small default set of declarations for expression construction. + * + * Export types derive from the bound declarations, without a second list of semantic annotations. Generated declarations can supply the same module, type and value tables to Draft.withPrelude. This default includes primitive types, List, Dict, UUID identities, equality and addition. It is not a complete standard-library binding. + * + * Draft's `program` constructs with {@link builtin}. This module also re-exports the semantic types of the declarations, such as `Prelude.Uuid` and the `Prelude.Arithmetic` signature. + * + * @module + */ +import { Result, pipe } from "effect"; + +import * as Module from "./Module.js"; +import * as Scope from "./Scope.js"; +import * as Structural from "./Structural.js"; + +import type * as Type from "../Type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Inputs from "./Inputs.js"; +import type * as Semantic from "./PreludeTypes.js"; +import type * as TypeExpression from "./TypeExpression.js"; + +export type * from "./PreludeTypes.js"; + +type TypeDeclaration = Module.Declaration< + TypeExpression.TypeExpression +>; +type ValueDeclaration = Module.Declaration< + Expression.Expression +>; + +// Explicit declaration annotations let isolated declaration emit retain the inferred module exports. +const primitiveDeclarations: { + readonly types: { + readonly Integer: TypeDeclaration; + readonly Number: TypeDeclaration; + readonly String: TypeDeclaration; + readonly Boolean: TypeDeclaration; + readonly Null: TypeDeclaration; + readonly Unknown: TypeDeclaration; + readonly Never: TypeDeclaration; + readonly List: Module.Declaration< + TypeExpression.Constructor + >; + readonly Dict: Module.Declaration< + TypeExpression.Constructor + >; + }; +} = { + types: { + Integer: Module.type(), + Number: Module.type(), + String: Module.type(), + Boolean: Module.type(), + Null: Module.type(), + Unknown: Module.type(), + Never: Module.type(), + List: Module.genericType(1), + Dict: Module.genericType(2), + }, +}; +const uuidDeclarations: { + readonly types: { readonly Uuid: TypeDeclaration }; + readonly values: { + readonly Uuid: ValueDeclaration< + Type.Function + >; + }; +} = { types: { Uuid: Module.type() }, values: { Uuid: Module.value() } }; +const entityDeclarations: { + readonly types: { readonly EntityUuid: TypeDeclaration }; + readonly values: { + readonly EntityUuid: ValueDeclaration< + Type.Function + >; + }; +} = { + types: { EntityUuid: Module.type() }, + values: { EntityUuid: Module.value() }, +}; +const comparisonDeclarations: { + readonly values: { + readonly eq: ValueDeclaration>; + }; +} = { values: { eq: Module.value() } }; +const arithmeticDeclarations: { + readonly values: { + readonly add: ValueDeclaration>; + }; +} = { values: { add: Module.value() } }; + +const primitives: Module.Module = pipe( + Module.define("::kernel::type", primitiveDeclarations), + Result.getOrThrow, +); +const uuid: Module.Module = pipe( + Module.define("::core::uuid", uuidDeclarations), + Result.getOrThrow, +); +const entity: Module.Module = pipe( + Module.define("::graph::types::knowledge::entity", entityDeclarations), + Result.getOrThrow, +); +const cmp: Module.Module = pipe( + Module.define("::core::cmp", comparisonDeclarations), + Result.getOrThrow, +); +const math: Module.Module = pipe( + Module.define("::core::math", arithmeticDeclarations), + Result.getOrThrow, +); + +/** + * The scope type of {@link builtin}. + * + * It derives the export types from the declaration tables without repeating their semantic annotations. + */ +export type Builtin = Scope.From<{ + readonly modules: { + readonly entity: typeof entity; + readonly uuid: typeof uuid; + readonly cmp: typeof cmp; + readonly math: typeof math; + }; + readonly types: Omit & { + readonly List: Structural.Constructor; + readonly Dict: Structural.Constructor; + } & typeof uuid.types & + typeof entity.types; + readonly values: typeof uuid.values & + typeof entity.values & + typeof cmp.values & + typeof math.values; +}>; + +/** + * The built-in declarations as module, type and value tables. + * + * - `types` holds `Integer`, `Number`, `String`, `Boolean`, `Null`, `Unknown`, `Never` and the generic `List` and `Dict`, all under `::kernel::type`. It also holds `Uuid` at `::core::uuid::Uuid` and `EntityUuid` at `::graph::types::knowledge::entity::EntityUuid`. + * - `values` holds the constructors `Uuid` and `EntityUuid` at the same paths as their types, `eq` at `::core::cmp::eq` and `add` at `::core::math::add`. + * - `modules` holds `uuid` at `::core::uuid`, `entity` at `::graph::types::knowledge::entity`, `cmp` at `::core::cmp` and `math` at `::core::math`. The `::kernel::type` module that declares the primitive types is not among them. + * + * `List` and `Dict` accept structural shorthand as well as type expressions, so `List(String)` and `List(Prelude.builtin.types.String)` emit the same type. `eq` accepts operands of any two types, which need not match. `add` accepts Integer and Number operands, as `Prelude.Arithmetic` describes. The SDK takes these signatures on trust, and the HashQL compiler checks the emitted calls. + * + * Draft's `program` constructs with these declarations, and its `$.prelude()` joins the three tables into one object. There `Uuid` is both the type and its constructor, and the module `cmp` exposes `eq` directly. + * + * @example Use built-in types and functions outside a program callback. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { Result } from "effect"; + * + * const { types, values } = Prelude.builtin; + * const compile = (value: Expression.AnyValue): string => + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(value))); + * + * assert.equal( + * compile(Expression.input("names", types.List(String))), + * '["::kernel::special_form::input","names","::kernel::type::List<::kernel::type::String>"]', + * ); + * assert.equal( + * compile(values.add(Expression.input("offset", types.Integer), 1n)), + * '["::core::math::add",["::kernel::special_form::input","offset","::kernel::type::Integer"],{"#literal":1}]', + * ); + * ``` + * + * @example Use one flattened name as a type and as a value constructor. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const nil = "00000000-0000-0000-0000-000000000000"; + * const result = program({ id: Prelude.builtin.types.Uuid }, ($) => { + * const { Uuid, cmp } = $.prelude(); + * return cmp.eq($.input("id", Uuid), Uuid(nil)); + * }); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Result.flatMap(result, Expression.toJExpr))), + * `["::core::cmp::eq",["::kernel::special_form::input","id","::core::uuid::Uuid"],["::core::uuid::Uuid",{"#literal":"${nil}"}]]`, + * ); + * ``` + */ +export const builtin: Builtin = Scope.merge(Scope.empty, { + modules: { entity, uuid, cmp, math }, + types: { + ...primitives.types, + List: Structural.constructor(primitives.types.List), + Dict: Structural.constructor(primitives.types.Dict), + ...uuid.types, + ...entity.types, + }, + values: { ...uuid.values, ...entity.values, ...cmp.values, ...math.values }, +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/PreludeTypes.ts b/libs/@local/hashql/sdk/typescript/src/Program/PreludeTypes.ts new file mode 100644 index 00000000000..96ccdbc2536 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/PreludeTypes.ts @@ -0,0 +1,64 @@ +/** + * Semantic operations used by the representative default declarations. + * + * Named identities use their absolute HashQL paths. Generic signatures inspect the semantic argument tuple supplied by the expression or type constructor, without widening it to a common element type. `Prelude` re-exports these types. + * + * @module + */ +import type * as Type from "../Type/index.js"; +import type { Conditional } from "./ExpressionType.js"; + +/** The UUID type, an opaque string named by its HashQL path. */ +export type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +/** The entity identifier type, an opaque wrapper around {@link Uuid}. */ +export type EntityUuid = Type.Opaque< + "::graph::types::knowledge::entity::EntityUuid", + Uuid +>; + +/** The operation of the built-in `List`, which maps one element type to a list type. */ +export interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : never; +} + +/** The operation of the built-in `Dict`, which maps a key type and a value type to a dictionary type. */ +export interface Dict extends Type.TypeConstructor { + readonly arity: 2; + readonly type: this["Target"] extends readonly [ + infer K extends Type.Any, + infer V extends Type.Any, + ] + ? Type.Dict + : never; +} + +/** + * The signature of the built-in `eq`, which compares two operands and returns Boolean. + * + * The operand types need not match. A call with any other number of arguments selects parameters that no argument satisfies. + */ +export interface Comparison extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [ + infer L extends Type.Any, + infer R extends Type.Any, + ] + ? Type.Function + : Type.Function; +} + +/** + * The signature of the built-in `add`. + * + * Each operand must be an Integer or a Number. The result is Integer when both operands are Integer, Number when both are Number, and the union of Integer and Number for one of each. Other operands select parameters that no argument satisfies, with a Never result. + */ +export interface Arithmetic extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [ + infer L extends Type.PrimitiveInteger | Type.PrimitiveNumber, + infer R extends Type.PrimitiveInteger | Type.PrimitiveNumber, + ] + ? Type.Function> + : Type.Function; +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts new file mode 100644 index 00000000000..5261a5fcc26 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts @@ -0,0 +1,191 @@ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module } from "../main.js"; +import * as Operators from "./Operators.js"; + +import type { Inputs, Type } from "../main.js"; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + Number: Module.type(), + Boolean: Module.type(), + }, + }), +); + +interface Identity extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.Function + : Type.Function; +} + +declare const hostNumber: number; +declare const optionalNumber: number | undefined; + +describe("primitive_types", () => { + test("host_numeric_types", () => { + expectTypeOf(Expression.literal(1)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(1.5)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(hostNumber)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(1n)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(true)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal("name")).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(null)).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("exact_operands", () => { + const integer = Expression.literal(1n); + const number = Expression.literal(1); + expectTypeOf(Operators.eq(integer, 2n)).toEqualTypeOf< + Operators.Predicate + >(); + Operators.eq(number, 2); + // @ts-expect-error A host number does not become Integer through its value. + Operators.eq(integer, 2); + // @ts-expect-error Integer does not implicitly widen to Number. + Operators.eq(number, 2n); + // @ts-expect-error Expression handles do not implicitly widen either. + Operators.eq(number, integer); + Operators.eq(number, Expression.assume()(integer)); + expectTypeOf(Expression.assume()(1n)).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error Boolean operations reject numeric truthiness. + Operators.and(Expression.literal(true), 1); + const id = Expression.fromJExpr< + Type.Opaque<"Id", Type.PrimitiveString>, + Inputs.Empty + >("id"); + // @ts-expect-error Strings do not stand in for nominal values. + Operators.eq(id, "id"); + }); +}); + +describe("primitive_arguments", () => { + test("fixed_and_generic", () => { + const identity = Expression.fromJExpr< + Type.GenericFunction, + Inputs.Empty + >("identity"); + expectTypeOf(identity(7)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(identity(7n)).toEqualTypeOf< + Expression.Expression + >(); + const fixed = Expression.fromJExpr< + Type.Function< + readonly [Type.PrimitiveNumber, Type.PrimitiveString], + Type.PrimitiveBoolean + >, + { readonly receiver: Type.PrimitiveBoolean } + >("fixed"); + const result = fixed(7, "literal"); + expectTypeOf>().toEqualTypeOf<{ + readonly receiver: Type.PrimitiveBoolean; + }>(); + // @ts-expect-error The exact parameter descriptor is Number, not Integer. + fixed(7n, "literal"); + // @ts-expect-error Primitive arguments do not disable arity checking. + fixed(7); + // @ts-expect-error Objects require explicit construction. + identity({ field: true }); + }); + + test("index_key", () => { + const list = Expression.fromJExpr< + Type.List, + Inputs.Empty + >("list"); + expectTypeOf(list.$index(0n)).toEqualTypeOf< + Expression.Expression< + Type.Union, + Inputs.Empty + > + >(); + // @ts-expect-error A list index requires Integer even when a number is integral. + list.$index(0); + const dict = Expression.fromJExpr< + Type.Dict, + Inputs.Empty + >("dict"); + const selected = dict.$index("key"); + expectTypeOf(selected).toEqualTypeOf< + Expression.Expression< + Type.Union, + Inputs.Empty + > + >(); + }); +}); + +describe("primitive_requirements", () => { + test("defaults_and_operations", () => { + const count = Expression.input("count", kernel.types.Integer, 1n); + const enabled = Expression.input("enabled", kernel.types.Boolean); + const result = Operators.or( + Operators.and(Operators.eq(count, 2n), enabled), + false, + ); + expectTypeOf>().toEqualTypeOf<{ + readonly count?: Type.PrimitiveInteger; + readonly enabled: Type.PrimitiveBoolean; + }>(); + const number = Expression.input("number", kernel.types.Number, 1); + expectTypeOf>().toEqualTypeOf<{ + readonly number?: Type.PrimitiveNumber; + }>(); + const uncertain = Expression.input( + "number", + kernel.types.Number, + optionalNumber, + ); + expectTypeOf>().toEqualTypeOf<{ + readonly number: Type.PrimitiveNumber; + }>(); + // @ts-expect-error Defaults retain the declared numeric distinction. + Expression.input("count", kernel.types.Integer, 1); + // @ts-expect-error A bigint default does not widen to Number. + Expression.input("number", kernel.types.Number, 1n); + }); + + test("conditional_branches", () => { + const count = Expression.input("count", kernel.types.Integer); + const expression = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a conditional branch + then: count, + else: 0n, + }); + expectTypeOf(expression).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveInteger, + { readonly count: Type.PrimitiveInteger } + > + >(); + const numeric = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a conditional branch + then: 1, + else: 2, + }); + expectTypeOf(numeric).toEqualTypeOf< + Expression.Expression + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts new file mode 100644 index 00000000000..035c12edf21 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts @@ -0,0 +1,102 @@ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, JExpr, Module } from "../main.js"; +import * as Operators from "./Operators.js"; + +import type { Inputs, Type } from "../main.js"; + +const compile = (value: Expression.AnyValue): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(value))); + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Number: Module.type() }, + }), +); + +describe("primitive_lowering", () => { + test.each([ + [1, '{"#literal":1}'], + [1n, '{"#literal":1}'], + [1.5, '{"#literal":1.5}'], + [9_007_199_254_740_993n, '{"#literal":9007199254740993}'], + ["identifier", '{"#literal":"identifier"}'], + [true, '{"#literal":true}'], + [null, '{"#literal":null}'], + ] as const)("literal: %s", (value, expected) => { + expect.hasAssertions(); + expect(compile(Expression.literal(value))).toBe(expected); + expect(compile(value)).toBe(expected); + }); + + test("function_and_index", () => { + expect.hasAssertions(); + const call = Expression.fromJExpr< + Type.Function< + readonly [Type.PrimitiveNumber, Type.PrimitiveString], + Type.PrimitiveBoolean + >, + Inputs.Empty + >("check"); + expect(compile(call(1, "name"))).toBe( + '["check",{"#literal":1},{"#literal":"name"}]', + ); + const list = Expression.fromJExpr< + Type.List, + Inputs.Empty + >("list"); + expect(compile(list.$index(0n))).toBe( + '["::kernel::special_form::index","list",{"#literal":0}]', + ); + }); + + test("default_and_boolean_operand", () => { + expect.hasAssertions(); + const number = Expression.input("number", kernel.types.Number, 1); + expect(compile(Operators.and(Operators.eq(number, 2), true))).toBe( + '["::core::bool::and",["::core::cmp::eq",["::kernel::special_form::input","number","::kernel::type::Number",{"#literal":1}],{"#literal":2}],{"#literal":true}]', + ); + }); +}); + +describe("primitive_failures", () => { + test.each([Number.NaN, Infinity, -Infinity])("nonfinite: %s", (value) => { + expect.hasAssertions(); + const number = Expression.input("number", kernel.types.Number); + for (const expression of [ + Expression.literal(value), + Operators.eq(number, value), + Expression.input("default", kernel.types.Number, value), + ]) { + const failure = Result.getOrThrow( + Result.flip(Expression.toJExpr(expression)), + ); + expect(failure.reason._tag).toBe("InvalidExpression"); + } + }); + + test("both_branches", () => { + expect.hasAssertions(); + const conditional = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a conditional branch + then: 1, + else: Number.NaN, + }); + const failure = Result.getOrThrow( + Result.flip(Expression.toJExpr(conditional)), + ); + expect(failure.reason._tag).toBe("InvalidExpression"); + }); + + test("assumption_preserves_syntax", () => { + expect.hasAssertions(); + const integer = Expression.literal(7n); + const number = Expression.assume()(integer); + expect(compile(number)).toBe('{"#literal":7}'); + expect(compile(integer)).toBe(compile(number)); + expect(compile(Expression.assume()(7n))).toBe( + compile(number), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts new file mode 100644 index 00000000000..9c959ed6018 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts @@ -0,0 +1,174 @@ +/** + * Recoverable failures while constructing a HashQL program. + * + * Each reason identifies a construction failure independently of its diagnostic wording. Parser failures retain their typed causes. {@link Construction} renders the human-readable message and provides constructors for failures shared by builders. + * + * @module + */ +import { Data } from "effect"; + +import type { Cause, Schema, SchemaIssue } from "effect"; + +interface NameFailure { + readonly name: string; + readonly cause: SchemaIssue.Issue; +} + +/** + * A structured explanation of a construction failure, selected by `_tag`. + * + * Name and syntax failures retain their parser cause. `CallbackException` retains the original thrown value inside `Cause.UnknownError`. HashQL compiler diagnostics and query execution errors belong to later stages, outside this reason type. + */ +export type Reason = + | Data.TaggedEnum<{ + /** A declaration name is not a valid HashQL identifier. */ + InvalidBindingName: NameFailure; + /** An imported name or alias is not a valid HashQL identifier. */ + InvalidImportName: NameFailure; + /** A query callback parameter name is not a valid HashQL identifier. */ + InvalidParameterName: NameFailure; + /** A module export name is not a valid HashQL identifier. */ + InvalidExportName: NameFailure; + /** A module export table has a symbol key rather than a string name. */ + SymbolExportName: { readonly name: symbol }; + /** An explicit input schema has a symbol key rather than a string name. */ + SymbolInputName: { readonly name: symbol }; + /** A syntax value failed J-Expr schema validation. */ + InvalidExpression: { readonly cause: Schema.SchemaError }; + /** A synchronous authoring callback threw a host value. */ + CallbackException: { readonly cause: Cause.UnknownError }; + /** A module path failed path parsing. */ + InvalidModulePath: NameFailure; + /** A module declaration used a relative path instead of the required absolute path. */ + RelativeModulePath: { readonly name: string }; + /** A generic type's declared arity is not a nonnegative safe integer. */ + InvalidTypeArity: { readonly arity: number }; + /** A type application supplied a different number of arguments from its declared arity. */ + TypeArgumentCount: { + readonly expected: number; + readonly received: number; + }; + /** Structural shorthand received a host constructor outside BigInt, Number, String and Boolean. */ + UnsupportedTypeConstructor: { readonly name: string }; + }> + /** A generic type constructor lacks its type arguments. */ + | { readonly _tag: "UnspecializedTypeConstructor" } + /** An authoring body returned something other than an expression handle. */ + | { readonly _tag: "InvalidBodyResult" }; + +/** Constructors and matching helpers for the tagged {@link Reason} variants. */ +export const Reason: Data.TaggedEnum.Constructor = + Data.taggedEnum(); + +const ConstructionBase: ReturnType< + typeof Data.TaggedError<"ProgramConstructionError"> +> = Data.TaggedError("ProgramConstructionError"); + +/** + * Failure to construct a program from declarations or expressions. + * + * Inspect `reason._tag` for handling and `message` for display. A builder returns this error in a Result, either directly or through later syntax extraction. Error constructors create values without throwing them. + * + * @example Handle an invalid numeric literal. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression } from "@local/hashql"; + * import { Result } from "effect"; + * + * const syntax = Expression.toJExpr(Expression.number(Number.NaN)); + * assert.ok(Result.isFailure(syntax)); + * assert.equal(syntax.failure.reason._tag, "InvalidExpression"); + * ``` + */ +export class Construction extends ConstructionBase<{ + readonly reason: Reason; +}> { + /** Retains the invalid declaration name and its parser issue. */ + static invalidBindingName( + name: string, + cause: SchemaIssue.Issue, + ): Construction { + return new Construction({ + reason: Reason.InvalidBindingName({ name, cause }), + }); + } + + /** Identifies an unsupported symbol key in a module's export table. */ + static symbolExportName(name: symbol): Construction { + return new Construction({ reason: Reason.SymbolExportName({ name }) }); + } + + /** Identifies an unsupported symbol key in an explicit input schema. */ + static symbolInputName(name: symbol): Construction { + return new Construction({ reason: Reason.SymbolInputName({ name }) }); + } + + /** Retains an arity outside the nonnegative safe-integer range. */ + static invalidTypeArity(arity: number): Construction { + return new Construction({ reason: Reason.InvalidTypeArity({ arity }) }); + } + + /** Records declared arity and the number of type arguments supplied. */ + static typeArgumentCount(expected: number, received: number): Construction { + return new Construction({ + reason: Reason.TypeArgumentCount({ expected, received }), + }); + } + + /** Identifies a host constructor not supported by structural type shorthand. */ + static unsupportedTypeConstructor(name: string): Construction { + return new Construction({ + reason: Reason.UnsupportedTypeConstructor({ name }), + }); + } + + /** Reports a generic type constructor used before specialization. */ + static unspecializedTypeConstructor(): Construction { + return new Construction({ reason: Reason.UnspecializedTypeConstructor() }); + } + + /** Reports a body result that is not an expression handle. */ + static invalidBodyResult(): Construction { + return new Construction({ reason: Reason.InvalidBodyResult() }); + } + + /** Retains a synchronous callback exception without replacing its original cause. */ + static callbackException(cause: Cause.UnknownError): Construction { + return new Construction({ reason: Reason.CallbackException({ cause }) }); + } + + /** Human-readable rendering of the reason. Use the reason's tag rather than this wording for programmatic handling. */ + override get message(): string { + return Reason.$match(this.reason, { + InvalidBindingName: ({ name }) => + `Invalid HashQL binding name: ${JSON.stringify(name)}`, + InvalidImportName: ({ name }) => + `Invalid HashQL import name: ${JSON.stringify(name)}`, + InvalidParameterName: ({ name }) => + `Invalid HashQL parameter name: ${JSON.stringify(name)}`, + InvalidExportName: ({ name }) => + `Invalid HashQL export name: ${JSON.stringify(name)}`, + SymbolExportName: ({ name }) => + `A HashQL export needs a string name, received ${String(name)}`, + SymbolInputName: ({ name }) => + `A HashQL input needs a string name, received ${String(name)}`, + InvalidExpression: () => + "The expression does not have valid J-Expr structure", + CallbackException: () => "A program callback threw an exception", + InvalidModulePath: ({ name }) => + `Invalid HashQL module path: ${JSON.stringify(name)}`, + RelativeModulePath: ({ name }) => + `A module declaration needs an absolute HashQL path: ${JSON.stringify(name)}`, + InvalidTypeArity: ({ arity }) => + `A type constructor needs a nonnegative safe integer arity, received ${arity}`, + TypeArgumentCount: ({ expected, received }) => + `Expected ${expected} type arguments, received ${received}`, + UnsupportedTypeConstructor: ({ name }) => + `Unsupported primitive type constructor: ${JSON.stringify(name)}`, + UnspecializedTypeConstructor: () => + "A generic type must be specialized before use", + InvalidBodyResult: () => + "An expression callback must return a HashQL expression", + }); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Query.ts b/libs/@local/hashql/sdk/typescript/src/Program/Query.ts new file mode 100644 index 00000000000..e530e4670fd --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Query.ts @@ -0,0 +1,32 @@ +/** + * The graph-producing function that query construction recognizes. + * + * Draft exposes `$.query.entities` when its prelude's values contain an `entities` function returning the recognized graph descriptor. The graph marker carries the vertex type through filtering and collection. + * + * @module + */ +import type * as Type from "../Type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Inputs from "./Inputs.js"; +import type * as Scope from "./Scope.js"; + +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +/** Reads the declared `entities` function's arguments, result, requirements and graph vertex, or resolves to `never` when its descriptor does not match. */ +export type EntityFunction = S["values"] extends { + readonly entities: infer E extends Expression.Any; +} + ? Expression.TypeOf extends Type.Function + ? R extends Graph + ? { + readonly args: A; + readonly returns: R; + readonly vertex: V; + readonly inputs: Inputs.Conservative>; + } + : never + : never + : never; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts b/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts new file mode 100644 index 00000000000..82d7f528deb --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts @@ -0,0 +1,135 @@ +/** + * Immutable tables of module, type and value exports. + * + * Missing namespace tables introduce no names. Optional tables contribute optional names instead of an arbitrary string index. Merging retains an earlier export when its replacement is optional, and snapshots include non-enumerable own exports without freezing the caller's records. + * + * A scope holds the names a construction callback can reach, which Draft's prelude supplies. Draft's `$.prelude()` joins the tables into one object in which a name can hold a module, a type and a value at once. + * + * @module + */ +import type * as Expression from "./Expression.js"; +import type * as Module from "./Module.js"; +import type * as TypeExpression from "./TypeExpression.js"; +import type { ReadonlyRecord } from "effect/Record"; + +/** A table of exports by name, in which an optional name can be absent. */ +interface Universe extends ReadonlyRecord {} + +/** The module, value and type tables of a construction scope. */ +export interface Scope { + /** Modules by local name, the starting points for imports and qualified references. */ + readonly modules: Universe; + /** Value expressions by name. */ + readonly values: Universe; + /** Type expressions and generic type constructors by name. */ + readonly types: Universe; +} + +/** + * Tables that supply a scope, such as a prelude. + * + * Each table is optional. A module record, the record `Module.root` returns and `Prelude.builtin` all fit. + */ +export interface Definition { + readonly modules?: Scope["modules"]; + readonly values?: Scope["values"]; + readonly types?: Scope["types"]; +} + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty namespace has no names +type EmptyNames = Record; + +/** The names one table of a definition contributes: none when omitted, optional when the table is optional. */ +type Names = K extends keyof D + ? undefined extends D[K] + ? Partial> + : NonNullable + : EmptyNames; + +/** The scope a definition supplies, with an empty table for each omitted one and optional names for each optional one. */ +export interface From { + readonly modules: Names; + readonly values: Names; + readonly types: Names; +} + +/** A scope with no names. */ +export type Empty = From; + +type RequiredKeys = { + [K in keyof S]-?: EmptyNames extends Pick ? never : K; +}[keyof S]; +type At = K extends keyof S ? S[K] : undefined; +type Overridden = K extends keyof A + ? K extends RequiredKeys + ? A[K] + : A[K] | At + : At; + +/** Optional replacements retain the earlier type as an alternative. */ +export type Extend = { + readonly [K in RequiredKeys | RequiredKeys]: Overridden; +} & { + readonly [K in Exclude< + keyof B | keyof A, + RequiredKeys | RequiredKeys + >]?: Overridden; +}; + +/** + * The scope that results from adding the names of `A` to `B`. + * + * In each table a name `A` guarantees replaces the earlier entry, and a name `A` declares as optional keeps the earlier entry as an alternative. + */ +export interface Merge { + readonly modules: Extend>; + readonly values: Extend>; + readonly types: Extend>; +} + +/** Copies own exports, including non-enumerable names, without freezing the caller's table. */ +export const snapshot = ( + entries: E, +): Readonly => { + const copy = { ...entries }; + + for (const name of Object.getOwnPropertyNames(entries)) { + Object.defineProperty(copy, name, { + value: entries[name], + enumerable: true, + }); + } + + return Object.freeze(copy); +}; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- combines separate namespaces rather than transforming the first argument +export const merge = ( + before: B, + added: A, +): Merge => { + const combined = Object.freeze({ + modules: Object.freeze({ + ...snapshot(before.modules), + ...snapshot(added.modules ?? {}), + }), + values: Object.freeze({ + ...snapshot(before.values), + ...snapshot(added.values ?? {}), + }), + types: Object.freeze({ + ...snapshot(before.types), + ...snapshot(added.types ?? {}), + }), + }); + + // SAFETY: each namespace copies all own exports, replacing an earlier value only when the later table supplies that name. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- object spread cannot express per-key optional override alternatives + return combined as Merge; +}; + +export const empty: Empty = Object.freeze({ + modules: Object.freeze({}), + values: Object.freeze({}), + types: Object.freeze({}), +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Structural.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test-d.ts new file mode 100644 index 00000000000..69c52386fee --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test-d.ts @@ -0,0 +1,160 @@ +/** + * Type-level checks for structural descriptors and input requirements. + * + * The generic forwarder checks that normalization retains its caller's type parameter. Mixed tuples distinguish positional mapping from a union of element types. + * + * @module + */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import * as JExpr from "../JExpr/index.js"; +import * as Expression from "./Expression.js"; +import * as Structural from "./Structural.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../Type/index.js"; +import type * as Inputs from "./Inputs.js"; + +interface Dictionary extends Type.TypeConstructor { + readonly arity: 2; + readonly type: this["Target"] extends readonly [ + infer K extends Type.Any, + infer V extends Type.Any, + ] + ? Type.Dict + : Type.Never; +} + +const dictionary = Structural.constructor( + Result.getOrThrow( + TypeExpression.constructor( + Result.getOrThrow(JExpr.Path.decodeResult("::kernel::type::Dict")), + 2, + ), + ), +); + +const withStringKey = ( + definition: D, +): TypeExpression.TypeExpression< + Type.Dict> +> => dictionary(String, definition); + +type Row = Type.Struct<{ readonly count: Type.PrimitiveInteger }>; + +const hostChoice = ( + flag: boolean, +): + | { + readonly count: Expression.Expression< + Type.PrimitiveInteger, + { readonly count: Type.PrimitiveInteger } + >; + } + | { + readonly count: Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty + >; + } => { + const count = Expression.input("count", Structural.type(BigInt)); + if (flag) { + return { count }; + } + return { count: Expression.integer(0) }; +}; + +describe("structural_constructor_types", () => { + test("argument_positions", () => { + expectTypeOf(dictionary(String, { count: BigInt })).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveString, + Type.Struct<{ readonly count: Type.PrimitiveInteger }> + > + > + >(); + expectTypeOf(dictionary(Number, [Boolean, String])).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveNumber, + Type.Tuple + > + > + >(); + }); + + test("generic_forwarding", () => { + expectTypeOf(withStringKey(BigInt)).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict + > + >(); + expectTypeOf(withStringKey({ enabled: Boolean })).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveString, + Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }> + > + > + >(); + }); + + test("nominal_argument", () => { + const identity = Symbol("Item"); + const item = TypeExpression.reference< + Type.Opaque + >(Result.getOrThrow(JExpr.Path.decodeResult("Item"))); + expectTypeOf(dictionary(String, item)).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveString, + Type.Opaque + > + > + >(); + }); + + test("relocated_types", () => { + const local = Result.getOrThrow(JExpr.Path.decodeResult("Dictionary")); + const moved = Result.getOrThrow(TypeExpression.relocate(dictionary, local)); + expectTypeOf(moved).toEqualTypeOf(); + expectTypeOf(moved(String, { count: BigInt })).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + const identity = Symbol("Item"); + const item = + TypeExpression.reference< + Type.Opaque + >(local); + const alias = Result.getOrThrow(TypeExpression.relocate(item, local)); + expectTypeOf(alias).toEqualTypeOf(); + // @ts-expect-error Relocation preserves the constructor's arity. + moved(String); + }); + + test("structural_requirements", () => { + const result = Structural.value()(hostChoice(true)); + expectTypeOf(result).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error The host choice may contain a required input. + const closed: Expression.Expression = result; + expectTypeOf(closed).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error Number is not the Integer descriptor required by Row. + Structural.value()({ count: 1 }); + }); + + test("argument_rejections", () => { + expectTypeOf>().toBeNever(); + // @ts-expect-error Dict requires both a key type and a value type. + dictionary(String); + // @ts-expect-error Dict accepts exactly two arguments. + dictionary(String, Number, Boolean); + // @ts-expect-error Host values are not type definitions. + dictionary("key", Number); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Structural.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test.ts new file mode 100644 index 00000000000..e1df6bc9a37 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test.ts @@ -0,0 +1,131 @@ +/** + * Runtime checks for structural normalization and constructor metadata forwarding. + * + * @module + */ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../JExpr/index.js"; +import * as TypeSyntax from "../JExpr/Type/index.js"; +import * as Structural from "./Structural.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../Type/index.js"; + +interface Dictionary extends Type.TypeConstructor { + readonly arity: 2; + readonly type: this["Target"] extends readonly [ + infer K extends Type.Any, + infer V extends Type.Any, + ] + ? Type.Dict + : Type.Never; +} + +const path = Result.getOrThrow(JExpr.Path.decodeResult("::kernel::type::Dict")); +const declaration = Result.getOrThrow( + TypeExpression.constructor(path, 2), +); +const dictionary = Structural.constructor(declaration); + +const compile = (definition: TypeExpression.Any): string => + TypeSyntax.compile(Result.getOrThrow(TypeExpression.toType(definition))); + +describe("structural_constructor", () => { + test("mixed_arguments", () => { + expect.hasAssertions(); + expect(compile(dictionary(String, { count: BigInt }))).toBe( + "::kernel::type::Dict<::kernel::type::String, (count: ::kernel::type::Integer)>", + ); + }); + + test("forwarded_metadata", () => { + expect.hasAssertions(); + const forwarded = new Proxy(declaration, { ownKeys: (): string[] => [] }); + const adapted = Structural.constructor(forwarded); + expect(adapted).toSatisfy(TypeExpression.isConstructor); + expect(compile(adapted(String, Number))).toBe( + "::kernel::type::Dict<::kernel::type::String, ::kernel::type::Number>", + ); + }); + + test("relocated_constructor", () => { + expect.hasAssertions(); + const local = Result.getOrThrow(JExpr.Path.decodeResult("Dictionary")); + const moved = Result.getOrThrow(TypeExpression.relocate(dictionary, local)); + expect(compile(moved(String, { count: BigInt }))).toBe( + "Dictionary<::kernel::type::String, (count: ::kernel::type::Integer)>", + ); + const second = Result.getOrThrow( + TypeExpression.relocate( + moved, + Result.getOrThrow(JExpr.Path.decodeResult("Other")), + ), + ); + expect(compile(second(Boolean, Number))).toBe( + "Other<::kernel::type::Boolean, ::kernel::type::Number>", + ); + expect(compile(dictionary(String, Number))).toBe( + "::kernel::type::Dict<::kernel::type::String, ::kernel::type::Number>", + ); + }); + + test("relocated_failure", () => { + expect.hasAssertions(); + const invalid = Structural.type({ "": Number }); + expect(TypeExpression.relocate(invalid, path)).toStrictEqual( + invalid.syntax, + ); + }); + + test("invalid_nested_name", () => { + expect.hasAssertions(); + const result = dictionary(String, { "": BigInt }).syntax; + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidBindingName", name: "" } }, + }); + }); + + test("unspecialized_type", () => { + expect.hasAssertions(); + // @ts-expect-error An unapplied constructor is not a type definition. + const result = Structural.type(declaration).syntax; + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "UnspecializedTypeConstructor" }, + message: "A generic type must be specialized before use", + }, + }); + }); + + test("unsupported_constructor", () => { + expect.hasAssertions(); + // @ts-expect-error Date is outside the supported primitive shorthand. + const result = Structural.type(Date).syntax; + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "UnsupportedTypeConstructor", name: "Date" }, + message: 'Unsupported primitive type constructor: "Date"', + }, + }); + }); + + test("dynamic_arity", () => { + expect.hasAssertions(); + const dynamic = Structural.constructor( + Result.getOrThrow( + TypeExpression.constructor(path, 2), + ), + ); + expect(dynamic(String).syntax).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "TypeArgumentCount", expected: 2, received: 1 }, + }, + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Structural.ts b/libs/@local/hashql/sdk/typescript/src/Program/Structural.ts new file mode 100644 index 00000000000..0f4031b3a0c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/Structural.ts @@ -0,0 +1,441 @@ +/** + * Structural shorthand for HashQL types and values. + * + * {@link type} normalizes host constructors, tuples and records into type syntax. {@link value} accepts a structural value only when its semantic descriptor matches the requested type. Both operations retain nested type information, and value construction combines input requirements from every possible host-side alternative. + * + * @module + */ +import { + Array, + Predicate, + Record, + Result, + Struct, + Tuple, + flow, + pipe, +} from "effect"; + +import * as JExpr from "../JExpr/index.js"; +import * as Syntax from "../JExpr/Type/index.js"; +import * as Expression from "./Expression.js"; +import * as ProgramError from "./ProgramError.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type { Relocatable, Relocate } from "../internal/relocation.js"; +import type * as Type from "../Type/index.js"; +import type * as Input from "./Inputs.js"; +import type { ReadonlyRecord } from "effect/Record"; + +interface Fields extends ReadonlyRecord {} + +/** + * A type handle, a supported host primitive constructor, a tuple of definitions or a record of field definitions. + * + * `BigInt`, `Number`, `String` and `Boolean` denote their HashQL primitive types. Arrays denote tuples, not lists. Use a declared generic type constructor for lists and dictionaries. See {@link type} for normalization. + */ +export type Definition = + | TypeExpression.Any + | BigIntConstructor + | NumberConstructor + | StringConstructor + | BooleanConstructor + | readonly Definition[] + | Fields; + +/** + * Resolves shorthand to its semantic descriptor without widening its fields. + * + * This conditional distributes over host alternatives: a choice between two definitions retains both possible descriptors. Inputs outside the shorthand language resolve to `never`, allowing the same operation to serve Effect's type-level mapping functions. + */ +export type TypeOf = + D extends TypeExpression.TypeExpression + ? T + : D extends BigIntConstructor + ? Type.PrimitiveInteger + : D extends NumberConstructor + ? Type.PrimitiveNumber + : D extends StringConstructor + ? Type.PrimitiveString + : D extends BooleanConstructor + ? Type.PrimitiveBoolean + : D extends readonly Definition[] + ? { + readonly _tag: "Tuple"; + readonly fields: { readonly [K in keyof D]: TypeOf }; + } + : D extends Fields + ? Type.Struct<{ readonly [K in keyof D]: TypeOf }> + : never; + +type TupleValues = { + readonly [K in keyof T]: Value; +}; + +/** + * A value accepted for descriptor `T`, including recursive record and tuple shorthand. + * + * Nominal descriptors require a matching handle rather than their underlying host representation. Lists and dictionaries likewise require expressions. A host array always denotes a tuple. + */ +export type Value = + | Expression.Value + | (T extends Type.Struct + ? { readonly [K in keyof F]: Value } + : T extends Type.Tuple.Any + ? TupleValues + : never); + +interface FieldValues extends ReadonlyRecord {} + +/** Expressions and host primitives, recursively nested in tuples or field records. */ +export type AnyValue = Expression.AnyValue | readonly AnyValue[] | FieldValues; + +/** + * Retains the input requirements of every possible host value. + * + * A TypeScript union represents a host-side choice between values. Both arms may have the same HashQL type while carrying different inputs. Construction can choose either arm, so the resulting expression must require the inputs of both arms. Tuple and record recursion also includes inputs hidden inside structural values. + */ +export type Requirements = Input.Conservative< + RequirementAlternatives +>; + +type RequirementAlternatives = V extends Expression.AnyValue + ? Expression.Inputs + : V extends readonly [ + infer H extends AnyValue, + ...infer T extends readonly AnyValue[], + ] + ? Input.Conservative, Requirements>> + : V extends readonly (infer M extends AnyValue)[] + ? [M] extends [never] + ? Input.Empty + : Input.Conservative> + : V extends FieldValues + ? [keyof V] extends [never] + ? Input.Empty + : Input.Conservative<{ [K in keyof V]: Requirements }[keyof V]> + : Input.Empty; + +/** + * Recognizes recursive type shorthand without confusing primitive values with constructors. + * + * This dispatch check examines enumerable own string-keyed values and the SDK type marker. It does not validate field names or stored type syntax. Empty records and arrays qualify. Host objects must be acyclic. + */ +// oxlint-disable-next-line typescript/no-restricted-types -- overload dispatch must distinguish arbitrary host arguments before normalization +export const isDefinition = (value: unknown): value is Definition => { + if (TypeExpression.isExport(value)) { + return Predicate.hasProperty(value, "syntax"); + } + + if ( + value === BigInt || + value === String || + value === Number || + value === Boolean + ) { + return true; + } + + if (!Predicate.isObjectOrArray(value) || Predicate.isFunction(value)) { + return false; + } + + return Object.values(value).every(isDefinition); +}; + +/** + * Recognizes structural value arguments, including expressions with type capabilities too. + * + * This dispatch check traverses enumerable own string-keyed values without validating field names or stored syntax. Non-finite numbers pass this check too. Validation belongs to {@link value} or {@link toJExpr}. Host objects must be acyclic. + */ +// oxlint-disable-next-line typescript/no-restricted-types -- overload dispatch must distinguish arbitrary host arguments before normalization +export const isValue = (value: unknown): value is AnyValue => { + if (Expression.isExpression(value)) { + return true; + } + + if (TypeExpression.isExport(value)) { + return false; + } + + const type = typeof value; + if ( + value === null || + type === "string" || + type === "number" || + type === "bigint" || + type === "boolean" + ) { + return true; + } + + if (!Predicate.isObjectOrArray(value) || Predicate.isFunction(value)) { + return false; + } + + return Object.values(value).every(isValue); +}; + +const primitiveSyntax = ( + name: "Integer" | "Number" | "String" | "Boolean", +): Syntax.Type => + Syntax.Reference.make({ + path: JExpr.Path.decodeResult(`::kernel::type::${name}`).pipe( + Result.getOrThrow, + ), + generics: [], + }); + +const primitives = { + integer: primitiveSyntax("Integer"), + number: primitiveSyntax("Number"), + string: primitiveSyntax("String"), + boolean: primitiveSyntax("Boolean"), +}; + +const typeSyntax = ( + definition: Definition, +): Result.Result => { + if (TypeExpression.isExport(definition)) { + if (Predicate.hasProperty(definition, "syntax")) { + return definition.syntax; + } + + return Result.fail( + ProgramError.Construction.unspecializedTypeConstructor(), + ); + } + + if (Predicate.isFunction(definition)) { + switch (definition) { + case BigInt: { + return Result.succeed(primitives.integer); + } + case Number: { + return Result.succeed(primitives.number); + } + case String: { + return Result.succeed(primitives.string); + } + case Boolean: { + return Result.succeed(primitives.boolean); + } + default: { + return Result.fail( + ProgramError.Construction.unsupportedTypeConstructor(definition.name), + ); + } + } + } + + if (Array.isArray(definition)) { + return pipe( + definition, + Array.map(typeSyntax), + Result.all, + Result.map((members) => ({ + _tag: "Tuple", + members, + })), + ); + } + + return pipe( + definition, + Record.toEntries, + Array.map(([name, member]) => + Result.all({ + name: pipe( + JExpr.Ident.decodeResult(name), + Result.mapError((cause) => + ProgramError.Construction.invalidBindingName(name, cause), + ), + ), + member: typeSyntax(member), + }), + ), + Result.all, + Result.map((fields) => ({ + _tag: "Struct", + members: fields.map(({ name, member }) => [name, member] as const), + })), + ); +}; + +/** + * Constructs a type expression from primitive, tuple and record shorthand. + * + * The descriptor retains each tuple position and record field. Runtime records contribute enumerable own string keys. Invalid field names and failed nested type handles remain construction failures in the returned handle's `syntax` Result. The resulting type description provides no runtime validator for host values. + * + * @example Describe a record with a nested tuple. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Structural } from "@local/hashql"; + * import { Result } from "effect"; + * + * const account = Structural.type({ name: String, location: [Number, Number] }); + * const input = Expression.input("account", account); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(input))), + * '["::kernel::special_form::input","account",{"#struct":{"name":"::kernel::type::String","location":{"#tuple":["::kernel::type::Number","::kernel::type::Number"]}}}]', + * ); + * ``` + */ +export const type = ( + definition: D, +): TypeExpression.TypeExpression> => + pipe(definition, typeSyntax, TypeExpression.fromResult>); + +/** Applies normalization independently at every position instead of collapsing the tuple to an element union. */ +interface Normalize extends Struct.Lambda { + readonly "~lambda.out": TypeExpression.TypeExpression< + TypeOf + >; + + ( + definition: D, + ): TypeExpression.TypeExpression>; +} + +const normalize = Tuple.map(Struct.lambda(type)); + +type ArgumentTypes = { + readonly [K in keyof A]: TypeOf; +}; + +/** A named generic type accepting the same shorthand as a local alias. */ +export interface Constructor + extends TypeExpression.AnyConstructor { + readonly [Relocate]: Relocatable>[typeof Relocate]; + + ( + ...definitions: A & { readonly length: F["arity"] } + ): TypeExpression.TypeExpression>>; +} + +/** + * Adapts a generic type declaration to accept {@link Definition} shorthand at each argument position. + * + * The original constructor still checks arity and retains failed type arguments. Relocation rebuilds the adapter around the new declaration path. Apply the returned constructor before using it as a type. + */ +export const constructor = ( + declaration: TypeExpression.Constructor, +): Constructor => + TypeExpression.adaptConstructor( + declaration, + (source) => + ( + ...definitions: A & { readonly length: F["arity"] } + ): TypeExpression.TypeExpression>> => + source>(...normalize(definitions)), + ); + +const valueSyntax = ( + value: AnyValue, +): Result.Result => { + if ( + Expression.isExpression(value) || + value === null || + typeof value !== "object" + ) { + return Expression.toJExpr(value); + } + + if (Array.isArray(value)) { + return pipe( + value, + Array.map(valueSyntax), + Result.all, + Result.map((members) => JExpr.tuple(...members)), + ); + } + + return pipe( + value, + Record.toEntries, + Array.map(([name, member]) => + pipe( + member, + valueSyntax, + Result.map((syntax) => [name, syntax] as const), + ), + ), + Result.all, + Result.map(flow(Record.fromEntries, JExpr.struct)), + ); +}; + +type ValueTypes = { + readonly [K in keyof V]: ValueType; +}; + +/** The semantic descriptor of a structural host value, without implicit widening. */ +export type ValueType = V extends Expression.AnyValue + ? Expression.TypeOf + : V extends readonly AnyValue[] + ? { + readonly _tag: "Tuple"; + readonly fields: ValueTypes; + } + : V extends FieldValues + ? Type.Struct<{ readonly [K in keyof V]: ValueType }> + : never; + +/** Accepts `V` only when its inferred structural descriptor and `T` are mutually assignable, preventing extra fields from disappearing from the reported type. */ +export type Exact = [T] extends [ + ValueType, +] + ? [ValueType] extends [T] + ? V + : never + : never; + +/** + * Constructs a value whose inferred structural descriptor matches the requested type. + * + * Supply the semantic descriptor first, then a value with matching fields and tuple positions. This exactness is a TypeScript constraint, not runtime semantic validation. Syntax validation returns failures through the resulting expression. Every nested expression contributes input requirements, including every alternative of a host-side union. + * + * Arrays encode tuples. Records encode enumerable own string keys; inherited, non-enumerable and symbol properties are not emitted. Host objects must be acyclic. + * + * @example Construct a typed record from host values. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Structural } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * type Account = Type.Struct<{ + * readonly name: Type.PrimitiveString; + * readonly active: Type.PrimitiveBoolean; + * }>; + * const account = Structural.value()({ name: "Ada", active: true }); + * assert.deepEqual(Result.getOrThrow(Expression.toJExpr(account)), { + * "#struct": { name: { "#literal": "Ada" }, active: { "#literal": true } }, + * }); + * ``` + */ +export const value = + () => + & AnyValue>( + input: V & Exact, + ): Expression.Expression> => + pipe( + input, + valueSyntax, + Result.flatMap(flow(Expression.fromJExpr, Expression.toNode)), + Expression.fromResult>, + ); + +/** + * Converts structural host values to validated J-Expr syntax without assigning a semantic descriptor. + * + * Arrays encode tuples and records encode enumerable own string keys, as in {@link value}. Invalid nested syntax returns a construction failure. Existing handles contribute their stored failures unchanged. Use {@link value} when the result needs a typed expression handle. + */ +export const toJExpr = ( + value: AnyValue, +): Result.Result => + pipe( + value, + valueSyntax, + Result.flatMap(flow(Expression.fromJExpr, Expression.toJExpr)), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts b/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts new file mode 100644 index 00000000000..88e24948667 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts @@ -0,0 +1,272 @@ +/** + * Type syntax annotated with its HashQL semantic meaning. + * + * A {@link TypeExpression} carries syntax or a construction failure alongside a type-level descriptor. A {@link Constructor} specializes a named generic type while preserving its semantic argument tuple. Declarations supply these descriptors, and the HashQL compiler validates their use in the emitted program. + * + * Type expressions come from module declarations, the built-in prelude, structural shorthand and Draft's type aliases. They appear wherever a program names a type, such as the type of an input. The operations here that annotate syntax or a path, {@link fromResult}, {@link fromType}, {@link reference} and {@link constructor}, attach the descriptor without checking it. + * + * A failed construction stays inside the type expression. It surfaces when a caller reads the syntax, either directly or through an expression or program that uses the type. + * + * @module + */ +import { Predicate, Result, identity, pipe } from "effect"; +import { dual } from "effect/Function"; + +import { + Relocate, + relocate as relocateHandle, +} from "../internal/relocation.js"; +import * as ProgramError from "./ProgramError.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type * as JExpr from "../JExpr/index.js"; +import type * as Syntax from "../JExpr/Type/index.js"; +import type * as Type from "../Type/index.js"; +import type { Types } from "effect"; + +const TypeId: unique symbol = Symbol("~hashql/TypeExpression"); +const ConstructorId: unique symbol = Symbol("~hashql/TypeConstructor"); + +/** A type expression with its semantic descriptor erased, for syntax-only operations. */ +export interface Any extends Relocatable { + /** The type syntax this handle emits, or the construction failure that prevented it. */ + readonly syntax: Result.Result; + readonly [TypeId]: Types.Covariant; +} + +/** Type syntax or its construction failure, annotated with its semantic type. */ +export interface TypeExpression extends Any { + readonly [TypeId]: Types.Covariant; + readonly [Relocate]: Relocatable>[typeof Relocate]; +} + +/** A generic type export with its parameterization erased. */ +export interface AnyConstructor extends Relocatable { + readonly [ConstructorId]: { + readonly path: JExpr.Path.Path; + readonly arity: number; + }; +} + +/** Maps each argument descriptor to the type expression accepted at that position. */ +type Arguments = { + readonly [K in keyof A]: TypeExpression; +}; + +/** + * A named generic type, specialized by supplying typed type expressions. + * + * The argument tuple carries semantic types, and `Arguments` maps each position to its handle. TypeScript infers the tuple from ordinary calls. A generic caller can also supply it explicitly without extracting and re-inferring types from already-normalized handles. + * + * A call emits a reference to the constructor's path with one generic argument per supplied type. The result's descriptor is `Type.Apply`. TypeScript rejects a call with the wrong number of arguments. At runtime, such a call returns a type expression holding a `TypeArgumentCount` failure. An argument's construction failure becomes the result's failure. + */ +export interface Constructor< + F extends Type.TypeConstructor, +> extends AnyConstructor { + readonly [Relocate]: Relocatable>[typeof Relocate]; + + ( + ...args: Arguments & { readonly length: F["arity"] } + ): TypeExpression>; +} + +/** An entry of a type namespace: a concrete type expression or a generic type constructor. */ +export type Export = Any | AnyConstructor; + +/** + * Recognizes concrete type expressions and generic type constructors. + * + * The guard checks for the SDK's marker properties and does not check a semantic descriptor. A joined namespace name that includes a type also passes. + */ +// oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries +export const isExport = (value: unknown): value is Export => + Predicate.hasProperty(value, TypeId) || + Predicate.hasProperty(value, ConstructorId); + +/** Recognizes generic type constructors by their marker property, including combined namespace handles. */ +// oxlint-disable-next-line typescript/no-restricted-types -- the guard accepts unchecked host values +export const isConstructor = (value: unknown): value is AnyConstructor => + Predicate.hasProperty(value, ConstructorId); + +/** + * Annotates type syntax, or a construction failure, with a trusted semantic descriptor. + * + * The caller must ensure that successful syntax denotes `T`. A failure stays in the handle until something reads its syntax. Rebinding a successful result produces a reference to the new path, while a failed result keeps its failure. + */ +export const fromResult = ( + syntax: Result.Result, +): TypeExpression => ({ + syntax, + [TypeId]: identity, + [Relocate]: (path) => + pipe( + syntax, + Result.map(() => + fromResult( + Result.succeed({ _tag: "Reference", path, generics: [] }), + ), + ), + ), +}); + +/** Reads the type syntax a type expression emits, or its construction failure. */ +export const toType = ( + type: Any, +): Result.Result => type.syntax; + +/** + * Annotates syntax supplied by a trusted type declaration. + * + * The caller must ensure that `syntax` denotes `T`, because the annotation performs no runtime type check. + */ +export const fromType = ( + syntax: Syntax.Type, +): TypeExpression => pipe(syntax, Result.succeed, fromResult); + +/** + * Binds a trusted semantic declaration to a named type reference. + * + * The result emits `path` as a type reference and carries the descriptor `T`. Nothing checks that the path exists or has that meaning. `Module.type` creates the same reference for a declared export. + */ +export const reference = ( + path: JExpr.Path.Path, +): TypeExpression => fromType({ _tag: "Reference", path, generics: [] }); + +/** + * Binds a trusted generic declaration to its named type reference. + * + * Runtime checking covers arity alone. The declaration supplies the relationship between the argument types and the resulting semantic type. + * + * An `arity` that is not a non-negative safe integer returns an `InvalidTypeArity` failure. The successful constructor checks the argument count of each call as {@link Constructor} describes. `Module.genericType` declares the same constructor for a module export. + * + * @example Specialize a generic type and inspect an arity failure. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude, TypeExpression } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * interface Pair extends Type.TypeConstructor { + * readonly arity: 2; + * readonly type: this["Target"] extends readonly [ + * infer L extends Type.Any, + * infer R extends Type.Any, + * ] + * ? Type.Tuple + * : Type.Never; + * } + * + * const path = Result.getOrThrow(JExpr.Path.decodeResult("::example::Pair")); + * const pair = Result.getOrThrow(TypeExpression.constructor(path, 2)); + * const { types } = Prelude.builtin; + * const entry = Expression.input("entry", pair(types.String, types.Integer)); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(entry))), + * '["::kernel::special_form::input","entry","::example::Pair<::kernel::type::String, ::kernel::type::Integer>"]', + * ); + * + * const invalid = TypeExpression.constructor(path, -1); + * assert.ok(Result.isFailure(invalid)); + * assert.equal(invalid.failure.reason._tag, "InvalidTypeArity"); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the reference under construction +export const constructor = ( + path: JExpr.Path.Path, + arity: F["arity"], +): Result.Result, ProgramError.Construction> => { + if (!Number.isSafeInteger(arity) || arity < 0) { + return Result.fail(ProgramError.Construction.invalidTypeArity(arity)); + } + + const instantiate = ( + ...args: Arguments & { readonly length: F["arity"] } + ): TypeExpression> => { + if (args.length !== arity) { + return pipe( + ProgramError.Construction.typeArgumentCount(arity, args.length), + Result.fail, + fromResult>, + ); + } + + return pipe( + args, + (arguments_) => arguments_.map(toType), + Result.all, + Result.map( + (arguments_): Syntax.Type => ({ + _tag: "Reference", + path, + generics: arguments_.map((bound) => ({ + _tag: "GenericArgument", + bound, + })), + }), + ), + fromResult>, + ); + }; + + return Result.succeed( + Object.assign(instantiate, { + [ConstructorId]: { path, arity }, + [Relocate]: (next: JExpr.Path.Path) => constructor(next, arity), + }), + ); +}; + +/** + * Rebinds a type reference or generic constructor while retaining its declared capabilities. + * + * Rebinding turns a concrete type expression into a plain reference to `path`, whatever syntax it emitted before, including a structural type. For a constructor it keeps the arity and emits applications at `path`. The result keeps the descriptor and leaves the original handle as it was. A type expression holding a construction failure returns that failure. Imports and `Module.relocate` use this operation to move each type export. It accepts the handle first or last. + */ +export const relocate: { + ( + path: JExpr.Path.Path, + ): ( + self: Export & Relocatable, + ) => Result.Result; + ( + self: Export & Relocatable, + path: JExpr.Path.Path, + ): Result.Result; +} = relocateHandle; + +/** An adapted callable retains both its signature and its rebinding operation. */ +type Adapted = C & + AnyConstructor & { + readonly [Relocate]: Relocatable>[typeof Relocate]; + }; + +/** + * Adapts a named constructor while retaining its argument normalization after rebinding. + * + * The adapter receives the rebound declaration each time. Retaining only the first callable would leave later calls pointing at the old path, so build calls from the adapter's argument rather than from a captured constructor. The result keeps the constructor marker, so {@link isConstructor} accepts it and namespaces treat it as a type export. Copying the marker explicitly supports forwarding proxies that do not enumerate it. The built-in `List` and `Dict` use this to accept structural shorthand. It accepts the constructor first or last. + */ +export const adaptConstructor: { + Any>( + adapt: (self: S) => C, + ): (self: S & Relocatable) => Adapted; + Any>( + self: S & Relocatable, + adapt: (self: S) => C, + ): Adapted; +} = dual( + 2, + Any>( + self: S & Relocatable, + adapt: (self: S) => C, + ): Adapted => { + const build = (source: S): Adapted => + Object.assign(adapt(source), { + [ConstructorId]: source[ConstructorId], + [Relocate]: ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe(relocateHandle(self, path), Result.map(build)), + }); + + return build(self); + }, +); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/index.ts b/libs/@local/hashql/sdk/typescript/src/Program/index.ts new file mode 100644 index 00000000000..5d7e3fa82a6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Program/index.ts @@ -0,0 +1,56 @@ +/** + * Shared completed programs and their J-Expr serialization. + * + * @module + */ +import { Result } from "effect"; + +import * as JExpr from "../JExpr/index.js"; +import * as Expression from "./Expression.js"; + +import type * as Type from "../Type/index.js"; +import type * as ProgramError from "./ProgramError.js"; + +/** + * A root expression ready for J-Expr serialization, carrying its result descriptor and input requirements. + * + * The wrapper does not establish that the expression constructed successfully or that the HashQL compiler accepts it. {@link compile} extracts syntax and returns any construction failure. Query execution is separate. + */ +export interface Program { + /** The expression whose syntax becomes the program, including its retained construction result. */ + readonly root: Expression.Expression; +} + +/** Extracts the semantic input record from a program's root, including optional requirements supplied by defaults. */ +export type Inputs

= P extends { readonly root: infer Root } + ? Expression.Inputs + : never; + +/** + * Wraps a root expression without validating or evaluating it. + * + * The constructor freezes the wrapper and retains the original handle. Its inferred result descriptor and inputs remain available through the {@link Program} type. See {@link compile} for serialization and failure handling. + */ +export const program = ( + root: Expression.Expression, +): Program => Object.freeze({ root }); + +/** + * Serializes a program to J-Expr JSON text, or returns its retained construction failure. + * + * This is syntax serialization, not HashQL compiler execution. It does not resolve names, check the program against a graph schema or execute a query. The J-Expr serializer preserves numeric literal source text. + * + * @example Serialize a completed expression for a HashQL consumer. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Program } from "@local/hashql"; + * import { Result } from "effect"; + * + * const program = Program.program(Expression.literal("hello")); + * assert.equal(Result.getOrThrow(Program.compile(program)), '{"#literal":"hello"}'); + * ``` + */ +export const compile = ( + self: Program, +): Result.Result => + Result.map(Expression.toJExpr(self.root), JExpr.compile); diff --git a/libs/@local/hashql/sdk/typescript/src/Type/index.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Type/index.test-d.ts new file mode 100644 index 00000000000..812ba4e89c4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Type/index.test-d.ts @@ -0,0 +1,187 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import type * as Type from "./index.js"; + +type User = Type.Struct<{ + readonly id: Type.Opaque<"UserId", Type.PrimitiveInteger>; + readonly names: Type.List; +}>; + +interface Recursive extends Type.Struct<{ + readonly children: Type.List; +}> {} + +const preserve = (value: T): T => value; +const inspect = (value: User): User => preserve(value); + +const children = (type: Type.All): readonly Type.All[] => { + switch (type._tag) { + case "Union": + case "Intersection": { + return type.types; + } + case "Opaque": { + return [type.type]; + } + case "Struct": { + return Object.values(type.fields); + } + case "Tuple": { + return type.fields; + } + case "Dict": { + return [type.key, type.value]; + } + case "List": { + return [type.element]; + } + case "Function": { + return [...type.parameters, type.returns]; + } + case "GenericFunction": + case "Integer": + case "Number": + case "String": + case "Boolean": + case "Null": + case "Never": + case "Unknown": { + return []; + } + default: { + expectTypeOf(type).toBeNever(); + return []; + } + } +}; + +describe("composite_types", () => { + test("generic_arguments", () => { + expectTypeOf().toEqualTypeOf<"UserId">(); + expectTypeOf< + User["fields"]["names"]["element"] + >().toEqualTypeOf(); + expectTypeOf< + Type.Dict["value"] + >().toEqualTypeOf(); + }); + + test("erased_constraint", () => { + expectTypeOf(inspect).returns.toEqualTypeOf(); + expectTypeOf().toExtend(); + expectTypeOf().not.toExtend(); + expectTypeOf>().not.toExtend(); + }); + + test("inspectable_forms", () => { + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); + expectTypeOf< + Type.Union + >().toExtend(); + expectTypeOf< + Type.Intersection< + readonly [User, Type.Struct<{ readonly age: Type.PrimitiveInteger }>] + > + >().toExtend(); + expectTypeOf< + Type.Opaque<"UserId", Type.PrimitiveInteger> + >().toExtend(); + expectTypeOf< + Type.Dict + >().toExtend(); + expectTypeOf>().toExtend(); + }); + + test("recursive_record", () => { + expectTypeOf().toExtend(); + expectTypeOf< + Recursive["fields"]["children"]["element"] + >().toEqualTypeOf(); + }); +}); + +describe("tuple_types", () => { + test("tuple_fixed", () => { + expectTypeOf["fields"]>().toEqualTypeOf< + readonly [] + >(); + expectTypeOf< + Type.Tuple< + readonly [Type.PrimitiveString, Type.PrimitiveInteger] + >["fields"] + >().toEqualTypeOf(); + expectTypeOf["fields"]>().toEqualTypeOf< + [Type.PrimitiveString] + >(); + expectTypeOf>().toExtend(); + expectTypeOf().toExtend(); + }); + + test("tuple_unbounded", () => { + expectTypeOf< + // @ts-expect-error An array has no fixed arity. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error A rest element has unbounded arity. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error A union containing an array has no fixed arity. + Type.Tuple + >(); + }); + + test("tuple_optional", () => { + expectTypeOf< + // @ts-expect-error Tuple elements must be present. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error A trailing optional element is not fixed-arity. + Type.Tuple + >(); + }); +}); + +describe("type_boundaries", () => { + test("raw_argument_rejection", () => { + expectTypeOf< + // @ts-expect-error Tuple fields are descriptors, not JavaScript value types. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error Struct fields must be descriptors. + Type.Struct<{ readonly age: number }> + >(); + expectTypeOf< + // @ts-expect-error Dictionary keys must be descriptors. + Type.Dict + >(); + expectTypeOf< + // @ts-expect-error The discriminant must name a supported type. + Type.List<{ readonly _tag: "Bogus" }> + >(); + }); + + test("primitive_payloads", () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toBeNull(); + expectTypeOf().toBeNever(); + expectTypeOf().toBeUnknown(); + }); + + test("opaque_names", () => { + expectTypeOf>().not.toExtend< + Type.Opaque<"PostId", Type.PrimitiveInteger> + >(); + }); + + test("discriminant_narrowing", () => { + expectTypeOf(children).returns.toEqualTypeOf(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/Type/index.ts b/libs/@local/hashql/sdk/typescript/src/Type/index.ts new file mode 100644 index 00000000000..ae530c84be4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/Type/index.ts @@ -0,0 +1,371 @@ +/** + * Compile-time descriptions of HashQL types. + * + * A descriptor is a TypeScript type that stands for a HashQL type, such as `Type.Struct<{ readonly name: Type.PrimitiveString }>`. Expressions and type expressions carry descriptors so that TypeScript can check calls, projections, indexing and input requirements while the SDK builds syntax. The package exports this module as types alone: no descriptor value exists at runtime, and nothing compares a descriptor with the HashQL declaration it annotates. Declarations such as `Module.value()` and `Module.type()` take the descriptor on trust, and the HashQL compiler still checks the emitted program. + * + * Type parameters accept descriptors rather than JavaScript value types, so TypeScript rejects `Type.List` and accepts `Type.List`. Use {@link Any} to constrain a generic without losing its concrete type arguments. Use {@link All} to inspect a type whose arguments are unknown and narrow it by `_tag`. Each generic type has corresponding `Any` and `All` forms. A descriptor with an erased child, such as `Type.List`, satisfies `Any` but not `All`. + * + * @example Type-only: describe a record and read its parts. + * ```ts + * import type { Type } from "@local/hashql"; + * + * type Equal = + * (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + * ? true + * : false; + * + * type User = Type.Struct<{ + * readonly id: Type.Opaque<"example::UserId", Type.PrimitiveInteger>; + * readonly names: Type.List; + * }>; + * + * export const elementIsString: Equal< + * User["fields"]["names"]["element"], + * Type.PrimitiveString + * > = true; + * export const idIsNominal: Equal< + * User["fields"]["id"]["name"], + * "example::UserId" + * > = true; + * ``` + * + * @module + */ + +import type { HKT } from "effect"; +import type { ReadonlyRecord } from "effect/Record"; + +/** A HashQL type with its parameters erased. */ +export interface Any { + readonly _tag: All["_tag"]; +} + +/** All supported type forms, with recursively inspectable children. */ +export type All = + | Union.All + | Intersection.All + | Opaque.All + | Struct.All + | Tuple.All + | Dict.All + | List.All + | Function.All + | GenericFunction.All + | Primitive + | Never + | Unknown; + +/** A type constraint with erased parameters. */ +type AnyType = Any; + +/** The union of inspectable type forms. */ +type AllTypes = All; + +/** A value belonging to at least one of the member types. */ +export interface Union { + readonly _tag: "Union"; + readonly types: T; +} + +export declare namespace Union { + /** A union with erased member parameters. */ + export type Any = Union; + /** A union whose members support discriminant narrowing. */ + export interface All extends Union {} +} + +/** A value satisfying every member type. */ +export interface Intersection { + readonly _tag: "Intersection"; + readonly types: T; +} + +export declare namespace Intersection { + /** An intersection with erased member parameters. */ + export type Any = Intersection; + /** An intersection whose members support discriminant narrowing. */ + export interface All extends Intersection {} +} + +/** + * A nominal type distinguished by its name and underlying type. + * + * TypeScript accepts an opaque descriptor only where both the name and the underlying type match. A parameter of type `Type.PrimitiveInteger` or `Type.Opaque<"PostId", Type.PrimitiveInteger>` rejects `Type.Opaque<"UserId", Type.PrimitiveInteger>`. Projections and indexing on an expression of an opaque type still reach the fields and elements of the underlying type. + * + * The name exists only in TypeScript. Emitted syntax names the declaration that introduced the type, such as `::core::uuid::Uuid`, rather than this name. Declarations that share a name and an underlying type are therefore interchangeable to TypeScript even when they emit different HashQL types. The built-in declarations use the absolute HashQL path as the name. Draft's newtype operation requires a `unique symbol`, which cannot coincide with a string name. + */ +export interface Opaque { + readonly _tag: "Opaque"; + /** The identity TypeScript compares, a string literal or a symbol type. */ + readonly name: Name; + /** The underlying representation. */ + readonly type: T; +} + +export declare namespace Opaque { + /** An opaque type with an erased name and underlying type parameters. */ + export type Any = Opaque; + /** An opaque type with an inspectable underlying type. */ + export interface All extends Opaque {} +} + +/** Field types with the concrete key set erased. */ +interface StructFields extends ReadonlyRecord {} + +/** A record with a type for each named field. */ +export interface Struct> { + readonly _tag: "Struct"; + readonly fields: T; +} + +export declare namespace Struct { + /** A struct with erased field names and type parameters. */ + export type Any = Struct>; + /** A struct whose field types support discriminant narrowing. */ + export interface All extends Struct> {} +} + +/** + * A fixed-length sequence with a type for each position. + * + * `T` must be a tuple of required elements. Arrays, optional elements and open-ended rest elements fail the constraint. `Tuple.Any` and `Tuple.All` erase the length for code that handles arbitrary tuple types. + */ +export interface Tuple< + T extends readonly Any[] & { + readonly length: number extends T["length"] ? never : number; + }, +> { + readonly _tag: "Tuple"; + readonly fields: T; +} + +export declare namespace Tuple { + /** A tuple with erased length and element type parameters. */ + export interface Any { + readonly _tag: "Tuple"; + readonly fields: readonly AnyType[]; + } + + /** A tuple whose element types support discriminant narrowing. */ + export interface All { + readonly _tag: "Tuple"; + readonly fields: readonly AllTypes[]; + } +} + +/** A dictionary with a common key type and value type. */ +export interface Dict { + readonly _tag: "Dict"; + readonly key: K; + readonly value: V; +} + +export declare namespace Dict { + /** A dictionary with erased key and value type parameters. */ + export type Any = Dict; + /** A dictionary with inspectable key and value types. */ + export interface All extends Dict {} +} + +/** A variable-length sequence with a common element type. */ +export interface List { + readonly _tag: "List"; + readonly element: T; +} + +export declare namespace List { + /** A list with erased element type parameters. */ + export type Any = List; + /** A list whose element type supports discriminant narrowing. */ + export interface All extends List {} +} + +/** A function with ordered parameters and a result type. */ +export interface Function< + Parameters extends readonly Any[], + Returns extends Any, +> { + readonly _tag: "Function"; + readonly parameters: Parameters; + readonly returns: Returns; +} + +export declare namespace Function { + /** A function with erased parameter and result types. */ + export interface Any { + readonly _tag: "Function"; + readonly parameters: readonly AnyType[]; + readonly returns: AnyType; + } + /** A function whose parameter and result types support discriminant narrowing. */ + export interface All extends Function {} +} + +/** + * A type-level operation whose input is a tuple of semantic types. + * + * An implementation reads its arguments from `this["Target"]` and computes the descriptor in `type`. This is Effect's `HKT.TypeLambda` encoding with the result constrained to a descriptor. {@link TypeConstructor} and {@link FunctionSignature} are the two kinds the SDK applies. + */ +export interface TypeLambda extends HKT.TypeLambda { + readonly type: Any; +} + +/** + * Computes the descriptor a {@link TypeLambda} produces for an argument tuple. + * + * TypeScript evaluates the operation during checking. The SDK has no runtime type interpreter, so the result is a static annotation on the syntax a call emits. + */ +export type Apply< + Lambda extends TypeLambda, + Arguments extends readonly Any[], +> = HKT.Kind; + +/** + * A generic type declaration with a fixed number of positional type arguments. + * + * Declare `arity` as a numeric literal. TypeScript checks that the arity argument to `Module.genericType` or `TypeExpression.constructor` equals that literal. A constructor call must supply exactly that many type arguments. The `type` member maps the argument descriptors in `this["Target"]` to the resulting type. + * + * @example Type-only: declare the result of a two-argument generic type. + * ```ts + * import type { Type } from "@local/hashql"; + * + * type Equal = + * (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + * ? true + * : false; + * + * interface Pair extends Type.TypeConstructor { + * readonly arity: 2; + * readonly type: this["Target"] extends readonly [ + * infer L extends Type.Any, + * infer R extends Type.Any, + * ] + * ? Type.Tuple + * : Type.Never; + * } + * + * export const applied: Equal< + * Type.Apply, + * Type.Tuple + * > = true; + * ``` + */ +export interface TypeConstructor extends TypeLambda { + /** The number of type arguments every application supplies. */ + readonly arity: number; +} + +/** + * Computes a function signature from the types of its call arguments. + * + * A call to an expression of type {@link GenericFunction} applies the signature to the descriptors of the actual arguments. TypeScript then checks each argument against the resulting `parameters` and types the call as `returns`. When the arguments do not fit the operation, return a function type whose parameters no argument satisfies, as the built-in signatures do with {@link Never}. + * + * @example Declare a generic function and call it. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Module } from "@local/hashql"; + * import type { Inputs, Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * interface First extends Type.FunctionSignature { + * readonly type: this["Target"] extends readonly [ + * infer L extends Type.Any, + * infer R extends Type.Any, + * ] + * ? Type.Function + * : Type.Function; + * } + * + * const pairs = Result.getOrThrow( + * Module.define("::example::pairs", { + * values: { first: Module.value>() }, + * }), + * ); + * const call: Expression.Expression = + * pairs.values.first("left", 1n); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(call))), + * '["::example::pairs::first",{"#literal":"left"},{"#literal":1}]', + * ); + * ``` + */ +export interface FunctionSignature extends TypeLambda { + readonly type: Function.Any; +} + +/** A function whose parameter and result types depend on its call arguments. */ +export interface GenericFunction { + readonly _tag: "GenericFunction"; + /** The operation that derives the signature of each call. */ + readonly signature: Signature; +} + +export declare namespace GenericFunction { + /** A generic function with its signature operation erased. */ + export type Any = GenericFunction; + /** A generic function, identical to {@link GenericFunction.Any} because its signature is an operation rather than an inspectable descriptor. */ + export interface All extends GenericFunction {} +} + +/** + * An arbitrary-precision integer. + * + * A `bigint` stands for this type in builder arguments. A JavaScript `number` stands for {@link PrimitiveNumber} even when its value is integral. + */ +export interface PrimitiveInteger { + readonly _tag: "Integer"; + readonly value: bigint; +} + +/** + * A number, including integer values. + * + * TypeScript does not widen {@link PrimitiveInteger} to this type, so a parameter of this type rejects an Integer expression or a `bigint`. + */ +export interface PrimitiveNumber { + readonly _tag: "Number"; + readonly value: number; +} + +/** A string value. */ +export interface PrimitiveString { + readonly _tag: "String"; + readonly value: string; +} + +/** A Boolean value. */ +export interface PrimitiveBoolean { + readonly _tag: "Boolean"; + readonly value: boolean; +} + +/** The null value. */ +export interface PrimitiveNull { + readonly _tag: "Null"; + readonly value: null; +} + +/** + * The primitive types. + * + * Each `value` member names the host JavaScript value type that builders accept in place of an expression of that type, such as `"text"` for {@link PrimitiveString} or `null` for {@link PrimitiveNull}. + */ +export type Primitive = + | PrimitiveInteger + | PrimitiveNumber + | PrimitiveString + | PrimitiveBoolean + | PrimitiveNull; + +/** The bottom type, which has no values. */ +export interface Never { + readonly _tag: "Never"; + readonly value: never; +} + +/** The top type, which includes every value. */ +export interface Unknown { + readonly _tag: "Unknown"; + // oxlint-disable-next-line typescript/no-restricted-types -- represents the HashQL top type + readonly value: unknown; +} diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts new file mode 100644 index 00000000000..3cc583e8633 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts @@ -0,0 +1,291 @@ +/** + * The explicit-input policy of a Draft program callback. + * + * Every operation that emits a value checks its requirements, including discarded let initializers and nested callback bodies. This policy belongs to the program boundary rather than Context: the constructor implementation can accept more values than a particular program permits. The result conservatively requires the entire supplied schema, including unused entries. + * + * @module + */ +import type * as Expression from "../Program/Expression.js"; +import type { ArgumentInputs, Arguments } from "../Program/ExpressionType.js"; +import type * as Input from "../Program/Inputs.js"; +import type * as Scope from "../Program/Scope.js"; +import type * as TypeExpression from "../Program/TypeExpression.js"; +import type * as Type from "../Type/index.js"; +import type * as Construction from "./Context.js"; +import type { ReadonlyRecord } from "effect/Record"; + +/** + * An input schema maps each program input's name to the input's type expression. + * + * Every own string key, including a non-enumerable one, becomes an input handle. A symbol key from an unchecked caller fails construction with `SymbolInputName` before the callback runs. + */ +export type Inputs = ReadonlyRecord; +type TypeInputs = { + readonly [K in keyof I]: I[K] extends TypeExpression.TypeExpression + ? T + : never; +}; +/** + * The input requirements of a program built from a schema, listing every entry as required with its semantic type. + * + * Entries the callback never uses, and entries whose every use supplies a default, remain required. A schema typed as a union of records requires the entries of every alternative, including an alternative with no entries. + * + * @example Type-only: a result keeps unused entries, and a discarded binding still needs its input declared. + * ```ts + * import { Expression, Prelude } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const { Integer } = Prelude.builtin.types; + * const schema = { limit: Integer, verbose: Prelude.builtin.types.Boolean }; + * const built = Result.getOrThrow(program(schema, ($, { limit }) => $.let("limit", limit))); + * type Whole = { + * readonly limit: Type.PrimitiveInteger; + * readonly verbose: Type.PrimitiveBoolean; + * }; + * const whole: Expression.Expression = built; + * // @ts-expect-error The unused `verbose` entry stays required. + * const partial: Expression.Expression> = built; + * + * const outside = Expression.input("outside", Integer); + * program({}, ($) => { + * // @ts-expect-error The schema does not declare `outside`. + * $.let("ignored", outside); + * return $.literal(true); + * }); + * ``` + */ +export type Requirements = Input.Conservative>; +/** The input handle for the schema key `K` with the type expression `D`, which references that input and requires `K`. */ +export type Handle = + D extends TypeExpression.TypeExpression + ? Expression.Expression>> + : never; +/** + * The frozen record a program callback receives as its second argument, holding one input handle per schema key. + * + * Each handle emits an input reference without a default at every use. + */ +export type Handles = { + readonly [K in keyof I]: Handle; +}; + +// oxlint-disable-next-line typescript/no-restricted-types -- distributes the check over host alternatives without erasing any input record +type Mismatches = I extends unknown + ? { + [K in keyof I]-?: K extends keyof S + ? [S[K]] extends [Exclude] + ? [Exclude] extends [S[K]] + ? never + : K + : K + : K; + }[keyof I] + : never; + +/** + * Accepts input requirements when the schema record `S` declares each of them with the same semantic type. + * + * It evaluates to `unknown`, which leaves an intersection unchanged, when every host-side alternative of the requirements fits. Otherwise it evaluates to `never`, which rejects the value it constrains. An input used with a default still needs a declaration. Erased requirements, such as those of `Expression.Any` or `Expression.Value`, never fit, because they cannot show which inputs they need. + */ +export type Check = [I] extends [never] + ? never + : [Mismatches>] extends [never] + ? // oxlint-disable-next-line typescript/no-restricted-types -- unknown is the identity of an accepted intersection constraint + unknown + : never; +type Accept = Check>; + +/** + * A graph query under construction in a program callback, whose arguments and predicates must fit the program's schema. + * + * The query is an expression of the graph type with `filter` and `collect`. Binding it with `let` produces a plain expression without those methods. + */ +type Query< + S extends Scope.Scope, + I, + T extends Type.Any, + V extends Type.Any, + R, +> = Expression.Expression & { + /** + * Adds a filter and constructs its predicate now, in its own declaration scope. + * + * `name` becomes the filter closure's parameter. `predicate` does not run when the query already carries a failure, or when `name` is not a valid HashQL identifier, which fails construction with `InvalidParameterName`. Otherwise `predicate` runs once, immediately, with a fresh restricted context and the vertex expression. The filter closure contains the declarations made through that context. The predicate returns a Boolean expression or host boolean whose input requirements fit the schema. An exception it throws becomes a `CallbackException` failure on the returned query. + */ + readonly filter: >( + name: string, + predicate: ( + $: Context, + vertex: Expression.Expression, + ) => P & Accept, + ) => Query>>; + /** Ends the query, emitting `::graph::tail::collect`, as a list of its vertices. */ + readonly collect: () => Expression.Expression, R>; +}; + +type EntityFunction = Construction.EntityFunction; +type QueryContext = [EntityFunction] extends [ + never, +] + ? // oxlint-disable-next-line typescript/no-generated-empty-object-type -- no graph declaration means no query entry point + Record + : { + /** Starts a graph query by calling the prelude's `entities` function, with arguments whose input requirements fit the schema. */ + readonly entities: < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, + >( + ...args: A & + Check["inputs"], ArgumentInputs>> + ) => Query< + S, + I, + EntityFunction["returns"], + EntityFunction["vertex"], + Input.Merge["inputs"], ArgumentInputs> + >; + }; + +/** + * The `$` argument of a program callback, which restricts the construction context to the program's input schema. + * + * `let`, `if` and `query` accept only values whose input requirements fit the schema, and branch and predicate callbacks receive the same restricted view. The other members are the unrestricted Draft `Context.Context` operations. The unrestricted constructor implements this view, but the view is not assignable to `Context.Context`, so a helper typed with the unrestricted context cannot receive a program's `$`. + */ +export interface Context extends Omit< + Construction.Context, + "let" | "if" | "query" +> { + /** + * Binds a value to a HashQL name and returns a reference to the binding. + * + * Draft emits the binding around this callback's returned expression, in call order with its other declarations, even when nothing refers to it. `value` is an expression or host primitive whose input requirements fit the schema, and the reference keeps its semantic type and requirements. An invalid name, or a value whose construction failed, does not interrupt the callback, but Draft records the failure and the program fails. The reference is the binding's bare name, so carrying it out of this callback leaves it without its binding. + */ + readonly let: ( + name: string, + value: E & Accept, + ) => Expression.Expression, Expression.Inputs>; + /** + * Graph query entry points, present when the prelude declares an `entities` function that returns a `::graph::Graph` opaque type. + * + * The function's result type determines the vertex type that filter predicates receive. Query arguments and predicate results must fit the schema. + * + * @example Filter a declared graph with a predicate-local binding. + * ```ts + * import assert from "node:assert/strict"; + * import { Module, Program } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { withPrelude } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * type Vertex = Type.Struct<{ readonly archived: Type.PrimitiveBoolean }>; + * type Graph = Type.Opaque<"::graph::Graph", Type.Struct<{ readonly "'marker": Vertex }>>; + * const graph = Result.getOrThrow( + * Module.define("::example::graph", { + * values: { entities: Module.value>() }, + * }), + * ); + * const { program } = withPrelude(graph); + * + * let predicates = 0; + * const live = program({}, ($) => + * $.query + * .entities() + * .filter("vertex", (predicate, vertex) => { + * predicates += 1; + * const archived = predicate.let("archived", vertex.archived); + * return predicate.isFalse(archived); + * }) + * .collect(), + * ); + * assert.equal(predicates, 1); + * assert.equal( + * Result.getOrThrow(Result.flatMap(live, (root) => Program.compile(Program.program(root)))), + * '["::graph::tail::collect",["::graph::body::filter",["::example::graph::entities"],["fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",["::kernel::special_form::let","archived",["::kernel::special_form::access","vertex","archived"],["::core::cmp::eq","archived",{"#literal":false}]]]]]', + * ); + * ``` + */ + readonly query: QueryContext; + /** + * Constructs a HashQL conditional from a Boolean condition and two branches. + * + * The condition and both branches must fit the schema, and the result combines their input requirements. HashQL decides the condition when the query runs, so construction always builds both branches. + * + * @example Construct both branches, one with a branch-local binding. + * ```ts + * import assert from "node:assert/strict"; + * import { Program } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const visited: string[] = []; + * const choice = program({}, ($) => + * $.if( + * false, + * (branch) => { + * visited.push("then"); + * return branch.let("inside", 1n); + * }, + * () => { + * visited.push("else"); + * return 2n; + * }, + * ), + * ); + * assert.deepEqual(visited, ["then", "else"]); + * assert.equal( + * Result.getOrThrow(Result.flatMap(choice, (root) => Program.compile(Program.program(root)))), + * '["::kernel::special_form::if",{"#literal":false},["::kernel::special_form::let","inside",{"#literal":1},"inside"],{"#literal":2}]', + * ); + * ``` + */ + readonly if: { + /** Uses values that already exist as the branches. No callback runs, and the branches get no declaration scope of their own. */ + < + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C & Accept, + branches: { + readonly then: T & Accept; + readonly else: E & Accept; + }, + ): Construction.Conditional; + /** + * Constructs each branch with a callback in its own declaration scope. + * + * Both callbacks run immediately, `then` first, whatever the condition's value. Each receives a fresh restricted context, and that branch contains the declarations made through it. Declarations made through a captured outer `$` belong to the outer callback instead. An exception thrown by a callback becomes a `CallbackException` failure on the returned expression and does not interrupt the enclosing callback. + */ + < + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C & Accept, + then: ($: Context) => T & Accept, + otherwise: ($: Context) => E & Accept, + ): Construction.Conditional; + }; +} + +/** + * The callback a Draft program runs with the restricted context and the input handles to obtain the root expression. + * + * The returned expression's input requirements must fit the schema. Returning anything other than an expression handle fails construction with `InvalidBodyResult`. The type rejects an asynchronous callback, and at runtime its promise fails construction the same way. + */ +export type Body< + S extends Scope.Scope, + I extends Inputs, + O extends Expression.AnyValue & Expression.Any, +> = ( + $: Context>, + inputs: Handles, +) => O & Check>, Expression.Inputs>; + +export type WithoutInputs< + S extends Scope.Scope, + I extends Inputs, + O extends Expression.AnyValue & Expression.Any, +> = ($: Context>) => ReturnType>; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts new file mode 100644 index 00000000000..c35cd981d3e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts @@ -0,0 +1,126 @@ +/** Type relationships across Draft construction and its explicit-input boundary. @module */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { + Expression, + JExpr, + Module, + Structural, + TypeExpression, +} from "../main.js"; +import * as Namespace from "../Program/Namespace.js"; +import * as Scope from "../Program/Scope.js"; +import * as Draft from "./index.js"; + +import type { Inputs, Type } from "../main.js"; +import type * as Context from "./Context.js"; + +const integer = Structural.type(BigInt); +const outside = Expression.input("outside", integer); +const unrestricted = ( + $: Context.Context, +): Expression.Expression => { + expectTypeOf($.let("outside", outside)).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveInteger, + { readonly outside: Type.PrimitiveInteger } + > + >(); + return $.literal(true); +}; +const optionalPrelude = (): { + readonly types?: { readonly Integer: typeof integer }; +} => ({ types: { Integer: integer } }); + +const optionalValue = (): { + readonly value?: Expression.Expression; +} => ({}); + +describe("construction_types", () => { + test("optional_override", () => { + const base = Scope.merge(Scope.empty, { + values: { value: Expression.integer(1) }, + }); + const merged = Scope.merge(base, { values: optionalValue() }); + expectTypeOf(merged.values.value).toEqualTypeOf< + | Expression.Expression + | Expression.Expression + | undefined + >(); + }); + + test("policy_separation", () => { + // @ts-expect-error an unrestricted helper can hide inputs in discarded declarations + Draft.withPrelude({}).program({}, unrestricted); + expectTypeOf(unrestricted); + }); + + test("optional_namespace", () => { + Draft.withPrelude(optionalPrelude()).program({}, ($) => { + expectTypeOf($.prelude().Integer).toEqualTypeOf< + typeof integer | undefined + >(); + expectTypeOf($.prelude()).not.toHaveProperty("Missing"); + return $.literal(true); + }); + }); + + test("nominal_rebinding", () => { + const identity = Symbol("Box"); + Draft.program({ outside: integer }, ($) => { + const Box = $.newtype("Box", identity, { value: BigInt }); + expectTypeOf>().toEqualTypeOf< + Type.Function< + readonly [Type.Struct<{ readonly value: Type.PrimitiveInteger }>], + Type.Opaque< + typeof identity, + Type.Struct<{ readonly value: Type.PrimitiveInteger }> + > + > + >(); + type Constructor = Type.Function< + readonly [Type.Struct<{ readonly value: Type.PrimitiveInteger }>], + Type.Opaque< + typeof identity, + Type.Struct<{ readonly value: Type.PrimitiveInteger }> + > + >; + const bound = $.let("constructor", Box); + expectTypeOf< + Expression.TypeOf + >().toEqualTypeOf(); + const pass = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("::test::pass"); + const passed = pass(Box); + expectTypeOf< + Expression.TypeOf + >().toEqualTypeOf(); + const module = Result.getOrThrow( + Module.define("::test", { types: { Box }, values: { Box } }), + ); + const names = Namespace.flatten(module); + const moved = Result.getOrThrow( + TypeExpression.relocate( + names.Box, + Result.getOrThrow(JExpr.Path.decodeResult("::local::Box")), + ), + ); + const value = moved({ value: outside }); + expectTypeOf>().toEqualTypeOf< + Type.Opaque< + typeof identity, + Type.Struct<{ readonly value: Type.PrimitiveInteger }> + > + >(); + expectTypeOf>().toEqualTypeOf<{ + readonly outside: Type.PrimitiveInteger; + }>(); + // @ts-expect-error rebinding must not widen nominal structure + moved({ value: "wrong" }); + return value; + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts new file mode 100644 index 00000000000..e19fed04232 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts @@ -0,0 +1,124 @@ +/** Boundary and rebinding checks for executed Draft construction. @module */ +import { Result, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { + Expression, + JExpr, + Module, + Structural, + TypeExpression, +} from "../main.js"; +import * as Namespace from "../Program/Namespace.js"; +import * as Draft from "./index.js"; + +const integer = Structural.type(BigInt); +const compile = (expression: Expression.Any): string => + pipe( + expression, + Expression.toJExpr, + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +describe("draft_construction", () => { + test("symbol_input", () => { + expect.hasAssertions(); + const key = Symbol("input"); + let visits = 0; + const result = Draft.program({ [key]: integer }, ($) => { + visits += 1; + return $.literal(true); + }); + expect(Result.getFailure(result)).toMatchObject({ + _tag: "Some", + value: { reason: { _tag: "SymbolInputName", name: key } }, + }); + expect(visits).toBe(0); + }); + + test("symbol_export", () => { + expect.hasAssertions(); + const name = Symbol("export"); + const { program } = Draft.withPrelude({ + values: { + // @ts-expect-error exercise a symbol export from an unchecked caller + [name]: Expression.integer(1), + }, + }); + let visits = 0; + const result = program({}, ($) => { + visits += 1; + return $.literal(true); + }); + expect(Result.getFailure(result)).toMatchObject({ + _tag: "Some", + value: { reason: { _tag: "SymbolExportName", name } }, + }); + expect(visits).toBe(0); + }); + + test("input_own_names", () => { + expect.hasAssertions(); + const schema = { count: integer, ["__proto__"]: integer }; + Object.defineProperty(schema, "count", { enumerable: false }); + const result = Draft.program(schema, ($, inputs) => { + expect(Object.getPrototypeOf(inputs)).toBe(Object.prototype); + expect(Object.hasOwn(inputs, "count")).toBe(true); + $.let("count", inputs.count); + // oxlint-disable-next-line eslint/no-proto -- this is a declared HashQL input, not the JavaScript prototype accessor + return inputs.__proto__; + }); + expect(compile(Result.getOrThrow(result))).toContain('"__proto__"'); + }); + + test("prelude_snapshot", () => { + expect.hasAssertions(); + const first = Expression.integer(1); + const values = { value: first }; + Object.defineProperty(values, "value", { enumerable: false }); + const { program } = Draft.withPrelude({ values }); + expect(Object.isFrozen(values)).toBe(false); + values.value = Expression.integer(2); + const result = program({}, ($) => $.prelude().value); + expect(compile(Result.getOrThrow(result))).toBe('{"#literal":1}'); + }); + + test("nominal_relocation", () => { + expect.hasAssertions(); + const identity = Symbol("Box"); + const result = Draft.program({}, ($) => { + const Box = $.newtype("Box", identity, { value: BigInt }); + const module = pipe( + Module.define("::test", { types: { Box }, values: { Box } }), + Result.getOrThrow, + ); + const joined = Namespace.flatten(module).Box; + const first = pipe( + joined, + TypeExpression.relocate( + Result.getOrThrow(JExpr.Path.decodeResult("::first::Box")), + ), + Result.getOrThrow, + ); + const moved = pipe( + first, + TypeExpression.relocate( + Result.getOrThrow(JExpr.Path.decodeResult("::second::Box")), + ), + Result.getOrThrow, + ); + expect(Expression.isExpression(moved)).toBe(true); + expect(TypeExpression.isExport(moved)).toBe(true); + expect(Result.getOrThrow(TypeExpression.toType(moved))).toStrictEqual({ + _tag: "Reference", + path: Result.getOrThrow(JExpr.Path.decodeResult("::second::Box")), + generics: [], + }); + return moved({ value: 2n }); + }); + expect(compile(Result.getOrThrow(result))).toContain( + '["::second::Box",{"#struct":{"value":{"#literal":2}}}]', + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts new file mode 100644 index 00000000000..5fdbec41475 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts @@ -0,0 +1,215 @@ +/** + * Typed construction operations inside a synchronous Draft callback. + * + * Context preserves each operation's semantic type and input requirements. It does not select an input policy: the program callback contract checks declarations against its explicit input schema. Nested callbacks receive fresh declaration collectors with the same prelude. + * + * @module + */ +import type { Relocatable, Relocate } from "../internal/relocation.js"; +import type { + Expression, + Inputs, + Module, + Operators, + Type, + TypeExpression, +} from "../main.js"; +import type { ArgumentInputs, Arguments } from "../Program/ExpressionType.js"; +import type * as Import from "../Program/Import.js"; +import type * as Namespace from "../Program/Namespace.js"; +import type * as QueryTypes from "../Program/Query.js"; +import type * as Scope from "../Program/Scope.js"; +import type * as Structural from "../Program/Structural.js"; + +/** + * The call signature of a Draft nominal constructor: it wraps an exactly typed value of the underlying type `T` as the nominal type. + * + * The argument can be an expression or structural shorthand, such as a record of expressions and primitives for a struct. TypeScript rejects missing, extra and wrongly typed fields. The result requires the inputs the argument requires. + */ +export type NominalCall = < + const V extends Structural.Value & Structural.AnyValue, +>( + value: Structural.Exact, +) => Expression.Expression, Structural.Requirements>; + +/** + * A Draft nominal constructor: an expression of function type that also accepts structural shorthand. + * + * Rebinding it, as an import or module export does, keeps both the call signature and the nominal identity. Each constructor has one rebinding result rather than an intersection of recursive overloads. + */ +export interface NominalValue + extends Expression.Any, NominalCall { + readonly "~hashql/Expression": Expression.Handle< + Type.Function>, + Inputs.Empty + >["~hashql/Expression"]; + readonly [Relocate]: Relocatable>[typeof Relocate]; +} + +/** The result of `newtype`: one handle that is both the nominal type expression and its constructor. */ +export type Nominal = Namespace.Joined< + NominalValue, + TypeExpression.TypeExpression> +>; + +/** + * A graph query under construction with the unrestricted context: an expression of the graph type with `filter` and `collect`. + * + * Binding it with `let` produces a plain expression without those methods. + */ +export type Query< + S extends Scope.Scope, + T extends Type.Any, + V extends Type.Any, + I, +> = Expression.Expression & { + /** + * Adds a filter and constructs its predicate now, in its own declaration scope. + * + * `name` becomes the filter closure's parameter. `predicate` does not run when the query already carries a failure, or when `name` is not a valid HashQL identifier, which fails construction with `InvalidParameterName`. Otherwise `predicate` runs once, immediately, with a fresh context and the vertex expression. The filter closure contains the declarations made through that context. An exception the predicate throws becomes a `CallbackException` failure on the returned query. + */ + readonly filter: >( + name: string, + predicate: ( + $: Context, + vertex: Expression.Expression, + ) => P, + ) => Query>>; + /** Ends the query, emitting `::graph::tail::collect`, as a list of its vertices. */ + readonly collect: () => Expression.Expression, I>; +}; + +/** The argument, result, vertex and input types of the scope's `entities` function, or `never` when it has none returning a graph. */ +export type EntityFunction = + QueryTypes.EntityFunction; + +/** The `entities` entry point: calls the scope's `entities` function and returns a query over its vertex type. */ +export type Entities = < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, +>( + ...args: A +) => Query< + S, + EntityFunction["returns"], + EntityFunction["vertex"], + Inputs.Merge["inputs"], ArgumentInputs> +>; + +/** The query entry points of a context: `entities` when the scope declares a graph-returning `entities` function, otherwise none. */ +export type QueryContext = [EntityFunction] extends [ + never, +] + ? // oxlint-disable-next-line typescript/no-generated-empty-object-type -- a scope without a graph declaration supplies no query entry point + Record + : { readonly entities: Entities }; + +/** The branch arguments of `if`: one record of values that already exist, or two callbacks that each construct a branch in its own context. */ +export type Branches< + S extends Scope.Scope, + T extends Expression.AnyValue, + E extends Expression.AnyValue, +> = + | readonly [branches: { readonly then: T; readonly else: E }] + | readonly [then: ($: Context) => T, otherwise: ($: Context) => E]; + +/** The expression `if` returns: its type combines the branch types, and its input requirements combine the condition's with both branches'. */ +export type Conditional< + C extends Expression.Value, + T extends Expression.AnyValue, + E extends Expression.AnyValue, +> = Expression.Expression< + Expression.Conditional, Expression.TypeOf>, + Inputs.Merge< + Expression.Inputs, + Inputs.Merge, Expression.Inputs> + > +>; + +/** + * The unrestricted Draft construction context for the scope `S`. + * + * Its operations construct syntax and collect declarations, accepting values regardless of their input requirements. Draft emits each declaration around the declaring callback's returned expression, in call order. Draft programs give their callbacks a view of this interface restricted to the program's input schema. That view is not assignable to this interface, and a callback written against this interface is not accepted as a program body. The predicate constructors `eq`, `ne`, `and`, `or`, `not`, `isTrue`, `isFalse` and `isNone` are the standalone `Operators` functions. + */ +export interface Context extends Operators.Operations { + /** + * Returns the prelude's exports as one record. + * + * Same-named module, type and value exports become one handle that keeps each capability. The record does not change when the callback imports a module. + */ + readonly prelude: () => Namespace.Flatten; + /** Returns the prelude's modules, each with its child exports also available directly as properties. */ + readonly modules: () => Namespace.Modules; + /** + * Imports a module's exports into the declaring callback and returns them as handles. + * + * Draft emits the import around the callback's returned expression, in call order with its other declarations. Omitting `selection` imports every export. Given a name array, `import` selects those exports. Given an alias record, it imports each listed export under a new name, where `"_"` keeps the export's own name. The returned record joins same-named exports as `prelude()` does and refers to them by their local names. It leaves `prelude()`, `modules()` and `query` unchanged. + * + * Unlike the other declarations, a failed import interrupts the callback, because it cannot supply the handles it promises. An invalid alias and a symbol key in the alias record both stop the callback with an `InvalidImportName` failure. The program returns the failure even if the callback catches the interruption. + */ + readonly import: { + ( + module: M & Import.Rebindable, + ): Namespace.Flatten>; + >( + module: M & Import.Rebindable, + selection: I, + ): Namespace.Flatten>; + }; + /** Lifts a host primitive to an expression whose type follows the host type. This is `Expression.literal`. */ + readonly literal: typeof Expression.literal; + /** Constructs an Integer literal, failing construction for a fractional or non-finite number. This is `Expression.integer`. */ + readonly integer: typeof Expression.integer; + /** Constructs a Number literal. This is `Expression.number`. */ + readonly number: typeof Expression.number; + /** Changes an expression's semantic type assumption without validating that semantic type. This is `Expression.assume`. */ + readonly assume: typeof Expression.assume; + /** References a program input, optionally with a default. This is `Expression.input`. */ + readonly input: typeof Expression.input; + /** Graph query entry points, present when the prelude declares an `entities` function that returns a `::graph::Graph` opaque type. */ + readonly query: QueryContext; + /** + * Binds a value to a HashQL name and returns a reference to the binding. + * + * Draft emits the binding around the declaring callback's returned expression, in call order with its other declarations, even when nothing refers to it. An invalid name, or a value whose construction failed, does not interrupt the callback, but Draft records the failure and the program fails. The reference is the binding's bare name, so carrying it out of the declaring callback leaves it without its binding. + */ + readonly let: ( + name: string, + value: E, + ) => Expression.Expression, Expression.Inputs>; + /** + * Declares a type alias and returns a reference to it. + * + * `definition` is a type expression or structural shorthand. `BigInt`, `Number`, `String` and `Boolean` denote the primitive types, and records and arrays of definitions denote structs and tuples. Draft emits the alias around the declaring callback's returned expression, in call order with its other declarations. An invalid name or definition leaves the callback running, but Draft records the failure and the program fails. + */ + readonly type: ( + name: string, + definition: D, + ) => TypeExpression.TypeExpression>; + /** + * Declares a nominal type and returns one handle that is both the type and its constructor. + * + * The handle is a type expression for `Type.Opaque`, where `T` is the definition's type, and a constructor from an exactly typed value of `T`, including structural shorthand. Calling it emits a call to the declared name. `identity` must have a `unique symbol` type. It distinguishes declarations in TypeScript, and the output never contains it. Draft emits the declaration and records its failures as for `type`. + */ + readonly newtype: < + const N extends symbol, + const D extends Structural.Definition, + >( + name: string, + identity: symbol extends N ? never : N, + definition: D, + ) => Nominal>; + /** + * Constructs a HashQL conditional from a Boolean condition and two branches. + * + * A `{ then, else }` record supplies values that already exist and creates no declaration scope. A pair of callbacks constructs the branches instead. Both run immediately, `then` first, whatever the condition's value, each with a fresh context whose declarations stay inside that branch. An exception thrown by a callback becomes a `CallbackException` failure on the returned expression and does not interrupt the enclosing callback. + */ + readonly if: < + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C, + ...branches: Branches + ) => Conditional; +} diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts new file mode 100644 index 00000000000..73a3f06a20d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts @@ -0,0 +1,180 @@ +import { Result } from "effect"; +// oxlint-disable unicorn/no-thenable -- then is the HashQL conditional-branch key +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Prelude, Structural } from "../main.js"; +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +import type { Inputs, Type, TypeExpression } from "../main.js"; + +const integer = Structural.type(BigInt); +const string = Structural.type(String); + +// oxlint-disable-next-line typescript/promise-function-async -- this fixture supplies a Promise where the synchronous API rejects one +const asynchronousBody = (): Promise< + Expression.Expression +> => Promise.resolve(Expression.literal(true)); + +const alternative = (left: A, _right: B): A | B => left; + +describe("draft_types", () => { + test("conservative_inputs", () => { + const result = Draft.program( + { count: integer, label: string }, + ($, inputs) => { + expectTypeOf(inputs.count).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveInteger, + { readonly count: Type.PrimitiveInteger } + > + >(); + $.let("discarded", inputs.count); + return $.literal(true); + }, + ); + expectTypeOf(Result.getOrThrow(result)).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveBoolean, + { + readonly count: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + } + > + >(); + expectTypeOf( + Result.getOrThrow(Draft.program({}, ($) => $.literal(true))), + ).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("schema_checks", () => { + const outside = Expression.input("outside", integer); + const optional = Expression.input("optional", integer, 1n); + // @ts-expect-error undeclared final input + Draft.program({}, () => outside); + Draft.program({}, ($) => { + // @ts-expect-error discarded initializer still requires an input + $.let("lost", outside); + // @ts-expect-error the schema must include optional external inputs + $.let("optional", optional); + $.if( + true, + // @ts-expect-error child final expression contains an undeclared input + () => outside, + () => 1n, + ); + // @ts-expect-error direct branch contains an undeclared input + $.if(true, { then: outside, else: 1n }); + return $.literal(true); + }); + Draft.program({ outside: integer }, ($) => $.let("allowed", outside)); + const selected = alternative(outside, Expression.input("other", integer)); + const composed = Expression.ifElse(true, { then: selected, else: 1n }); + expectTypeOf(composed); + // @ts-expect-error composition cannot erase alternative undeclared inputs + Draft.program({}, ($) => $.let("lostAlternative", composed)); + // @ts-expect-error same input name with incompatible type + Draft.program({ outside: string }, () => outside); + // @ts-expect-error async callbacks do not construct programs + Draft.program({}, asynchronousBody); + }); + + test("nominal_identity", () => { + const identity = Symbol("Foo"); + const otherIdentity = Symbol("Foo"); + Draft.program({ count: integer }, ($, inputs) => { + const Foo = $.newtype("Foo", identity, { foo: BigInt }); + const Other = $.newtype("Foo", otherIdentity, { foo: BigInt }); + const widened: symbol = identity; + // @ts-expect-error a widened symbol cannot supply a distinct nominal identity + $.newtype("Wide", widened, BigInt); + // @ts-expect-error semantic descriptors are not runtime type definitions + $.type("Phantom", { _tag: "Integer" }); + const value = Foo({ foo: inputs.count }); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + // @ts-expect-error primitive host number is not Integer + Foo({ foo: 2 }); + // @ts-expect-error missing structural field + Foo({}); + // @ts-expect-error extra structural field is not an exact ascription + Foo({ foo: 2n, extra: true }); + // @ts-expect-error distinct unique symbols retain nominal identity + const mismatch: typeof value = Other({ foo: inputs.count }); + expectTypeOf(mismatch); + // @ts-expect-error cannot substitute a plain underlying record for nominal value + const underlying: typeof value = $.literal(2n); + expectTypeOf(underlying); + return value; + }); + }); + + test("metadata_types", () => { + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Shared: Module.type() }, + values: { + Shared: + Module.value< + Type.Struct<{ readonly syntax: Type.PrimitiveInteger }> + >(), + }, + }), + ); + Draft.withPrelude(custom).program({}, ($) => { + const { Shared } = $.prelude(); + // @ts-expect-error metadata is a Result, not also an expression handle + const impossible: Expression.Any = Shared.syntax; + expectTypeOf(impossible); + return Shared.$project("syntax"); + }); + }); + + test("prelude_capabilities", () => { + Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => { + const { Uuid, EntityUuid, eq, add, List, Integer } = $.prelude(); + const comparison = $.let("comparison", EntityUuid(Uuid("uuid"))); + const list = List(Integer); + expectTypeOf(list).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + // @ts-expect-error arithmetic excludes strings + add("one", "two"); + // @ts-expect-error List has one type argument + List(Integer, Integer); + // @ts-expect-error module keys remain precise + expectTypeOf($.modules().uuid.UnknownExport); + const hidden = Expression.input("hidden", Prelude.builtin.types.Boolean); + $.query.entities(inputs.axis).filter( + "vertex", + // @ts-expect-error predicate final expressions must fit the schema + () => hidden, + ); + $.query.entities(inputs.axis).filter("vertex", (predicate) => { + // @ts-expect-error discarded predicate declarations must fit the schema + predicate.let("hidden", hidden); + return true; + }); + // @ts-expect-error nominal constructor requires a Uuid + EntityUuid("uuid"); + return $.query + .entities(inputs.axis) + .filter("vertex", (branch, vertex) => { + const selected = branch.let( + "selected", + vertex.metadata.record_id.entity_id.entity_uuid, + ); + return eq(selected, comparison); + }) + .collect(); + }); + Draft.withPrelude({}).program({}, ($) => { + // @ts-expect-error custom prelude replaces builtins + expectTypeOf($.prelude().Uuid); + return $.literal(true); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts new file mode 100644 index 00000000000..3b25eaa811d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts @@ -0,0 +1,498 @@ +import { Result, Schema, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { + Expression, + JExpr, + Module, + Prelude, + Program, + TypeExpression, +} from "../main.js"; +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; + +const compile = ( + result: Result.Result, +): Schema.Json => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + // oxlint-disable-next-line effecttsgo/schema-sync -- malformed emitted JSON must fail this synchronous test helper + Schema.decodeSync(Schema.fromJsonString(Schema.Json)), + ); + +// oxlint-disable-next-line typescript/promise-function-async -- this fixture supplies a Promise where the synchronous API rejects one +const asynchronousBody = (): Promise< + Expression.Expression +> => Promise.resolve(Expression.literal(true)); + +interface IdentitySignature extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.Function + : Type.Function; +} + +const call = (name: string, ...args: readonly Schema.Json[]): Schema.Json => [ + name, + ...args, +]; +const literal = (value: string | number | boolean): Schema.Json => ({ + "#literal": value, +}); + +describe("draft", () => { + test("ordered_declarations", () => { + expect.hasAssertions(); + let calls = 0; + const identity = Symbol("Foo"); + const result = Draft.program({}, ($) => { + calls += 1; + const Count = $.type("Count", BigInt); + const Foo = $.newtype("Foo", identity, { foo: Count }); + const value = $.let("value", Foo({ foo: 2n })); + expect(TypeExpression.isExport(Foo)).toBe(true); + expect(Expression.isExpression(Foo)).toBe(true); + expect(TypeExpression.isExport(Count)).toBe(true); + return value; + }); + const output = Result.getOrThrow( + Program.compile(Program.program(Result.getOrThrow(result))), + ); + expect(JSON.parse(output)).toStrictEqual( + call( + "::kernel::special_form::type", + "Count", + "::kernel::type::Integer", + call( + "::kernel::special_form::newtype", + "Foo", + { "#struct": { foo: "Count" } }, + call( + "::kernel::special_form::let", + "value", + call("Foo", { "#struct": { foo: literal(2) } }), + "value", + ), + ), + ), + ); + compile(result); + expect(calls).toBe(1); + }); + + test("branch_collectors", () => { + expect.hasAssertions(); + const visits: string[] = []; + const result = Draft.program({}, ($) => + $.if( + false, + (branch) => { + visits.push("then"); + return branch.let("inside", branch.literal(1n)); + }, + (branch) => { + visits.push("else"); + return branch.let("other", branch.literal(2n)); + }, + ), + ); + expect(visits).toStrictEqual(["then", "else"]); + expect(compile(result)).toStrictEqual( + call( + "::kernel::special_form::if", + literal(false), + call("::kernel::special_form::let", "inside", literal(1), "inside"), + call("::kernel::special_form::let", "other", literal(2), "other"), + ), + ); + expect( + // oxlint-disable-next-line unicorn/no-thenable -- then is the HashQL conditional-branch key + compile(Draft.program({}, ($) => $.if(true, { then: 1n, else: 2n }))), + ).toStrictEqual( + call("::kernel::special_form::if", literal(true), literal(1), literal(2)), + ); + }); + + test("reentrant_collectors", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const outer = $.let("outer", 1n); + const inner = Draft.program({}, (nested) => nested.let("inner", 2n)); + expect(compile(inner)).toStrictEqual( + call("::kernel::special_form::let", "inner", literal(2), "inner"), + ); + return $.if( + true, + (branch) => + branch.if( + false, + (child) => child.let("deep", outer), + () => outer, + ), + () => outer, + ); + }); + expect(JSON.stringify(compile(result))).not.toContain('"inner"'); + expect(JSON.stringify(compile(result))).toContain('"deep"'); + }); + + test("custom_query_predicate", () => { + expect.hasAssertions(); + const result = Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => { + const { EntityUuid, Uuid, eq } = $.prelude(); + expect($.prelude().Axis).toBe(Fixtures.axis); + expect(TypeExpression.isExport(Uuid)).toBe(true); + expect(Expression.isExpression(Uuid)).toBe(true); + const comparison = $.let( + "comparison", + EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ); + return $.query + .entities(inputs.axis) + .filter("vertex", (predicate, vertex) => { + const selected = predicate.let( + "selected", + vertex.metadata.record_id.entity_id.entity_uuid, + ); + return eq(selected, comparison); + }) + .collect(); + }); + const syntax = JSON.stringify(compile(result)); + expect(syntax).toContain('"::test::graph::entities"'); + expect(syntax).toContain('"::test::graph::Axis"'); + expect(compile(result)).toStrictEqual([ + "::kernel::special_form::let", + "comparison", + expect.anything(), + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + expect.anything(), + [ + "fn", + { "#tuple": [] }, + { "#struct": { vertex: "_" } }, + "_", + [ + "::kernel::special_form::let", + "selected", + expect.anything(), + ["::core::cmp::eq", "selected", "comparison"], + ], + ], + ], + ], + ]); + expect(syntax).toContain('"::core::uuid::Uuid"'); + }); + + test("custom_prelude", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Item: Module.type() }, + values: { + Item: Module.value< + Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + > + >(), + }, + }), + ); + const originalKeys = Reflect.ownKeys(custom.types.Item); + const { program } = Draft.withPrelude(custom); + const result = program({}, ($) => { + const { Item } = $.prelude(); + expect(TypeExpression.isExport(Item)).toBe(true); + expect(Expression.isExpression(Item)).toBe(true); + expect($.prelude()).not.toHaveProperty("Uuid"); + expect(Result.getOrThrow(TypeExpression.toType(Item))).toStrictEqual( + Result.getOrThrow(TypeExpression.toType(custom.types.Item)), + ); + return Item(2n); + }); + expect(compile(result)).toStrictEqual(call("::custom::Item", literal(2))); + expect(Reflect.ownKeys(custom.types.Item)).toStrictEqual(originalKeys); + expect(Object.isFrozen(custom.types)).toBe(true); + }); + + test("generic_value_collision", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Both: Module.genericType(1) }, + values: { + Both: Module.value< + Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + > + >(), + }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + const { Both } = $.prelude(); + expect(TypeExpression.isExport(Both)).toBe(true); + expect(Expression.isExpression(Both)).toBe(true); + const specialized = Both(Prelude.builtin.types.Integer); + expect(TypeExpression.isExport(specialized)).toBe(true); + expect(Result.getOrThrow(TypeExpression.toType(specialized))._tag).toBe( + "Reference", + ); + return Both(2n); + }); + expect(compile(result)).toStrictEqual(call("::custom::Both", literal(2))); + }); + + test("three_namespace_collision", () => { + expect.hasAssertions(); + const child = Result.getOrThrow( + Module.define("::custom::child", { + types: { Integer: Module.type() }, + }), + ); + const generic = Result.getOrThrow( + Module.define("::custom", { + types: { Both: Module.genericType(1) }, + values: { + Both: Module.value>(), + }, + }), + ); + const built = Draft.withPrelude({ + ...generic, + modules: { Both: child }, + }).program({}, ($) => { + const { Both } = $.prelude(); + expect([ + Module.isModule(Both), + TypeExpression.isConstructor(Both), + Expression.isExpression(Both), + ]).toStrictEqual([true, true, true]); + expect([Both.types.Integer, $.modules().Both.Integer]).toStrictEqual([ + child.types.Integer, + child.types.Integer, + ]); + const applied = Both(child.types.Integer); + expect(TypeExpression.isExport(applied)).toBe(true); + const combinedArgument = Draft.withPrelude(Prelude.builtin).program( + {}, + (nested) => { + const result = Both(nested.prelude().Uuid); + expect([ + TypeExpression.isExport(result), + Expression.isExpression(result), + ]).toStrictEqual([true, true]); + return nested.literal(true); + }, + ); + expect(Result.isSuccess(combinedArgument)).toBe(true); + return Both(2n); + }); + expect(compile(built)).toStrictEqual(call("::custom::Both", literal(2))); + }); + + test("nested_nominal_export", () => { + expect.hasAssertions(); + const library = Result.getOrThrow( + Module.define("::custom::library", { + modules: { entity: Prelude.builtin.modules.entity }, + }), + ); + const root = Result.getOrThrow( + Module.define("::custom", { modules: { library } }), + ); + const result = Draft.withPrelude({ + modules: { root }, + values: { Uuid: Prelude.builtin.values.Uuid }, + }).program({}, ($) => { + const EntityUuid = $.modules().root.library.entity.EntityUuid; + expect(TypeExpression.isExport(EntityUuid)).toBe(true); + expect(Expression.isExpression(EntityUuid)).toBe(true); + expect(Module.isModule($.modules().root.library.entity)).toBe(true); + const alias = $.type("Id", EntityUuid); + expect(Result.isSuccess(TypeExpression.toType(alias))).toBe(true); + return EntityUuid($.prelude().Uuid("uuid")); + }); + expect(compile(result)).toStrictEqual( + call( + "::kernel::special_form::type", + "Id", + "::graph::types::knowledge::entity::EntityUuid", + call( + "::graph::types::knowledge::entity::EntityUuid", + call("::core::uuid::Uuid", literal("uuid")), + ), + ), + ); + }); + + test("metadata_projection", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Shared: Module.type() }, + values: { + Shared: + Module.value< + Type.Struct<{ readonly syntax: Type.PrimitiveInteger }> + >(), + }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + const { Shared } = $.prelude(); + expect(Result.isSuccess(Shared.syntax)).toBe(true); + expect(Result.isSuccess(TypeExpression.toType(Shared))).toBe(true); + return Shared.$project("syntax"); + }); + expect(compile(result)).toStrictEqual( + call("::kernel::special_form::access", "::custom::Shared", "syntax"), + ); + }); + + test("structural_shorthand", () => { + expect.hasAssertions(); + const identity = Symbol("Tuple"); + const result = Draft.program({}, ($) => { + const { List, Dict, String: StringType, Integer } = $.prelude(); + $.type("Collections", { + list: List(BigInt), + dict: Dict(StringType, Integer), + nested: List({ value: BigInt }), + flag: Boolean, + text: String, + number: Number, + }); + const Tuple = $.newtype("Tuple", identity, [BigInt, String]); + return Tuple([2n, "two"]); + }); + expect(JSON.stringify(compile(result))).toContain('"#tuple"'); + expect(JSON.stringify(compile(result))).toContain( + "::kernel::type::List<::kernel::type::Integer>", + ); + }); + + test("construction_failures", () => { + expect.hasAssertions(); + for (const result of [ + Draft.program({}, ($) => { + $.let("not a name", 1n); + return $.literal(true); + }), + Draft.program({}, ($) => { + $.let("bad", Infinity); + return $.literal(true); + }), + Draft.program({}, ($) => { + $.type("bad", { "not a field": BigInt }); + return $.literal(true); + }), + Draft.program({}, ($) => + $.if( + true, + () => 1n, + (branch) => { + branch.let("bad", Number.NaN); + return 2n; + }, + ), + ), + ]) { + expect(result._tag).toBe("Failure"); + } + + // @ts-expect-error exercise an unchecked JavaScript caller + const asynchronous = Draft.program({}, asynchronousBody); + expect(Result.isFailure(asynchronous)).toBe(true); + }); + + test("failed_type_declaration", () => { + expect.hasAssertions(); + // @ts-expect-error The runtime call omits the required type argument. + const invalid = Prelude.builtin.types.List(); + const identity: unique symbol = Symbol("Invalid"); + const alias = Draft.program({}, ($) => { + $.type("Alias", invalid); + return $.literal(true); + }); + const nominal = Draft.program({}, ($) => { + $.newtype("Nominal", identity, invalid); + return $.literal(true); + }); + expect(alias).toStrictEqual(TypeExpression.toType(invalid)); + expect(nominal).toStrictEqual(TypeExpression.toType(invalid)); + }); + + test("invalid_query_and_nominal", () => { + expect.hasAssertions(); + let visits = 0; + const query = Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => + $.query + .entities(inputs.axis) + .filter("not a name", () => { + visits += 1; + return true; + }) + .collect(), + ); + expect(Result.isFailure(query)).toBe(true); + expect(visits).toBe(0); + const identity = Symbol("Bad"); + const value = Draft.program({}, ($) => { + const Bad = $.newtype("Bad", identity, { number: Number }); + return Bad({ number: Infinity }); + }); + expect(Result.isFailure(value)).toBe(true); + const declaration = Draft.program({}, ($) => { + $.newtype("not a name", identity, BigInt); + return $.literal(true); + }); + expect(Result.isFailure(declaration)).toBe(true); + }); + + test("external_inputs", () => { + expect.hasAssertions(); + const external = Expression.input("count", Prelude.builtin.types.Integer); + const result = Draft.program( + { count: Prelude.builtin.types.Integer }, + ($) => { + $.let("unused", external); + return $.literal(true); + }, + ); + expect(compile(result)).toStrictEqual( + call( + "::kernel::special_form::let", + "unused", + call( + "::kernel::special_form::input", + "count", + "::kernel::type::Integer", + ), + literal(true), + ), + ); + }); + + test("escaped_references", () => { + expect.hasAssertions(); + let escaped: Expression.Expression = + Expression.integer(0); + Draft.program({}, ($) => { + escaped = $.let("local", 1n); + return escaped; + }); + expect(compile(Draft.program({}, () => escaped))).toBe("local"); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Exception.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Exception.test.ts new file mode 100644 index 00000000000..90c7df679d0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Exception.test.ts @@ -0,0 +1,62 @@ +import { Cause, Result, pipe } from "effect"; +import { assert, describe, expect, test } from "vitest"; + +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +describe("draft_exceptions", () => { + test.each([new Error("user exception"), "non-error", undefined])( + "host_exception_%#", + (thrown) => { + expect.hasAssertions(); + const result = Draft.program({}, () => { + // oxlint-disable-next-line typescript/only-throw-error -- unchecked JavaScript callbacks can throw arbitrary values + throw thrown; + }); + const failure = pipe(result, Result.flip, Result.getOrThrow); + assert(failure.reason._tag === "CallbackException"); + expect(failure.reason.cause).toBeInstanceOf(Cause.UnknownError); + expect(failure.reason.cause.cause).toBe(thrown); + expect(failure.message).toBe("A program callback threw an exception"); + }, + ); + + test("branch_exception", () => { + expect.hasAssertions(); + const thrown = new Error("branch callback"); + const fail = (): bigint => { + throw thrown; + }; + const results = [ + Draft.program({}, ($) => $.if(false, fail, () => 1n)), + Draft.program({}, ($) => $.if(true, () => 1n, fail)), + ]; + for (const result of results) { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + } + }); + + test("predicate_exception", () => { + expect.hasAssertions(); + const thrown = new Error("predicate callback"); + const result = Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => + $.query + .entities(inputs.axis) + .filter("vertex", (): boolean => { + throw thrown; + }) + .collect(), + ); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Import.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Import.test-d.ts new file mode 100644 index 00000000000..1311de34b5e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Import.test-d.ts @@ -0,0 +1,54 @@ +/** Import selections retain names, signatures and input requirements. @module */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Prelude } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Type } from "../main.js"; + +const integer = Prelude.builtin.types.Integer; +const outside = Expression.input("outside", integer); +const source = Result.getOrThrow( + Module.define("::requirements", { + values: { outside }, + types: { Integer: integer }, + }), +); + +describe("draft_import_types", () => { + test("import_names", () => { + Draft.program({ outside: integer }, ($) => { + const selected = $.import(source, { outside: "local" }); + expectTypeOf(selected).toHaveProperty("local"); + expectTypeOf(selected).not.toHaveProperty("outside"); + expectTypeOf(selected).not.toHaveProperty("Integer"); + expectTypeOf(selected.local).toEqualTypeOf(); + // @ts-expect-error An import does not mutate the existing context's prelude type. + expectTypeOf($.prelude().local); + // @ts-expect-error A selection must name a declared export. + $.import(source, ["absent"]); + // @ts-expect-error Alias sources must name declared exports. + $.import(source, { absent: "local" }); + return selected.local; + }); + }); + + test("import_requirements", () => { + // @ts-expect-error Imported handles keep requirements from their declarations. + Draft.program({}, ($) => $.import(source).outside); + Draft.program({}, ($) => { + const imported = $.import(source); + // @ts-expect-error Discarding an initializer cannot conceal an imported requirement. + $.let("discarded", imported.outside); + return $.literal(true); + }); + const result = Draft.program( + { outside: integer }, + ($) => $.import(source).outside, + ); + expectTypeOf< + Expression.Inputs> + >().toEqualTypeOf<{ readonly outside: Type.PrimitiveInteger }>(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts new file mode 100644 index 00000000000..d7ebe997939 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts @@ -0,0 +1,235 @@ +/** Lexical imports preserve selected capabilities and callback boundaries. @module */ +import { Result, pipe } from "effect"; +import { describe, expect, expectTypeOf, test } from "vitest"; + +import * as TypeSyntax from "../JExpr/Type/index.js"; +import { Expression, JExpr, Module, Prelude, TypeExpression } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; + +const child = Result.getOrThrow( + Module.define("::leaf", { + values: { enabled: Module.value() }, + }), +); +const declarations = Result.getOrThrow( + Module.define("::example", { + modules: { child }, + types: { + Whole: Module.type(), + List: Prelude.builtin.types.List, + }, + values: { + Whole: + Module.value< + Type.Function + >(), + }, + }), +); +const compile = ( + result: Result.Result, +): string => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +describe("draft_import", () => { + test("selected_capabilities", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const { Whole, List } = $.import(declarations, ["Whole", "List"]); + expectTypeOf(Whole(1n)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(List(String)).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + expect( + TypeSyntax.compile( + Result.getOrThrow(TypeExpression.toType(List(String))), + ), + ).toBe("List<::kernel::type::String>"); + expect( + TypeSyntax.compile(Result.getOrThrow(TypeExpression.toType(Whole))), + ).toBe("Whole"); + return Whole(1n); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::example",{"#tuple":["Whole","List"]},["Whole",{"#literal":1}]]', + ); + }); + + test("wildcard_and_nested_module", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const imported = $.import(declarations); + const { active } = $.import(imported.child, { enabled: "active" }); + expectTypeOf(active).toEqualTypeOf(); + return $.and(active, true); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::example","*",["::kernel::special_form::use","child",{"#struct":{"enabled":"active"}},["::core::bool::and","active",{"#literal":true}]]]', + ); + }); + + test("branch_scope", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => + $.if( + true, + ($) => { + const { Whole } = $.import(declarations, { Whole: "_" }); + return Whole(1n); + }, + () => 0n, + ), + ); + expect(compile(result)).toBe( + '["::kernel::special_form::if",{"#literal":true},["::kernel::special_form::use","::example",{"#struct":{"Whole":"Whole"}},["Whole",{"#literal":1}]],{"#literal":0}]', + ); + }); + + test("adapted_callable", () => { + expect.hasAssertions(); + const original = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("::original"); + const adapted = Expression.adaptCallable( + original, + (self) => + (value: { + readonly text: string; + }): Expression.Expression => + self(value.text), + ); + const source = Result.getOrThrow( + Module.define("::adapted", { values: { call: adapted } }), + ); + const result = Draft.program({}, ($) => { + const { invoke } = $.import(source, { call: "invoke" }); + expectTypeOf(invoke).toEqualTypeOf(adapted); + return invoke({ text: "value" }); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::adapted",{"#struct":{"call":"invoke"}},["invoke",{"#literal":"value"}]]', + ); + }); + + test("symbol_alias", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const imported = $.import(declarations, { Whole: "+" }); + expect(Object.hasOwn(imported, "+")).toBe(true); + return imported["+"](1n); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::example",{"#struct":{"Whole":"`+`"}},["`+`",{"#literal":1}]]', + ); + }); + + test("own_names", () => { + expect.hasAssertions(); + const values = { + ["__proto__"]: Expression.literal(true), + hidden: Expression.literal(false), + }; + Object.defineProperty(values, "hidden", { enumerable: false }); + const source = Result.getOrThrow(Module.define("::own", { values })); + const result = Draft.program({}, ($) => { + const imported = $.import(source); + expect(Object.hasOwn(imported, "__proto__")).toBe(true); + expect(Object.hasOwn(imported, "hidden")).toBe(true); + const { __proto__: prototypeNamed } = imported; + return $.and(prototypeNamed, imported.hidden); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::own","*",["::core::bool::and","__proto__","hidden"]]', + ); + expect(Object.isFrozen(values)).toBe(false); + }); + + test("repeated_alias", () => { + expect.hasAssertions(); + const source = Result.getOrThrow( + Module.define("::aliases", { + values: { + first: Module.value(), + second: Module.value(), + }, + }), + ); + const result = Draft.program( + {}, + ($) => + $.import(source, { first: "selected", second: "selected" }).selected, + ); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::aliases",{"#struct":{"first":"selected","second":"selected"}},"selected"]', + ); + }); + + test("symbol_selection", () => { + expect.hasAssertions(); + const hidden = Symbol("hidden"); + const selection = { Whole: "Whole", [hidden]: "hidden" }; + const result = Draft.program({}, ($) => { + $.import(declarations, selection); + return $.literal(true); + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidImportName", name: String(hidden) } }, + }); + }); + + test("invalid_alias", () => { + expect.hasAssertions(); + let continued = false; + const result = Draft.program({}, ($) => { + const { "bad name": whole } = $.import(declarations, { + Whole: "bad name", + }); + continued = true; + return whole(1n); + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidImportName", name: "bad name" } }, + }); + expect(continued).toBe(false); + }); + + test("caught_import_failure", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + try { + $.import(declarations, { Whole: "bad name" }); + } catch { + /* The collector must still retain this construction failure. */ + } + return $.literal(true); + }); + expect(Result.isFailure(result)).toBe(true); + }); + + test("host_exception", () => { + expect.hasAssertions(); + const error = new Error("host callback"); + const result = Draft.program({}, ($) => { + $.import(declarations); + throw error; + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: error } }, + }, + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts new file mode 100644 index 00000000000..884d4d4bb2a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts @@ -0,0 +1,99 @@ +/** + * Draft integration checks for flattened prelude and module views. + * + * @module + */ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, Module, Structural, TypeExpression } from "../main.js"; +import * as Operators from "../Program/Operators.js"; +import * as Draft from "./index.js"; + +import type { Type } from "../main.js"; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : Type.Never; +} + +const child = Result.getOrThrow( + Module.define("::child", { + values: { + name: Module.value(), + // oxlint-disable-next-line unicorn/no-thenable -- this is a HashQL export name + then: Module.value(), + $: Module.value(), + }, + types: { ["__proto__"]: Module.type() }, + }), +); + +describe("draft_namespace", () => { + test("joined_constructor", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Both: Module.genericType(1) }, + modules: { Both: child }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + const { Both } = $.prelude(); + expect(Both.name).toBe(child.values.name); + expect(Both).toSatisfy(TypeExpression.isConstructor); + expect(Both(Structural.type(BigInt))).toSatisfy(TypeExpression.isExport); + return Both.name; + }); + expect(result).toSatisfy(Result.isSuccess); + }); + + test("then_export", () => { + expect.hasAssertions(); + const result = Draft.withPrelude({ + modules: { Both: child }, + values: { Both: Expression.integer(1) }, + }).program({}, ($) => { + const { Both } = $.prelude(); + expect(Both.then).toBe(child.values.then); + expect($.modules().Both.then).toBe(child.values.then); + expect(Both.values.$).toBe(child.values.$); + expect(Both.$).toBe(child.values.$); + return Operators.eq(Both, 1n); + }); + expect(result).toSatisfy(Result.isSuccess); + }); + + test("prototype_type", () => { + expect.hasAssertions(); + const result = Draft.withPrelude(child).program({}, ($) => { + // oxlint-disable-next-line eslint/no-proto -- __proto__ names a HashQL type export + const type = $.prelude().__proto__; + expect(type).toSatisfy(TypeExpression.isExport); + return $.literal(true); + }); + expect(result).toSatisfy(Result.isSuccess); + }); + + test("prototype_join", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + modules: { ["__proto__"]: child }, + types: { ["__proto__"]: Module.type() }, + values: { ["__proto__"]: Module.value() }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + // oxlint-disable-next-line eslint/no-proto -- __proto__ names a HashQL export in all three namespaces + const entry = $.prelude().__proto__; + expect(entry).toSatisfy(TypeExpression.isExport); + expect(entry).toSatisfy(Expression.isExpression); + expect(entry).toSatisfy(Module.isModule); + return entry; + }); + expect(result).toSatisfy(Result.isSuccess); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Query.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Query.test-d.ts new file mode 100644 index 00000000000..37c652480fb --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Query.test-d.ts @@ -0,0 +1,80 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; +import type { Result } from "effect"; + +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +describe("draft_query_types", () => { + test("graph_vertex", () => { + const { program } = Draft.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, + }); + const result = program({}, ($) => + $.query + .entities() + .filter("item", (_, item) => { + expectTypeOf(item).toEqualTypeOf< + Expression.Expression + >(); + return $.isFalse(item.enabled); + }) + .collect(), + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression, Inputs.Empty>, + ProgramError.Construction + > + >(); + program({}, ($) => { + // @ts-expect-error A predicate must return a Boolean. + $.query.entities().filter("item", (_, item) => item); + // @ts-expect-error Query construction has no compatibility adapter. + expectTypeOf($.query.from); + return $.literal(true); + }); + }); + + test("primitive_arguments", () => { + const { program } = Draft.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, + }); + const result = program({}, ($) => + $.query + .entities(1) + .filter("vertex", () => true) + .collect(), + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression, Inputs.Empty>, + ProgramError.Construction + > + >(); + program({}, ($) => { + // @ts-expect-error Query arguments use the declaration's exact numeric descriptor. + $.query.entities(1n); + // @ts-expect-error A predicate does not accept numeric truthiness. + $.query.entities(1).filter("vertex", () => 1); + return $.literal(true); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Query.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Query.test.ts new file mode 100644 index 00000000000..34955b60488 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Query.test.ts @@ -0,0 +1,77 @@ +import { Result, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, JExpr } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; + +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +const { program } = Draft.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, +}); + +const compile = ( + result: Result.Result, +): string => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +describe("draft_query", () => { + test("named_filter", () => { + expect.hasAssertions(); + let calls = 0; + const result = program({}, ($) => + $.query + .entities(1) + .filter("item", (_, item) => { + calls += 1; + return $.isFalse(item.enabled); + }) + .collect(), + ); + expect(compile(result)).toBe( + '["::graph::tail::collect",["::graph::body::filter",["entities",{"#literal":1}],["fn",{"#tuple":[]},{"#struct":{"item":"_"}},"_",["::core::cmp::eq",["::kernel::special_form::access","item","enabled"],{"#literal":false}]]]]', + ); + expect(calls).toBe(1); + }); + + test("primitive_predicate", () => { + expect.hasAssertions(); + const result = program({}, ($) => + $.query + .entities(1) + .filter("vertex", () => true) + .collect(), + ); + expect(compile(result)).toBe( + '["::graph::tail::collect",["::graph::body::filter",["entities",{"#literal":1}],["fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",{"#literal":true}]]]', + ); + }); + + test("predicate_failure", () => { + expect.hasAssertions(); + const result = program({}, ($) => + $.query + .entities(1) + .filter("item", () => $.eq(Number.NaN, 1)) + .collect(), + ); + const failure = pipe(result, Result.flip, Result.getOrThrow); + expect(failure.reason._tag).toBe("InvalidExpression"); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts new file mode 100644 index 00000000000..27ac7971e8e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts @@ -0,0 +1,266 @@ +import { Result } from "effect"; +// oxlint-disable unicorn/no-thenable -- then names a HashQL branch or declared export +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Prelude, Structural } from "../main.js"; +import * as Operators from "../Program/Operators.js"; +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +import type { Inputs, Type } from "../main.js"; + +const integer = Structural.type(BigInt); +const outside = Expression.input("outside", integer); +type Box = Type.Struct<{ readonly foo: Type.PrimitiveInteger }>; + +const chooseBox = (): + | { readonly foo: Expression.Expression } + | { readonly foo: typeof outside } => ({ foo: outside }); + +const chooseTuple = (): + | readonly [Expression.Expression] + | readonly [typeof outside] => [outside]; + +const alternative = (left: A, _right: B): A | B => left; +const chooseAxes = (): + | Inputs.Empty + | { readonly axis: typeof Fixtures.axis } => ({ axis: Fixtures.axis }); + +const chooseSchema = (): + | Inputs.Empty + | { readonly outside: typeof integer } => ({ outside: integer }); + +describe("draft_requirements", () => { + test("structural_alternatives", () => { + const structural = Structural.value()(chooseBox()); + // @ts-expect-error a closed annotation cannot discard the required host alternative + const closed: Expression.Expression = structural; + expectTypeOf(closed); + expectTypeOf>().toEqualTypeOf<{ + readonly outside: Type.PrimitiveInteger; + }>(); + const tuple = + Structural.value>()( + chooseTuple(), + ); + // @ts-expect-error tuple alternatives also keep every requirement + const closedTuple: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = tuple; + expectTypeOf(closedTuple); + const identity = Symbol("Box"); + Draft.program({}, ($) => { + const Nominal = $.newtype("Box", identity, { foo: BigInt }); + const nominal = Nominal(chooseBox()); + // @ts-expect-error the nominal producer normalizes before exposing variance + const closedNominal: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = nominal; + expectTypeOf(closedNominal); + // @ts-expect-error discarded nominal initializers still need their inputs + $.let("lost", nominal); + // @ts-expect-error discarded structural initializers still need their inputs + $.let("lostStruct", structural); + return $.literal(true); + }); + Draft.program({ outside: integer }, ($) => $.let("allowed", structural)); + }); + + test("erased_requirements", () => { + const erased: Expression.Any = outside; + const erasedValue: Expression.Value = outside; + const conditional = Expression.ifElse(true, { + then: erasedValue, + else: 1n, + }); + const assumed = Expression.assume()(erased); + const structural = Structural.value()({ foo: erasedValue }); + const call = Prelude.builtin.values.add(erasedValue, 1n); + const defaulted = Expression.input("defaulted", integer, erasedValue); + const erasedReceiver: Expression.Expression = + outside; + const receiverCall = Operators.eq(erasedReceiver, outside); + const erasedCallee: Expression.Expression< + Expression.TypeOf, + never + > = Prelude.builtin.values.add; + const calleeCall = erasedCallee(outside, 1n); + const mixedAny = Expression.ifElse(true, { then: erased, else: 1n }); + const chooseErasedTuple = (): + | readonly [typeof erasedValue] + | readonly [bigint] => [erasedValue]; + const erasedTuple = + Structural.value>()( + chooseErasedTuple(), + ); + // @ts-expect-error an outer tuple alternative must not discard internal erasure + const closedTuple: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = erasedTuple; + expectTypeOf(closedTuple); + // @ts-expect-error a named argument cannot discharge an erased receiver + const closedReceiver: Expression.Expression< + Type.PrimitiveBoolean, + { readonly outside: Type.PrimitiveInteger } + > = receiverCall; + // @ts-expect-error a named argument cannot discharge an erased callee + const closedCallee: Expression.Expression< + Expression.TypeOf, + { readonly outside: Type.PrimitiveInteger } + > = calleeCall; + // @ts-expect-error a primitive branch cannot discharge an erased expression + const closedAny: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = mixedAny; + expectTypeOf(closedReceiver); + expectTypeOf(closedCallee); + expectTypeOf(closedAny); + const mixed = Expression.ifElse(true, { + then: alternative(erasedValue, Expression.integer(1)), + else: 1n, + }); + // @ts-expect-error conditional composition must not convert erasure to Empty + const closed: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = conditional; + // @ts-expect-error structural composition must not convert erasure to Empty + const closedStruct: Expression.Expression = structural; + // @ts-expect-error argument composition must not convert erasure to Empty + const closedCall: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = call; + // @ts-expect-error the unknown host alternative cannot disappear + const closedMixed: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = mixed; + expectTypeOf(closed); + expectTypeOf(closedStruct); + expectTypeOf(closedCall); + expectTypeOf(closedMixed); + // @ts-expect-error erased program output cannot prove the schema contract + Draft.program({ outside: integer }, () => erased); + Draft.program({ outside: integer, defaulted: integer }, ($) => { + // @ts-expect-error even a matching schema cannot recover erased information + $.let("any", erased); + // @ts-expect-error Value erases requirements too + $.let("value", erasedValue); + // @ts-expect-error conditional composition retains erasure + $.let("conditional", conditional); + // @ts-expect-error semantic assumptions do not recover input requirements + $.let("assumed", assumed); + // @ts-expect-error structural composition retains erasure + $.let("structural", structural); + // @ts-expect-error calls retain erasure + $.let("call", call); + // @ts-expect-error input defaults retain erasure + $.let("defaulted", defaulted); + // @ts-expect-error callee requirements remain erased after argument composition + $.let("callee", calleeCall); + // @ts-expect-error receiver requirements remain erased after operand composition + $.let("receiver", receiverCall); + const identity = Symbol("Erased"); + const Nominal = $.newtype("Erased", identity, { foo: BigInt }); + const nominal = Nominal({ foo: erasedValue }); + // @ts-expect-error nominal composition cannot restore erased requirements + const closedNominal: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = nominal; + expectTypeOf(closedNominal); + // @ts-expect-error nominal initializers retain erased requirements + $.let("nominal", nominal); + // @ts-expect-error direct branches cannot accept erased values + $.if(true, { then: erasedValue, else: 1n }); + $.if( + true, + // @ts-expect-error callback branches cannot accept erased values + () => erasedValue, + () => 1n, + ); + return $.literal(true); + }); + const erasedPredicate: Expression.Value = + Expression.input("flag", Structural.type(Boolean)); + Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => { + // @ts-expect-error query callbacks cannot prove erased requirements + $.query.entities(inputs.axis).filter("vertex", () => erasedPredicate); + return $.literal(true); + }); + }); + + test("schema_alternatives", () => { + const result = Draft.program(chooseSchema(), ($) => $.literal(true)); + // @ts-expect-error an empty alternative does not remove the explicit schema promise + const closed: Expression.Expression = + Result.getOrThrow(result); + expectTypeOf(closed); + const output = Result.getOrThrow(result); + expectTypeOf>().toEqualTypeOf<{ + readonly outside: Type.PrimitiveInteger; + }>(); + const branch = Draft.program(chooseSchema(), ($) => + $.if( + true, + (child) => child.let("outside", outside), + () => 1n, + ), + ); + // @ts-expect-error child contexts retain the conservative schema + const closedBranch: Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty + > = Result.getOrThrow(branch); + expectTypeOf(closedBranch); + const axis = Expression.input("axis", Fixtures.axis); + Fixtures.program(chooseAxes(), ($) => { + const query = $.query + .entities(axis) + .filter("vertex", (predicate) => predicate.let("selected", true)); + // @ts-expect-error query contexts retain the same conservative schema + const closedQuery: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = query; + expectTypeOf(closedQuery); + return query.collect(); + }); + }); + + test("joined_expression_operations", () => { + const child = Result.getOrThrow( + Module.define("::child", { + values: { + then: Module.value(), + $: Module.value(), + }, + }), + ); + Draft.withPrelude({ + modules: { Both: child }, + values: { Both: outside }, + }).program({ outside: integer }, ($) => { + const { Both } = $.prelude(); + const thenValue = Both.then; + const dollarValue = Both.$; + expectTypeOf(dollarValue).toEqualTypeOf(); + expectTypeOf(Both).not.toHaveProperty("$project"); + expectTypeOf(Both).not.toHaveProperty("$index"); + expectTypeOf($.modules().Both.then).toEqualTypeOf< + typeof child.values.then + >(); + expectTypeOf(thenValue).toEqualTypeOf(); + expectTypeOf(dollarValue); + expectTypeOf(Both.values.then).toEqualTypeOf< + Expression.Expression + >(); + return $.literal(true); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts new file mode 100644 index 00000000000..1eb06177818 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts @@ -0,0 +1,475 @@ +/** + * Collects declarations while a synchronous callback constructs an expression. + * + * Handles retain semantic parameters until conversion to syntax. Only the declaration wrappers are heterogeneous: each is already an AST operation, so their collection needs no type recovery. A child collector prevents branch and predicate declarations from escaping their lexical body. Callback exceptions retain their original cause inside construction failures. + * + * @module + */ +import { Cause, Data, Result, pipe } from "effect"; + +import { + Expression, + JExpr, + Operators, + ProgramError, + Structural, + TypeExpression, +} from "../main.js"; +import * as AST from "../Program/AST/index.js"; +import * as Import from "../Program/Import.js"; +import * as Namespace from "../Program/Namespace.js"; + +import type * as Syntax from "../JExpr/Type/index.js"; +import type { Inputs, Module, Type } from "../main.js"; +import type { ArgumentInputs, Arguments } from "../Program/ExpressionType.js"; +import type * as Scope from "../Program/Scope.js"; +import type * as Body from "./Body.js"; +import type * as Context from "./Context.js"; + +type Wrap = (child: AST.Node) => AST.Node; + +/** Adds structural argument normalization without losing the nominal identity on relocation. */ +const nominalValue = ( + expression: Expression.Expression< + Type.Function>, + Inputs.Empty + >, +): Context.NominalValue => + Expression.adaptCallable(expression, (self) => { + const construct: Context.NominalCall = < + const V extends Structural.Value & Structural.AnyValue, + >( + value: Structural.Exact, + ): Expression.Expression, Structural.Requirements> => + pipe( + { + callee: Expression.toJExpr(self), + argument: Structural.toJExpr(value), + }, + Result.all, + Result.map( + ({ callee, argument }) => new AST.Expr(JExpr.call(callee, argument)), + ), + Expression.fromResult, Structural.Requirements>, + ); + + return construct; + }); + +const nominal = ( + binding: Result.Result, ProgramError.Construction>, +): Context.Nominal => { + const type = pipe( + binding, + Result.map( + (bound): Syntax.Type => ({ + _tag: "Reference", + path: { rooted: false, segments: [bound.name] }, + generics: [], + }), + ), + TypeExpression.fromResult>, + ); + + const value = pipe( + binding, + Result.map((bound) => new AST.Expr(JExpr.Ident.compile(bound.name))), + Expression.fromResult< + Type.Function>, + Inputs.Empty + >, + nominalValue, + ); + + return Namespace.combine< + Context.NominalValue, + TypeExpression.TypeExpression> + >(value, type); +}; + +/** Stops a callback when an import cannot supply its promised handles. */ +const ConstructionFailure = Data.TaggedError("DraftConstructionFailure")<{ + readonly failure: ProgramError.Construction; +}>; + +class ContextImpl implements Context.Context { + readonly #scope: S & Namespace.Rebindable; + readonly #prelude: Namespace.Flatten; + readonly #modules: Namespace.Modules; + readonly #wrappers: Result.Result[] = []; + readonly query: Context.QueryContext; + readonly literal = Expression.literal; + readonly integer = Expression.integer; + readonly number = Expression.number; + readonly assume = Expression.assume; + readonly input = Expression.input; + readonly eq = Operators.eq; + readonly ne = Operators.ne; + readonly and = Operators.and; + readonly or = Operators.or; + readonly not = Operators.not; + readonly isTrue = Operators.isTrue; + readonly isFalse = Operators.isFalse; + readonly isNone = Operators.isNone; + + constructor(scope: S & Namespace.Rebindable) { + this.#scope = scope; + this.#prelude = Namespace.flatten(scope); + this.#modules = Namespace.modules(scope); + this.query = this.#queries(); + } + + prelude(): Namespace.Flatten { + return this.#prelude; + } + modules(): Namespace.Modules { + return this.#modules; + } + + import( + module: M & Import.Rebindable, + ): Namespace.Flatten>; + import>( + module: M & Import.Rebindable, + selection: I, + ): Namespace.Flatten>; + import>( + module: M & Import.Rebindable, + // oxlint-disable-next-line hash/prefer-options-object -- the optional argument is the import selection itself + selection: I | "*" = "*", + ): Namespace.Flatten> { + const declaration = Import.bind(module, selection); + this.#wrappers.push( + pipe( + declaration, + Result.map((imported) => imported.wrap), + ), + ); + // Keep the failure in the collector even if host code catches the private control-flow exception. + const imported = Result.getOrThrowWith( + declaration, + (failure) => new ConstructionFailure({ failure }), + ); + return Namespace.flatten>(imported.scope); + } + + let( + name: string, + value: E, + ): Expression.Expression, Expression.Inputs> { + const binding = pipe( + Expression.toNode(value), + Result.flatMap((node) => AST.make(name, node)), + ); + + this.#wrappers.push( + pipe( + binding, + Result.map( + (bound): Wrap => + (child) => + new AST.Let(bound, child), + ), + ), + ); + + return pipe( + binding, + Result.map((bound) => new AST.Expr(JExpr.Ident.compile(bound.name))), + Expression.fromResult, Expression.Inputs>, + ); + } + + type( + name: string, + definition: D, + ): TypeExpression.TypeExpression> { + const binding = pipe( + definition, + Structural.type, + TypeExpression.toType, + Result.flatMap((syntax) => AST.make(name, syntax)), + ); + + this.#wrappers.push( + pipe( + binding, + Result.map( + (bound): Wrap => + (child) => + new AST.Type(bound, child), + ), + ), + ); + + return pipe( + binding, + Result.map( + (bound): Syntax.Type => ({ + _tag: "Reference", + path: { rooted: false, segments: [bound.name] }, + generics: [], + }), + ), + TypeExpression.fromResult>, + ); + } + + readonly newtype: Context.Context["newtype"] = < + const N extends symbol, + const D extends Structural.Definition, + >( + name: string, + _identity: symbol extends N ? never : N, + definition: D, + ): Context.Nominal> => { + const binding = pipe( + definition, + Structural.type, + TypeExpression.toType, + Result.flatMap((syntax) => AST.make(name, syntax)), + ); + + this.#wrappers.push( + pipe( + binding, + Result.map( + (bound): Wrap => + (child) => + new AST.Newtype(bound, child), + ), + ), + ); + + return nominal>(binding); + }; + + if< + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C, + ...branches: Context.Branches + ): Context.Conditional { + const resolve = (): { + readonly consequent: Result.Result; + readonly alternate: Result.Result; + } => { + if (branches.length === 2) { + return { + consequent: new ContextImpl(this.#scope).build(branches[0]), + alternate: new ContextImpl(this.#scope).build(branches[1]), + }; + } + + return { + consequent: Expression.toNode(branches[0].then), + alternate: Expression.toNode(branches[0].else), + }; + }; + + const { consequent, alternate } = resolve(); + return pipe( + { condition: Expression.toNode(condition), consequent, alternate }, + Result.all, + Result.map( + (nodes) => + new AST.If(nodes.condition, nodes.consequent, nodes.alternate), + ), + Expression.fromResult< + Expression.Conditional, Expression.TypeOf>, + Inputs.Merge< + Expression.Inputs, + Inputs.Merge, Expression.Inputs> + > + >, + ); + } + + #query( + expression: Expression.Expression, + ): Context.Query { + const filter = >( + name: string, + predicate: ( + $: Context.Context, + vertex: Expression.Expression, + ) => P, + ): Context.Query>> => { + const scope = this.#scope; + const node = Result.gen(function* () { + const graph = yield* Expression.toJExpr(expression); + const ident = yield* pipe( + JExpr.Ident.decodeResult(name), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidParameterName({ + name, + cause, + }), + }), + ), + ); + + const parameter = JExpr.Ident.compile(ident); + const vertex = Expression.fromJExpr(parameter); + const body = yield* new ContextImpl(scope).build(($) => + predicate($, vertex), + ); + + return new AST.Expr( + JExpr.call( + "::graph::body::filter", + graph, + JExpr.fn({ + params: { [parameter]: JExpr.infer }, + body: body.compile(), + }), + ), + ); + }); + + return this.#query>>( + Expression.fromResult(node), + ); + }; + + const collect = (): Expression.Expression, I> => + pipe( + expression, + Expression.toJExpr, + Result.map( + (graph) => new AST.Expr(JExpr.call("::graph::tail::collect", graph)), + ), + Expression.fromResult, I>, + ); + + const proxy = new Proxy(expression, { + // oxlint-disable-next-line typescript/no-restricted-types -- proxy forwarding can return any expression property + get: (target, property, receiver): unknown => { + if (property === "filter") { + return filter; + } + + if (property === "collect") { + return collect; + } + + return Reflect.get(target, property, receiver); + }, + }); + + // SAFETY: the typed handle retains its semantic type and input requirements. The filter and collect methods retain the vertex type and propagate requirements. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy does not express the two supplied query methods + return proxy as Context.Query; + } + + #queries(): Context.QueryContext { + const declaration = this.#scope.values["entities"]; + if (declaration === undefined) { + return {}; + } + + const entities: Context.Entities = < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, + >( + ...args: A + ) => { + const expression = pipe( + { + callee: Expression.toJExpr(declaration), + args: Result.all(args.map(Expression.toJExpr)), + }, + Result.all, + Result.map( + ({ callee, args: values }) => + new AST.Expr(JExpr.call(callee, ...values)), + ), + Expression.fromResult< + Context.EntityFunction["returns"], + Inputs.Merge["inputs"], ArgumentInputs> + >, + ); + + return this.#query< + Context.EntityFunction["returns"], + Context.EntityFunction["vertex"], + Inputs.Merge["inputs"], ArgumentInputs> + >(expression); + }; + + return { entities }; + } + + build( + body: ($: Context.Context) => Expression.AnyValue, + ): Result.Result { + try { + const expression = body(this); + if ( + !Expression.isExpression(expression) && + !( + expression === null || + ["string", "number", "bigint", "boolean"].includes(typeof expression) + ) + ) { + return Result.fail(ProgramError.Construction.invalidBodyResult()); + } + + return pipe( + { + wrappers: Result.all(this.#wrappers), + node: Expression.toNode(expression), + }, + Result.all, + Result.map(({ wrappers, node }) => { + let root = node; + for (const wrap of wrappers.toReversed()) { + root = wrap(root); + } + + return root; + }), + ); + } catch (error) { + if (error instanceof ConstructionFailure) { + return Result.fail(error.failure); + } + + return Result.fail( + ProgramError.Construction.callbackException( + new Cause.UnknownError(error), + ), + ); + } + } +} + +/** Evaluates only callbacks checked against the complete explicit-input policy. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the scope and callback construct a new program +export const evaluate = < + S extends Scope.Scope, + I extends Body.Inputs, + O extends Expression.AnyValue & Expression.Any, +>( + scope: S & Namespace.Rebindable, + body: Body.WithoutInputs, +): Result.Result< + Expression.Expression, Body.Requirements>, + ProgramError.Construction +> => + pipe( + new ContextImpl(scope).build(($) => { + const expression = body($); + if (Expression.isExpression(expression)) { + return expression; + } + return Expression.fromResult, Body.Requirements>( + Result.fail(ProgramError.Construction.invalidBodyResult()), + ); + }), + Result.map(Expression.fromNode, Body.Requirements>), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts b/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts new file mode 100644 index 00000000000..51e7701a7c9 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts @@ -0,0 +1,54 @@ +/** + * Small trusted declarations for Draft query-construction tests. + * + * The vertex contains only the fields the tests project. These declarations exercise custom-prelude typing and syntax construction, not the graph service's complete entity or temporal schema. + * + * @module + */ +import { Result, pipe } from "effect"; + +import { Module, Prelude } from "../main.js"; +import * as Scope from "../Program/Scope.js"; +import * as Draft from "./index.js"; + +import type { Expression, Inputs, Type, TypeExpression } from "../main.js"; + +export type Vertex = Type.Struct<{ + readonly metadata: Type.Struct<{ + readonly record_id: Type.Struct<{ + readonly entity_id: Type.Struct<{ + readonly entity_uuid: Prelude.EntityUuid; + }>; + }>; + }>; +}>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; +type Entities = Type.Function; +const declarations: { + readonly types: { + readonly Axis: Module.Declaration< + TypeExpression.TypeExpression + >; + }; + readonly values: { + readonly entities: Module.Declaration< + Expression.Expression + >; + }; +} = { types: { Axis: Module.type() }, values: { entities: Module.value() } }; +const graph: Module.Module = pipe( + Module.define("::test::graph", declarations), + Result.getOrThrow, +); + +export const scope: Scope.Merge = Scope.merge( + Prelude.builtin, + graph, +); +export const axis: typeof graph.types.Axis = graph.types.Axis; +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the schema and callback construct a test program +export const program: Draft.Program = + Draft.withPrelude(scope).program; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/index.ts b/libs/@local/hashql/sdk/typescript/src/draft/index.ts new file mode 100644 index 00000000000..4b58cec6bb6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/index.ts @@ -0,0 +1,242 @@ +/** + * Synchronous program construction with an explicit input schema. + * + * {@link program} runs one callback that receives a construction context `$` and typed handles for the inputs its schema declares. Draft emits the declarations made through `$`, such as `$.let`, `$.type`, `$.newtype` and `$.import`, around the callback's returned expression in call order. Every emitted initializer and nested body must fit the schema, so the result can retain unused declared inputs without overlooking discarded declarations. Branch and query-predicate callbacks receive their own contexts, whose declarations stay inside that branch or predicate. + * + * {@link program} uses `Prelude.builtin`. {@link withPrelude} creates a program constructor for custom declarations instead, replacing the default and retaining their exact export keys. The `Context` namespace names the construction operation types. + * + * @example Bind a computed value and compare it with an input. + * ```ts + * import assert from "node:assert/strict"; + * import { Prelude, Program } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const atLimit = program({ count: Prelude.builtin.types.Integer }, ($, { count }) => { + * const { add } = $.prelude(); + * const next = $.let("next", add(count, 1n)); + * return $.eq(next, 10n); + * }); + * assert.equal( + * Result.getOrThrow(Result.flatMap(atLimit, (root) => Program.compile(Program.program(root)))), + * '["::kernel::special_form::let","next",["::core::math::add",["::kernel::special_form::input","count","::kernel::type::Integer"],{"#literal":1}],["::core::cmp::eq","next",{"#literal":10}]]', + * ); + * ``` + * + * @module + */ +import { Result, pipe } from "effect"; + +import * as Expression from "../Program/Expression.js"; +import * as Prelude from "../Program/Prelude.js"; +import * as ProgramError from "../Program/ProgramError.js"; +import * as Scope from "../Program/Scope.js"; +import * as Scribe from "./Scribe.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type { Type, TypeExpression } from "../main.js"; +import type * as Namespace from "../Program/Namespace.js"; +import type * as Body from "./Body.js"; + +export type * as Context from "./Context.js"; + +/** + * A Draft program constructor whose callbacks see the scope `S`. + * + * It takes an input schema and a callback, and returns the root expression or a construction failure. The result requires every schema entry. {@link program} documents the callback's timing and failure contract, which every constructor from {@link withPrelude} shares. + */ +export type Program = < + const I extends Body.Inputs, + const O extends Expression.AnyValue & Expression.Any, +>( + inputs: I, + draft: Body.Body, +) => Result.Result< + Expression.Expression, Body.Requirements>, + ProgramError.Construction +>; + +function inputHandle( + name: K, + type: D, +): Body.Handle; +function inputHandle( + name: K, + type: TypeExpression.TypeExpression, +): Expression.Expression>> { + return Expression.input(name, type); +} + +/** Creates each handle at the same schema key and semantic type, including its own input name. */ +const inputHandles = ( + schema: I, +): Result.Result, ProgramError.Construction> => { + const [symbol] = Object.getOwnPropertySymbols(schema); + if (symbol !== undefined) { + return Result.fail(ProgramError.Construction.symbolInputName(symbol)); + } + + const handles: Partial> = {}; + const member = (name: K): Body.Handles[K] => + inputHandle(name, schema[name]); + + for (const name of Object.getOwnPropertyNames(schema)) { + Object.defineProperty(handles, name, { + value: member(name), + enumerable: true, + }); + } + + // SAFETY: the loop fills every own string key with the handle for that exact key and semantic type. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- TypeScript cannot establish completion of a generic mapped record + return Result.succeed(Object.freeze(handles as Body.Handles)); +}; + +type Rebindings = { + readonly [K in keyof E]: E[K] extends undefined + ? undefined + : Relocatable; +}; + +/** + * Creates a program constructor whose callbacks see a custom prelude instead of the built-in one. + * + * The prelude's optional `modules`, `types` and `values` records replace `Prelude.builtin` entirely, without widening the supplied export tables. A callback reaches them through `$.prelude()`, which joins same-named exports into one handle, and `$.modules()`. A `values.entities` function that returns a `::graph::Graph` opaque type enables `$.query.entities`. A module from `Module.define` is a valid prelude. Seeding emits no HashQL, because each export already refers to its declaration. + * + * `withPrelude` copies the records' own string-keyed exports, including non-enumerable ones, when you call it. Later changes to the records do not reach the returned constructor, and `withPrelude` does not freeze them. The parameter type requires each export to be a rebindable SDK producer, such as a module, type expression or expression handle. A symbol-keyed export from an unchecked caller makes every program call return a `SymbolExportName` failure before its callback runs. + * + * @example Use a module as the whole prelude. + * ```ts + * import assert from "node:assert/strict"; + * import { Module, Program } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { withPrelude } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * type Add = Type.Function< + * readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + * Type.PrimitiveInteger + * >; + * const math = Result.getOrThrow( + * Module.define("::core::math", { values: { add: Module.value() } }), + * ); + * const { program } = withPrelude(math); + * + * const sum = program({}, ($) => { + * const names = $.prelude(); + * assert.equal("Uuid" in names, false); + * return names.add(1n, 2n); + * }); + * assert.equal( + * Result.getOrThrow(Result.flatMap(sum, (root) => Program.compile(Program.program(root)))), + * '["::core::math::add",{"#literal":1},{"#literal":2}]', + * ); + * ``` + */ +export function withPrelude( + prelude: S & Namespace.Rebindable, +): { readonly program: Program> }; +export function withPrelude< + M extends Scope.Scope["modules"] & Rebindings, + T extends Scope.Scope["types"] & Rebindings, + V extends Scope.Scope["values"] & Rebindings, +>(prelude: { + readonly modules?: M; + readonly types?: T; + readonly values?: V; +}): { + readonly program: Program<{ + readonly modules: Readonly | Scope.Empty["modules"]; + readonly types: Readonly | Scope.Empty["types"]; + readonly values: Readonly | Scope.Empty["values"]; + }>; +} { + const scope = Object.freeze({ + modules: Scope.snapshot(prelude.modules ?? {}), + types: Scope.snapshot(prelude.types ?? {}), + values: Scope.snapshot(prelude.values ?? {}), + }); + + const validate = (): Result.Result< + typeof scope, + ProgramError.Construction + > => { + for (const table of [scope.modules, scope.types, scope.values]) { + const [name] = Object.getOwnPropertySymbols(table); + if (name !== undefined) { + return Result.fail(ProgramError.Construction.symbolExportName(name)); + } + } + + return Result.succeed(scope); + }; + + const validated = validate(); + const program: Program = < + const I extends Body.Inputs, + const O extends Expression.AnyValue & Expression.Any, + >( + inputs: I, + draft: Body.Body, + ) => + pipe( + Result.all({ scope: validated, handles: inputHandles(inputs) }), + Result.flatMap(({ scope: accepted, handles }) => + Scribe.evaluate(accepted, (context) => + draft(context, handles), + ), + ), + ); + + return Object.freeze({ program }); +} + +/** + * Constructs a program's root expression with the built-in prelude. + * + * The callback runs synchronously with a construction context and typed input handles. Its operations build syntax rather than executing a query. The root expression retains every declared input requirement, including unused schema entries. A symbol input name causes a construction failure before the callback runs. + * + * Both conditional branch callbacks construct syntax, regardless of the condition's value. Host-side effects in those callbacks happen during construction. + * + * Use {@link withPrelude} to supply custom declarations. + * + * @param inputs - The input names and their semantic type expressions. + * @param draft - A synchronous construction callback returning an expression handle. + * @returns The root expression or a construction failure. Synchronous callback exceptions become `CallbackException` failures retaining the thrown value. Expected construction failures retain their original reasons. + * + * @example Construct and serialize a program. + * ```ts + * import assert from "node:assert/strict"; + * import { Program } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * let calls = 0; + * const result = program({}, ($) => { + * calls += 1; + * return $.literal("ready"); + * }); + * assert.equal(calls, 1); + * assert.equal( + * Result.getOrThrow(Result.flatMap(result, (root) => Program.compile(Program.program(root)))), + * '{"#literal":"ready"}', + * ); + * ``` + * + * @example Inspect a callback failure. + * ```ts + * import assert from "node:assert/strict"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const result = program({}, () => { + * throw new Error("Missing application configuration"); + * }); + * assert.ok(Result.isFailure(result)); + * assert.equal(result.failure.reason._tag, "CallbackException"); + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the schema and callback construct a new program +export const program: Program = withPrelude( + Prelude.builtin, +).program; diff --git a/libs/@local/hashql/sdk/typescript/src/internal/array.ts b/libs/@local/hashql/sdk/typescript/src/internal/array.ts new file mode 100644 index 00000000000..df3e6846929 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/array.ts @@ -0,0 +1,11 @@ +/** + * Array helpers that narrow readonly unions, which `Array.isArray` does not. + * + * @internal + */ + +/** Narrows `value` to its readonly array members. */ +// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- `T` accepts the non-array members without widening to `unknown` +export const isReadonlyArray = ( + value: T | readonly E[], +): value is readonly E[] => Array.isArray(value); diff --git a/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts b/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts new file mode 100644 index 00000000000..4be84e3c496 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts @@ -0,0 +1,36 @@ +/** + * Typed rebinding of handles to another HashQL path. + * + * Each producer retains its own rebinding function while its semantic parameters are in scope. Consumers can then move a handle without reconstructing those parameters from an erased export. The result type names the capabilities the producer preserves, rather than promising to retain arbitrary properties added by a caller. + * + * @module + */ +import { dual } from "effect/Function"; + +import type * as JExpr from "../JExpr/index.js"; +import type * as ProgramError from "../Program/ProgramError.js"; +import type { Result } from "effect"; + +export const Relocate: unique symbol = Symbol("~hashql/Relocate"); + +export interface Relocatable { + readonly [Relocate]: ( + path: JExpr.Path.Path, + ) => Result.Result; +} + +export const relocate: { + ( + path: JExpr.Path.Path, + ): (self: Relocatable) => Result.Result; + ( + self: Relocatable, + path: JExpr.Path.Path, + ): Result.Result; +} = dual( + 2, + ( + self: Relocatable, + path: JExpr.Path.Path, + ): Result.Result => self[Relocate](path), +); diff --git a/libs/@local/hashql/sdk/typescript/src/internal/scan.ts b/libs/@local/hashql/sdk/typescript/src/internal/scan.ts new file mode 100644 index 00000000000..db477b7e770 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/scan.ts @@ -0,0 +1,155 @@ +/** + * Scans HashQL identifiers and paths while preserving quoted separators. + * + * Backtick-quoted identifiers can contain `::`. Each identifier must consume its closing backtick before a path separator can begin. + * + * @internal + */ + +import { Filter, Option } from "effect"; + +/** The kinds of identifier, matching `IdentKind` in `hashql-core`. */ +export type Kind = "Lexical" | "Symbol" | "BaseUrl"; + +/** An identifier found in the input, without its backticks. */ +export interface ScanIdent { + readonly kind: Kind; + readonly value: string; + /** Index just past the identifier, including any closing backtick. */ + readonly end: number; +} + +const backtick = "`"; + +/** ASCII operator characters, or any non-ASCII punctuation or symbol. */ +export const symbolCharacterPattern: string = String.raw`(?:[!#$%&*+./<=>?@\\^|~\[\]-]|(?![\0-\x7F])[\p{P}\p{S}])`; + +/** RFC 3986 reserved, unreserved and percent characters (`ALLOWED_URL_CHARS`). */ +const urlChar = String.raw`[\w!#$%&'()*+,./:;=?@\[\]~-]`; + +/** A Unicode character that can start a lexical identifier. */ +export const lexicalStartPattern: string = String.raw`\p{XID_Start}`; + +/** A Unicode character that can follow the first character of a lexical identifier. */ +export const lexicalContinuePattern: string = String.raw`\p{XID_Continue}`; + +/** `XID_Start XID_Continue*`, or `_` followed by at least one `XID_Continue`. */ +export const lexicalPattern: string = String.raw`(?:${lexicalStartPattern}${lexicalContinuePattern}*|_${lexicalContinuePattern}+)`; + +/** One or more symbol characters. */ +export const symbolPattern: string = String.raw`(?:${symbolCharacterPattern}+)`; + +/** + * An HTTP(S) URL-shaped identifier ending in `/`. + * + * The first character after `//` must be a non-slash URL character. This checks spelling rather than URL validity. + */ +export const baseUrlPattern: string = String.raw`(?:https?://${urlChar.replace("/", "")}${urlChar}*/)`; + +const lexical = new RegExp(lexicalPattern, "uy"); +const symbol = new RegExp(symbolPattern, "uy"); +const escapedSymbol = new RegExp( + `${backtick}(${symbolPattern})${backtick}`, + "uy", +); +const escapedBaseUrl = new RegExp( + `${backtick}(${baseUrlPattern})${backtick}`, + "uy", +); + +/** `ws("::")` from the backend: a separator with optional surrounding whitespace. */ +const separator = /[\t\n\r ]*::[\t\n\r ]*/uy; + +/** A leading `::` marking a rooted path, with optional trailing whitespace. */ +const root = /::[\t\n\r ]*/uy; + +const matchAtRaw = ( + expression: RegExp, + input: string, + start: number, +): Option.Option => { + expression.lastIndex = start; + return Option.fromNullishOr(expression.exec(input)); +}; + +const matchAt = + ( + expression: RegExp, + input: string, + start: number, + ): ((kind: Kind, group: 0 | 1) => Option.Option) => + (kind: Kind, group: 0 | 1): Option.Option => + Option.filterMap( + matchAtRaw(expression, input, start), + Filter.fromPredicateOption((match) => + Option.fromNullishOr(match[group]).pipe( + Option.map((value) => ({ + kind, + value, + end: match.index + match[0].length, + })), + ), + ), + ); + +const scanIdent = (input: string, start: number): Option.Option => { + if (input.startsWith(backtick, start)) { + return Option.orElse( + matchAt(escapedSymbol, input, start)("Symbol", 1), + () => matchAt(escapedBaseUrl, input, start)("BaseUrl", 1), + ); + } + + return Option.orElse(matchAt(lexical, input, start)("Lexical", 0), () => + matchAt(symbol, input, start)("Symbol", 0), + ); +}; + +export const scanIdentExact = (input: string): Option.Option => + scanIdent(input, 0).pipe( + Option.filter((ident) => ident.end === input.length), + ); + +/** A path split into its parts. */ +interface ScanPath { + readonly rooted: boolean; + readonly segments: readonly [ScanIdent, ...ScanIdent[]]; +} + +/** + * Splits `input` into an optional leading `::` and `::`-separated identifiers. + * + * Whitespace is allowed around separators, as in the backend. Leading and + * trailing whitespace, empty segments and per-segment generic arguments are + * rejected. + */ +export const scanPath = (input: string): Option.Option => { + const rootMatch = matchAtRaw(root, input, 0); + const first = scanIdent(input, rootMatch.valueOrUndefined?.[0].length ?? 0); + + if (Option.isNone(first)) { + return Option.none(); + } + + const segments: [ScanIdent, ...ScanIdent[]] = [first.value]; + let position = first.value.end; + + while (position < input.length) { + const next = matchAtRaw(separator, input, position); + + if (Option.isNone(next)) { + return Option.none(); + } + + const segment = scanIdent(input, next.value.index + next.value[0].length); + + if (Option.isNone(segment)) { + return Option.none(); + } + + segments.push(segment.value); + position = segment.value.end; + } + + return Option.some({ rooted: rootMatch._tag === "Some", segments }); +}; diff --git a/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.test.ts b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.test.ts new file mode 100644 index 00000000000..5f6be37183d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.test.ts @@ -0,0 +1,23 @@ +import { Result, Schema, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { exactly } from "./schema-arbitrary.js"; + +const generatePattern = (): string => "[a-z]+"; +const cases = [ + { name: "direct_default", schema: exactly("[a-z]+") }, + { name: "direct_hint", schema: exactly("[a-z]+", generatePattern) }, + { name: "pipe_default", schema: pipe("[a-z]+", exactly()) }, + { name: "pipe_hint", schema: pipe("[a-z]+", exactly(generatePattern)) }, +]; + +describe("exact_pattern", () => { + test.each(cases)("$name", ({ schema }) => { + expect.hasAssertions(); + const decode = Schema.decodeResult(schema); + expect(Result.getOrThrow(decode("letters"))).toBe("letters"); + expect(Result.isFailure(decode("1letters"))).toBe(true); + expect(Result.isFailure(decode("letters1"))).toBe(true); + expect(Result.isFailure(decode("letters\n"))).toBe(true); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts new file mode 100644 index 00000000000..c29bfd80cfb --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts @@ -0,0 +1,63 @@ +/** + * Constructive arbitrary generation for schema string patterns. + * + * Effect's arbitrary compiler requires explicit character ranges for Unicode properties and lookarounds. Generation hints supply those ranges while schema validation retains the original pattern. + * + * @internal + */ +import { Schema } from "effect"; +import { dual, memoize } from "effect/Function"; + +/** Expands a character pattern into Unicode ranges for arbitrary generation. */ +export const characterClass: (pattern: Readonly) => string = memoize( + (pattern): string => { + const maximumCodePoint = 1_114_111; + const hexadecimalRadix = 16; + const ranges: string[] = []; + let start: number | undefined = undefined; + + // include a sentinel after the final code point to close any remaining range + for (let codePoint = 0; codePoint <= maximumCodePoint + 1; codePoint += 1) { + if ( + codePoint <= maximumCodePoint && + pattern.test(String.fromCodePoint(codePoint)) + ) { + start ??= codePoint; + } else if (start !== undefined) { + const first = `\\u{${start.toString(hexadecimalRadix)}}`; + if (start === codePoint - 1) { + ranges.push(first); + } else { + const last = `\\u{${(codePoint - 1).toString(hexadecimalRadix)}}`; + ranges.push(`${first}-${last}`); + } + start = undefined; + } + } + + return `[${ranges.join("")}]`; + }, +); + +/** Requires the entire value to match a pattern, with separate generation hints. */ +export const exactly: { + (generatePattern?: () => string): (pattern: string) => Schema.String; + (pattern: string, generatePattern?: () => string): Schema.String; +} = dual( + (args) => typeof args[0] === "string", + ( + pattern: string, + generatePattern: () => string = () => pattern, + ): Schema.String => + Schema.String.check( + // `$` also matches before a final line terminator. The lookahead requires end of input. + Schema.isPattern(new RegExp(`^(?:${pattern})(?![\\s\\S])`, "u"), { + arbitraryConstraint: { + // expansion runs only during arbitrary derivation, using the same Unicode tables as validation + get patterns(): readonly [Schema.Annotations.ToArbitrary.Pattern] { + return [{ source: `^(?:${generatePattern()})$`, flags: "u" }]; + }, + }, + }), + ), +); diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index 033fd01e328..47910a919b3 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -1,2 +1,22 @@ -// oxlint-disable-next-line unicorn/require-module-specifiers -- This scaffold intentionally exposes no API. -export {}; +/** + * Typed HashQL syntax construction and J-Expr encoding. + * + * Use `@local/hashql/draft` to author a program synchronously against an explicit input schema. {@link Expression} also provides direct construction, and {@link Program} wraps a root expression for serialization. + * + * {@link Type} describes semantic types at compile time. {@link TypeExpression} carries their syntax at runtime. {@link Module} declares trusted external names, and {@link JExpr} provides the lower-level syntax model. The SDK builds programs but does not execute them. Its type declarations require TypeScript 7. + * + * @module + */ +export * as JExpr from "./JExpr/index.js"; +export * as Expression from "./Program/Expression.js"; +export * as Module from "./Program/Module.js"; +export * as Operators from "./Program/Operators.js"; +export * as Prelude from "./Program/Prelude.js"; +export * as Structural from "./Program/Structural.js"; +export * as Program from "./Program/index.js"; +export * as ProgramError from "./Program/ProgramError.js"; +export { program } from "./Program/index.js"; +export { ifElse as If, assume } from "./Program/Expression.js"; +export * as TypeExpression from "./Program/TypeExpression.js"; +export type * as Type from "./Type/index.js"; +export type * as Inputs from "./Program/Inputs.js"; diff --git a/libs/@local/hashql/sdk/typescript/tsconfig.json b/libs/@local/hashql/sdk/typescript/tsconfig.json index 8d0f942d866..84e2b2d3868 100644 --- a/libs/@local/hashql/sdk/typescript/tsconfig.json +++ b/libs/@local/hashql/sdk/typescript/tsconfig.json @@ -12,5 +12,5 @@ "isolatedDeclarations": true, "noEmit": true }, - "include": ["src", "oxlint.config.ts", "tsdown.config.ts"] + "include": ["src", "examples", "oxlint.config.ts", "tsdown.config.ts"] } diff --git a/libs/@local/hashql/sdk/typescript/tsdoc.json b/libs/@local/hashql/sdk/typescript/tsdoc.json index 802e1e09536..10f257f74bf 100644 --- a/libs/@local/hashql/sdk/typescript/tsdoc.json +++ b/libs/@local/hashql/sdk/typescript/tsdoc.json @@ -1,5 +1,6 @@ { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "extends": ["@microsoft/api-extractor/extends/tsdoc-base.json"], "tagDefinitions": [ { "tagName": "@category", diff --git a/libs/@local/hashql/sdk/typescript/tsdown.config.ts b/libs/@local/hashql/sdk/typescript/tsdown.config.ts index 94f0cfb436d..dfaa6e16d6e 100644 --- a/libs/@local/hashql/sdk/typescript/tsdown.config.ts +++ b/libs/@local/hashql/sdk/typescript/tsdown.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from "tsdown"; import type { UserConfig } from "tsdown"; const config: UserConfig = defineConfig({ - entry: ["src/main.ts"], + entry: ["src/main.ts", "src/draft/index.ts"], format: "esm", platform: "neutral", unbundle: true, diff --git a/yarn.config.cjs b/yarn.config.cjs index 7917e429f97..c0c5a46a7ab 100644 --- a/yarn.config.cjs +++ b/yarn.config.cjs @@ -263,7 +263,7 @@ function enforceDevDependenciesAreProperlyDeclared({ Yarn }) { /** @type {Record | undefined} */ const scripts = workspace.manifest.scripts; - if (!scripts) { + if (!scripts || ignoredWorkspaces.includes(workspace.ident)) { continue; } diff --git a/yarn.lock b/yarn.lock index 5a9f7ec9eeb..b54c2bbb82e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -74,6 +74,13 @@ __metadata: languageName: node linkType: hard +"@alloc/quick-lru@npm:^5.2.0": + version: 5.3.0 + resolution: "@alloc/quick-lru@npm:5.3.0" + checksum: 10c0/de92309b58674d17e627e43b73db9744a7f47d1987f1e3995ed0b3bb218b25df61940cc311a3c83429bc482e140f3d90851725cac5250222f9a9a5e5ec8a4343 + languageName: node + linkType: hard + "@anthropic-ai/bedrock-sdk@npm:0.26.3": version: 0.26.3 resolution: "@anthropic-ai/bedrock-sdk@npm:0.26.3" @@ -4185,9 +4192,9 @@ __metadata: linkType: hard "@babel/runtime@npm:^7.0.0, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.13.10, @babel/runtime@npm:^7.15.4, @babel/runtime@npm:^7.16.3, @babel/runtime@npm:^7.18.3, @babel/runtime@npm:^7.18.6, @babel/runtime@npm:^7.23.8, @babel/runtime@npm:^7.23.9, @babel/runtime@npm:^7.24.5, @babel/runtime@npm:^7.26.0, @babel/runtime@npm:^7.26.10, @babel/runtime@npm:^7.28.4, @babel/runtime@npm:^7.28.6, @babel/runtime@npm:^7.29.7, @babel/runtime@npm:^7.5.5, @babel/runtime@npm:^7.7.6, @babel/runtime@npm:^7.8.7, @babel/runtime@npm:^7.9.2": - version: 7.29.7 - resolution: "@babel/runtime@npm:7.29.7" - checksum: 10c0/ca11572f7146b21e0bde6a9ed4bb6a89eafbee5f0944c7eb54d0d8a2dac962c33638a1d611e14faa71dfbb92b4b5f9236232208568a6b7d5c6f3f39ddb91771e + version: 7.29.10 + resolution: "@babel/runtime@npm:7.29.10" + checksum: 10c0/32f975da8e9c2cae6b33e1a477f8fe8bbff6722c982b5ce35f99affaf3a7a1b612c8272b43afa0e51d3000928d6f3ba38f9296301115db5640264907c027b0cd languageName: node linkType: hard @@ -4270,7 +4277,7 @@ __metadata: languageName: node linkType: hard -"@base-ui/react@npm:1.8.0": +"@base-ui/react@npm:1.8.0, @base-ui/react@npm:^1.8.0": version: 1.8.0 resolution: "@base-ui/react@npm:1.8.0" dependencies: @@ -5551,7 +5558,7 @@ __metadata: languageName: node linkType: hard -"@emnapi/core@npm:1.11.2, @emnapi/core@npm:^1.4.3": +"@emnapi/core@npm:1.11.2": version: 1.11.2 resolution: "@emnapi/core@npm:1.11.2" dependencies: @@ -5571,6 +5578,16 @@ __metadata: languageName: node linkType: hard +"@emnapi/core@npm:^1.11.1, @emnapi/core@npm:^1.4.3": + version: 1.11.3 + resolution: "@emnapi/core@npm:1.11.3" + dependencies: + "@emnapi/wasi-threads": "npm:1.2.3" + tslib: "npm:^2.4.0" + checksum: 10c0/4ca08d349a82d5d2887ccc9e12df630877b0412ddcd59b9faee61e3c3947ccead27a18257a18bfe17abdf2b0709857808ad75d423ac49edd50c32fb140a7ed6e + languageName: node + linkType: hard + "@emnapi/runtime@npm:1.11.1": version: 1.11.1 resolution: "@emnapi/runtime@npm:1.11.1" @@ -5598,7 +5615,7 @@ __metadata: languageName: node linkType: hard -"@emnapi/runtime@npm:^1.11.3, @emnapi/runtime@npm:^1.4.3": +"@emnapi/runtime@npm:^1.11.1, @emnapi/runtime@npm:^1.11.3, @emnapi/runtime@npm:^1.4.3": version: 1.11.3 resolution: "@emnapi/runtime@npm:1.11.3" dependencies: @@ -5625,6 +5642,15 @@ __metadata: languageName: node linkType: hard +"@emnapi/wasi-threads@npm:1.2.3, @emnapi/wasi-threads@npm:^1.2.2": + version: 1.2.3 + resolution: "@emnapi/wasi-threads@npm:1.2.3" + dependencies: + tslib: "npm:^2.4.0" + checksum: 10c0/5aed84bc5dbe867973b20406ca1ed95661a4892ecaef80378fdf2d37424b3f7b9c428df8a3e1d82b783a3345a530032bf049e699e1f113ea52203c3e9b4e6ce5 + languageName: node + linkType: hard + "@emotion/babel-plugin@npm:^11.13.5": version: 11.13.5 resolution: "@emotion/babel-plugin@npm:11.13.5" @@ -6819,6 +6845,104 @@ __metadata: languageName: node linkType: hard +"@fuma-translate/react@npm:^1.0.2": + version: 1.0.2 + resolution: "@fuma-translate/react@npm:1.0.2" + peerDependencies: + "@types/react": "*" + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/459792f25c4dbe682cddaaeef0d0eee9bf10779a160797c2a959746c87cd754337287437508a0e8d300c1078145c496265ec0919f154be42f6a685bf480fda78 + languageName: node + linkType: hard + +"@fumadocs/local-content@npm:0.2.2": + version: 0.2.2 + resolution: "@fumadocs/local-content@npm:0.2.2" + dependencies: + chokidar: "npm:^5.0.0" + picomatch: "npm:^4.0.7" + tinyglobby: "npm:^0.2.17" + ws: "npm:^8.21.3" + peerDependencies: + "@types/react": "*" + fumadocs-core: ^16.15.0 + react: ^19.2.0 + vite: ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + "@types/react": + optional: true + react: + optional: true + vite: + optional: true + checksum: 10c0/aa67643d9c9dbf588bbb6afce595df645213201fcdf1bb3d3a4e5d7b29726e9136818a980c330be4bbdfb8150d9846ce492a6559cc505e6e632945e50834573f + languageName: node + linkType: hard + +"@fumadocs/satteri@npm:0.5.1": + version: 0.5.1 + resolution: "@fumadocs/satteri@npm:0.5.1" + dependencies: + "@fumadocs/local-content": "npm:0.2.2" + "@fumari/image-size": "npm:^0.1.1" + "@standard-schema/spec": "npm:^1.1.0" + estree-util-to-js: "npm:^2.0.0" + fumadocs-typescript: "npm:^5.4.1" + github-slugger: "npm:^2.0.0" + hast-util-to-estree: "npm:^3.1.3" + katex: "npm:^0.18.7" + npm-to-yarn: "npm:^3.2.0" + satteri: "npm:^0.10.5" + yuku-codegen: "npm:^0.9.5" + yuku-parser: "npm:^0.9.5" + peerDependencies: + "@types/hast": "*" + "@types/mdast": "*" + "@types/mdx": "*" + "@types/react": "*" + fumadocs-core: ^16.15.3 + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + "@types/hast": + optional: true + "@types/mdast": + optional: true + "@types/mdx": + optional: true + "@types/react": + optional: true + react: + optional: true + react-dom: + optional: true + checksum: 10c0/20d5eeceeaf4498f41f8f3eead554af61612189a78f4f7f94c3f4fef56b9af32a9a6386c5901c43d4aa0e2debc5b65de6422d164ca097f9d2070715d69025c30 + languageName: node + linkType: hard + +"@fumadocs/tailwind@npm:0.1.2": + version: 0.1.2 + resolution: "@fumadocs/tailwind@npm:0.1.2" + peerDependencies: + tailwindcss: ^4.0.0 + peerDependenciesMeta: + tailwindcss: + optional: true + checksum: 10c0/f15abd61032f59d2db428a916eb215322075f19fc57a11b127910a89ce2c25e1a88cd10cb9cef1cbe8fdd6a3502cd03d6933a04383c266eef2dd0505d311b801 + languageName: node + linkType: hard + +"@fumari/image-size@npm:^0.1.1": + version: 0.1.1 + resolution: "@fumari/image-size@npm:0.1.1" + checksum: 10c0/80f645cfffd67f3fd4e25897e2a0c1f65c0f4a786b512c48b0f0c897d5d6e19779b4b1467aae1e0012650bc1a9ee63478775cf93dc05a3de617c32278ce34624 + languageName: node + linkType: hard + "@glideapps/glide-data-grid@npm:6.0.3": version: 6.0.3 resolution: "@glideapps/glide-data-grid@npm:6.0.3" @@ -10105,13 +10229,64 @@ __metadata: languageName: unknown linkType: soft -"@local/hashql@workspace:libs/@local/hashql/sdk/typescript": +"@local/hashql-typescript-docs@workspace:libs/@local/hashql/sdk/typescript-docs": + version: 0.0.0-use.local + resolution: "@local/hashql-typescript-docs@workspace:libs/@local/hashql/sdk/typescript-docs" + dependencies: + "@effect/platform-node": "npm:4.0.3" + "@effect/vitest": "npm:4.0.3" + "@fumadocs/satteri": "npm:0.5.1" + "@local/hashql": "workspace:*" + "@local/oxlint": "workspace:*" + "@local/tsconfig": "workspace:*" + "@microsoft/api-extractor": "npm:7.59.4" + "@microsoft/api-extractor-model": "npm:7.33.15" + "@microsoft/tsdoc": "npm:0.17.1" + "@microsoft/tsdoc-config": "npm:0.18.3" + "@tailwindcss/postcss": "npm:4.3.3" + "@tsconfig/bases": "catalog:" + "@types/hast": "npm:3.0.5" + "@types/mdast": "npm:4.0.4" + "@types/mdx": "npm:2.0.14" + "@types/node": "catalog:" + "@types/react": "npm:19.2.14" + "@types/react-dom": "npm:19.2.3" + effect: "npm:4.0.3" + fumadocs-core: "npm:16.16.2" + fumadocs-mdx: "npm:15.4.6" + fumadocs-twoslash: "npm:4.0.1" + fumadocs-ui: "npm:16.16.2" + mdast-util-mdx-jsx: "npm:3.1.3" + next: "npm:16.3.8" + oxc-parser: "npm:0.152.0" + oxc-resolver: "npm:11.24.2" + oxfmt: "npm:0.71.0" + oxlint: "catalog:" + react: "npm:19.2.6" + react-dom: "npm:19.2.6" + remark-frontmatter: "npm:5.0.0" + remark-mdx: "npm:3.1.1" + remark-stringify: "npm:11.0.0" + satteri: "npm:0.10.5" + shiki: "npm:4.5.0" + tailwindcss: "npm:4.3.3" + tsx: "catalog:" + typescript: "catalog:" + unified: "npm:11.0.5" + vite: "catalog:" + vitest: "catalog:" + yaml: "npm:2.9.1" + languageName: unknown + linkType: soft + +"@local/hashql@workspace:*, @local/hashql@workspace:libs/@local/hashql/sdk/typescript": version: 0.0.0-use.local resolution: "@local/hashql@workspace:libs/@local/hashql/sdk/typescript" dependencies: "@local/oxlint": "workspace:*" "@local/tsconfig": "workspace:*" "@tsconfig/bases": "catalog:" + effect: "npm:4.0.3" oxlint: "catalog:" tsdown: "npm:0.23.0" typescript: "catalog:" @@ -10490,6 +10665,40 @@ __metadata: languageName: node linkType: hard +"@microsoft/api-extractor-model@npm:7.33.15": + version: 7.33.15 + resolution: "@microsoft/api-extractor-model@npm:7.33.15" + dependencies: + "@microsoft/tsdoc": "npm:~0.17.0" + "@microsoft/tsdoc-config": "npm:~0.18.2" + "@rushstack/node-core-library": "npm:5.25.1" + checksum: 10c0/7dce2166e3d5c0f562f99893f2b8a078e24121ed57a10970e3bcbf33cc13916dc4fd2523b685e60288d058a4b3557fa9759320cb529683a5ad743bb80e943a58 + languageName: node + linkType: hard + +"@microsoft/api-extractor@npm:7.59.4": + version: 7.59.4 + resolution: "@microsoft/api-extractor@npm:7.59.4" + dependencies: + "@microsoft/api-extractor-model": "npm:7.33.15" + "@microsoft/tsdoc": "npm:~0.17.0" + "@microsoft/tsdoc-config": "npm:~0.18.2" + "@rushstack/node-core-library": "npm:5.25.1" + "@rushstack/rig-package": "npm:0.7.4" + "@rushstack/terminal": "npm:0.24.7" + "@rushstack/ts-command-line": "npm:5.3.17" + diff: "npm:~8.0.2" + minimatch: "npm:10.2.3" + resolve: "npm:~1.22.1" + semver: "npm:~7.7.4" + source-map: "npm:~0.6.1" + typescript: "npm:5.9.3" + bin: + api-extractor: bin/api-extractor + checksum: 10c0/2b805f72318edb8dab720a2b2eb2a6b82faebbb6a6b5b836fced38875e61d344b14c7edf63724a27ab091fed4df8ef9923141f579fb1ddc7679d48ce02301e96 + languageName: node + linkType: hard + "@microsoft/fetch-event-source@npm:^2.0.1": version: 2.0.1 resolution: "@microsoft/fetch-event-source@npm:2.0.1" @@ -10509,6 +10718,18 @@ __metadata: languageName: node linkType: hard +"@microsoft/tsdoc-config@npm:0.18.3, @microsoft/tsdoc-config@npm:~0.18.2": + version: 0.18.3 + resolution: "@microsoft/tsdoc-config@npm:0.18.3" + dependencies: + "@microsoft/tsdoc": "npm:0.17.1" + ajv: "npm:~8.18.0" + jju: "npm:~1.4.0" + resolve: "npm:~1.22.2" + checksum: 10c0/8a065caa452bb7f6aa6b0cf95acad970b7e10af39a856988ba5df7e19bc482444454f7dc48b86d98908b6600b009757c34a769ba302e3bc5ef04d1076ac71fc9 + languageName: node + linkType: hard + "@microsoft/tsdoc@npm:0.16.0": version: 0.16.0 resolution: "@microsoft/tsdoc@npm:0.16.0" @@ -10516,6 +10737,13 @@ __metadata: languageName: node linkType: hard +"@microsoft/tsdoc@npm:0.17.1, @microsoft/tsdoc@npm:~0.17.0": + version: 0.17.1 + resolution: "@microsoft/tsdoc@npm:0.17.1" + checksum: 10c0/a8d5dd60edc60a8f4de7b1b260cd0633205457a630316b75fd2afe0a633d3acd3389b4e483c047d681981da89cd6448e8f6e0387dc32533ecd63fbce3a580a92 + languageName: node + linkType: hard + "@modelcontextprotocol/client@npm:2.0.0": version: 2.0.0 resolution: "@modelcontextprotocol/client@npm:2.0.0" @@ -11880,6 +12108,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-android-arm-eabi@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-android-arm-eabi@npm:0.152.0" + conditions: os=android & cpu=arm + languageName: node + linkType: hard + "@oxc-parser/binding-android-arm64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-android-arm64@npm:0.127.0" @@ -11887,6 +12122,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-android-arm64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-android-arm64@npm:0.152.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-darwin-arm64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-darwin-arm64@npm:0.127.0" @@ -11894,6 +12136,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-darwin-arm64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-darwin-arm64@npm:0.152.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-darwin-x64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-darwin-x64@npm:0.127.0" @@ -11901,6 +12150,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-darwin-x64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-darwin-x64@npm:0.152.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + "@oxc-parser/binding-freebsd-x64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-freebsd-x64@npm:0.127.0" @@ -11908,6 +12164,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-freebsd-x64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-freebsd-x64@npm:0.152.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm-gnueabihf@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm-gnueabihf@npm:0.127.0" @@ -11915,6 +12178,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm-gnueabihf@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm-gnueabihf@npm:0.152.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm-musleabihf@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm-musleabihf@npm:0.127.0" @@ -11922,6 +12192,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm-musleabihf@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm-musleabihf@npm:0.152.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm64-gnu@npm:0.127.0" @@ -11929,6 +12206,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm64-gnu@npm:0.152.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm64-musl@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm64-musl@npm:0.127.0" @@ -11936,6 +12220,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm64-musl@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm64-musl@npm:0.152.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + "@oxc-parser/binding-linux-ppc64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-ppc64-gnu@npm:0.127.0" @@ -11943,6 +12234,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-ppc64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-ppc64-gnu@npm:0.152.0" + conditions: os=linux & cpu=ppc64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-riscv64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-riscv64-gnu@npm:0.127.0" @@ -11950,6 +12248,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-riscv64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-riscv64-gnu@npm:0.152.0" + conditions: os=linux & cpu=riscv64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-riscv64-musl@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-riscv64-musl@npm:0.127.0" @@ -11957,6 +12262,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-riscv64-musl@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-riscv64-musl@npm:0.152.0" + conditions: os=linux & cpu=riscv64 & libc=musl + languageName: node + linkType: hard + "@oxc-parser/binding-linux-s390x-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-s390x-gnu@npm:0.127.0" @@ -11964,6 +12276,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-s390x-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-s390x-gnu@npm:0.152.0" + conditions: os=linux & cpu=s390x & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-x64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-x64-gnu@npm:0.127.0" @@ -11971,6 +12290,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-x64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-x64-gnu@npm:0.152.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-x64-musl@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-x64-musl@npm:0.127.0" @@ -11978,6 +12304,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-x64-musl@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-x64-musl@npm:0.152.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + "@oxc-parser/binding-openharmony-arm64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-openharmony-arm64@npm:0.127.0" @@ -11985,6 +12318,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-openharmony-arm64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-openharmony-arm64@npm:0.152.0" + conditions: os=openharmony & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-wasm32-wasi@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-wasm32-wasi@npm:0.127.0" @@ -12003,6 +12343,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-win32-arm64-msvc@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-win32-arm64-msvc@npm:0.152.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-win32-ia32-msvc@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-win32-ia32-msvc@npm:0.127.0" @@ -12010,6 +12357,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-win32-ia32-msvc@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-win32-ia32-msvc@npm:0.152.0" + conditions: os=win32 & cpu=ia32 + languageName: node + linkType: hard + "@oxc-parser/binding-win32-x64-msvc@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-win32-x64-msvc@npm:0.127.0" @@ -12017,6 +12371,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-win32-x64-msvc@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-win32-x64-msvc@npm:0.152.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@oxc-project/types@npm:=0.147.0": version: 0.147.0 resolution: "@oxc-project/types@npm:0.147.0" @@ -12024,7 +12385,7 @@ __metadata: languageName: node linkType: hard -"@oxc-project/types@npm:=0.152.0": +"@oxc-project/types@npm:=0.152.0, @oxc-project/types@npm:^0.152.0": version: 0.152.0 resolution: "@oxc-project/types@npm:0.152.0" checksum: 10c0/5958369f7a2d9fb1f8061ab3aa1abf9b3565cc8895e7e8b3800cd08b6d8077d7ddb4e383ff472811a63302954170a2a52c60fcd7cca38e416910c5f39861d0db @@ -13476,6 +13837,13 @@ __metadata: languageName: node linkType: hard +"@radix-ui/number@npm:1.1.3": + version: 1.1.3 + resolution: "@radix-ui/number@npm:1.1.3" + checksum: 10c0/da682127b62196a617d30d8b085a0b422b067a6155982aa313d33824cbeae16b95547a41ec74e0cf8cb67b30f5f825b3e9222abf6871b2ae0bf12badad4310d6 + languageName: node + linkType: hard + "@radix-ui/primitive@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/primitive@npm:1.0.1" @@ -13492,6 +13860,40 @@ __metadata: languageName: node linkType: hard +"@radix-ui/primitive@npm:1.1.7": + version: 1.1.7 + resolution: "@radix-ui/primitive@npm:1.1.7" + checksum: 10c0/6b1f8b964a57ece3490582d60df79a1c80fdba4c4331b806c4e04b11f42ac46d40a927bfc692dbd881136ec38c3f060c525dbacd6182ba6f3f0bd4284db1028e + languageName: node + linkType: hard + +"@radix-ui/react-accordion@npm:^1.2.20": + version: 1.2.21 + resolution: "@radix-ui/react-accordion@npm:1.2.21" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-collapsible": "npm:1.1.21" + "@radix-ui/react-collection": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/7bf0870e37ea16081a265fc64b6da4cf08c02705acc8abb083bda49f5d17f0bb4fc277cb64aa9644c94dbf5128cf059b126fb31d9753ac37e2cb28e0f4468457 + languageName: node + linkType: hard + "@radix-ui/react-alert-dialog@npm:^1.0.0": version: 1.1.2 resolution: "@radix-ui/react-alert-dialog@npm:1.1.2" @@ -13555,6 +13957,51 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-arrow@npm:1.1.16": + version: 1.1.16 + resolution: "@radix-ui/react-arrow@npm:1.1.16" + dependencies: + "@radix-ui/react-primitive": "npm:2.1.11" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/4415c516475e8468a0f23643e0a31f7642b53c2f53039324d82a969cf69239822b80350a42cf52f66300562e345c542fba9cd715ddaaadc0c695db510d606682 + languageName: node + linkType: hard + +"@radix-ui/react-collapsible@npm:1.1.21, @radix-ui/react-collapsible@npm:^1.1.20": + version: 1.1.21 + resolution: "@radix-ui/react-collapsible@npm:1.1.21" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/6e1ec58ef0848f1ec932a783456a9b5938a5de67adee2203ddb95c32b54e73c9a2858583db18853f8a8e237655f33fb15c7deb12c3d9ccbe4c923c53b312a2c1 + languageName: node + linkType: hard + "@radix-ui/react-collection@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-collection@npm:1.0.3" @@ -13600,6 +14047,28 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-collection@npm:1.1.16": + version: 1.1.16 + resolution: "@radix-ui/react-collection@npm:1.1.16" + dependencies: + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/625282244a1b90d8dda98ec325cad7bf0a18134d7b3eade8e3a5af3403872f5e9261c90155e368e120a3836816d724c26c0890faa06231f54b6582ce11c622af + languageName: node + linkType: hard + "@radix-ui/react-compose-refs@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-compose-refs@npm:1.0.1" @@ -13628,6 +14097,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-compose-refs@npm:1.1.5": + version: 1.1.5 + resolution: "@radix-ui/react-compose-refs@npm:1.1.5" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/ab5cc8cc2f5be285981cffb64aa956d3a28427c649a953d125e900e1befb8b9a55f2d7a31bc01059d29df43ff4ae14ebc6cca7e4c2084d638cef5e5aef7cc263 + languageName: node + linkType: hard + "@radix-ui/react-context-menu@npm:^2.1.1": version: 2.2.2 resolution: "@radix-ui/react-context-menu@npm:2.2.2" @@ -13693,7 +14175,20 @@ __metadata: languageName: node linkType: hard -"@radix-ui/react-dialog@npm:1.1.2, @radix-ui/react-dialog@npm:^1.0.2": +"@radix-ui/react-context@npm:1.2.2": + version: 1.2.2 + resolution: "@radix-ui/react-context@npm:1.2.2" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/f5c15339558d64901c99f243a2538be9b28eb20e0dae1e44c8872ed12580ec27f5f309fd491f85f1b0dcb214c90fdae7eede7fe2b0d26569c4dbeffbeff451c0 + languageName: node + linkType: hard + +"@radix-ui/react-dialog@npm:1.1.2": version: 1.1.2 resolution: "@radix-ui/react-dialog@npm:1.1.2" dependencies: @@ -13725,6 +14220,39 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-dialog@npm:^1.0.2, @radix-ui/react-dialog@npm:^1.1.23": + version: 1.2.0 + resolution: "@radix-ui/react-dialog@npm:1.2.0" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-dismissable-layer": "npm:1.1.20" + "@radix-ui/react-focus-guards": "npm:1.1.6" + "@radix-ui/react-focus-scope": "npm:1.2.0" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-portal": "npm:1.1.18" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + aria-hidden: "npm:^1.2.4" + react-remove-scroll: "npm:^2.7.2" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/f84958bed5ffaefb9d257cda6193f5ef79c48f0b8aec2fe3fa86aabf0c44edd2a1e6d969e399c3ead5623ff4c1040b365ef48ed5c4d4a36c2d8125bc41440e5d + languageName: node + linkType: hard + "@radix-ui/react-direction@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-direction@npm:1.0.1" @@ -13753,6 +14281,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-direction@npm:1.1.5, @radix-ui/react-direction@npm:^1.1.4": + version: 1.1.5 + resolution: "@radix-ui/react-direction@npm:1.1.5" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/a59a145b93fef5d101dff28dba7f5877aa6a051d9ae1106e8d80b73305f3d3d46f54195377eb690524e7954323e3cdc15d757e85da233a77d116c8b3491ada5e + languageName: node + linkType: hard + "@radix-ui/react-dismissable-layer@npm:1.0.4": version: 1.0.4 resolution: "@radix-ui/react-dismissable-layer@npm:1.0.4" @@ -13800,6 +14341,29 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-dismissable-layer@npm:1.1.20": + version: 1.1.20 + resolution: "@radix-ui/react-dismissable-layer@npm:1.1.20" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-effect-event": "npm:0.0.5" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/cd42f18d72fd30fed0b8e9888f8da204d315ffa4d55209d3a713950eb6c81666b4bb46d0b07625d0c3bd86e9ce6ac2ed1489e03b166f4944cc4524289b2820e8 + languageName: node + linkType: hard + "@radix-ui/react-dropdown-menu@npm:^2.0.1": version: 2.1.2 resolution: "@radix-ui/react-dropdown-menu@npm:2.1.2" @@ -13853,6 +14417,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-focus-guards@npm:1.1.6": + version: 1.1.6 + resolution: "@radix-ui/react-focus-guards@npm:1.1.6" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/5579dfe369f254183a010964e6df8b74c7b36e50189aef18c92538d0196785d68869e3170af77005276f393cd112b7711d5c7cb9e7ec2ca1e0b4794157447978 + languageName: node + linkType: hard + "@radix-ui/react-focus-scope@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-focus-scope@npm:1.0.3" @@ -13896,6 +14473,27 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-focus-scope@npm:1.2.0": + version: 1.2.0 + resolution: "@radix-ui/react-focus-scope@npm:1.2.0" + dependencies: + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/67a62110fdf44172f9da44b4b05b2723ab96a4045b5f4e98445cf18825e12456972860852779802200047ad37f9f192884633de11918f066ca8a27b4ad4c3161 + languageName: node + linkType: hard + "@radix-ui/react-id@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-id@npm:1.0.1" @@ -13927,6 +14525,21 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-id@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-id@npm:1.1.4" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/7afa00d12d7f52b5067034108eb7d5551928f9d52875589f858ea1d5117cac3684f8ea291d4f09a88b9499bc4bb6e3279e4a9073d7c8feb15a855d28656b53a4 + languageName: node + linkType: hard + "@radix-ui/react-menu@npm:2.1.2": version: 2.1.2 resolution: "@radix-ui/react-menu@npm:2.1.2" @@ -13963,25 +14576,59 @@ __metadata: languageName: node linkType: hard -"@radix-ui/react-popover@npm:^1.0.2": - version: 1.1.2 - resolution: "@radix-ui/react-popover@npm:1.1.2" - dependencies: - "@radix-ui/primitive": "npm:1.1.0" - "@radix-ui/react-compose-refs": "npm:1.1.0" - "@radix-ui/react-context": "npm:1.1.1" - "@radix-ui/react-dismissable-layer": "npm:1.1.1" - "@radix-ui/react-focus-guards": "npm:1.1.1" - "@radix-ui/react-focus-scope": "npm:1.1.0" - "@radix-ui/react-id": "npm:1.1.0" - "@radix-ui/react-popper": "npm:1.2.0" - "@radix-ui/react-portal": "npm:1.1.2" - "@radix-ui/react-presence": "npm:1.1.1" - "@radix-ui/react-primitive": "npm:2.0.0" - "@radix-ui/react-slot": "npm:1.1.0" - "@radix-ui/react-use-controllable-state": "npm:1.1.0" - aria-hidden: "npm:^1.1.1" - react-remove-scroll: "npm:2.6.0" +"@radix-ui/react-navigation-menu@npm:^1.2.22": + version: 1.3.0 + resolution: "@radix-ui/react-navigation-menu@npm:1.3.0" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-collection": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-dismissable-layer": "npm:1.1.20" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + "@radix-ui/react-use-previous": "npm:1.1.4" + "@radix-ui/react-visually-hidden": "npm:1.2.12" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/6bc91839b2ae091dcbb3d0a3a9454f2353f8a70f1f54b6186538e3ce511aec6df27b8ab06286914313b899fbfaa6bc80f68ee63f9bbdff842921200c43730c56 + languageName: node + linkType: hard + +"@radix-ui/react-popover@npm:^1.0.2, @radix-ui/react-popover@npm:^1.1.23": + version: 1.2.0 + resolution: "@radix-ui/react-popover@npm:1.2.0" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-dismissable-layer": "npm:1.1.20" + "@radix-ui/react-focus-guards": "npm:1.1.6" + "@radix-ui/react-focus-scope": "npm:1.2.0" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-popper": "npm:1.3.8" + "@radix-ui/react-portal": "npm:1.1.18" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + aria-hidden: "npm:^1.2.4" + react-remove-scroll: "npm:^2.7.2" peerDependencies: "@types/react": "*" "@types/react-dom": "*" @@ -13992,7 +14639,7 @@ __metadata: optional: true "@types/react-dom": optional: true - checksum: 10c0/d8fb4e3507a3cd6168bdbb6b840fb8eb538b3b1ce62192a1dcc4e8e4947fbf082c437c0ad5f6faed078006dcb7073867e493378d04c50372c6ea826c5a811f2c + checksum: 10c0/98d4dfc51814bc687626d49d1d2a266b7ed55f46b3e76c311f7bb08c9db574da30dfcd997bad9fb1c00d863d7fc2d0592f02ef73596025904b19a209cdd72e68 languageName: node linkType: hard @@ -14053,6 +14700,34 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-popper@npm:1.3.8": + version: 1.3.8 + resolution: "@radix-ui/react-popper@npm:1.3.8" + dependencies: + "@floating-ui/react-dom": "npm:^2.0.0" + "@radix-ui/react-arrow": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + "@radix-ui/react-use-rect": "npm:1.1.4" + "@radix-ui/react-use-size": "npm:1.1.5" + "@radix-ui/rect": "npm:1.1.3" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/4ffdb1ac696cd3dfdeb14e994f37f8c483977ffdb8ca7c1ae7de3a5e819588f094a63b163f255e6f02e35e5a22d488a2bad78ca63825777aebc547e026378aca + languageName: node + linkType: hard + "@radix-ui/react-portal@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-portal@npm:1.0.3" @@ -14073,6 +14748,26 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-portal@npm:1.1.18": + version: 1.1.18 + resolution: "@radix-ui/react-portal@npm:1.1.18" + dependencies: + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/f24928e9bdb9d2c3a6e97598eb4631e1be61419775b445b03c07e402aebf36c1ed12bfc0e6b21c536ebbe17fb50a0cad410d7463b3af2f04e5b4302a817517e9 + languageName: node + linkType: hard + "@radix-ui/react-portal@npm:1.1.2": version: 1.1.2 resolution: "@radix-ui/react-portal@npm:1.1.2" @@ -14113,6 +14808,25 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-presence@npm:1.1.11, @radix-ui/react-presence@npm:^1.1.10": + version: 1.1.11 + resolution: "@radix-ui/react-presence@npm:1.1.11" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/480ab17f9a2a1d962d7a6b8f7d3ca0342fd4124a22c70d6dce4d4b54a0ffd60e5863ca3ad351a9132e565b4d6eeb479162f7449b5a42cdd7e294bf6b8247d9ba + languageName: node + linkType: hard + "@radix-ui/react-primitive@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-primitive@npm:1.0.3" @@ -14152,6 +14866,25 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-primitive@npm:2.1.11": + version: 2.1.11 + resolution: "@radix-ui/react-primitive@npm:2.1.11" + dependencies: + "@radix-ui/react-slot": "npm:1.4.0" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/686665064e118791fa484fc9dbf3e6106b3876620fc5fa82b50919801c9d683b648de7b3db03d6c700407c5bc1820156437899f74776adb76226fb62ef9a79f6 + languageName: node + linkType: hard + "@radix-ui/react-roving-focus@npm:1.1.0": version: 1.1.0 resolution: "@radix-ui/react-roving-focus@npm:1.1.0" @@ -14179,6 +14912,63 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-roving-focus@npm:1.1.20": + version: 1.1.20 + resolution: "@radix-ui/react-roving-focus@npm:1.1.20" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-collection": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-is-hydrated": "npm:0.1.3" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/2074812db86c2c348af80f0505d24e863e2771538083ed7acf4f515a749a06beed19ff9590fb98a9c3aacd981a27d3c3f002036713cfe72e3076863dde02b273 + languageName: node + linkType: hard + +"@radix-ui/react-scroll-area@npm:^1.2.18": + version: 1.3.0 + resolution: "@radix-ui/react-scroll-area@npm:1.3.0" + dependencies: + "@radix-ui/number": "npm:1.1.3" + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/ec144e0b42036631dd1d898412f5638f2a1b45dfc0b91fc0fe9dca348c5044120e324a095c95f576df2aa00a7f734cafd9d95cee893f97552a483e13455f17f6 + languageName: node + linkType: hard + "@radix-ui/react-select@npm:^1.2.0": version: 1.2.2 resolution: "@radix-ui/react-select@npm:1.2.2" @@ -14279,6 +15069,47 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-slot@npm:1.4.0, @radix-ui/react-slot@npm:^1.3.3": + version: 1.4.0 + resolution: "@radix-ui/react-slot@npm:1.4.0" + dependencies: + "@radix-ui/react-compose-refs": "npm:1.1.5" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/a8c5be704183d4e388280191d6245458b45b059ea8530a523e8f87820b6eab407e06b749f63df5284204e66fc2ba5c8a934a74c61a17272f79ca98eae1403baa + languageName: node + linkType: hard + +"@radix-ui/react-tabs@npm:^1.1.21": + version: 1.1.22 + resolution: "@radix-ui/react-tabs@npm:1.1.22" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-roving-focus": "npm:1.1.20" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/5cc3698ec307606bd0f5a2e6c0d273aaf958e344d6035f071566b0372cceae1ecd8827ea92745e4bd0a1f1264014ad3366cc72f094c161e0fdac20922826ea00 + languageName: node + linkType: hard + "@radix-ui/react-toast@npm:^1.1.1": version: 1.2.2 resolution: "@radix-ui/react-toast@npm:1.2.2" @@ -14337,6 +15168,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-callback-ref@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-callback-ref@npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/d5cc1248ab6a58b12eefd3115c98fb438b74b2e6dec463d2e097d27df8e9f40b9d8693ee10a422da4f7a688fbe52c62cc2fe3aa5972020b9425b86a2a28f5f01 + languageName: node + linkType: hard + "@radix-ui/react-use-controllable-state@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-controllable-state@npm:1.0.1" @@ -14368,6 +15212,38 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-controllable-state@npm:1.2.6": + version: 1.2.6 + resolution: "@radix-ui/react-use-controllable-state@npm:1.2.6" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-use-effect-event": "npm:0.0.5" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/1672c3fa5c1f2dbc354db4d403523eef15bcbe24448b911e67e3e95f351b72ffc1dc1021a225d98116cd78d1c96e6280f1645ac6d6b9930df46b180b8a6f11a5 + languageName: node + linkType: hard + +"@radix-ui/react-use-effect-event@npm:0.0.5": + version: 0.0.5 + resolution: "@radix-ui/react-use-effect-event@npm:0.0.5" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/36eb3523d3c30e88615e0492aed5c644e61eb4fec98097de0fb2ee1cf33d7684b76e8a34bedb0aa7c25b412e0ef56c83b16772e9716d03d61901bc1b98cb1993 + languageName: node + linkType: hard + "@radix-ui/react-use-escape-keydown@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-use-escape-keydown@npm:1.0.3" @@ -14399,6 +15275,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-is-hydrated@npm:0.1.3": + version: 0.1.3 + resolution: "@radix-ui/react-use-is-hydrated@npm:0.1.3" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/ec5d8cd7dcb825d23c9e622cb78605242ae6ae5744549f4713fd543a2a2003c356031bac3bd8db353579e6cd9f71798b59915f54de7b78b442e847024f2a5ff9 + languageName: node + linkType: hard + "@radix-ui/react-use-layout-effect@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-layout-effect@npm:1.0.1" @@ -14427,6 +15316,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-layout-effect@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-layout-effect@npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/427df10bb3c55de36afd6b9a749fb4b72b0f78840ae4abb5dda24aa09d653ede2d264c96a8030f58db353498f42b2bce929510c777004e250f7845b06c782bcf + languageName: node + linkType: hard + "@radix-ui/react-use-previous@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-previous@npm:1.0.1" @@ -14455,6 +15357,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-previous@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-previous@npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/e291d635ef2ec1813ad499aa4d14b6da81042831549140e8a71ab982540322a9abbe629ebffb175258b9c60e77fd0736b9b4fe1cd76066912fd5270783030778 + languageName: node + linkType: hard + "@radix-ui/react-use-rect@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-rect@npm:1.0.1" @@ -14486,6 +15401,21 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-rect@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-rect@npm:1.1.4" + dependencies: + "@radix-ui/rect": "npm:1.1.3" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/3acfe9265f9fbdcdead05ec4540a95d8932fb53e9eabd73c080650122424d3d5247260d349ea2d91b2712af9670a27ac2110400671b98d061b2347390fe29490 + languageName: node + linkType: hard + "@radix-ui/react-use-size@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-size@npm:1.0.1" @@ -14517,6 +15447,21 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-size@npm:1.1.5": + version: 1.1.5 + resolution: "@radix-ui/react-use-size@npm:1.1.5" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/03f05b04f6bd342e07b749d9e92700e21c3d0e5309d2d5d1f4fab719e76f4db5d21683b664c491b9fdebccbfe798f37a12deb6e6afd99ce2b2e4a58eae649811 + languageName: node + linkType: hard + "@radix-ui/react-visually-hidden@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-visually-hidden@npm:1.0.3" @@ -14556,6 +15501,25 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-visually-hidden@npm:1.2.12": + version: 1.2.12 + resolution: "@radix-ui/react-visually-hidden@npm:1.2.12" + dependencies: + "@radix-ui/react-primitive": "npm:2.1.11" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/37202abfe37d26167199988d375ecdcd973c6f0e95d486645fb671d5f963a7b4ceaf1c18b5d20df7e3ff82b04ba6fc0ec3ab321017d12e8b620b4f7d181833a9 + languageName: node + linkType: hard + "@radix-ui/rect@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/rect@npm:1.0.1" @@ -14572,6 +15536,13 @@ __metadata: languageName: node linkType: hard +"@radix-ui/rect@npm:1.1.3": + version: 1.1.3 + resolution: "@radix-ui/rect@npm:1.1.3" + checksum: 10c0/9396d6c4dbd8da51c0bef7481e1e46e7f371e27cc6a55c1079e854f3aa9f7dd89e02d98cc36e861e8d43fbb775eb76b06bdf5879fa12f25116bea676af2926da + languageName: node + linkType: hard + "@react-sigma/core@npm:4.0.3": version: 4.0.3 resolution: "@react-sigma/core@npm:4.0.3" @@ -15275,6 +16246,77 @@ __metadata: languageName: node linkType: hard +"@rushstack/node-core-library@npm:5.25.1": + version: 5.25.1 + resolution: "@rushstack/node-core-library@npm:5.25.1" + dependencies: + ajv: "npm:~8.20.0" + ajv-draft-04: "npm:~1.0.0" + ajv-formats: "npm:~3.0.1" + fs-extra: "npm:~11.3.0" + import-lazy: "npm:~4.0.0" + jju: "npm:~1.4.0" + resolve: "npm:~1.22.1" + semver: "npm:~7.7.4" + peerDependencies: + "@types/node": "*" + peerDependenciesMeta: + "@types/node": + optional: true + checksum: 10c0/914fe8144516d4d2162ae734eb00772952245aa0c9ba861320f9165dd893e4283ace0ec2892e15a2418e0232155a64445d69ba886756bc33f4d1369dad776b85 + languageName: node + linkType: hard + +"@rushstack/problem-matcher@npm:0.2.1": + version: 0.2.1 + resolution: "@rushstack/problem-matcher@npm:0.2.1" + peerDependencies: + "@types/node": "*" + peerDependenciesMeta: + "@types/node": + optional: true + checksum: 10c0/d6cf27f6bfcdc00763e6d51e582d4faef7109ba8906e6bb3bc375edae551c54a589ed61b7e01e9ae1dbdd4a7075fd82f2da541918b52f2233d6c86393beeaaa7 + languageName: node + linkType: hard + +"@rushstack/rig-package@npm:0.7.4": + version: 0.7.4 + resolution: "@rushstack/rig-package@npm:0.7.4" + dependencies: + jju: "npm:~1.4.0" + resolve: "npm:~1.22.1" + checksum: 10c0/0a279f10760e6b2f1252d69dc54b3912ee6e15c510f68185297c447994bfa7bb0ad5c59893b50ad3378efb0a00cd0470f537e559df2d34c60880f68ce3741d0b + languageName: node + linkType: hard + +"@rushstack/terminal@npm:0.24.7": + version: 0.24.7 + resolution: "@rushstack/terminal@npm:0.24.7" + dependencies: + "@rushstack/node-core-library": "npm:5.25.1" + "@rushstack/problem-matcher": "npm:0.2.1" + supports-color: "npm:~8.1.1" + peerDependencies: + "@types/node": "*" + peerDependenciesMeta: + "@types/node": + optional: true + checksum: 10c0/c47827b37bedb25bc572e1564b847a082ed6a6017d8ac73020e4cbd27ddbca298b5970f949026ae381755b12c531f0d9600e59fbd9a4b5373d5d9069b90a14f7 + languageName: node + linkType: hard + +"@rushstack/ts-command-line@npm:5.3.17": + version: 5.3.17 + resolution: "@rushstack/ts-command-line@npm:5.3.17" + dependencies: + "@rushstack/terminal": "npm:0.24.7" + "@types/argparse": "npm:1.0.38" + argparse: "npm:~1.0.9" + string-argv: "npm:~0.3.1" + checksum: 10c0/ced54b17f9295a43ba57f2a999037a81cac0b05f5441de7c257f033085d8a8d1defec2d6c811f1fc4f0c1f95357d1b1f90c1408200b2fec3137926368e8f5cf9 + languageName: node + linkType: hard + "@scalar/helpers@npm:0.16.0": version: 0.16.0 resolution: "@scalar/helpers@npm:0.16.0" @@ -15713,76 +16755,76 @@ __metadata: languageName: node linkType: hard -"@shikijs/core@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/core@npm:4.4.2" +"@shikijs/core@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/core@npm:4.5.0" dependencies: - "@shikijs/primitive": "npm:4.4.2" - "@shikijs/types": "npm:4.4.2" + "@shikijs/primitive": "npm:4.5.0" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" hast-util-to-html: "npm:^9.0.5" - checksum: 10c0/35058e528dcaea04d3bbf2c3ab6defc352b1d1cc90ac1283645af45f1f208218717ce10e24b27dd03fabdc2b039bedfd0bf69712de1d7ab8f0c67d8c343c6a7e + checksum: 10c0/67319596a078d314c1f336693661787cd0d226748b0a0e3267461cb99adf7328afe9c6d8a0ae2c114827751bf0a81f6f41e19d14b7b8711774e35cb0547e6a26 languageName: node linkType: hard -"@shikijs/engine-javascript@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/engine-javascript@npm:4.4.2" +"@shikijs/engine-javascript@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/engine-javascript@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" oniguruma-to-es: "npm:^4.3.6" - checksum: 10c0/2e8cf60249567da010ce73d08acba9a42ef86c29e6ac8876d196558ba633d666498c98a47f1e3ba59308b78e8b74d7e5793a9061ab1b78919fa28528c3de531a + checksum: 10c0/a0ab77786102424313ca86d0ee1a4997b76b728fd2dc37d672ef5bc25f034fb41163081f0f82c2b7dead7d51d0040717150b6f74f3c469e7543863463de44609 languageName: node linkType: hard -"@shikijs/engine-oniguruma@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/engine-oniguruma@npm:4.4.2" +"@shikijs/engine-oniguruma@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/engine-oniguruma@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" - checksum: 10c0/35ce68c3d1cfdf96626521db8f5256770f6327dcd083f8144bc8fcc43a37ae5d83c4472223784fa70b292c3bed67fa02a5130cfc6c54324d08730c760e5ee1a4 + checksum: 10c0/d1b8f010b9b8cfd6a2aae71eba0d0984465679f28e7344195c177eee9bb722313957afa1086af164cce0ffdcb47879639cd503ba84bd7739e1bc12c1100394d4 languageName: node linkType: hard -"@shikijs/langs@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/langs@npm:4.4.2" +"@shikijs/langs@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/langs@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" - checksum: 10c0/041026bd22f2a4b0a073304bf507adc0c175994edf89238ef8e94abc9eeda707e8eed0ee71c0ed2e4c662fb981b7e48d5f5165fd64ffb15596c1273e429da18c + "@shikijs/types": "npm:4.5.0" + checksum: 10c0/ea7282d2b4eff871c187d79bffd3abc3c1409f55c66483891bcae2b020e2f7658da555d7ef52f4b43333e950ad123bf71c0615109dbf734e4a367a0462afe5a2 languageName: node linkType: hard -"@shikijs/primitive@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/primitive@npm:4.4.2" +"@shikijs/primitive@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/primitive@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" - checksum: 10c0/6b60cd2ef0f385435283266a9c99e9274dc1a56af8f7bd31189a1b4133c31a27678cb58c5ef96772b71a031c3aa0364e1378a8d962f865a04cf6ad8dae1eba5c + checksum: 10c0/69db5b348ce778c22413800876a91e4209fc8139e40328e9446f790d4e4c72ea06230cfc9f3ee617cf1bb847d5a75d34d2c8efef50f8ecd1d2efd37ca45b771f languageName: node linkType: hard -"@shikijs/themes@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/themes@npm:4.4.2" +"@shikijs/themes@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/themes@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" - checksum: 10c0/36247ea8db358e8ccf1070d5b113d685abeb53af681f7ab0c07e025c71d53097d50fe5715ec46fb70b137bc821300cb368401effd1c076d80df6c319ae4a9d37 + "@shikijs/types": "npm:4.5.0" + checksum: 10c0/c60b6e26f4f2dd7dc0f706e81a0d3369f2711a6d4859054b5bd01396e865602d3a941b9132e6ecd234ceb5e67dd615a1a344f6d7f6398b3cdedb21b1aa821221 languageName: node linkType: hard -"@shikijs/types@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/types@npm:4.4.2" +"@shikijs/types@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/types@npm:4.5.0" dependencies: "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" - checksum: 10c0/219e6ec76378a3740545327d184771fd9b697e4c5a0a409cf3dbdb5cef5eb6e046433aa2509a9bdef7adcd0b22f70d6ca18da3a035f45679da639249caa53a6a + checksum: 10c0/139acc1740e97df84e20a45ae171b470569d3f10f0183afa36845506a7a6ea5d54e5dee7b0d1f177213f4ce26ee0f0e250cc0942c3cb07176f916584f1ee2376 languageName: node linkType: hard @@ -17418,6 +18460,170 @@ __metadata: languageName: node linkType: hard +"@tailwindcss/node@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/node@npm:4.3.3" + dependencies: + "@jridgewell/remapping": "npm:^2.3.5" + enhanced-resolve: "npm:^5.24.1" + jiti: "npm:^2.7.0" + lightningcss: "npm:1.32.0" + magic-string: "npm:^0.30.21" + source-map-js: "npm:^1.2.1" + tailwindcss: "npm:4.3.3" + checksum: 10c0/0123669be5b3e78d42b0e10cb34d547fb8574c8e7dc7a97a141c8a4ab4215852b5b1b99b97763e898e1da1493ee8424cb72e28225cc4876828c95156f94d7f0e + languageName: node + linkType: hard + +"@tailwindcss/oxide-android-arm64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-android-arm64@npm:4.3.3" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-darwin-arm64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-darwin-arm64@npm:4.3.3" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-darwin-x64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-darwin-x64@npm:4.3.3" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-freebsd-x64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-freebsd-x64@npm:4.3.3" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-arm-gnueabihf@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-arm-gnueabihf@npm:4.3.3" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-arm64-gnu@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-arm64-gnu@npm:4.3.3" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-arm64-musl@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-arm64-musl@npm:4.3.3" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-x64-gnu@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-x64-gnu@npm:4.3.3" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-x64-musl@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-x64-musl@npm:4.3.3" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@tailwindcss/oxide-wasm32-wasi@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-wasm32-wasi@npm:4.3.3" + dependencies: + "@emnapi/core": "npm:^1.11.1" + "@emnapi/runtime": "npm:^1.11.1" + "@emnapi/wasi-threads": "npm:^1.2.2" + "@napi-rs/wasm-runtime": "npm:^1.1.4" + "@tybys/wasm-util": "npm:^0.10.2" + tslib: "npm:^2.8.1" + conditions: cpu=wasm32 + languageName: node + linkType: hard + +"@tailwindcss/oxide-win32-arm64-msvc@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-win32-arm64-msvc@npm:4.3.3" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-win32-x64-msvc@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-win32-x64-msvc@npm:4.3.3" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + +"@tailwindcss/oxide@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide@npm:4.3.3" + dependencies: + "@tailwindcss/oxide-android-arm64": "npm:4.3.3" + "@tailwindcss/oxide-darwin-arm64": "npm:4.3.3" + "@tailwindcss/oxide-darwin-x64": "npm:4.3.3" + "@tailwindcss/oxide-freebsd-x64": "npm:4.3.3" + "@tailwindcss/oxide-linux-arm-gnueabihf": "npm:4.3.3" + "@tailwindcss/oxide-linux-arm64-gnu": "npm:4.3.3" + "@tailwindcss/oxide-linux-arm64-musl": "npm:4.3.3" + "@tailwindcss/oxide-linux-x64-gnu": "npm:4.3.3" + "@tailwindcss/oxide-linux-x64-musl": "npm:4.3.3" + "@tailwindcss/oxide-wasm32-wasi": "npm:4.3.3" + "@tailwindcss/oxide-win32-arm64-msvc": "npm:4.3.3" + "@tailwindcss/oxide-win32-x64-msvc": "npm:4.3.3" + dependenciesMeta: + "@tailwindcss/oxide-android-arm64": + optional: true + "@tailwindcss/oxide-darwin-arm64": + optional: true + "@tailwindcss/oxide-darwin-x64": + optional: true + "@tailwindcss/oxide-freebsd-x64": + optional: true + "@tailwindcss/oxide-linux-arm-gnueabihf": + optional: true + "@tailwindcss/oxide-linux-arm64-gnu": + optional: true + "@tailwindcss/oxide-linux-arm64-musl": + optional: true + "@tailwindcss/oxide-linux-x64-gnu": + optional: true + "@tailwindcss/oxide-linux-x64-musl": + optional: true + "@tailwindcss/oxide-wasm32-wasi": + optional: true + "@tailwindcss/oxide-win32-arm64-msvc": + optional: true + "@tailwindcss/oxide-win32-x64-msvc": + optional: true + checksum: 10c0/6c38b25226dad252347451ed8953a998432b51f1e068b25e021215b886ccf8bcf3af58faf5f4ab50368091e657ca2fa341df1deca6101651eddb567122f2acb5 + languageName: node + linkType: hard + +"@tailwindcss/postcss@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/postcss@npm:4.3.3" + dependencies: + "@alloc/quick-lru": "npm:^5.2.0" + "@tailwindcss/node": "npm:4.3.3" + "@tailwindcss/oxide": "npm:4.3.3" + postcss: "npm:^8.5.16" + tailwindcss: "npm:4.3.3" + checksum: 10c0/50b33643a4ba50c0d2ea0fd769d16072b0b3d2f31180df667fe5ad4ef60464b5f00931cfd5f2de2116a91219edb7a2dbd4c073b5c2f23393eab6ef1163db8dbf + languageName: node + linkType: hard + "@tanstack/devtools-event-client@npm:^0.4.1": version: 0.4.3 resolution: "@tanstack/devtools-event-client@npm:0.4.3" @@ -18156,12 +19362,12 @@ __metadata: languageName: node linkType: hard -"@tybys/wasm-util@npm:^0.10.0, @tybys/wasm-util@npm:^0.10.3": - version: 0.10.3 - resolution: "@tybys/wasm-util@npm:0.10.3" +"@tybys/wasm-util@npm:^0.10.0, @tybys/wasm-util@npm:^0.10.2, @tybys/wasm-util@npm:^0.10.3": + version: 0.10.4 + resolution: "@tybys/wasm-util@npm:0.10.4" dependencies: tslib: "npm:^2.4.0" - checksum: 10c0/fd2bd2a79c6cd8c79ed1cf7a0fa375c64589264c88a27acaf9756d556b453ea222b62a4f68dd2fbb8b3a78b6bab3b1f4fb2431b6afc6aeda8344b53a521a1cd3 + checksum: 10c0/27947f254efa3f2bc41f47040f57f41c246200c6439a9fd54c69f50940e320022c320275f138e30b543ee81ce69593905dfa7ba0831577ab636f829aafa70701 languageName: node linkType: hard @@ -18174,6 +19380,13 @@ __metadata: languageName: node linkType: hard +"@types/argparse@npm:1.0.38": + version: 1.0.38 + resolution: "@types/argparse@npm:1.0.38" + checksum: 10c0/4fc892da5df16923f48180da2d1f4562fa8b0507cf636b24780444fa0a1d7321d4dc0c0ecbee6152968823f5a2ae0d321b4f8c705a489bf1ae1245bdeb0868fd + languageName: node + linkType: hard + "@types/aria-query@npm:^5.0.1": version: 5.0.4 resolution: "@types/aria-query@npm:5.0.4" @@ -18785,6 +19998,15 @@ __metadata: languageName: node linkType: hard +"@types/hast@npm:3.0.5, @types/hast@npm:^3.0.0, @types/hast@npm:^3.0.4, @types/hast@npm:^3.0.5": + version: 3.0.5 + resolution: "@types/hast@npm:3.0.5" + dependencies: + "@types/unist": "npm:*" + checksum: 10c0/f3af8594a6903a507ed191eda944af18099198d6708c29102ae17118c3e20779f6929e91ed37e033541fd28d58055d8a5910a4366dbdf976cf81b13a464741fb + languageName: node + linkType: hard + "@types/hast@npm:^2.0.0": version: 2.3.10 resolution: "@types/hast@npm:2.3.10" @@ -18794,15 +20016,6 @@ __metadata: languageName: node linkType: hard -"@types/hast@npm:^3.0.0, @types/hast@npm:^3.0.4, @types/hast@npm:^3.0.5": - version: 3.0.5 - resolution: "@types/hast@npm:3.0.5" - dependencies: - "@types/unist": "npm:*" - checksum: 10c0/f3af8594a6903a507ed191eda944af18099198d6708c29102ae17118c3e20779f6929e91ed37e033541fd28d58055d8a5910a4366dbdf976cf81b13a464741fb - languageName: node - linkType: hard - "@types/hoist-non-react-statics@npm:^3.3.0": version: 3.3.5 resolution: "@types/hoist-non-react-statics@npm:3.3.5" @@ -19001,7 +20214,7 @@ __metadata: languageName: node linkType: hard -"@types/mdast@npm:^4.0.0, @types/mdast@npm:^4.0.4": +"@types/mdast@npm:4.0.4, @types/mdast@npm:^4.0.0, @types/mdast@npm:^4.0.4": version: 4.0.4 resolution: "@types/mdast@npm:4.0.4" dependencies: @@ -19010,10 +20223,10 @@ __metadata: languageName: node linkType: hard -"@types/mdx@npm:^2.0.0": - version: 2.0.13 - resolution: "@types/mdx@npm:2.0.13" - checksum: 10c0/5edf1099505ac568da55f9ae8a93e7e314e8cbc13d3445d0be61b75941226b005e1390d9b95caecf5dcb00c9d1bab2f1f60f6ff9876dc091a48b547495007720 +"@types/mdx@npm:2.0.14, @types/mdx@npm:^2.0.0": + version: 2.0.14 + resolution: "@types/mdx@npm:2.0.14" + checksum: 10c0/f1e3873c1e36e2685fb99222bf81a23c55a8e2edf49d0c45cabf2c875b0ae814cd6050cce5770ff1c6881ac747d2ad33731e1de32139b04cf181d8d7e1943ff4 languageName: node linkType: hard @@ -21045,6 +22258,90 @@ __metadata: languageName: node linkType: hard +"@yuku-analyzer/binding-android-arm64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-android-arm64@npm:0.10.2" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-darwin-arm64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-darwin-arm64@npm:0.10.2" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-darwin-x64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-darwin-x64@npm:0.10.2" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-freebsd-x64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-freebsd-x64@npm:0.10.2" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm-gnu@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm-gnu@npm:0.10.2" + conditions: os=linux & cpu=arm & libc=glibc + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm-musl@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm-musl@npm:0.10.2" + conditions: os=linux & cpu=arm & libc=musl + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm64-gnu@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm64-gnu@npm:0.10.2" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm64-musl@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm64-musl@npm:0.10.2" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-x64-gnu@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-x64-gnu@npm:0.10.2" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-x64-musl@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-x64-musl@npm:0.10.2" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@yuku-analyzer/binding-win32-arm64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-win32-arm64@npm:0.10.2" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-win32-x64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-win32-x64@npm:0.10.2" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@yuku-codegen/binding-android-arm64@npm:0.10.2": version: 0.10.2 resolution: "@yuku-codegen/binding-android-arm64@npm:0.10.2" @@ -21052,9 +22349,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-android-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-android-arm64@npm:0.9.3" +"@yuku-codegen/binding-android-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-android-arm64@npm:0.9.5" conditions: os=android & cpu=arm64 languageName: node linkType: hard @@ -21066,9 +22363,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-darwin-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-darwin-arm64@npm:0.9.3" +"@yuku-codegen/binding-darwin-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-darwin-arm64@npm:0.9.5" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard @@ -21080,9 +22377,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-darwin-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-darwin-x64@npm:0.9.3" +"@yuku-codegen/binding-darwin-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-darwin-x64@npm:0.9.5" conditions: os=darwin & cpu=x64 languageName: node linkType: hard @@ -21094,9 +22391,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-freebsd-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-freebsd-x64@npm:0.9.3" +"@yuku-codegen/binding-freebsd-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-freebsd-x64@npm:0.9.5" conditions: os=freebsd & cpu=x64 languageName: node linkType: hard @@ -21108,9 +22405,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm-gnu@npm:0.9.3" +"@yuku-codegen/binding-linux-arm-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm-gnu@npm:0.9.5" conditions: os=linux & cpu=arm & libc=glibc languageName: node linkType: hard @@ -21122,9 +22419,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm-musl@npm:0.9.3" +"@yuku-codegen/binding-linux-arm-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm-musl@npm:0.9.5" conditions: os=linux & cpu=arm & libc=musl languageName: node linkType: hard @@ -21136,9 +22433,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.3" +"@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard @@ -21150,9 +22447,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm64-musl@npm:0.9.3" +"@yuku-codegen/binding-linux-arm64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm64-musl@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard @@ -21164,9 +22461,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-x64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-x64-gnu@npm:0.9.3" +"@yuku-codegen/binding-linux-x64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-x64-gnu@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard @@ -21178,9 +22475,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-x64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-x64-musl@npm:0.9.3" +"@yuku-codegen/binding-linux-x64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-x64-musl@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard @@ -21192,9 +22489,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-win32-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-win32-arm64@npm:0.9.3" +"@yuku-codegen/binding-win32-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-win32-arm64@npm:0.9.5" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard @@ -21206,9 +22503,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-win32-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-win32-x64@npm:0.9.3" +"@yuku-codegen/binding-win32-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-win32-x64@npm:0.9.5" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -21220,9 +22517,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-android-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-android-arm64@npm:0.9.3" +"@yuku-parser/binding-android-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-android-arm64@npm:0.9.5" conditions: os=android & cpu=arm64 languageName: node linkType: hard @@ -21234,9 +22531,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-darwin-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-darwin-arm64@npm:0.9.3" +"@yuku-parser/binding-darwin-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-darwin-arm64@npm:0.9.5" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard @@ -21248,9 +22545,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-darwin-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-darwin-x64@npm:0.9.3" +"@yuku-parser/binding-darwin-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-darwin-x64@npm:0.9.5" conditions: os=darwin & cpu=x64 languageName: node linkType: hard @@ -21262,9 +22559,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-freebsd-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-freebsd-x64@npm:0.9.3" +"@yuku-parser/binding-freebsd-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-freebsd-x64@npm:0.9.5" conditions: os=freebsd & cpu=x64 languageName: node linkType: hard @@ -21276,9 +22573,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm-gnu@npm:0.9.3" +"@yuku-parser/binding-linux-arm-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm-gnu@npm:0.9.5" conditions: os=linux & cpu=arm & libc=glibc languageName: node linkType: hard @@ -21290,9 +22587,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm-musl@npm:0.9.3" +"@yuku-parser/binding-linux-arm-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm-musl@npm:0.9.5" conditions: os=linux & cpu=arm & libc=musl languageName: node linkType: hard @@ -21304,9 +22601,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm64-gnu@npm:0.9.3" +"@yuku-parser/binding-linux-arm64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm64-gnu@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard @@ -21318,9 +22615,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm64-musl@npm:0.9.3" +"@yuku-parser/binding-linux-arm64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm64-musl@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard @@ -21332,9 +22629,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-x64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-x64-gnu@npm:0.9.3" +"@yuku-parser/binding-linux-x64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-x64-gnu@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard @@ -21346,9 +22643,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-x64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-x64-musl@npm:0.9.3" +"@yuku-parser/binding-linux-x64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-x64-musl@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard @@ -21360,9 +22657,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-win32-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-win32-arm64@npm:0.9.3" +"@yuku-parser/binding-win32-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-win32-arm64@npm:0.9.5" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard @@ -21374,9 +22671,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-win32-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-win32-x64@npm:0.9.3" +"@yuku-parser/binding-win32-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-win32-x64@npm:0.9.5" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -21388,10 +22685,10 @@ __metadata: languageName: node linkType: hard -"@yuku-toolchain/types@npm:^0.9.3": - version: 0.9.3 - resolution: "@yuku-toolchain/types@npm:0.9.3" - checksum: 10c0/6f3b45ac664764b6f76322af4db5110641a45c812182580394a1816a359b65b5979791f8fc43f66733411127c59bb67272234f6f44aabe1945fe5724113f3f92 +"@yuku-toolchain/types@npm:^0.9.5": + version: 0.9.5 + resolution: "@yuku-toolchain/types@npm:0.9.5" + checksum: 10c0/cc20d7de43e393656501263a8d123cb2b03a9f281e23fbb8f9a2984dded5fab5df1c3007587ec978ada752328ca708f2ffadd1e0046c5f4a60c4d06a46ff694c languageName: node linkType: hard @@ -22552,7 +23849,7 @@ __metadata: languageName: node linkType: hard -"ajv-draft-04@npm:^1.0.0": +"ajv-draft-04@npm:^1.0.0, ajv-draft-04@npm:~1.0.0": version: 1.0.0 resolution: "ajv-draft-04@npm:1.0.0" peerDependencies: @@ -22564,7 +23861,7 @@ __metadata: languageName: node linkType: hard -"ajv-formats@npm:3.0.1, ajv-formats@npm:^3.0.1": +"ajv-formats@npm:3.0.1, ajv-formats@npm:^3.0.1, ajv-formats@npm:~3.0.1": version: 3.0.1 resolution: "ajv-formats@npm:3.0.1" dependencies: @@ -22645,7 +23942,7 @@ __metadata: languageName: node linkType: hard -"ajv@npm:^8.0.0, ajv@npm:^8.0.1, ajv@npm:^8.11.2, ajv@npm:^8.17.1, ajv@npm:^8.20.0, ajv@npm:^8.9.0": +"ajv@npm:^8.0.0, ajv@npm:^8.0.1, ajv@npm:^8.11.2, ajv@npm:^8.17.1, ajv@npm:^8.20.0, ajv@npm:^8.9.0, ajv@npm:~8.20.0": version: 8.20.0 resolution: "ajv@npm:8.20.0" dependencies: @@ -22837,12 +24134,21 @@ __metadata: languageName: node linkType: hard -"aria-hidden@npm:^1.1.1": - version: 1.2.4 - resolution: "aria-hidden@npm:1.2.4" +"argparse@npm:~1.0.9": + version: 1.0.10 + resolution: "argparse@npm:1.0.10" + dependencies: + sprintf-js: "npm:~1.0.2" + checksum: 10c0/b2972c5c23c63df66bca144dbc65d180efa74f25f8fd9b7d9a0a6c88ae839db32df3d54770dcb6460cf840d232b60695d1a6b1053f599d84e73f7437087712de + languageName: node + linkType: hard + +"aria-hidden@npm:^1.1.1, aria-hidden@npm:^1.2.4": + version: 1.2.6 + resolution: "aria-hidden@npm:1.2.6" dependencies: tslib: "npm:^2.0.0" - checksum: 10c0/8abcab2e1432efc4db415e97cb3959649ddf52c8fc815d7384f43f3d3abf56f1c12852575d00df9a8927f421d7e0712652dd5f8db244ea57634344e29ecfc74a + checksum: 10c0/7720cb539497a9f760f68f98a4b30f22c6767aa0e72fa7d58279f7c164e258fc38b2699828f8de881aab0fc8e9c56d1313a3f1a965046fc0381a554dbc72b54a languageName: node linkType: hard @@ -24283,6 +25589,15 @@ __metadata: languageName: node linkType: hard +"class-variance-authority@npm:^0.7.1": + version: 0.7.1 + resolution: "class-variance-authority@npm:0.7.1" + dependencies: + clsx: "npm:^2.1.1" + checksum: 10c0/0f438cea22131808b99272de0fa933c2532d5659773bfec0c583de7b3f038378996d3350683426b8e9c74a6286699382106d71fbec52f0dd5fbb191792cccb5b + languageName: node + linkType: hard + "classcat@npm:^5.0.3, classcat@npm:^5.0.4": version: 5.0.5 resolution: "classcat@npm:5.0.5" @@ -24479,6 +25794,24 @@ __metadata: languageName: node linkType: hard +"cn@npm:^0.2.6": + version: 0.2.6 + resolution: "cn@npm:0.2.6" + bin: + cn: bin/cn.mjs + checksum: 10c0/7d5744771e897061e210d5aa49563d254518e7e032ec372991d8e1ebb1d61057b4ec538810de31ac267153e610c141ec54b0befd006c0220e772a652824b9830 + languageName: node + linkType: hard + +"cn@npm:^0.4.0": + version: 0.4.0 + resolution: "cn@npm:0.4.0" + bin: + cn: bin/cn.mjs + checksum: 10c0/e71351cdceb7dbc9b468dcb9cacc304212532fb6bb4545979426f22791f5c4738f37d13825eb68172ae355fbe8afc30386371753d093f1031f17f35a8d10f303 + languageName: node + linkType: hard + "co@npm:^4.6.0": version: 4.6.0 resolution: "co@npm:4.6.0" @@ -24776,6 +26109,13 @@ __metadata: languageName: node linkType: hard +"compute-scroll-into-view@npm:^3.0.2": + version: 3.1.1 + resolution: "compute-scroll-into-view@npm:3.1.1" + checksum: 10c0/59761ed62304a9599b52ad75d0d6fbf0669ee2ab7dd472fdb0ad9da36628414c014dea7b5810046560180ad30ffec52a953d19297f66a1d4f3aa0999b9d2521d + languageName: node + linkType: hard + "concat-map@npm:0.0.1": version: 0.0.1 resolution: "concat-map@npm:0.0.1" @@ -26032,7 +27372,7 @@ __metadata: languageName: node linkType: hard -"diff@npm:^8.0.2": +"diff@npm:^8.0.2, diff@npm:~8.0.2": version: 8.0.4 resolution: "diff@npm:8.0.4" checksum: 10c0/7ee5d03926db4039be7252ac3b0abaae1bd122a2ca971e5ca7270e444e36ff83dd906fad1a719740ca347e97ed5dc8f458a76a8391dbcd7aff363bdafb348a00 @@ -26536,7 +27876,7 @@ __metadata: languageName: node linkType: hard -"enhanced-resolve@npm:5.24.1, enhanced-resolve@npm:^5.15.0, enhanced-resolve@npm:^5.22.0, enhanced-resolve@npm:^5.7.0": +"enhanced-resolve@npm:5.24.1": version: 5.24.1 resolution: "enhanced-resolve@npm:5.24.1" dependencies: @@ -26546,6 +27886,16 @@ __metadata: languageName: node linkType: hard +"enhanced-resolve@npm:^5.15.0, enhanced-resolve@npm:^5.22.0, enhanced-resolve@npm:^5.24.1, enhanced-resolve@npm:^5.7.0": + version: 5.26.0 + resolution: "enhanced-resolve@npm:5.26.0" + dependencies: + graceful-fs: "npm:^4.2.4" + tapable: "npm:^2.3.3" + checksum: 10c0/fea1f02aa89793fecfd3ab0764be988fdf10dd5147ef65548726d918e68e3b9cf84224de37387356b54eee69363e4d59d9624dd7be9a23a0b1f568c46fa7a8a2 + languageName: node + linkType: hard + "entities@npm:^2.0.0": version: 2.2.0 resolution: "entities@npm:2.2.0" @@ -26887,7 +28237,7 @@ __metadata: languageName: node linkType: hard -"esbuild@npm:^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0, esbuild@npm:^0.28.0, esbuild@npm:^0.28.1": +"esbuild@npm:^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0, esbuild@npm:^0.28.0, esbuild@npm:^0.28.1, esbuild@npm:^0.28.2": version: 0.28.2 resolution: "esbuild@npm:0.28.2" dependencies: @@ -28124,6 +29474,15 @@ __metadata: languageName: node linkType: hard +"estree-util-value-to-estree@npm:^3.5.0": + version: 3.5.0 + resolution: "estree-util-value-to-estree@npm:3.5.0" + dependencies: + "@types/estree": "npm:^1.0.0" + checksum: 10c0/05c8d4b3338598929122cbfd6b127b22de4600dda8178b789b0d139e5b296e57a2343e487d6e108d8c39b18550dae2af3a110093698684db810954f353e9099b + languageName: node + linkType: hard + "estree-util-visit@npm:^2.0.0": version: 2.0.0 resolution: "estree-util-visit@npm:2.0.0" @@ -29092,6 +30451,25 @@ __metadata: languageName: node linkType: hard +"framer-motion@npm:14.0.0": + version: 14.0.0 + resolution: "framer-motion@npm:14.0.0" + dependencies: + motion-dom: "npm:14.0.0" + motion-utils: "npm:14.0.0" + tslib: "npm:^2.4.0" + peerDependencies: + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true + checksum: 10c0/cc1421daef8e8245263999de59b13b3e6a5a0e6331ffba7eaf52186ce3c4da671dce96091e2f43ee982855d8c3ee86fb4c094a65507a8abc78322b98e0fceeed + languageName: node + linkType: hard + "fresh@npm:^2.0.0": version: 2.0.0 resolution: "fresh@npm:2.0.0" @@ -29146,6 +30524,17 @@ __metadata: languageName: node linkType: hard +"fs-extra@npm:~11.3.0": + version: 11.3.6 + resolution: "fs-extra@npm:11.3.6" + dependencies: + graceful-fs: "npm:^4.2.0" + jsonfile: "npm:^6.0.1" + universalify: "npm:^2.0.0" + checksum: 10c0/191c96bf71519fe08595f7920b6e568f6e44b48ed968624f35cb3bb7f4f9b05718b99cd6bf81938c0f7b1daa6d151383c33e0cbfdfe4d95419d7ea121de8e91a + languageName: node + linkType: hard + "fs-minipass@npm:^3.0.0": version: 3.0.3 resolution: "fs-minipass@npm:3.0.3" @@ -29214,6 +30603,265 @@ __metadata: languageName: node linkType: hard +"fumadocs-core@npm:16.16.2": + version: 16.16.2 + resolution: "fumadocs-core@npm:16.16.2" + dependencies: + "@fumari/image-size": "npm:^0.1.1" + estree-util-value-to-estree: "npm:^3.5.0" + github-slugger: "npm:^2.0.0" + hast-util-to-estree: "npm:^3.1.3" + hast-util-to-jsx-runtime: "npm:^2.3.6" + mdast-util-mdx: "npm:^3.0.0" + mdast-util-to-markdown: "npm:^2.1.3" + npm-to-yarn: "npm:3.2.0" + remark: "npm:^15.0.1" + remark-gfm: "npm:^4.0.1" + remark-rehype: "npm:^11.1.2" + scroll-into-view-if-needed: "npm:^3.1.0" + shiki: "npm:^4.5.0" + tinyglobby: "npm:^0.2.17" + unified: "npm:^11.0.5" + unist-util-visit: "npm:^5.1.0" + vfile: "npm:^6.0.3" + yaml: "npm:^2.9.1" + zbsearch: "npm:^4.0.1" + peerDependencies: + "@mdx-js/mdx": "*" + "@mixedbread/sdk": 0.x.x + "@modelcontextprotocol/server": 2.x.x + "@orama/core": 1.x.x + "@oramacloud/client": 2.x.x + "@tanstack/react-router": 1.x.x + "@types/estree-jsx": "*" + "@types/hast": "*" + "@types/mdast": "*" + "@types/react": "*" + algoliasearch: 5.x.x + flexsearch: "*" + lucide-react: "*" + meilisearch: ">=0.50.0 <1.0.0" + next: 16.x.x + react: ^19.2.0 + react-dom: ^19.2.0 + react-router: 7.x.x || 8.x.x + waku: "*" + zod: 4.x.x + peerDependenciesMeta: + "@mdx-js/mdx": + optional: true + "@mixedbread/sdk": + optional: true + "@modelcontextprotocol/server": + optional: true + "@orama/core": + optional: true + "@oramacloud/client": + optional: true + "@tanstack/react-router": + optional: true + "@types/estree-jsx": + optional: true + "@types/hast": + optional: true + "@types/mdast": + optional: true + "@types/react": + optional: true + algoliasearch: + optional: true + flexsearch: + optional: true + lucide-react: + optional: true + meilisearch: + optional: true + next: + optional: true + react: + optional: true + react-dom: + optional: true + react-router: + optional: true + waku: + optional: true + zod: + optional: true + checksum: 10c0/dbfab29fe4a91d8e5a16dd60851e7385d1a55516ba3ec874bba67531013b82406792d6bd0c511e663ee9bfb72908af0fa0f39611c0fa604a0ee0959ad4d2c8d2 + languageName: node + linkType: hard + +"fumadocs-mdx@npm:15.4.6": + version: 15.4.6 + resolution: "fumadocs-mdx@npm:15.4.6" + dependencies: + "@mdx-js/mdx": "npm:^3.1.1" + "@standard-schema/spec": "npm:^1.1.0" + chokidar: "npm:^5.0.0" + esbuild: "npm:^0.28.2" + estree-util-value-to-estree: "npm:^3.5.0" + github-slugger: "npm:^2.0.0" + magic-string: "npm:^1.4.1" + mdast-util-mdx: "npm:^3.0.0" + picocolors: "npm:^1.1.1" + picomatch: "npm:^4.0.7" + tinyexec: "npm:^1.3.1" + tinyglobby: "npm:^0.2.17" + unified: "npm:^11.0.5" + unist-util-remove-position: "npm:^5.0.0" + unist-util-visit: "npm:^5.1.0" + vfile: "npm:^6.0.3" + yaml: "npm:^2.9.1" + yuku-analyzer: "npm:^0.10.2" + zod: "npm:^4.6.5" + peerDependencies: + "@fumadocs/satteri": 0.x.x + "@types/mdast": "*" + "@types/mdx": "*" + "@types/react": "*" + fumadocs-core: ^16.15.3 + mdast-util-directive: "*" + next: ^15.3.0 || ^16.0.0 + react: ^19.2.0 + rolldown: "*" + satteri: ^0.10.5 + vite: 7.x.x || 8.x.x + peerDependenciesMeta: + "@fumadocs/satteri": + optional: true + "@types/mdast": + optional: true + "@types/mdx": + optional: true + "@types/react": + optional: true + mdast-util-directive: + optional: true + next: + optional: true + react: + optional: true + rolldown: + optional: true + satteri: + optional: true + vite: + optional: true + bin: + fumadocs-mdx: ./bin.js + checksum: 10c0/1c14283aa67a97d8431473ba9392bec26a0101e329546795c3b0e5b03b77cce83e71213100339459cc4a5acf9988e272561cea2370773d4488b115fc8494f73a + languageName: node + linkType: hard + +"fumadocs-twoslash@npm:4.0.1": + version: 4.0.1 + resolution: "fumadocs-twoslash@npm:4.0.1" + dependencies: + "@base-ui/react": "npm:^1.8.0" + "@types/hast": "npm:^3.0.5" + cn: "npm:^0.2.6" + mdast-util-from-markdown: "npm:^2.0.3" + mdast-util-to-hast: "npm:^13.2.1" + typescript: "npm:~7.0.2" + peerDependencies: + "@types/react": "*" + fumadocs-core: ^16.15.7 + fumadocs-ui: ^16.7.16 + react: ^19.2.0 + react-dom: ^19.2.0 + shiki: ^4.4.3 + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/c21deed51c7c32ef1fd3546e28d6e2704786849216975b63366d053cef134636a9c1613a1db062a1aed584bf21b0e61bdad961c4d555fb091319658056ae4bf7 + languageName: node + linkType: hard + +"fumadocs-typescript@npm:^5.4.1": + version: 5.4.1 + resolution: "fumadocs-typescript@npm:5.4.1" + dependencies: + estree-util-value-to-estree: "npm:^3.5.0" + hast-util-to-estree: "npm:^3.1.3" + hast-util-to-jsx-runtime: "npm:^2.3.6" + remark: "npm:^15.0.1" + remark-rehype: "npm:^11.1.2" + shiki: "npm:^4.4.3" + typescript: "npm:~7.0.2" + unified: "npm:^11.0.5" + unist-util-visit: "npm:^5.1.0" + peerDependencies: + "@types/estree": "*" + "@types/hast": "*" + "@types/mdast": "*" + "@types/react": "*" + fumadocs-core: ^16.7.0 + fumadocs-ui: ^16.7.0 + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + "@types/estree": + optional: true + "@types/hast": + optional: true + "@types/mdast": + optional: true + "@types/react": + optional: true + fumadocs-ui: + optional: true + checksum: 10c0/70dc83d45a2edf5442bbb350c26ba387e80260ab53a584cf6c9535e604e687c9e8cf9e80fdbb7c53ce2ae8a7a90c3ca61b30c9745160e3a60ac607ac0b517142 + languageName: node + linkType: hard + +"fumadocs-ui@npm:16.16.2": + version: 16.16.2 + resolution: "fumadocs-ui@npm:16.16.2" + dependencies: + "@fuma-translate/react": "npm:^1.0.2" + "@fumadocs/tailwind": "npm:0.1.2" + "@radix-ui/react-accordion": "npm:^1.2.20" + "@radix-ui/react-collapsible": "npm:^1.1.20" + "@radix-ui/react-dialog": "npm:^1.1.23" + "@radix-ui/react-direction": "npm:^1.1.4" + "@radix-ui/react-navigation-menu": "npm:^1.2.22" + "@radix-ui/react-popover": "npm:^1.1.23" + "@radix-ui/react-presence": "npm:^1.1.10" + "@radix-ui/react-scroll-area": "npm:^1.2.18" + "@radix-ui/react-slot": "npm:^1.3.3" + "@radix-ui/react-tabs": "npm:^1.1.21" + class-variance-authority: "npm:^0.7.1" + cn: "npm:^0.4.0" + lucide-react: "npm:^1.50.0" + motion: "npm:^14.0.0" + next-themes: "npm:^0.4.6" + react-remove-scroll: "npm:^2.7.2" + rehype-raw: "npm:^7.0.0" + scroll-into-view-if-needed: "npm:^3.1.0" + shiki: "npm:^4.5.0" + unist-util-visit: "npm:^5.1.0" + peerDependencies: + "@types/mdx": "*" + "@types/react": "*" + fumadocs-core: 16.16.2 + next: 16.x.x + react: ^19.2.0 + react-dom: ^19.2.0 + takumi-js: "*" + peerDependenciesMeta: + "@types/mdx": + optional: true + "@types/react": + optional: true + next: + optional: true + takumi-js: + optional: true + checksum: 10c0/6aaab53e69a172b883d9003192371f4f63e04927582c4dc8acedc19a1daaca1e5dc3b3f92bdd235da72d038a66cdcc58f21e1abd4a76d0e78bd98ba3c7a77daf + languageName: node + linkType: hard + "function-bind@npm:^1.1.2": version: 1.1.2 resolution: "function-bind@npm:1.1.2" @@ -30354,7 +32002,7 @@ __metadata: languageName: node linkType: hard -"hast-util-to-estree@npm:^3.0.0": +"hast-util-to-estree@npm:^3.0.0, hast-util-to-estree@npm:^3.1.3": version: 3.1.3 resolution: "hast-util-to-estree@npm:3.1.3" dependencies: @@ -30397,7 +32045,7 @@ __metadata: languageName: node linkType: hard -"hast-util-to-jsx-runtime@npm:^2.0.0": +"hast-util-to-jsx-runtime@npm:^2.0.0, hast-util-to-jsx-runtime@npm:^2.3.6": version: 2.3.6 resolution: "hast-util-to-jsx-runtime@npm:2.3.6" dependencies: @@ -31306,6 +32954,13 @@ __metadata: languageName: node linkType: hard +"import-lazy@npm:~4.0.0": + version: 4.0.0 + resolution: "import-lazy@npm:4.0.0" + checksum: 10c0/a3520313e2c31f25c0b06aa66d167f329832b68a4f957d7c9daf6e0fa41822b6e84948191648b9b9d8ca82f94740cdf15eecf2401a5b42cd1c33fd84f2225cca + languageName: node + linkType: hard + "import-local@npm:^3.0.2": version: 3.2.0 resolution: "import-local@npm:3.2.0" @@ -31677,12 +33332,12 @@ __metadata: languageName: node linkType: hard -"is-core-module@npm:^2.13.0, is-core-module@npm:^2.16.0, is-core-module@npm:^2.16.1": - version: 2.16.1 - resolution: "is-core-module@npm:2.16.1" +"is-core-module@npm:^2.13.0, is-core-module@npm:^2.16.1, is-core-module@npm:^2.17.0": + version: 2.17.0 + resolution: "is-core-module@npm:2.17.0" dependencies: - hasown: "npm:^2.0.2" - checksum: 10c0/898443c14780a577e807618aaae2b6f745c8538eca5c7bc11388a3f2dc6de82b9902bcc7eb74f07be672b11bbe82dd6a6edded44a00cb3d8f933d0459905eedd + hasown: "npm:^2.0.4" + checksum: 10c0/3dc7c15ea42f846180cd2cdd57af62270e0a8d0ed31c17c85735d554089d39975e2e82e65fc7c8280a3c476ca3d0d09992d0860b4998abb769a277341feb6698 languageName: node linkType: hard @@ -33019,6 +34674,17 @@ __metadata: languageName: node linkType: hard +"katex@npm:^0.18.7": + version: 0.18.10 + resolution: "katex@npm:0.18.10" + dependencies: + commander: "npm:^15.0.0" + bin: + katex: cli.js + checksum: 10c0/3864a236334e9c7aef906b2fdd70defb76edfe8362372ccd5504167e8b22bbc1a48210e5d03e30e464c0c0f669e6d467b3b8b01120598fb1968c275fa5059721 + languageName: node + linkType: hard + "keygrip@npm:~1.1.0": version: 1.1.0 resolution: "keygrip@npm:1.1.0" @@ -33363,6 +35029,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-android-arm64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-android-arm64@npm:1.32.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + "lightningcss-android-arm64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-android-arm64@npm:1.33.0" @@ -33377,6 +35050,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-darwin-arm64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-darwin-arm64@npm:1.32.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + "lightningcss-darwin-arm64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-darwin-arm64@npm:1.33.0" @@ -33391,6 +35071,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-darwin-x64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-darwin-x64@npm:1.32.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + "lightningcss-darwin-x64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-darwin-x64@npm:1.33.0" @@ -33405,6 +35092,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-freebsd-x64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-freebsd-x64@npm:1.32.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + "lightningcss-freebsd-x64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-freebsd-x64@npm:1.33.0" @@ -33419,6 +35113,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-arm-gnueabihf@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-arm-gnueabihf@npm:1.32.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + "lightningcss-linux-arm-gnueabihf@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-arm-gnueabihf@npm:1.33.0" @@ -33433,6 +35134,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-arm64-gnu@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-arm64-gnu@npm:1.32.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + "lightningcss-linux-arm64-gnu@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-arm64-gnu@npm:1.33.0" @@ -33447,6 +35155,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-arm64-musl@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-arm64-musl@npm:1.32.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + "lightningcss-linux-arm64-musl@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-arm64-musl@npm:1.33.0" @@ -33461,6 +35176,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-x64-gnu@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-x64-gnu@npm:1.32.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + "lightningcss-linux-x64-gnu@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-x64-gnu@npm:1.33.0" @@ -33475,6 +35197,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-x64-musl@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-x64-musl@npm:1.32.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + "lightningcss-linux-x64-musl@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-x64-musl@npm:1.33.0" @@ -33489,6 +35218,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-win32-arm64-msvc@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-win32-arm64-msvc@npm:1.32.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + "lightningcss-win32-arm64-msvc@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-win32-arm64-msvc@npm:1.33.0" @@ -33503,6 +35239,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-win32-x64-msvc@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-win32-x64-msvc@npm:1.32.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "lightningcss-win32-x64-msvc@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-win32-x64-msvc@npm:1.33.0" @@ -33553,6 +35296,49 @@ __metadata: languageName: node linkType: hard +"lightningcss@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss@npm:1.32.0" + dependencies: + detect-libc: "npm:^2.0.3" + lightningcss-android-arm64: "npm:1.32.0" + lightningcss-darwin-arm64: "npm:1.32.0" + lightningcss-darwin-x64: "npm:1.32.0" + lightningcss-freebsd-x64: "npm:1.32.0" + lightningcss-linux-arm-gnueabihf: "npm:1.32.0" + lightningcss-linux-arm64-gnu: "npm:1.32.0" + lightningcss-linux-arm64-musl: "npm:1.32.0" + lightningcss-linux-x64-gnu: "npm:1.32.0" + lightningcss-linux-x64-musl: "npm:1.32.0" + lightningcss-win32-arm64-msvc: "npm:1.32.0" + lightningcss-win32-x64-msvc: "npm:1.32.0" + dependenciesMeta: + lightningcss-android-arm64: + optional: true + lightningcss-darwin-arm64: + optional: true + lightningcss-darwin-x64: + optional: true + lightningcss-freebsd-x64: + optional: true + lightningcss-linux-arm-gnueabihf: + optional: true + lightningcss-linux-arm64-gnu: + optional: true + lightningcss-linux-arm64-musl: + optional: true + lightningcss-linux-x64-gnu: + optional: true + lightningcss-linux-x64-musl: + optional: true + lightningcss-win32-arm64-msvc: + optional: true + lightningcss-win32-x64-msvc: + optional: true + checksum: 10c0/70945bd55097af46fc9fab7f5ed09cd5869d85940a2acab7ee06d0117004a1d68155708a2d462531cea2fc3c67aefc9333a7068c80b0b78dd404c16838809e03 + languageName: node + linkType: hard + "lightningcss@npm:^1.33.0": version: 1.33.0 resolution: "lightningcss@npm:1.33.0" @@ -34066,6 +35852,19 @@ __metadata: languageName: node linkType: hard +"lucide-react@npm:^1.50.0": + version: 1.54.0 + resolution: "lucide-react@npm:1.54.0" + peerDependencies: + "@types/react": "*" + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/28c80675dfd7daf76cc50fd737245c108b1d65c56c065babc3fd23d8f626cbec76aff9115a5f83e5124f80c7342b2042c64160aea6e5cb63021906b643bb2e99 + languageName: node + linkType: hard + "luxon@npm:^3.2.1": version: 3.5.0 resolution: "luxon@npm:3.5.0" @@ -34098,12 +35897,12 @@ __metadata: languageName: node linkType: hard -"magic-string@npm:^1.0.0, magic-string@npm:^1.2.3": - version: 1.4.2 - resolution: "magic-string@npm:1.4.2" +"magic-string@npm:^1.0.0, magic-string@npm:^1.2.3, magic-string@npm:^1.4.1": + version: 1.4.3 + resolution: "magic-string@npm:1.4.3" dependencies: "@jridgewell/sourcemap-codec": "npm:^1.6.0" - checksum: 10c0/d3e222c202f99ec4861e7316f473f9b1cfe335ebdf38d4f67335f842f3fe248f01ee00fd3e1a8206bcbe9855e0c41515d7c210300d8fcf6eefbb982d79e423c6 + checksum: 10c0/857743a1e7039d2e867505bb272a57cc605f610b90f6bf9ef6cbf9654e9cd64330ec35e564a58ca455350529872c3ecc01f37da934da130391237f9f593cc565 languageName: node linkType: hard @@ -34285,9 +36084,9 @@ __metadata: languageName: node linkType: hard -"mdast-util-from-markdown@npm:^2.0.0": - version: 2.0.2 - resolution: "mdast-util-from-markdown@npm:2.0.2" +"mdast-util-from-markdown@npm:^2.0.0, mdast-util-from-markdown@npm:^2.0.3": + version: 2.1.0 + resolution: "mdast-util-from-markdown@npm:2.1.0" dependencies: "@types/mdast": "npm:^4.0.0" "@types/unist": "npm:^3.0.0" @@ -34301,7 +36100,21 @@ __metadata: micromark-util-symbol: "npm:^2.0.0" micromark-util-types: "npm:^2.0.0" unist-util-stringify-position: "npm:^4.0.0" - checksum: 10c0/76eb2bd2c6f7a0318087c73376b8af6d7561c1e16654e7667e640f391341096c56142618fd0ff62f6d39e5ab4895898b9789c84cd7cec2874359a437a0e1ff15 + checksum: 10c0/63cf2c77a3b731536eb29d777bfe134c829221a07597e83c696f1e65c7893b94d617c886ec277e5f95de7b4055b11c5253c5eca01ca7549f5f47b4dc133e571c + languageName: node + linkType: hard + +"mdast-util-frontmatter@npm:^2.0.0": + version: 2.0.1 + resolution: "mdast-util-frontmatter@npm:2.0.1" + dependencies: + "@types/mdast": "npm:^4.0.0" + devlop: "npm:^1.0.0" + escape-string-regexp: "npm:^5.0.0" + mdast-util-from-markdown: "npm:^2.0.0" + mdast-util-to-markdown: "npm:^2.0.0" + micromark-extension-frontmatter: "npm:^2.0.0" + checksum: 10c0/d9b0b70dd9c574cc0220d4e05dd8e9d86ac972a6a5af9e0c49c839b31cb750d4313445cfbbdf9264a7fbe3f8c8d920b45358b8500f4286e6b9dc830095b25b9a languageName: node linkType: hard @@ -34396,7 +36209,7 @@ __metadata: languageName: node linkType: hard -"mdast-util-mdx-jsx@npm:^3.0.0": +"mdast-util-mdx-jsx@npm:3.1.3, mdast-util-mdx-jsx@npm:^3.0.0": version: 3.1.3 resolution: "mdast-util-mdx-jsx@npm:3.1.3" dependencies: @@ -34453,7 +36266,7 @@ __metadata: languageName: node linkType: hard -"mdast-util-to-hast@npm:^13.0.0": +"mdast-util-to-hast@npm:^13.0.0, mdast-util-to-hast@npm:^13.2.1": version: 13.2.1 resolution: "mdast-util-to-hast@npm:13.2.1" dependencies: @@ -34470,20 +36283,22 @@ __metadata: languageName: node linkType: hard -"mdast-util-to-markdown@npm:^2.0.0, mdast-util-to-markdown@npm:^2.1.2": - version: 2.1.2 - resolution: "mdast-util-to-markdown@npm:2.1.2" +"mdast-util-to-markdown@npm:^2.0.0, mdast-util-to-markdown@npm:^2.1.2, mdast-util-to-markdown@npm:^2.1.3": + version: 2.2.0 + resolution: "mdast-util-to-markdown@npm:2.2.0" dependencies: "@types/mdast": "npm:^4.0.0" "@types/unist": "npm:^3.0.0" longest-streak: "npm:^3.0.0" mdast-util-phrasing: "npm:^4.0.0" mdast-util-to-string: "npm:^4.0.0" + micromark-util-character: "npm:^2.0.0" micromark-util-classify-character: "npm:^2.0.0" micromark-util-decode-string: "npm:^2.0.0" + micromark-util-html-tag-name: "npm:^2.0.0" unist-util-visit: "npm:^5.0.0" zwitch: "npm:^2.0.0" - checksum: 10c0/4649722a6099f12e797bd8d6469b2b43b44e526b5182862d9c7766a3431caad2c0112929c538a972f214e63c015395e5d3f54bd81d9ac1b16e6d8baaf582f749 + checksum: 10c0/584ad697cc2e94f5a276f732d66125024a8b9ea57f9b6dcc67bc09be8414fa82bb96b790c6aff0b18b4c7e88df36ab83f781429460c2b8cc0559260d6c63358c languageName: node linkType: hard @@ -34695,6 +36510,18 @@ __metadata: languageName: node linkType: hard +"micromark-extension-frontmatter@npm:^2.0.0": + version: 2.0.0 + resolution: "micromark-extension-frontmatter@npm:2.0.0" + dependencies: + fault: "npm:^2.0.0" + micromark-util-character: "npm:^2.0.0" + micromark-util-symbol: "npm:^2.0.0" + micromark-util-types: "npm:^2.0.0" + checksum: 10c0/7d0d876e598917a67146d29f536d6fbbf9d1b2401a77e2f64a3f80f934a63ff26fa94b01759c9185c24b2a91e4e6abf908fa7aa246f00a7778a6b37a17464300 + languageName: node + linkType: hard + "micromark-extension-gfm-autolink-literal@npm:^2.0.0": version: 2.1.0 resolution: "micromark-extension-gfm-autolink-literal@npm:2.1.0" @@ -35233,6 +37060,15 @@ __metadata: languageName: node linkType: hard +"minimatch@npm:10.2.3": + version: 10.2.3 + resolution: "minimatch@npm:10.2.3" + dependencies: + brace-expansion: "npm:^5.0.2" + checksum: 10c0/d9ae5f355e8bb77a42dd8c20b950141cec8773ef8716a2bb6df7a6840cc44a00ed828883884e4f1c7b5cb505fa06a17e3ea9ca2edb18fd1dec865ea7f9fcf0e5 + languageName: node + linkType: hard + "minimatch@npm:^10.0.0, minimatch@npm:^10.0.1, minimatch@npm:^10.1.1, minimatch@npm:^10.2.2": version: 10.2.4 resolution: "minimatch@npm:10.2.4" @@ -35445,6 +37281,15 @@ __metadata: languageName: node linkType: hard +"motion-dom@npm:14.0.0": + version: 14.0.0 + resolution: "motion-dom@npm:14.0.0" + dependencies: + motion-utils: "npm:14.0.0" + checksum: 10c0/d45be2d5ca62f1c02519917c580a529cbeb05a6f585e6abc019bd0b8eaad75122eb3c037abbdc00d6bd3964b58c32cd2b6cb3ddaebbfffe901cddf79457ac630 + languageName: node + linkType: hard + "motion-dom@npm:^11.18.1": version: 11.18.1 resolution: "motion-dom@npm:11.18.1" @@ -35454,6 +37299,13 @@ __metadata: languageName: node linkType: hard +"motion-utils@npm:14.0.0": + version: 14.0.0 + resolution: "motion-utils@npm:14.0.0" + checksum: 10c0/02c3d67bfacedddb91f9a69944eb5b89cd9b15ed7aae968d9d65ec804be63197adfacc7d364586b679999b7573196b8cc6f300cb932ba6dd8e5a4b1760da33c1 + languageName: node + linkType: hard + "motion-utils@npm:^11.18.1": version: 11.18.1 resolution: "motion-utils@npm:11.18.1" @@ -35461,6 +37313,24 @@ __metadata: languageName: node linkType: hard +"motion@npm:^14.0.0": + version: 14.0.0 + resolution: "motion@npm:14.0.0" + dependencies: + framer-motion: "npm:14.0.0" + tslib: "npm:^2.4.0" + peerDependencies: + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true + checksum: 10c0/2bdbfd36a20013e3e3d072e9edfcfd261e3553a7950697e77cabc3c4607b39a9e73c218fb750b83cda4eac1a8de409b62bcc7d680eb3687209758801829e6d5c + languageName: node + linkType: hard + "mqtt-packet@npm:^9.0.1": version: 9.0.1 resolution: "mqtt-packet@npm:9.0.1" @@ -35697,12 +37567,12 @@ __metadata: languageName: node linkType: hard -"nanoid@npm:^3.0.0, nanoid@npm:^3.3.17, nanoid@npm:^3.3.18": - version: 3.3.19 - resolution: "nanoid@npm:3.3.19" +"nanoid@npm:^3.0.0, nanoid@npm:^3.3.17, nanoid@npm:^3.3.19": + version: 3.3.20 + resolution: "nanoid@npm:3.3.20" bin: nanoid: bin/nanoid.cjs - checksum: 10c0/ce7afa6258bfaa00bdc8de291cfe9913280eaa403b7d9cff3db4e4200c1913e7163577df74897958da144db473a96c67f74f57db0f542fbfe409df677bae3255 + checksum: 10c0/856e8bf3bddb959d65997bd94908be030dbc5e6ed88fb3af2a638e51d1938f4d4f454c7c7231aba340775224f88b8cfd3ce1693c70471bfd05f5b6a2227c0c1e languageName: node linkType: hard @@ -35822,6 +37692,16 @@ __metadata: languageName: node linkType: hard +"next-themes@npm:^0.4.6": + version: 0.4.6 + resolution: "next-themes@npm:0.4.6" + peerDependencies: + react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc + react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc + checksum: 10c0/83590c11d359ce7e4ced14f6ea9dd7a691d5ce6843fe2dc520fc27e29ae1c535118478d03e7f172609c41b1ef1b8da6b8dd2d2acd6cd79cac1abbdbd5b99f2c4 + languageName: node + linkType: hard + "next-tick@npm:^1.1.0": version: 1.1.0 resolution: "next-tick@npm:1.1.0" @@ -36198,6 +38078,13 @@ __metadata: languageName: node linkType: hard +"npm-to-yarn@npm:3.2.0, npm-to-yarn@npm:^3.2.0": + version: 3.2.0 + resolution: "npm-to-yarn@npm:3.2.0" + checksum: 10c0/b8e8a2bffa25ca436bbed202bbe13f05c2be85e72a15199f84923c2438e549f112c0da64071ce5be120859e798c3a2f5af80dac9ba636b772b980b783fdd5bdf + languageName: node + linkType: hard + "nprogress@npm:^0.2.0": version: 0.2.0 resolution: "nprogress@npm:0.2.0" @@ -36702,6 +38589,73 @@ __metadata: languageName: node linkType: hard +"oxc-parser@npm:0.152.0": + version: 0.152.0 + resolution: "oxc-parser@npm:0.152.0" + dependencies: + "@oxc-parser/binding-android-arm-eabi": "npm:0.152.0" + "@oxc-parser/binding-android-arm64": "npm:0.152.0" + "@oxc-parser/binding-darwin-arm64": "npm:0.152.0" + "@oxc-parser/binding-darwin-x64": "npm:0.152.0" + "@oxc-parser/binding-freebsd-x64": "npm:0.152.0" + "@oxc-parser/binding-linux-arm-gnueabihf": "npm:0.152.0" + "@oxc-parser/binding-linux-arm-musleabihf": "npm:0.152.0" + "@oxc-parser/binding-linux-arm64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-arm64-musl": "npm:0.152.0" + "@oxc-parser/binding-linux-ppc64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-riscv64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-riscv64-musl": "npm:0.152.0" + "@oxc-parser/binding-linux-s390x-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-x64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-x64-musl": "npm:0.152.0" + "@oxc-parser/binding-openharmony-arm64": "npm:0.152.0" + "@oxc-parser/binding-win32-arm64-msvc": "npm:0.152.0" + "@oxc-parser/binding-win32-ia32-msvc": "npm:0.152.0" + "@oxc-parser/binding-win32-x64-msvc": "npm:0.152.0" + "@oxc-project/types": "npm:^0.152.0" + dependenciesMeta: + "@oxc-parser/binding-android-arm-eabi": + optional: true + "@oxc-parser/binding-android-arm64": + optional: true + "@oxc-parser/binding-darwin-arm64": + optional: true + "@oxc-parser/binding-darwin-x64": + optional: true + "@oxc-parser/binding-freebsd-x64": + optional: true + "@oxc-parser/binding-linux-arm-gnueabihf": + optional: true + "@oxc-parser/binding-linux-arm-musleabihf": + optional: true + "@oxc-parser/binding-linux-arm64-gnu": + optional: true + "@oxc-parser/binding-linux-arm64-musl": + optional: true + "@oxc-parser/binding-linux-ppc64-gnu": + optional: true + "@oxc-parser/binding-linux-riscv64-gnu": + optional: true + "@oxc-parser/binding-linux-riscv64-musl": + optional: true + "@oxc-parser/binding-linux-s390x-gnu": + optional: true + "@oxc-parser/binding-linux-x64-gnu": + optional: true + "@oxc-parser/binding-linux-x64-musl": + optional: true + "@oxc-parser/binding-openharmony-arm64": + optional: true + "@oxc-parser/binding-win32-arm64-msvc": + optional: true + "@oxc-parser/binding-win32-ia32-msvc": + optional: true + "@oxc-parser/binding-win32-x64-msvc": + optional: true + checksum: 10c0/1a4c6e193fa4c18615a8c4da49491df44264e69a14fa2666c3d108c33a6cee2e772f9c71ae94da49a2a99cfdbb6357517daed9d74dae04d55ebb93981b721868 + languageName: node + linkType: hard + "oxc-parser@npm:^0.127.0": version: 0.127.0 resolution: "oxc-parser@npm:0.127.0" @@ -36772,7 +38726,7 @@ __metadata: languageName: node linkType: hard -"oxc-resolver@npm:^11.19.1": +"oxc-resolver@npm:11.24.2, oxc-resolver@npm:^11.19.1": version: 11.24.2 resolution: "oxc-resolver@npm:11.24.2" dependencies: @@ -38253,14 +40207,14 @@ __metadata: languageName: node linkType: hard -"postcss@npm:^8.3.11, postcss@npm:^8.4.14, postcss@npm:^8.4.33, postcss@npm:^8.4.38, postcss@npm:^8.5.26, postcss@npm:^8.5.28, postcss@npm:^8.5.3, postcss@npm:^8.5.6": - version: 8.5.28 - resolution: "postcss@npm:8.5.28" +"postcss@npm:^8.3.11, postcss@npm:^8.4.14, postcss@npm:^8.4.33, postcss@npm:^8.4.38, postcss@npm:^8.5.16, postcss@npm:^8.5.26, postcss@npm:^8.5.28, postcss@npm:^8.5.3, postcss@npm:^8.5.6": + version: 8.5.29 + resolution: "postcss@npm:8.5.29" dependencies: - nanoid: "npm:^3.3.18" + nanoid: "npm:^3.3.19" picocolors: "npm:^1.1.1" - source-map-js: "npm:^1.2.1" - checksum: 10c0/9fe44215a6628d89c8a75184b92f5b2f77e16f9e5b13b39b9009bb7e8e6eccddf82c8854bae922db1f17ace6ef3445073fe38abff513caeb03e5285b1b55620a + source-map-js: "npm:^1.2.2" + checksum: 10c0/5d0c45a511e8ede0fe124d04885877525e69e3c1476f0c8c22ed53f3945bace9ca5ef8578274bdfe916b1cd0301253a52c5dbd8695115fae805cee55465088fc languageName: node linkType: hard @@ -39385,19 +41339,19 @@ __metadata: languageName: node linkType: hard -"react-remove-scroll-bar@npm:^2.3.3, react-remove-scroll-bar@npm:^2.3.6": - version: 2.3.6 - resolution: "react-remove-scroll-bar@npm:2.3.6" +"react-remove-scroll-bar@npm:^2.3.3, react-remove-scroll-bar@npm:^2.3.6, react-remove-scroll-bar@npm:^2.3.7": + version: 2.3.8 + resolution: "react-remove-scroll-bar@npm:2.3.8" dependencies: - react-style-singleton: "npm:^2.2.1" + react-style-singleton: "npm:^2.2.2" tslib: "npm:^2.0.0" peerDependencies: - "@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 peerDependenciesMeta: "@types/react": optional: true - checksum: 10c0/4e32ee04bf655a8bd3b4aacf6ffc596ae9eb1b9ba27eef83f7002632ee75371f61516ae62250634a9eae4b2c8fc6f6982d9b182de260f6c11841841e6e2e7515 + checksum: 10c0/9a0675c66cbb52c325bdbfaed80987a829c4504cefd8ff2dd3b6b3afc9a1500b8ec57b212e92c1fb654396d07bbe18830a8146fe77677d2a29ce40b5e1f78654 languageName: node linkType: hard @@ -39439,6 +41393,25 @@ __metadata: languageName: node linkType: hard +"react-remove-scroll@npm:^2.7.2": + version: 2.7.2 + resolution: "react-remove-scroll@npm:2.7.2" + dependencies: + react-remove-scroll-bar: "npm:^2.3.7" + react-style-singleton: "npm:^2.2.3" + tslib: "npm:^2.1.0" + use-callback-ref: "npm:^1.3.3" + use-sidecar: "npm:^1.1.3" + peerDependencies: + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/b5f3315bead75e72853f492c0b51ba8fb4fa09a4534d7fc42d6fcd59ca3e047cf213279ffc1e35b337e314ef5a04cb2b12544c85e0078802271731c27c09e5aa + languageName: node + linkType: hard + "react-resizable-panels@npm:4.6.5": version: 4.6.5 resolution: "react-resizable-panels@npm:4.6.5" @@ -39473,20 +41446,19 @@ __metadata: languageName: node linkType: hard -"react-style-singleton@npm:^2.2.1": - version: 2.2.1 - resolution: "react-style-singleton@npm:2.2.1" +"react-style-singleton@npm:^2.2.1, react-style-singleton@npm:^2.2.2, react-style-singleton@npm:^2.2.3": + version: 2.2.3 + resolution: "react-style-singleton@npm:2.2.3" dependencies: get-nonce: "npm:^1.0.0" - invariant: "npm:^2.2.4" tslib: "npm:^2.0.0" peerDependencies: - "@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc peerDependenciesMeta: "@types/react": optional: true - checksum: 10c0/6d66f3bdb65e1ec79089f80314da97c9a005087a04ee034255a5de129a4c0d9fd0bf99fa7bf642781ac2dc745ca687aae3de082bd8afdd0d117bc953241e15ad + checksum: 10c0/841938ff16d16a6b76895f4cb2e1fea957e5fe3b30febbf03a54892dae1c9153f2383e231dea0b3ba41192ad2f2849448fa859caccd288943bce32639e971bee languageName: node linkType: hard @@ -40170,6 +42142,18 @@ __metadata: languageName: node linkType: hard +"remark-frontmatter@npm:5.0.0": + version: 5.0.0 + resolution: "remark-frontmatter@npm:5.0.0" + dependencies: + "@types/mdast": "npm:^4.0.0" + mdast-util-frontmatter: "npm:^2.0.0" + micromark-extension-frontmatter: "npm:^2.0.0" + unified: "npm:^11.0.0" + checksum: 10c0/102325d5edbcf30eaf74de8a0a6e03096cc2370dfef19080fd2dd208f368fbb2323388751ac9931a1aa38a4f2828fa4bad6c52dc5249dcadcd34861693b52bf9 + languageName: node + linkType: hard + "remark-gfm@npm:4.0.1, remark-gfm@npm:^4.0.0, remark-gfm@npm:^4.0.1": version: 4.0.1 resolution: "remark-gfm@npm:4.0.1" @@ -40184,7 +42168,7 @@ __metadata: languageName: node linkType: hard -"remark-mdx@npm:^3.0.0": +"remark-mdx@npm:3.1.1, remark-mdx@npm:^3.0.0": version: 3.1.1 resolution: "remark-mdx@npm:3.1.1" dependencies: @@ -40231,7 +42215,7 @@ __metadata: languageName: node linkType: hard -"remark-stringify@npm:^11.0.0": +"remark-stringify@npm:11.0.0, remark-stringify@npm:^11.0.0": version: 11.0.0 resolution: "remark-stringify@npm:11.0.0" dependencies: @@ -40242,6 +42226,18 @@ __metadata: languageName: node linkType: hard +"remark@npm:^15.0.1": + version: 15.0.1 + resolution: "remark@npm:15.0.1" + dependencies: + "@types/mdast": "npm:^4.0.0" + remark-parse: "npm:^11.0.0" + remark-stringify: "npm:^11.0.0" + unified: "npm:^11.0.0" + checksum: 10c0/ba675e4a5b114355991d2c6f5b09a632121fc8825257b0d148b3938420713f9e9b6f012120604435d5c217d42742f60195ac6f898dc1339d313a6608a84dbc49 + languageName: node + linkType: hard + "remedial@npm:^1.0.7": version: 1.0.8 resolution: "remedial@npm:1.0.8" @@ -40336,9 +42332,9 @@ __metadata: linkType: hard "reselect@npm:^5.1.0, reselect@npm:^5.2.0": - version: 5.2.0 - resolution: "reselect@npm:5.2.0" - checksum: 10c0/d0a8497e404b25a769fe792eacae88b9b576c30870450cd243d76ec9427d91a59c4a2cc00d824d283448b444c4c698a8f961d771c8ae39c759313afb31950e2e + version: 5.3.0 + resolution: "reselect@npm:5.3.0" + checksum: 10c0/c79728e4f315152bfb2d82456d35075b705392d9e72c485d7d9b1061bd80af628416216d80f02a42f24dbb24d738aec7fec45806930aaa1d17c32e9875fa1bd6 languageName: node linkType: hard @@ -40386,16 +42382,17 @@ __metadata: languageName: node linkType: hard -"resolve@npm:^1.10.0, resolve@npm:^1.19.0, resolve@npm:^1.20.0, resolve@npm:^1.22.1, resolve@npm:^1.22.10, resolve@npm:^1.22.4, resolve@npm:^1.22.8, resolve@npm:~1.22.2": - version: 1.22.10 - resolution: "resolve@npm:1.22.10" +"resolve@npm:^1.10.0, resolve@npm:^1.19.0, resolve@npm:^1.20.0, resolve@npm:^1.22.1, resolve@npm:^1.22.10, resolve@npm:^1.22.4, resolve@npm:^1.22.8, resolve@npm:~1.22.1, resolve@npm:~1.22.2": + version: 1.22.13 + resolution: "resolve@npm:1.22.13" dependencies: - is-core-module: "npm:^2.16.0" + es-errors: "npm:^1.3.0" + is-core-module: "npm:^2.17.0" path-parse: "npm:^1.0.7" supports-preserve-symlinks-flag: "npm:^1.0.0" bin: resolve: bin/resolve - checksum: 10c0/8967e1f4e2cc40f79b7e080b4582b9a8c5ee36ffb46041dccb20e6461161adf69f843b43067b4a375de926a2cd669157e29a29578191def399dd5ef89a1b5203 + checksum: 10c0/8dac5b33a1f9f241500fcaf42f9033cdcaf3738c908a60a50a976ff2f6129063cbc5368b4092e42d2d264ad22aa94aaff207f3efa8d0185c68454439b11a1973 languageName: node linkType: hard @@ -40412,16 +42409,17 @@ __metadata: languageName: node linkType: hard -"resolve@patch:resolve@npm%3A^1.10.0#optional!builtin, resolve@patch:resolve@npm%3A^1.19.0#optional!builtin, resolve@patch:resolve@npm%3A^1.20.0#optional!builtin, resolve@patch:resolve@npm%3A^1.22.1#optional!builtin, resolve@patch:resolve@npm%3A^1.22.10#optional!builtin, resolve@patch:resolve@npm%3A^1.22.4#optional!builtin, resolve@patch:resolve@npm%3A^1.22.8#optional!builtin, resolve@patch:resolve@npm%3A~1.22.2#optional!builtin": - version: 1.22.10 - resolution: "resolve@patch:resolve@npm%3A1.22.10#optional!builtin::version=1.22.10&hash=9bd1a5" +"resolve@patch:resolve@npm%3A^1.10.0#optional!builtin, resolve@patch:resolve@npm%3A^1.19.0#optional!builtin, resolve@patch:resolve@npm%3A^1.20.0#optional!builtin, resolve@patch:resolve@npm%3A^1.22.1#optional!builtin, resolve@patch:resolve@npm%3A^1.22.10#optional!builtin, resolve@patch:resolve@npm%3A^1.22.4#optional!builtin, resolve@patch:resolve@npm%3A^1.22.8#optional!builtin, resolve@patch:resolve@npm%3A~1.22.1#optional!builtin, resolve@patch:resolve@npm%3A~1.22.2#optional!builtin": + version: 1.22.13 + resolution: "resolve@patch:resolve@npm%3A1.22.13#optional!builtin::version=1.22.13&hash=9bd1a5" dependencies: - is-core-module: "npm:^2.16.0" + es-errors: "npm:^1.3.0" + is-core-module: "npm:^2.17.0" path-parse: "npm:^1.0.7" supports-preserve-symlinks-flag: "npm:^1.0.0" bin: resolve: bin/resolve - checksum: 10c0/da5c4a85971e6eeb821805d117092321c6c257a6e1e45382c0b7ef41368a7e98690e01a08bac88b111443410a49e2fb17d1802ac5c51c8fc5532d77bef9f4be9 + checksum: 10c0/bc58ee02e647a4250453eeb067796bdc087f6a89d4d5780bfe479f402ec11b9461babc155a6452020b56f3845cf49b1afd9c95fe3fc8347cba6567aa9b10c106 languageName: node linkType: hard @@ -41064,7 +43062,7 @@ __metadata: languageName: node linkType: hard -"satteri@npm:^0.10.3": +"satteri@npm:0.10.5, satteri@npm:^0.10.3, satteri@npm:^0.10.5": version: 0.10.5 resolution: "satteri@npm:0.10.5" dependencies: @@ -41190,6 +43188,15 @@ __metadata: languageName: node linkType: hard +"scroll-into-view-if-needed@npm:^3.1.0": + version: 3.1.0 + resolution: "scroll-into-view-if-needed@npm:3.1.0" + dependencies: + compute-scroll-into-view: "npm:^3.0.2" + checksum: 10c0/1f46b090e1e04fcfdef1e384f6d7e615f9f84d4176faf4dbba7347cc0a6e491e5d578eaf4dbe9618dd3d8d38efafde58535b3e00f2a21ce4178c14be364850ff + languageName: node + linkType: hard + "scslre@npm:^0.3.0": version: 0.3.0 resolution: "scslre@npm:0.3.0" @@ -41293,6 +43300,15 @@ __metadata: languageName: node linkType: hard +"semver@npm:~7.7.4": + version: 7.7.4 + resolution: "semver@npm:7.7.4" + bin: + semver: bin/semver.js + checksum: 10c0/5215ad0234e2845d4ea5bb9d836d42b03499546ddafb12075566899fc617f68794bb6f146076b6881d755de17d6c6cc73372555879ec7dce2c2feee947866ad2 + languageName: node + linkType: hard + "send@npm:^1.1.0, send@npm:^1.2.0": version: 1.2.0 resolution: "send@npm:1.2.0" @@ -41631,19 +43647,19 @@ __metadata: languageName: node linkType: hard -"shiki@npm:^4.0.2": - version: 4.4.2 - resolution: "shiki@npm:4.4.2" - dependencies: - "@shikijs/core": "npm:4.4.2" - "@shikijs/engine-javascript": "npm:4.4.2" - "@shikijs/engine-oniguruma": "npm:4.4.2" - "@shikijs/langs": "npm:4.4.2" - "@shikijs/themes": "npm:4.4.2" - "@shikijs/types": "npm:4.4.2" +"shiki@npm:4.5.0, shiki@npm:^4.0.2, shiki@npm:^4.4.3, shiki@npm:^4.5.0": + version: 4.5.0 + resolution: "shiki@npm:4.5.0" + dependencies: + "@shikijs/core": "npm:4.5.0" + "@shikijs/engine-javascript": "npm:4.5.0" + "@shikijs/engine-oniguruma": "npm:4.5.0" + "@shikijs/langs": "npm:4.5.0" + "@shikijs/themes": "npm:4.5.0" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" - checksum: 10c0/2bae4e358c561373ef5b5a7c3456466d91ae413250abad83a6281bc37b178fd5a6b9d5d68c9b2071d3c4f97ae11262faf04d453ecb9a5fd06af5bb765b6ef2dd + checksum: 10c0/eab0f3ca35caacbfe78a538d91b4956ff4f06aacaf3234e4f6f8d0c594d6a1612d022afbc3f11c4345dd87bb7a1dafcb8edd9ecace797b25097d91cfd473d0d1 languageName: node linkType: hard @@ -41936,7 +43952,7 @@ __metadata: languageName: node linkType: hard -"source-map-js@npm:>=0.6.2 <2.0.0, source-map-js@npm:^1.0.1, source-map-js@npm:^1.0.2, source-map-js@npm:^1.2.1": +"source-map-js@npm:>=0.6.2 <2.0.0, source-map-js@npm:^1.0.1, source-map-js@npm:^1.0.2, source-map-js@npm:^1.2.1, source-map-js@npm:^1.2.2": version: 1.2.2 resolution: "source-map-js@npm:1.2.2" checksum: 10c0/d5d6dec62266834f83dd4f8a2606a196fb1a006ca5d53b0ef80ee513b7eba2f4e2ae241f4bc129ae7e9b80dea24f6e3d92b446b7e6e96be7653cab8888168a94 @@ -42100,6 +44116,13 @@ __metadata: languageName: node linkType: hard +"sprintf-js@npm:~1.0.2": + version: 1.0.3 + resolution: "sprintf-js@npm:1.0.3" + checksum: 10c0/ecadcfe4c771890140da5023d43e190b7566d9cf8b2d238600f31bec0fc653f328da4450eb04bd59a431771a8e9cc0e118f0aa3974b683a4981b4e07abc2a5bb + languageName: node + linkType: hard + "ssri@npm:^13.0.0": version: 13.0.1 resolution: "ssri@npm:13.0.1" @@ -42276,7 +44299,7 @@ __metadata: languageName: node linkType: hard -"string-argv@npm:^0.3.2": +"string-argv@npm:^0.3.2, string-argv@npm:~0.3.1": version: 0.3.2 resolution: "string-argv@npm:0.3.2" checksum: 10c0/75c02a83759ad1722e040b86823909d9a2fc75d15dd71ec4b537c3560746e33b5f5a07f7332d1e3f88319909f82190843aa2f0a0d8c8d591ec08e93d5b8dec82 @@ -42665,7 +44688,7 @@ __metadata: languageName: node linkType: hard -"supports-color@npm:^8.0.0, supports-color@npm:^8.1.1": +"supports-color@npm:^8.0.0, supports-color@npm:^8.1.1, supports-color@npm:~8.1.1": version: 8.1.1 resolution: "supports-color@npm:8.1.1" dependencies: @@ -42828,6 +44851,13 @@ __metadata: languageName: node linkType: hard +"tailwindcss@npm:4.3.3": + version: 4.3.3 + resolution: "tailwindcss@npm:4.3.3" + checksum: 10c0/7e9cd7553cd890ffa5350efb0ca8971ba5435257d0f98bf0714994ac8f1fee5c7cdf9a9da47fe83e8ac995d728410837ac49d3ef5ea66b5afe1db312086ffae2 + languageName: node + linkType: hard + "tapable@npm:^2.0.0, tapable@npm:^2.2.1, tapable@npm:^2.3.0, tapable@npm:^2.3.3": version: 2.3.3 resolution: "tapable@npm:2.3.3" @@ -43939,6 +45969,16 @@ __metadata: languageName: node linkType: hard +"typescript@npm:5.9.3": + version: 5.9.3 + resolution: "typescript@npm:5.9.3" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/6bd7552ce39f97e711db5aa048f6f9995b53f1c52f7d8667c1abdc1700c68a76a308f579cd309ce6b53646deb4e9a1be7c813a93baaf0a28ccd536a30270e1c5 + languageName: node + linkType: hard + "typescript@npm:6.0.2": version: 6.0.2 resolution: "typescript@npm:6.0.2" @@ -43949,7 +45989,7 @@ __metadata: languageName: node linkType: hard -"typescript@npm:7.0.2": +"typescript@npm:7.0.2, typescript@npm:~7.0.2": version: 7.0.2 resolution: "typescript@npm:7.0.2" dependencies: @@ -44040,6 +46080,16 @@ __metadata: languageName: node linkType: hard +"typescript@patch:typescript@npm%3A5.9.3#optional!builtin": + version: 5.9.3 + resolution: "typescript@patch:typescript@npm%3A5.9.3#optional!builtin::version=5.9.3&hash=5786d5" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/ad09fdf7a756814dce65bc60c1657b40d44451346858eea230e10f2e95a289d9183b6e32e5c11e95acc0ccc214b4f36289dcad4bf1886b0adb84d711d336a430 + languageName: node + linkType: hard + "typescript@patch:typescript@npm%3A6.0.2#optional!builtin": version: 6.0.2 resolution: "typescript@patch:typescript@npm%3A6.0.2#optional!builtin::version=6.0.2&hash=5786d5" @@ -44060,7 +46110,7 @@ __metadata: languageName: node linkType: hard -"typescript@patch:typescript@npm%3A7.0.2#optional!builtin": +"typescript@patch:typescript@npm%3A7.0.2#optional!builtin, typescript@patch:typescript@npm%3A~7.0.2#optional!builtin": version: 7.0.2 resolution: "typescript@patch:typescript@npm%3A7.0.2#optional!builtin::version=7.0.2&hash=3bafbf" dependencies: @@ -44382,7 +46432,7 @@ __metadata: languageName: node linkType: hard -"unified@npm:^11.0.0, unified@npm:^11.0.4, unified@npm:^11.0.5": +"unified@npm:11.0.5, unified@npm:^11.0.0, unified@npm:^11.0.4, unified@npm:^11.0.5": version: 11.0.5 resolution: "unified@npm:11.0.5" dependencies: @@ -44881,7 +46931,7 @@ __metadata: languageName: node linkType: hard -"use-callback-ref@npm:1.3.3, use-callback-ref@npm:^1.3.0": +"use-callback-ref@npm:1.3.3, use-callback-ref@npm:^1.3.0, use-callback-ref@npm:^1.3.3": version: 1.3.3 resolution: "use-callback-ref@npm:1.3.3" dependencies: @@ -44934,19 +46984,19 @@ __metadata: languageName: node linkType: hard -"use-sidecar@npm:^1.1.2": - version: 1.1.2 - resolution: "use-sidecar@npm:1.1.2" +"use-sidecar@npm:^1.1.2, use-sidecar@npm:^1.1.3": + version: 1.1.3 + resolution: "use-sidecar@npm:1.1.3" dependencies: detect-node-es: "npm:^1.1.0" tslib: "npm:^2.0.0" peerDependencies: - "@types/react": ^16.9.0 || ^17.0.0 || ^18.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc peerDependenciesMeta: "@types/react": optional: true - checksum: 10c0/89f0018fd9aee1fc17c85ac18c4bf8944d460d453d0d0e04ddbc8eaddf3fa591e9c74a1f8a438a1bff368a7a2417fab380bdb3df899d2194c4375b0982736de0 + checksum: 10c0/161599bf921cfaa41c85d2b01c871975ee99260f3e874c2d41c05890d41170297bdcf314bc5185e7a700de2034ac5b888e3efc8e9f35724f4918f53538d717c9 languageName: node linkType: hard @@ -46514,6 +48564,15 @@ __metadata: languageName: node linkType: hard +"yaml@npm:2.9.1, yaml@npm:^2.3.1, yaml@npm:^2.8.3, yaml@npm:^2.9.0, yaml@npm:^2.9.1": + version: 2.9.1 + resolution: "yaml@npm:2.9.1" + bin: + yaml: bin.mjs + checksum: 10c0/9d06676ef02b89559a8b10a71882bd2cdae81e8393dc8dbc871615c3259475d9609ad973d19cb3c9e71e72d6206e3d1e7aa241c7e55f3d16fd2e77db305827d6 + languageName: node + linkType: hard + "yaml@npm:^1.10.0": version: 1.10.3 resolution: "yaml@npm:1.10.3" @@ -46521,15 +48580,6 @@ __metadata: languageName: node linkType: hard -"yaml@npm:^2.3.1, yaml@npm:^2.8.3, yaml@npm:^2.9.0": - version: 2.9.0 - resolution: "yaml@npm:2.9.0" - bin: - yaml: bin.mjs - checksum: 10c0/f340718df45e97a9551b9bf9dac61c80050bc464513b710debfb5067c380c8472e3b67809cffacb4ab5ffb5e66ef9310816c88b05f371cec60abfedd8c88e0a2 - languageName: node - linkType: hard - "yargs-parser@npm:^21.1.1": version: 21.1.1 resolution: "yargs-parser@npm:21.1.1" @@ -46650,6 +48700,53 @@ __metadata: languageName: node linkType: hard +"yuku-analyzer@npm:^0.10.2": + version: 0.10.2 + resolution: "yuku-analyzer@npm:0.10.2" + dependencies: + "@yuku-analyzer/binding-android-arm64": "npm:0.10.2" + "@yuku-analyzer/binding-darwin-arm64": "npm:0.10.2" + "@yuku-analyzer/binding-darwin-x64": "npm:0.10.2" + "@yuku-analyzer/binding-freebsd-x64": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm-gnu": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm-musl": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm64-gnu": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm64-musl": "npm:0.10.2" + "@yuku-analyzer/binding-linux-x64-gnu": "npm:0.10.2" + "@yuku-analyzer/binding-linux-x64-musl": "npm:0.10.2" + "@yuku-analyzer/binding-win32-arm64": "npm:0.10.2" + "@yuku-analyzer/binding-win32-x64": "npm:0.10.2" + "@yuku-toolchain/types": "npm:^0.10.2" + yuku-ast: "npm:^0.10.2" + dependenciesMeta: + "@yuku-analyzer/binding-android-arm64": + optional: true + "@yuku-analyzer/binding-darwin-arm64": + optional: true + "@yuku-analyzer/binding-darwin-x64": + optional: true + "@yuku-analyzer/binding-freebsd-x64": + optional: true + "@yuku-analyzer/binding-linux-arm-gnu": + optional: true + "@yuku-analyzer/binding-linux-arm-musl": + optional: true + "@yuku-analyzer/binding-linux-arm64-gnu": + optional: true + "@yuku-analyzer/binding-linux-arm64-musl": + optional: true + "@yuku-analyzer/binding-linux-x64-gnu": + optional: true + "@yuku-analyzer/binding-linux-x64-musl": + optional: true + "@yuku-analyzer/binding-win32-arm64": + optional: true + "@yuku-analyzer/binding-win32-x64": + optional: true + checksum: 10c0/ac80a5c37f908c28fa1de0ebb6d7c8a247a527c3db483e77edaeb3284abc3b43a123c8d8d9b1503150ff0564d3e7f066970ed9f290ffcb3e99955c99a203e488 + languageName: node + linkType: hard + "yuku-ast@npm:^0.10.1, yuku-ast@npm:^0.10.2": version: 0.10.2 resolution: "yuku-ast@npm:0.10.2" @@ -46659,12 +48756,12 @@ __metadata: languageName: node linkType: hard -"yuku-ast@npm:^0.9.3": - version: 0.9.3 - resolution: "yuku-ast@npm:0.9.3" +"yuku-ast@npm:^0.9.3, yuku-ast@npm:^0.9.5": + version: 0.9.5 + resolution: "yuku-ast@npm:0.9.5" dependencies: - "@yuku-toolchain/types": "npm:^0.9.3" - checksum: 10c0/ddb1eb96e59405c14387ca89fb2b543e335c0e8a6928bd09205cf67d7977a7d115f081180dbcc95bcb9733e4c86955c4f7f4d15f2c8bdf5a7a1b6cb112ed25dc + "@yuku-toolchain/types": "npm:^0.9.5" + checksum: 10c0/cc6159880196008f10765e9c64d6fbc6ceab87ea5451d88907992bf007d10e1bc533c93a5a7b00bb3ac5903e13fed76be447f65d3f8e6a6da210509009e32043 languageName: node linkType: hard @@ -46714,23 +48811,23 @@ __metadata: languageName: node linkType: hard -"yuku-codegen@npm:^0.9.3": - version: 0.9.3 - resolution: "yuku-codegen@npm:0.9.3" - dependencies: - "@yuku-codegen/binding-android-arm64": "npm:0.9.3" - "@yuku-codegen/binding-darwin-arm64": "npm:0.9.3" - "@yuku-codegen/binding-darwin-x64": "npm:0.9.3" - "@yuku-codegen/binding-freebsd-x64": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm-gnu": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm-musl": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm64-gnu": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm64-musl": "npm:0.9.3" - "@yuku-codegen/binding-linux-x64-gnu": "npm:0.9.3" - "@yuku-codegen/binding-linux-x64-musl": "npm:0.9.3" - "@yuku-codegen/binding-win32-arm64": "npm:0.9.3" - "@yuku-codegen/binding-win32-x64": "npm:0.9.3" - "@yuku-toolchain/types": "npm:^0.9.3" +"yuku-codegen@npm:^0.9.3, yuku-codegen@npm:^0.9.5": + version: 0.9.5 + resolution: "yuku-codegen@npm:0.9.5" + dependencies: + "@yuku-codegen/binding-android-arm64": "npm:0.9.5" + "@yuku-codegen/binding-darwin-arm64": "npm:0.9.5" + "@yuku-codegen/binding-darwin-x64": "npm:0.9.5" + "@yuku-codegen/binding-freebsd-x64": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm-gnu": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm-musl": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm64-gnu": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm64-musl": "npm:0.9.5" + "@yuku-codegen/binding-linux-x64-gnu": "npm:0.9.5" + "@yuku-codegen/binding-linux-x64-musl": "npm:0.9.5" + "@yuku-codegen/binding-win32-arm64": "npm:0.9.5" + "@yuku-codegen/binding-win32-x64": "npm:0.9.5" + "@yuku-toolchain/types": "npm:^0.9.5" dependenciesMeta: "@yuku-codegen/binding-android-arm64": optional: true @@ -46756,7 +48853,7 @@ __metadata: optional: true "@yuku-codegen/binding-win32-x64": optional: true - checksum: 10c0/3468b011a118b636d0854c0c1bf464234d54a957060127446f71ed1bc17a4aab72e97667d86e3e7dbcde99b331514a2b8c95cc4cf28dbc14960440a21b5636c9 + checksum: 10c0/fff0d52b38af71a4f2f76ef44406a0c3237957ca2ed0118c156e495b48d03a431f8132808b7f52e8c09d9838267c3cbd6074b9a3e4bca825d442b7a4613bedd8 languageName: node linkType: hard @@ -46807,24 +48904,24 @@ __metadata: languageName: node linkType: hard -"yuku-parser@npm:^0.9.3": - version: 0.9.3 - resolution: "yuku-parser@npm:0.9.3" - dependencies: - "@yuku-parser/binding-android-arm64": "npm:0.9.3" - "@yuku-parser/binding-darwin-arm64": "npm:0.9.3" - "@yuku-parser/binding-darwin-x64": "npm:0.9.3" - "@yuku-parser/binding-freebsd-x64": "npm:0.9.3" - "@yuku-parser/binding-linux-arm-gnu": "npm:0.9.3" - "@yuku-parser/binding-linux-arm-musl": "npm:0.9.3" - "@yuku-parser/binding-linux-arm64-gnu": "npm:0.9.3" - "@yuku-parser/binding-linux-arm64-musl": "npm:0.9.3" - "@yuku-parser/binding-linux-x64-gnu": "npm:0.9.3" - "@yuku-parser/binding-linux-x64-musl": "npm:0.9.3" - "@yuku-parser/binding-win32-arm64": "npm:0.9.3" - "@yuku-parser/binding-win32-x64": "npm:0.9.3" - "@yuku-toolchain/types": "npm:^0.9.3" - yuku-ast: "npm:^0.9.3" +"yuku-parser@npm:^0.9.3, yuku-parser@npm:^0.9.5": + version: 0.9.5 + resolution: "yuku-parser@npm:0.9.5" + dependencies: + "@yuku-parser/binding-android-arm64": "npm:0.9.5" + "@yuku-parser/binding-darwin-arm64": "npm:0.9.5" + "@yuku-parser/binding-darwin-x64": "npm:0.9.5" + "@yuku-parser/binding-freebsd-x64": "npm:0.9.5" + "@yuku-parser/binding-linux-arm-gnu": "npm:0.9.5" + "@yuku-parser/binding-linux-arm-musl": "npm:0.9.5" + "@yuku-parser/binding-linux-arm64-gnu": "npm:0.9.5" + "@yuku-parser/binding-linux-arm64-musl": "npm:0.9.5" + "@yuku-parser/binding-linux-x64-gnu": "npm:0.9.5" + "@yuku-parser/binding-linux-x64-musl": "npm:0.9.5" + "@yuku-parser/binding-win32-arm64": "npm:0.9.5" + "@yuku-parser/binding-win32-x64": "npm:0.9.5" + "@yuku-toolchain/types": "npm:^0.9.5" + yuku-ast: "npm:^0.9.5" dependenciesMeta: "@yuku-parser/binding-android-arm64": optional: true @@ -46850,7 +48947,14 @@ __metadata: optional: true "@yuku-parser/binding-win32-x64": optional: true - checksum: 10c0/a6805b88dcea1165e31d798ffca825a68d52bedcc1ee3bf252d8434e82a4f894d28a7a78fa666c351cf976b095f20994f34ad8042412281e69d07630d229a37c + checksum: 10c0/e01bd82ac6369166320cfe64770e9e3cbd48a502844cd11afc5b11bb5cbbe484c70af804e0dde50142cc6daad9689ffeb88099731a836e32601df07813527489 + languageName: node + linkType: hard + +"zbsearch@npm:^4.0.1": + version: 4.0.1 + resolution: "zbsearch@npm:4.0.1" + checksum: 10c0/c19146c1116c816b52c613ab841b22214d49e4c9dbb58c523a71e2c32aa70466d57e61092836726f8a918d77aaf8a6bf336cd5f576e813e260a9a17e352eb2b8 languageName: node linkType: hard @@ -46916,7 +49020,7 @@ __metadata: languageName: node linkType: hard -"zod@npm:4.4.3, zod@npm:^3.25 || ^4.0, zod@npm:^3.25.0 || ^4.0.0, zod@npm:^4.0.0, zod@npm:^4.1.5, zod@npm:^4.2.0, zod@npm:^4.3.6, zod@npm:^4.4.3": +"zod@npm:4.4.3": version: 4.4.3 resolution: "zod@npm:4.4.3" checksum: 10c0/7ea31b558e88f9faf44f31dd185e2e1cbf51fed3081787fb96cc2534749b50c0acfc6da7f0922a7353ed092dd358c7d50c28ea96c94d04af64191bd33152eca3 @@ -46930,6 +49034,13 @@ __metadata: languageName: node linkType: hard +"zod@npm:^3.25 || ^4.0, zod@npm:^3.25.0 || ^4.0.0, zod@npm:^4.0.0, zod@npm:^4.1.5, zod@npm:^4.2.0, zod@npm:^4.3.6, zod@npm:^4.4.3, zod@npm:^4.6.5": + version: 4.6.5 + resolution: "zod@npm:4.6.5" + checksum: 10c0/32eb6c5e98becbe045675b2141c3611451c16ba567f9779231d79af41c4d651ca1c22f154aef7e6c6e77b929f23e43f1154ca05b82e119e922353725d6776af5 + languageName: node + linkType: hard + "zrender@npm:6.1.0": version: 6.1.0 resolution: "zrender@npm:6.1.0"