web_lib

Common web application libraries
git clone https://radroots.dev/git/web_lib.git
Log | Files | Refs | LICENSE

commit 9b9fad6672e80e0deb05ae8371599e33bb390cfc
parent 1c221a891ea981bd2400d0c3a96b5827da6a5641
Author: triesap <triesap@radroots.dev>
Date:   Mon, 22 Dec 2025 16:01:17 +0000

merge: import utils-nostr

Diffstat:
Autils-nostr/.gitignore | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/LICENSE | 675+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/package.json | 45+++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/lib.ts | 25+++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/accept/lib.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/conveyance/lib.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/fulfillment/lib.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/invoice/lib.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/order/lib.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/payment/lib.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/receipt/lib.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/domain/trade/listing/tags.ts | 14++++++++++++++
Autils-nostr/src/domain/trade/tags.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/comment/lib.ts | 22++++++++++++++++++++++
Autils-nostr/src/events/comment/parse.ts | 20++++++++++++++++++++
Autils-nostr/src/events/comment/tags.ts | 38++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/follow/lib.ts | 22++++++++++++++++++++++
Autils-nostr/src/events/follow/parse.ts | 19+++++++++++++++++++
Autils-nostr/src/events/follow/tags.ts | 12++++++++++++
Autils-nostr/src/events/job/lib.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/job/tags.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/job/utils.ts | 34++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/lib.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/listing/lib.ts | 22++++++++++++++++++++++
Autils-nostr/src/events/listing/parse.ts | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/listing/tags.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/events/profile/lib.ts | 20++++++++++++++++++++
Autils-nostr/src/events/profile/parse.ts | 19+++++++++++++++++++
Autils-nostr/src/events/reaction/lib.ts | 22++++++++++++++++++++++
Autils-nostr/src/events/reaction/parse.ts | 19+++++++++++++++++++
Autils-nostr/src/events/reaction/tags.ts | 16++++++++++++++++
Autils-nostr/src/events/subscription.ts | 36++++++++++++++++++++++++++++++++++++
Autils-nostr/src/index.ts | 38++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/keys/lib.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/relay/lib.ts | 33+++++++++++++++++++++++++++++++++
Autils-nostr/src/schemas/lib.ts | 8++++++++
Autils-nostr/src/types/lib.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autils-nostr/src/types/ndk.ts | 10++++++++++
Autils-nostr/src/utils/ndk.ts | 14++++++++++++++
Autils-nostr/src/utils/relays.ts | 22++++++++++++++++++++++
Autils-nostr/src/utils/tags.ts | 11+++++++++++
Autils-nostr/tsconfig.cjs.json | 15+++++++++++++++
Autils-nostr/tsconfig.esm.json | 13+++++++++++++
Autils-nostr/tsconfig.json | 3+++
44 files changed, 2602 insertions(+), 0 deletions(-)

diff --git a/utils-nostr/.gitignore b/utils-nostr/.gitignore @@ -0,0 +1,50 @@ +# dependencies +node_modules +.pnp +.pnp.js + +# testing +coverage + +# svelte +.svelte-kit + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# turbo +.turbo + + +# Output +.output +/build +dist + +# local env files +.env* +!.env.example + + +# Vite +vite.config.js.timestamp-* +vite.config.ts.timestamp-* + +# local +.tmp* +.backup* +.dev* +.vscode +notes*.txt +notes*.md +notes*.json +git-diff*.txt +prompt*.txt +tree*.txt +justfile +\ No newline at end of file diff --git a/utils-nostr/LICENSE b/utils-nostr/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. +\ No newline at end of file diff --git a/utils-nostr/package.json b/utils-nostr/package.json @@ -0,0 +1,44 @@ +{ + "name": "@radroots/utils-nostr", + "version": "0.0.1", + "private": true, + "license": "GPLv3", + "type": "module", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.js", + "types": "./dist/types/index.d.ts", + "exports": { + ".": { + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.js", + "require": "./dist/cjs/index.js" + } + }, + "scripts": { + "build:esm": "tsc -p tsconfig.esm.json", + "build:cjs": "tsc -p tsconfig.cjs.json", + "build": "npm run clean && npm run build:esm && npm run build:cjs", + "prebuild": "npm run clean", + "clean": "rimraf dist", + "dev": "npm run watch", + "watch": "tsc -w" + }, + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@radroots/tsconfig": "*", + "rimraf": "^6.0.1", + "typescript": "5.8.3" + }, + "dependencies": { + "@radroots/events-bindings": "*", + "@radroots/trade-bindings": "*", + "@radroots/utils": "*", + "@noble/curves": "^1.6.0", + "@noble/hashes": "^1.4.0", + "@nostr-dev-kit/ndk": "2.14.33", + "nostr-geotags": "*", + "nostr-tools": "^2.10.4" + } +} +\ No newline at end of file diff --git a/utils-nostr/src/domain/trade/lib.ts b/utils-nostr/src/domain/trade/lib.ts @@ -0,0 +1,25 @@ +import { KIND_TRADE_LISTING_ACCEPT_REQ, KIND_TRADE_LISTING_ACCEPT_RES, KIND_TRADE_LISTING_CANCEL_REQ, KIND_TRADE_LISTING_CANCEL_RES, KIND_TRADE_LISTING_CONVEYANCE_REQ, KIND_TRADE_LISTING_CONVEYANCE_RES, KIND_TRADE_LISTING_FULFILL_REQ, KIND_TRADE_LISTING_FULFILL_RES, KIND_TRADE_LISTING_INVOICE_REQ, KIND_TRADE_LISTING_INVOICE_RES, KIND_TRADE_LISTING_ORDER_REQ, KIND_TRADE_LISTING_ORDER_RES, KIND_TRADE_LISTING_PAYMENT_REQ, KIND_TRADE_LISTING_PAYMENT_RES, KIND_TRADE_LISTING_RECEIPT_REQ, KIND_TRADE_LISTING_RECEIPT_RES, KIND_TRADE_LISTING_REFUND_REQ, KIND_TRADE_LISTING_REFUND_RES } from "@radroots/trade-bindings"; + +export const REQUEST_KINDS: Record<string, number> = { + order: KIND_TRADE_LISTING_ORDER_REQ, + accept: KIND_TRADE_LISTING_ACCEPT_REQ, + conveyance: KIND_TRADE_LISTING_CONVEYANCE_REQ, + invoice: KIND_TRADE_LISTING_INVOICE_REQ, + payment: KIND_TRADE_LISTING_PAYMENT_REQ, + fulfillment: KIND_TRADE_LISTING_FULFILL_REQ, + receipt: KIND_TRADE_LISTING_RECEIPT_REQ, + cancel: KIND_TRADE_LISTING_CANCEL_REQ, + refund: KIND_TRADE_LISTING_REFUND_REQ, +}; + +export const RESULT_KINDS: Record<string, number> = { + order: KIND_TRADE_LISTING_ORDER_RES, + accept: KIND_TRADE_LISTING_ACCEPT_RES, + conveyance: KIND_TRADE_LISTING_CONVEYANCE_RES, + invoice: KIND_TRADE_LISTING_INVOICE_RES, + payment: KIND_TRADE_LISTING_PAYMENT_RES, + fulfillment: KIND_TRADE_LISTING_FULFILL_RES, + receipt: KIND_TRADE_LISTING_RECEIPT_RES, + cancel: KIND_TRADE_LISTING_CANCEL_RES, + refund: KIND_TRADE_LISTING_REFUND_RES, +}; diff --git a/utils-nostr/src/domain/trade/listing/accept/lib.ts b/utils-nostr/src/domain/trade/listing/accept/lib.ts @@ -0,0 +1,62 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { KIND_TRADE_LISTING_ACCEPT_REQ, KIND_TRADE_LISTING_ACCEPT_RES, MARKER_LISTING, MARKER_PREVIOUS, TradeListingAcceptRequest, TradeListingAcceptResult } from "@radroots/trade-bindings"; +import { ndk_event } from "../../../../events/lib.js"; +import { NDKEventFigure } from "../../../../types/ndk.js"; +import { + build_request_tags, + build_result_tags, + CommonRequestOpts, + CommonResultOpts, + make_event_input +} from "../../tags.js"; +import { tags_trade_listing_chain } from "../tags.js"; + +export const ndk_event_trade_listing_accept_request = async ( + opts: NDKEventFigure<{ data: TradeListingAcceptRequest; options?: CommonRequestOpts }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data, options } = opts; + + const inputs: RadrootsJobInput[] = [ + make_event_input(data.order_result_event_id, MARKER_PREVIOUS), + make_event_input(data.listing_event_id, MARKER_LISTING), + ]; + + const tags = build_request_tags(KIND_TRADE_LISTING_ACCEPT_REQ, inputs, options); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_ACCEPT_REQ, content: "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; + +export const ndk_event_trade_listing_accept_result = async ( + opts: NDKEventFigure<{ + request_event_id: string; + content: TradeListingAcceptResult | string; + options?: CommonResultOpts; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, content, options } = opts; + + const base_tags = build_result_tags( + KIND_TRADE_LISTING_ACCEPT_RES, + request_event_id, + options + ); + const tags = options?.chain + ? [...base_tags, ...tags_trade_listing_chain(options.chain)] + : base_tags; + + const content_body = typeof content === "string" ? content : JSON.stringify(content); + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_ACCEPT_RES, content: content_body, tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; diff --git a/utils-nostr/src/domain/trade/listing/conveyance/lib.ts b/utils-nostr/src/domain/trade/listing/conveyance/lib.ts @@ -0,0 +1,63 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { KIND_TRADE_LISTING_CONVEYANCE_REQ, KIND_TRADE_LISTING_CONVEYANCE_RES, MARKER_ACCEPT_RESULT, MARKER_PAYLOAD, TradeListingConveyanceRequest, TradeListingConveyanceResult } from "@radroots/trade-bindings"; +import { ndk_event } from "../../../../events/lib.js"; +import { NDKEventFigure } from "../../../../types/ndk.js"; +import { + build_request_tags, + build_result_tags, + CommonRequestOpts, + CommonResultOpts, + make_event_input, + make_text_input, +} from "../../tags.js"; +import { tags_trade_listing_chain } from "../tags.js"; + +export const ndk_event_trade_listing_conveyance_request = async ( + opts: NDKEventFigure<{ data: TradeListingConveyanceRequest; options?: CommonRequestOpts }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data, options } = opts; + + const inputs: RadrootsJobInput[] = [ + make_event_input(data.accept_result_event_id, MARKER_ACCEPT_RESULT), + make_text_input({ method: data.method }, MARKER_PAYLOAD), + ]; + + const tags = build_request_tags(KIND_TRADE_LISTING_CONVEYANCE_REQ, inputs, options); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_CONVEYANCE_REQ, content: "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; + +export const ndk_event_trade_listing_conveyance_result = async ( + opts: NDKEventFigure<{ + request_event_id: string; + content: TradeListingConveyanceResult | string; + options?: CommonResultOpts; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, content, options } = opts; + + const base_tags = build_result_tags( + KIND_TRADE_LISTING_CONVEYANCE_RES, + request_event_id, + options + ); + const tags = options?.chain + ? [...base_tags, ...tags_trade_listing_chain(options.chain)] + : base_tags; + + const content_body = typeof content === "string" ? content : JSON.stringify(content); + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_CONVEYANCE_RES, content: content_body, tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/domain/trade/listing/fulfillment/lib.ts b/utils-nostr/src/domain/trade/listing/fulfillment/lib.ts @@ -0,0 +1,61 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { KIND_TRADE_LISTING_FULFILL_REQ, KIND_TRADE_LISTING_FULFILL_RES, MARKER_PREVIOUS, TradeListingFulfillmentRequest, TradeListingFulfillmentState } from "@radroots/trade-bindings"; +import { ndk_event } from "../../../../events/lib.js"; +import { NDKEventFigure } from "../../../../types/ndk.js"; +import { + build_request_tags, + build_result_tags, + CommonRequestOpts, + CommonResultOpts, + make_event_input +} from "../../tags.js"; +import { tags_trade_listing_chain } from "../tags.js"; + +export const ndk_event_trade_listing_fulfillment_request = async ( + opts: NDKEventFigure<{ data: TradeListingFulfillmentRequest; options?: CommonRequestOpts }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data, options } = opts; + + const inputs: RadrootsJobInput[] = [ + make_event_input(data.payment_result_event_id, MARKER_PREVIOUS), + ]; + + const tags = build_request_tags(KIND_TRADE_LISTING_FULFILL_REQ, inputs, options); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_FULFILL_REQ, content: "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; + +export const ndk_event_trade_listing_fulfillment_result = async ( + opts: NDKEventFigure<{ + request_event_id: string; + content: TradeListingFulfillmentState | string; + options?: CommonResultOpts; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, content, options } = opts; + + const base_tags = build_result_tags( + KIND_TRADE_LISTING_FULFILL_RES, + request_event_id, + options + ); + const tags = options?.chain + ? [...base_tags, ...tags_trade_listing_chain(options.chain)] + : base_tags; + + const content_body = typeof content === "string" ? content : JSON.stringify(content); + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_FULFILL_RES, content: content_body, tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/domain/trade/listing/invoice/lib.ts b/utils-nostr/src/domain/trade/listing/invoice/lib.ts @@ -0,0 +1,73 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { KIND_TRADE_LISTING_INVOICE_REQ, KIND_TRADE_LISTING_INVOICE_RES, MARKER_ACCEPT_RESULT, TradeListingInvoiceRequest, TradeListingInvoiceResult } from "@radroots/trade-bindings"; +import { ndk_event } from "../../../../events/lib.js"; +import { NDKEventFigure } from "../../../../types/ndk.js"; +import { + build_request_tags, + build_result_tags, + CommonRequestOpts, + CommonResultOpts, + make_event_input +} from "../../tags.js"; +import { tags_trade_listing_chain } from "../tags.js"; + +export const ndk_event_trade_listing_invoice_request = async ( + opts: NDKEventFigure<{ data: TradeListingInvoiceRequest; options?: CommonRequestOpts }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data, options } = opts; + + const inputs: RadrootsJobInput[] = [ + make_event_input(data.accept_result_event_id, MARKER_ACCEPT_RESULT), + ]; + + const tags = build_request_tags(KIND_TRADE_LISTING_INVOICE_REQ, inputs, options); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_INVOICE_REQ, content: "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; + +export const ndk_event_trade_listing_invoice_result = async ( + opts: NDKEventFigure<{ + request_event_id: string; + content: TradeListingInvoiceResult | string; + options?: Omit<CommonResultOpts, "payment_sat" | "payment_bolt11"> & { + chain?: { e_root: string; d?: string; e_prev?: string }; + }; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, content, options } = opts; + + const parsed: TradeListingInvoiceResult | undefined = + typeof content === "string" ? undefined : (content as TradeListingInvoiceResult); + + const base_tags = build_result_tags( + KIND_TRADE_LISTING_INVOICE_RES, + request_event_id, + options, + parsed + ? { + payment_sat: parsed.total_sat, + payment_bolt11: parsed.bolt11, + } + : undefined + ); + + const tags = options?.chain + ? [...base_tags, ...tags_trade_listing_chain(options.chain)] + : base_tags; + + const content_body = typeof content === "string" ? content : JSON.stringify(content); + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_INVOICE_RES, content: content_body, tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/domain/trade/listing/order/lib.ts b/utils-nostr/src/domain/trade/listing/order/lib.ts @@ -0,0 +1,70 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { KIND_TRADE_LISTING_ORDER_REQ, KIND_TRADE_LISTING_ORDER_RES, MARKER_LISTING, MARKER_PAYLOAD, TradeListingOrderResult, type TradeListingOrderRequest } from "@radroots/trade-bindings"; +import { ndk_event } from "../../../../events/lib.js"; +import { NDKEventFigure } from "../../../../types/ndk.js"; +import { + build_request_tags, + build_result_tags, + CommonRequestOpts, + CommonResultOpts, + make_event_input, + make_text_input, +} from "../../tags.js"; +import { tags_trade_listing_chain } from "../tags.js"; + +export const ndk_event_trade_listing_order_request = async ( + opts: NDKEventFigure<{ data: TradeListingOrderRequest; options?: CommonRequestOpts }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data, options } = opts; + + const inputs: RadrootsJobInput[] = [ + make_event_input(data.event.id, MARKER_LISTING), + make_text_input(data.payload, MARKER_PAYLOAD), + ]; + + const tags = build_request_tags(KIND_TRADE_LISTING_ORDER_REQ, inputs, options); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_ORDER_REQ, content: "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; + +export const ndk_event_trade_listing_order_result = async ( + opts: NDKEventFigure<{ + request_event_id: string; + content: TradeListingOrderResult | string; + options?: CommonResultOpts; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, content, options } = opts; + + const include_inputs = + options?.include_inputs && !options.encrypted + ? options.include_inputs.map(s => make_text_input(s, MARKER_PAYLOAD)) + : []; + + const base_tags = build_result_tags( + KIND_TRADE_LISTING_ORDER_RES, + request_event_id, + options, + { inputs: include_inputs } + ); + + const tags = options?.chain + ? [...base_tags, ...tags_trade_listing_chain(options.chain)] + : base_tags; + + const content_body = typeof content === "string" ? content : JSON.stringify(content); + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_ORDER_RES, content: content_body, tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; diff --git a/utils-nostr/src/domain/trade/listing/payment/lib.ts b/utils-nostr/src/domain/trade/listing/payment/lib.ts @@ -0,0 +1,63 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { KIND_TRADE_LISTING_PAYMENT_REQ, KIND_TRADE_LISTING_PAYMENT_RES, MARKER_INVOICE_RESULT, MARKER_PROOF, TradeListingPaymentProofRequest, TradeListingPaymentResult } from "@radroots/trade-bindings"; +import { ndk_event } from "../../../../events/lib.js"; +import { NDKEventFigure } from "../../../../types/ndk.js"; +import { + build_request_tags, + build_result_tags, + CommonRequestOpts, + CommonResultOpts, + make_event_input, + make_text_input, +} from "../../tags.js"; +import { tags_trade_listing_chain } from "../tags.js"; + +export const ndk_event_trade_listing_payment_request = async ( + opts: NDKEventFigure<{ data: TradeListingPaymentProofRequest; options?: CommonRequestOpts }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data, options } = opts; + + const inputs: RadrootsJobInput[] = [ + make_event_input(data.invoice_result_event_id, MARKER_INVOICE_RESULT), + make_text_input(data.proof, MARKER_PROOF), + ]; + + const tags = build_request_tags(KIND_TRADE_LISTING_PAYMENT_REQ, inputs, options); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_PAYMENT_REQ, content: "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; + +export const ndk_event_trade_listing_payment_result = async ( + opts: NDKEventFigure<{ + request_event_id: string; + content: TradeListingPaymentResult | string; + options?: CommonResultOpts; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, content, options } = opts; + + const base_tags = build_result_tags( + KIND_TRADE_LISTING_PAYMENT_RES, + request_event_id, + options + ); + const tags = options?.chain + ? [...base_tags, ...tags_trade_listing_chain(options.chain)] + : base_tags; + + const content_body = typeof content === "string" ? content : JSON.stringify(content); + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_PAYMENT_RES, content: content_body, tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; diff --git a/utils-nostr/src/domain/trade/listing/receipt/lib.ts b/utils-nostr/src/domain/trade/listing/receipt/lib.ts @@ -0,0 +1,63 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { KIND_TRADE_LISTING_RECEIPT_REQ, KIND_TRADE_LISTING_RECEIPT_RES, MARKER_FULFILLMENT_RESULT, MARKER_PAYLOAD, TradeListingReceiptRequest, TradeListingReceiptResult } from "@radroots/trade-bindings"; +import { ndk_event } from "../../../../events/lib.js"; +import { NDKEventFigure } from "../../../../types/ndk.js"; +import { + build_request_tags, + build_result_tags, + CommonRequestOpts, + CommonResultOpts, + make_event_input, + make_text_input, +} from "../../tags.js"; +import { tags_trade_listing_chain } from "../tags.js"; + +export const ndk_event_trade_listing_receipt_request = async ( + opts: NDKEventFigure<{ data: TradeListingReceiptRequest; options?: CommonRequestOpts }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data, options } = opts; + + const inputs: RadrootsJobInput[] = [ + make_event_input(data.fulfillment_result_event_id, MARKER_FULFILLMENT_RESULT), + ...(data.note ? [make_text_input({ note: data.note }, MARKER_PAYLOAD)] : []), + ]; + + const tags = build_request_tags(KIND_TRADE_LISTING_RECEIPT_REQ, inputs, options); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_RECEIPT_REQ, content: "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; + +export const ndk_event_trade_listing_receipt_result = async ( + opts: NDKEventFigure<{ + request_event_id: string; + content: TradeListingReceiptResult | string; + options?: CommonResultOpts; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, content, options } = opts; + + const base_tags = build_result_tags( + KIND_TRADE_LISTING_RECEIPT_RES, + request_event_id, + options + ); + const tags = options?.chain + ? [...base_tags, ...tags_trade_listing_chain(options.chain)] + : base_tags; + + const content_body = typeof content === "string" ? content : JSON.stringify(content); + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_TRADE_LISTING_RECEIPT_RES, content: content_body, tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; diff --git a/utils-nostr/src/domain/trade/listing/tags.ts b/utils-nostr/src/domain/trade/listing/tags.ts @@ -0,0 +1,14 @@ +import { TAG_D, TAG_E_PREV, TAG_E_ROOT } from "@radroots/events-bindings"; +import { NostrEventTags } from "../../../types/lib.js"; + +export const tags_trade_listing_chain = (opts: { + e_root: string; + d?: string; + e_prev?: string; +}): NostrEventTags => { + const tags: NostrEventTags = []; + tags.push([TAG_E_ROOT, opts.e_root]); + if (opts.e_prev) tags.push([TAG_E_PREV, opts.e_prev]); + if (opts.d) tags.push([TAG_D, opts.d]); + return tags; +}; diff --git a/utils-nostr/src/domain/trade/tags.ts b/utils-nostr/src/domain/trade/tags.ts @@ -0,0 +1,88 @@ +import { RadrootsJobInput } from "@radroots/events-bindings"; +import { tags_job_request, tags_job_result } from "../../events/job/tags.js"; + +export type CommonRequestOpts = { + output?: string; + bid_sat?: number; + relays?: string[]; + providers?: string[]; + topics?: string[]; + encrypted?: boolean; + params?: Array<{ key: string; value: string }>; +}; + +export type CommonResultOpts = { + request_relay_hint?: string; + request_json?: string; + customer_pubkey?: string; + payment_sat?: number; + payment_bolt11?: string; + encrypted?: boolean; + include_inputs?: string[]; + chain?: { e_root: string; d?: string; e_prev?: string }; +}; + +export const make_event_input = ( + id: string, + marker: string, + relay?: string +): RadrootsJobInput => ({ + data: id, + input_type: "event", + ...(relay ? { relay } : {}), + marker, +}); + +export const make_text_input = ( + payload: unknown, + marker: string +): RadrootsJobInput => ({ + data: typeof payload === "string" ? payload : JSON.stringify(payload), + input_type: "text", + marker, +}); + +export const build_request_tags = ( + kind: number, + inputs: RadrootsJobInput[], + opts?: CommonRequestOpts +) => + tags_job_request({ + kind, + inputs, + output: opts?.output, + params: opts?.params ?? [], + bid_sat: opts?.bid_sat, + relays: opts?.relays ?? [], + providers: opts?.providers ?? [], + topics: opts?.topics ?? [], + encrypted: !!opts?.encrypted, + }); + +export const build_result_tags = ( + kind: number, + request_event_id: string, + opts?: CommonResultOpts, + extra?: { + inputs?: RadrootsJobInput[]; + payment_sat?: number; + payment_bolt11?: string; + } +) => + tags_job_result({ + kind, + request_event: { + id: request_event_id, + ...(opts?.request_relay_hint ? { relays: opts.request_relay_hint } : {}), + }, + request_json: opts?.request_json, + inputs: !opts?.encrypted && extra?.inputs?.length ? extra.inputs : [], + customer_pubkey: opts?.customer_pubkey, + payment: + extra?.payment_sat !== undefined + ? { amount_sat: extra.payment_sat, bolt11: extra.payment_bolt11 } + : opts?.payment_sat !== undefined + ? { amount_sat: opts.payment_sat, bolt11: opts.payment_bolt11 } + : undefined, + encrypted: !!opts?.encrypted, + }); diff --git a/utils-nostr/src/events/comment/lib.ts b/utils-nostr/src/events/comment/lib.ts @@ -0,0 +1,21 @@ +import { NDKEvent, NDKKind } from "@nostr-dev-kit/ndk"; +import { RadrootsComment } from "@radroots/events-bindings"; +import { NDKEventFigure } from "../../types/ndk.js"; +import { ndk_event } from "../lib.js"; +import { tags_comment } from "./tags.js"; + +export const KIND_RADROOTS_COMMENT = 1111; +export type KindRadrootsComment = typeof KIND_RADROOTS_COMMENT; + +export const ndk_event_comment = async (opts: NDKEventFigure<{ data: RadrootsComment; }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: NDKKind.GenericReply, + content: data.content, + tags: tags_comment(data) + }, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/comment/parse.ts b/utils-nostr/src/events/comment/parse.ts @@ -0,0 +1,20 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { radroots_comment_schema, RadrootsComment } from "@radroots/events-bindings"; +import { parse_nostr_event_basis } from "../lib.js"; +import { NdkEventBasis } from "../subscription.js"; +import { KIND_RADROOTS_COMMENT, type KindRadrootsComment } from "./lib.js"; + +export type RadrootsCommentNostrEvent = NdkEventBasis<KindRadrootsComment> & { comment: RadrootsComment; } + +export const parse_nostr_comment_event = (event: NDKEvent): RadrootsCommentNostrEvent | undefined => { + const ev = parse_nostr_event_basis(event, KIND_RADROOTS_COMMENT); + if (!ev) return undefined; + try { + const parsed = JSON.parse(event.content); + const comment = radroots_comment_schema.parse(parsed); + return { ...ev, comment }; + } catch { + return undefined; + } +}; + diff --git a/utils-nostr/src/events/comment/tags.ts b/utils-nostr/src/events/comment/tags.ts @@ -0,0 +1,37 @@ +import { RadrootsComment } from "@radroots/events-bindings"; +import { NostrEventTags } from "../../types/lib.js"; + +export const tags_comment = (opts: RadrootsComment): NostrEventTags => { + const { root: root_event, parent: parent_event } = opts; + + const root = { + kind: root_event.kind.toString(), + author: root_event.author, + id: root_event.id, + d_tag: root_event.d_tag, + relays: root_event.relays || [], + }; + + const parent = (parent_event && parent_event.id) + ? { + kind: parent_event.kind.toString(), + author: parent_event.author, + id: parent_event.id, + d_tag: parent_event.d_tag, + relays: parent_event.relays || [], + } + : root; + + const tags: NostrEventTags = [ + ["E", root.id, ...root.relays], + ["P", root.author], + ["K", root.kind], + ...(root.d_tag ? [["A", `${root.kind}:${root.author}:${root.d_tag}`, ...root.relays]] : []), + ["e", parent.id, ...parent.relays], + ["p", parent.author], + ["k", parent.kind], + ...(parent.d_tag ? [["a", `${parent.kind}:${parent.author}:${parent.d_tag}`, ...parent.relays]] : []), + ]; + + return tags; +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/follow/lib.ts b/utils-nostr/src/events/follow/lib.ts @@ -0,0 +1,21 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsFollow } from "@radroots/events-bindings"; +import { NDKEventFigure } from "../../types/ndk.js"; +import { ndk_event } from "../lib.js"; +import { tags_follow_list } from "./tags.js"; + +export const KIND_RADROOTS_FOLLOW = 3; +export type KindRadrootsFollow = typeof KIND_RADROOTS_FOLLOW; + +export const ndk_event_follows = async (opts: NDKEventFigure<{ data: RadrootsFollow; }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: 3, + content: ``, + tags: tags_follow_list(data.list), + }, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/follow/parse.ts b/utils-nostr/src/events/follow/parse.ts @@ -0,0 +1,19 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsFollow, radroots_follow_schema } from "@radroots/events-bindings"; +import { parse_nostr_event_basis } from "../lib.js"; +import { NdkEventBasis } from "../subscription.js"; +import { KIND_RADROOTS_FOLLOW, type KindRadrootsFollow } from "./lib.js"; + +export type RadrootsFollowNostrEvent = NdkEventBasis<KindRadrootsFollow> & { follow: RadrootsFollow; } + +export const parse_nostr_follow_event = (event: NDKEvent): RadrootsFollowNostrEvent | undefined => { + const ev = parse_nostr_event_basis(event, KIND_RADROOTS_FOLLOW); + if (!ev) return undefined; + try { + const parsed = JSON.parse(event.content); + const follow = radroots_follow_schema.parse(parsed); + return { ...ev, follow }; + } catch { + return undefined; + } +}; diff --git a/utils-nostr/src/events/follow/tags.ts b/utils-nostr/src/events/follow/tags.ts @@ -0,0 +1,11 @@ +import { RadrootsFollowProfile } from "@radroots/events-bindings"; +import { NostrEventTags } from "../../types/lib.js"; + +export const tags_follow_list = (list: RadrootsFollowProfile[]): NostrEventTags => { + return list.map(({ public_key, relay_url, contact_name }) => { + const entry = [`p`, public_key]; + if (relay_url) entry.push(relay_url); + if (contact_name) entry.push(contact_name); + return entry; + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/job/lib.ts b/utils-nostr/src/events/job/lib.ts @@ -0,0 +1,95 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { JobFeedbackStatus, KIND_JOB_FEEDBACK, RadrootsJobFeedback, RadrootsJobRequest, RadrootsJobResult } from "@radroots/events-bindings"; +import { NDKEventFigure } from "../../types/ndk.js"; +import { ndk_event } from "../lib.js"; +import { tags_job_feedback, tags_job_request, tags_job_result } from "./tags.js"; + +export const ndk_event_job_request = async (opts: NDKEventFigure<{ data: RadrootsJobRequest; }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: data.kind, + content: "", + tags: tags_job_request(data), + }, + }); +}; + +export const ndk_event_job_result = async (opts: NDKEventFigure<{ data: RadrootsJobResult; }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: data.kind, + content: data.content || "", + tags: tags_job_result(data), + }, + }); +}; + +export const ndk_event_job_feedback = async (opts: NDKEventFigure<{ data: RadrootsJobFeedback; }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: data.kind, + content: data.content || "", + tags: tags_job_feedback(data), + }, + }); +}; + +export const ndk_event_job_feedback_todo = async ( + opts: NDKEventFigure<{ + request_event_id: string; + status: + | JobFeedbackStatus + | "payment-required" + | "processing" + | "error" + | "success" + | "partial"; + content?: string; + options?: { + request_relay_hint?: string; + extra_info?: string; + customer_pubkey?: string; + amount_sat?: number; + bolt11?: string; + encrypted?: boolean; + }; + }> +): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, request_event_id, status, content, options } = opts; + + const fb: RadrootsJobFeedback = { + kind: KIND_JOB_FEEDBACK, + status: status as JobFeedbackStatus, + extra_info: options?.extra_info, + request_event: { + id: request_event_id, + ...(options?.request_relay_hint ? { relays: options.request_relay_hint } : {}), + }, + customer_pubkey: options?.customer_pubkey, + payment: + options?.amount_sat !== undefined + ? { amount_sat: options.amount_sat, bolt11: options?.bolt11 } + : undefined, + content, + encrypted: !!options?.encrypted, + }; + + const tags = tags_job_feedback(fb); + + return await ndk_event({ + ndk, + ndk_user, + basis: { kind: KIND_JOB_FEEDBACK, content: content ?? "", tags }, + client: opts.client, + date_published: opts.date_published, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/job/tags.ts b/utils-nostr/src/events/job/tags.ts @@ -0,0 +1,75 @@ +import { RadrootsJobFeedback, RadrootsJobInput, RadrootsJobRequest, RadrootsJobResult } from "@radroots/events-bindings"; +import { NostrEventTag, NostrEventTags } from "../../types/lib.js"; + +export const tag_job_input = (input: RadrootsJobInput): NostrEventTag => { + const t: NostrEventTag = ["i", input.data, input.input_type]; + if (input.relay) t.push(input.relay); + if (input.marker) t.push(input.marker); + return t; +}; + +export const tag_job_output = (mime: string): NostrEventTag => ["output", mime]; + +export const tag_job_param = (key: string, value: string): NostrEventTag => ["param", key, value]; + +export const tag_job_bid = (sat: number): NostrEventTag => ["bid", String(sat)]; + +export const tags_job_relays = (relays: string[]): NostrEventTags => + relays.map(r => ["relays", r]); + +export const tags_job_providers = (pubkeys: string[]): NostrEventTags => + pubkeys.map(p => ["p", p]); + +export const tags_job_topics = (topics: string[]): NostrEventTags => + topics.map(t => ["t", t]); + +export const tag_job_amount = (msat: number, bolt11?: string | null): NostrEventTag => + bolt11 ? ["amount", String(msat), bolt11] : ["amount", String(msat)]; + +export const tag_job_encrypted = (): NostrEventTag => ["encrypted"]; + +export const tags_job_request = (opts: RadrootsJobRequest): NostrEventTags => { + const tags: NostrEventTags = []; + for (const input of opts.inputs) tags.push(tag_job_input(input)); + if (opts.output) tags.push(tag_job_output(opts.output)); + if (opts.params) for (const p of opts.params) tags.push(tag_job_param(p.key, p.value)); + if (typeof opts.bid_sat === "number") tags.push(tag_job_bid(opts.bid_sat)); + if (opts.relays?.length) tags.push(...tags_job_relays(opts.relays)); + if (opts.providers?.length) tags.push(...tags_job_providers(opts.providers)); + if (opts.topics?.length) tags.push(...tags_job_topics(opts.topics)); + if (opts.encrypted) tags.push(tag_job_encrypted()); + return tags; +}; + +export const tags_job_result = (opts: RadrootsJobResult): NostrEventTags => { + const tags: NostrEventTags = []; + const event_tag: NostrEventTag = ["e", opts.request_event.id]; + if (opts.request_event.relays) event_tag.push(opts.request_event.relays); + tags.push(event_tag); + if (opts.request_json) tags.push(["request", opts.request_json]); + if (!opts.encrypted && opts.inputs?.length) for (const input of opts.inputs) tags.push(tag_job_input(input)); + if (opts.customer_pubkey) tags.push(["p", opts.customer_pubkey]); + if (opts.payment?.amount_sat !== undefined) { + const msat = Math.round(Number(opts.payment.amount_sat) * 1000); + tags.push(tag_job_amount(msat, opts.payment.bolt11)); + } + if (opts.encrypted) tags.push(tag_job_encrypted()); + return tags; +}; + +export const tags_job_feedback = (opts: RadrootsJobFeedback): NostrEventTags => { + const tags: NostrEventTags = []; + const status_tag: NostrEventTag = ["status", String(opts.status)]; + if (opts.extra_info) status_tag.push(opts.extra_info); + tags.push(status_tag); + if (opts.payment?.amount_sat !== undefined) { + const msat = Math.round(Number(opts.payment.amount_sat) * 1000); + tags.push(tag_job_amount(msat, opts.payment.bolt11)); + } + const event_tag: NostrEventTag = ["e", opts.request_event.id]; + if (opts.request_event.relays) event_tag.push(opts.request_event.relays); + tags.push(event_tag); + if (opts.customer_pubkey) tags.push(["p", opts.customer_pubkey]); + if (opts.encrypted) tags.push(tag_job_encrypted()); + return tags; +}; diff --git a/utils-nostr/src/events/job/utils.ts b/utils-nostr/src/events/job/utils.ts @@ -0,0 +1,34 @@ +import { JobInputType, KIND_JOB_FEEDBACK } from "@radroots/events-bindings"; +import { TradeListingStage } from "@radroots/trade-bindings"; +import { + REQUEST_KINDS, + RESULT_KINDS, +} from "../../domain/trade/lib.js"; +import type { NostrEventTags } from "../../types/lib.js"; + +export function get_job_input_data_for_marker( + tags: NostrEventTags, + marker: string, + input_type: JobInputType = "event" +): string | undefined { + for (const t of tags) { + if (t[0] !== "i") continue; + if (t[2] !== input_type) continue; + const tag_marker = t.length >= 5 ? t[4] : t.length >= 4 ? t[3] : undefined; + if (tag_marker === marker) return t[1]; + } + return undefined; +} + +export function get_trade_listing_stage_from_event_kind( + kind: number +): TradeListingStage | undefined { + for (const key of Object.keys(REQUEST_KINDS) as TradeListingStage[]) { + if (REQUEST_KINDS[key] === kind) return key; + } + for (const key of Object.keys(RESULT_KINDS) as TradeListingStage[]) { + if (RESULT_KINDS[key] === kind) return key; + } + if (kind === KIND_JOB_FEEDBACK) return TradeListingStage.Order; + return undefined; +} diff --git a/utils-nostr/src/events/lib.ts b/utils-nostr/src/events/lib.ts @@ -0,0 +1,88 @@ +import { schnorr } from "@noble/curves/secp256k1"; +import { hexToBytes } from "@noble/hashes/utils"; +import { NDKEvent, NDKTag } from "@nostr-dev-kit/ndk"; +import { time_now_ms, time_now_s, uuidv4 } from "@radroots/utils"; +import { finalizeEvent, getEventHash, nip19, type NostrEvent as NostrToolsEvent } from "nostr-tools"; +import { ILibNostrEventSign, ILibNostrNeventEncode, NostrEventTags } from "../types/lib.js"; +import { NDKEventFigure } from "../types/ndk.js"; +import { tag_client } from "../utils/tags.js"; +import { NdkEventBasis } from "./subscription.js"; + +export const get_event_tag = (tags: NDKTag[], key: string): string => tags.find(t => t[0] === key)?.[1] ?? ''; +export const get_event_tags = (tags: NDKTag[], key: string): NDKTag[] => tags.filter(t => t[0] === key); + +export const parse_nostr_event_basis = <T extends number>(event: NDKEvent, kind: T): NdkEventBasis<T> | undefined => { + if (!event || typeof event.created_at !== 'number' || event.kind !== kind) return undefined; + return { id: event.id, published_at: event.created_at, author: event.pubkey, kind: event.kind as T }; +}; + +export const lib_nostr_event_verify = (event: NostrToolsEvent): boolean => { + const hash = getEventHash(event); + if (hash !== event.id) return false + const valid = schnorr.verify(event.sig, hash, event.pubkey); + return valid; +}; + +export const lib_nostr_event_sign = (opts: ILibNostrEventSign): NostrToolsEvent => { + return finalizeEvent(opts.event, hexToBytes(opts.secret_key)) +}; + +export const lib_nostr_event_sign_attest = (secret_key: string): NostrToolsEvent => { + return lib_nostr_event_sign({ + secret_key, + event: { + kind: 1, + created_at: time_now_s(), + tags: [], + content: uuidv4(), + }, + }); +}; + + +export const lib_nostr_event_verify_serialized = async (event_serialized: string): Promise<{ public_key: string } | undefined> => { + try { + const event = JSON.parse(event_serialized); + const hash = getEventHash(event); + if (hash !== event.id) return undefined; + const valid = schnorr.verify(event.sig, hash, event.pubkey); + if (valid) return { public_key: String(event.pubkey) }; + return undefined; + } catch { + return undefined; + } +}; + +export const lib_nostr_nevent_encode = (opts: ILibNostrNeventEncode): string => { + return nip19.neventEncode(opts); +}; + +export const ndk_event = async (opts: NDKEventFigure<{ + basis: { + kind: number; + content: string; + tags?: NostrEventTags; + } +}>): Promise<NDKEvent | undefined> => { + try { + const { ndk: ndk, ndk_user: ndk_user, basis } = opts; + const time_now = time_now_ms(); + const published_at = opts.date_published ? Math.floor(opts.date_published.getTime() / 1000).toString() + : time_now.toString() + const tags: NostrEventTags = [ + ['published_at', published_at], + ]; + if (basis.tags?.length) tags.push(...basis.tags); + if (opts.client) tags.push(tag_client(opts.client, tags.find(i => i[0] === `d_tag`)?.[1] || undefined)); + const ev = new NDKEvent(ndk, { + kind: basis.kind, + pubkey: ndk_user.pubkey, + content: basis.content, + created_at: time_now, + tags + }); + return ev; + } catch (e) { + console.log(`(error) ndk_event `, e); + }; +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/listing/lib.ts b/utils-nostr/src/events/listing/lib.ts @@ -0,0 +1,21 @@ +import { NDKEvent, NDKKind } from "@nostr-dev-kit/ndk"; +import { type RadrootsListing } from "@radroots/events-bindings"; +import { NDKEventFigure } from "../../types/ndk.js"; +import { ndk_event } from "../lib.js"; +import { tags_listing } from "./tags.js"; + +export const KIND_RADROOTS_LISTING = 30402; +export type KindRadrootsListing = typeof KIND_RADROOTS_LISTING; + +export const ndk_event_classified = async (opts: NDKEventFigure<{ data: RadrootsListing; }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: NDKKind.Classified, + content: ``, + tags: tags_listing(data), + }, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/listing/parse.ts b/utils-nostr/src/events/listing/parse.ts @@ -0,0 +1,190 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import type { RadrootsCoreMoney, RadrootsCoreQuantity, RadrootsCoreQuantityPrice } from "@radroots/core-bindings"; +import { type RadrootsListing, type RadrootsListingDiscount, radroots_listing_discount_schema, radroots_listing_image_schema, radroots_listing_location_schema, radroots_listing_price_schema, radroots_listing_product_schema, radroots_listing_quantity_schema, radroots_listing_schema } from "@radroots/events-bindings"; +import { get_event_tag, get_event_tags, parse_nostr_event_basis } from "../lib.js"; +import { NdkEventBasis } from "../subscription.js"; +import { KIND_RADROOTS_LISTING, type KindRadrootsListing } from "./lib.js"; + +export type RadrootsListingNostrEvent = NdkEventBasis<KindRadrootsListing> & { listing: RadrootsListing; }; + +type CoreUnit = RadrootsCoreQuantity["unit"]; +type CoreCurrency = RadrootsCoreMoney["currency"]; + +const to_number = (value?: string): number | undefined => { + if (value === undefined) return undefined; + const num = Number(value); + return Number.isFinite(num) ? num : undefined; +}; + +const clean_string = (value?: string | null) => value?.trim() || undefined; + +const parse_currency_code = (code?: string): CoreCurrency | undefined => { + const cleaned = clean_string(code); + if (!cleaned || cleaned.length < 3) return undefined; + const upper = cleaned.toUpperCase(); + return [upper.charCodeAt(0), upper.charCodeAt(1), upper.charCodeAt(2)] as CoreCurrency; +}; + +const parse_unit_code = (unit?: string): CoreUnit | undefined => { + switch ((unit ?? "").trim().toLowerCase()) { + case "each": + case "ea": + case "count": + return "Each" as CoreUnit; + case "kg": + case "kilogram": + case "kilograms": + return "MassKg" as CoreUnit; + case "g": + case "gram": + case "grams": + return "MassG" as CoreUnit; + case "oz": + case "ounce": + case "ounces": + return "MassOz" as CoreUnit; + case "lb": + case "pound": + case "pounds": + return "MassLb" as CoreUnit; + case "l": + case "liter": + case "litre": + case "liters": + case "litres": + return "VolumeL" as CoreUnit; + case "ml": + case "milliliter": + case "millilitre": + case "milliliters": + case "millilitres": + return "VolumeMl" as CoreUnit; + default: + return undefined; + } +}; + +const parse_quantity_tag = (tag: string[]) => { + if (tag.length < 3) return undefined; + const amount = to_number(tag[1]); + const unit = parse_unit_code(tag[2]); + if (amount === undefined || !unit) return undefined; + const label = clean_string(tag[3]); + const count = to_number(tag[4]); + const value: RadrootsCoreQuantity = label ? { amount, unit, label } : { amount, unit }; + return radroots_listing_quantity_schema.parse({ value, label, count }); +}; + +const parse_price_tag = (tag: string[]) => { + if (tag.length < 5) return undefined; + const amount = to_number(tag[1]); + const currency = parse_currency_code(tag[2]); + const quantity_amount = to_number(tag[3]); + const quantity_unit = parse_unit_code(tag[4]); + if (amount === undefined || !currency || quantity_amount === undefined || !quantity_unit) return undefined; + const label = clean_string(tag[5]); + const money: RadrootsCoreMoney = { amount, currency }; + const quantity: RadrootsCoreQuantity = label ? { amount: quantity_amount, unit: quantity_unit, label } : { amount: quantity_amount, unit: quantity_unit }; + return radroots_listing_price_schema.parse({ amount: money, quantity }); +}; + +const parse_discount_tag = (tag: string[]) => { + const prefix = "price-discount-"; + if (!tag[0]?.startsWith(prefix) || tag.length < 2) return undefined; + const kind = tag[0].slice(prefix.length) as RadrootsListingDiscount["kind"]; + try { + const amount = JSON.parse(tag[1]); + return radroots_listing_discount_schema.parse({ kind, amount }); + } catch { + return undefined; + } +}; + +const parse_image_tag = (tag: string[]) => { + if (tag[0] !== "image" || !tag[1]) return undefined; + const image: any = { url: tag[1] }; + if (tag[2]) { + const [w, h] = tag[2].split("x").map(v => Number(v)); + if (Number.isFinite(w) && Number.isFinite(h)) image.size = { w, h }; + } + return radroots_listing_image_schema.parse(image); +}; + +export const parse_nostr_listing_event = (event: NDKEvent): RadrootsListingNostrEvent | undefined => { + const ev = parse_nostr_event_basis(event, KIND_RADROOTS_LISTING); + if (!ev) return undefined; + try { + const tags = event.tags; + + const d_tag = get_event_tag(tags, "d"); + + const product_raw = { + key: get_event_tag(tags, "key"), + title: get_event_tag(tags, "title"), + category: get_event_tag(tags, "category"), + summary: get_event_tag(tags, "summary"), + process: get_event_tag(tags, "process"), + lot: get_event_tag(tags, "lot"), + location: get_event_tag(tags, "location"), + profile: get_event_tag(tags, "profile"), + year: get_event_tag(tags, "year") + }; + + const product = radroots_listing_product_schema.parse(product_raw); + + const quantities = get_event_tags(tags, "quantity") + .map(parse_quantity_tag) + .filter(Boolean) as RadrootsListing["quantities"]; + + const prices = get_event_tags(tags, "price") + .map(parse_price_tag) + .filter(Boolean) as RadrootsCoreQuantityPrice[]; + + const discounts = tags + .filter(t => t[0]?.startsWith("price-discount-")) + .map(parse_discount_tag) + .filter(Boolean); + + const images = get_event_tags(tags, "image") + .map(parse_image_tag) + .filter(Boolean); + + const location_parts = get_event_tags(tags, "location")[0]?.slice(1) ?? []; + + const location_raw: any = {}; + if (location_parts[0]) location_raw.primary = location_parts[0]; + if (location_parts[1]) location_raw.city = location_parts[1]; + if (location_parts[2]) location_raw.region = location_parts[2]; + if (location_parts[3]) location_raw.country = location_parts[3]; + + if (location_raw.primary) { + const geohash = get_event_tags(tags, "g")[0]?.[1]; + if (geohash) location_raw.geohash = geohash; + + for (const loc_tag of get_event_tags(tags, "l")) { + if (loc_tag.length < 3) continue; + const coord = Number(loc_tag[1]); + if (!Number.isFinite(coord)) continue; + if (loc_tag[2] === "dd.lat") location_raw.lat = coord; + if (loc_tag[2] === "dd.lon") location_raw.lng = coord; + } + } + + const location = location_raw.primary + ? radroots_listing_location_schema.parse(location_raw) + : undefined; + + const listing = radroots_listing_schema.parse({ + d_tag, + product, + quantities, + prices, + discounts: discounts.length ? discounts : undefined, + location, + images: images.length ? images : undefined + }); + return { ...ev, listing }; + } catch { + return undefined; + } +}; diff --git a/utils-nostr/src/events/listing/tags.ts b/utils-nostr/src/events/listing/tags.ts @@ -0,0 +1,118 @@ +import type { RadrootsCoreQuantityPrice } from "@radroots/core-bindings"; +import type { RadrootsListing, RadrootsListingDiscount, RadrootsListingImage, RadrootsListingLocation, RadrootsListingQuantity } from "@radroots/events-bindings"; +import ngeotags, { type InputData as NostrGeotagsInputData } from "nostr-geotags"; +import { NostrEventTag, NostrEventTagLocation, NostrEventTags } from "../../types/lib.js"; + +type CoreUnit = RadrootsListingQuantity["value"]["unit"]; +type CoreCurrency = RadrootsCoreQuantityPrice["amount"]["currency"]; + +const currency_to_code = (currency: CoreCurrency): string => { + if (Array.isArray(currency) && currency.length >= 3) { + const [a, b, c] = currency; + return String.fromCharCode(Number(a), Number(b), Number(c)); + } + return String(currency); +}; + +const unit_to_code = (unit: CoreUnit): string => { + switch (unit) { + case "Each": return "each"; + case "MassKg": return "kg"; + case "MassG": return "g"; + case "MassOz": return "oz"; + case "MassLb": return "lb"; + case "VolumeL": return "l"; + case "VolumeMl": return "ml"; + default: return String(unit).toLowerCase(); + } +}; + +const clean_label = (value?: string | null) => value?.trim() || undefined; + +const normalize_listing_location = (location?: RadrootsListingLocation | null): NostrEventTagLocation | undefined => { + if (!location?.primary) return undefined; + const { primary, city, region, country, lat, lng } = location; + return { + primary, + city: city ?? undefined, + region: region ?? undefined, + country: country ?? undefined, + lat: typeof lat === "number" ? lat : undefined, + lng: typeof lng === "number" ? lng : undefined, + }; +}; + +const normalize_image_size = (size: RadrootsListingImage["size"]) => + size && typeof size?.w === "number" && typeof size?.h === "number" ? size : undefined; + +export const tag_listing_quantity = (opts: RadrootsListingQuantity): NostrEventTag => { + const tag: NostrEventTag = ["quantity", String(opts.value.amount), unit_to_code(opts.value.unit)]; + const label = clean_label(opts.label ?? opts.value.label); + if (label) tag.push(label); + if (opts.count !== undefined && opts.count !== null) tag.push(String(opts.count)); + return tag; +}; + +export const tag_listing_price = (price: RadrootsCoreQuantityPrice): NostrEventTag => { + const tag: NostrEventTag = [ + "price", + String(price.amount.amount), + currency_to_code(price.amount.currency).toLowerCase(), + String(price.quantity.amount), + unit_to_code(price.quantity.unit), + ]; + const label = clean_label(price.quantity.label); + if (label) tag.push(label); + return tag; +}; + +export const tag_listing_price_discount = (discount: RadrootsListingDiscount): NostrEventTag => { + const tag: NostrEventTag = [`price-discount-${discount.kind}`]; + tag.push(JSON.stringify(discount.amount)); + return tag; +}; + +export const tag_listing_location = (opts: NostrEventTagLocation): NostrEventTag => { + if (!opts.primary) return []; + const tag: NostrEventTag = ["location", opts.primary]; + if (opts.city) tag.push(opts.city); + if (opts.region) tag.push(opts.region); + if (opts.country) tag.push(opts.country); + return tag; +}; + +export const tags_listing_location_geotags = (opts: NostrEventTagLocation): NostrEventTags => { + const { lat, lng: lon, city, region, country } = opts; + const country_raw = country || ``; + const country_code = country_raw && country_raw?.length <= 3 ? country_raw : undefined; + const country_name = country_raw && country_raw?.length > 3 ? country_raw : undefined; + const input: NostrGeotagsInputData = { lat, lon, city, regionName: region, countryCode: country_code, countryName: country_name }; + return ngeotags(input, { geohash: true, gps: true, city: true, iso31662: true }); +}; + +export const tag_listing_image = (opts: RadrootsListingImage): NostrEventTag => { + const tag: NostrEventTag = ["image", opts.url]; + const size = normalize_image_size(opts.size); + if (size) tag.push(`${size.w}x${size.h}`); + return tag; +}; + +export const tags_listing = (opts: RadrootsListing): NostrEventTags => { + const { d_tag, product, quantities, prices } = opts; + const tags: NostrEventTags = [["d", d_tag]]; + for (const [k, v] of Object.entries(product)) if (v) tags.push([k, String(v)]); + for (const quantity of quantities) { + tags.push(tag_listing_quantity(quantity)); + } + for (const price of prices) { + tags.push(tag_listing_price(price)); + } + if (opts.discounts?.length) for (const discount of opts.discounts) if (discount) tags.push(tag_listing_price_discount(discount)); + const location = normalize_listing_location(opts.location); + if (location) { + tags.push(tag_listing_location(location)); + tags.push(...tags_listing_location_geotags(location)); + } + if (opts.images) for (const image_tags of opts.images) if (image_tags) tags.push(tag_listing_image(image_tags)); + return tags; +}; diff --git a/utils-nostr/src/events/profile/lib.ts b/utils-nostr/src/events/profile/lib.ts @@ -0,0 +1,19 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { type RadrootsProfile } from "@radroots/events-bindings"; +import { NDKEventFigure } from "../../types/ndk.js"; +import { ndk_event } from "../lib.js"; + +export const KIND_RADROOTS_PROFILE = 0; +export type KindRadrootsProfile = typeof KIND_RADROOTS_PROFILE; + +export const ndk_event_profile = async (opts: NDKEventFigure<{ data: RadrootsProfile }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: 0, + content: JSON.stringify(data), + }, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/profile/parse.ts b/utils-nostr/src/events/profile/parse.ts @@ -0,0 +1,19 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { type RadrootsProfile, radroots_profile_schema } from "@radroots/events-bindings"; +import { parse_nostr_event_basis } from "../lib.js"; +import { NdkEventBasis } from "../subscription.js"; +import { KIND_RADROOTS_PROFILE, type KindRadrootsProfile } from "./lib.js"; + +export type RadrootsProfileNostrEvent = NdkEventBasis<KindRadrootsProfile> & { profile: RadrootsProfile; } + +export const parse_nostr_profile_event = (event: NDKEvent): RadrootsProfileNostrEvent | undefined => { + const ev = parse_nostr_event_basis(event, KIND_RADROOTS_PROFILE); + if (!ev) return undefined; + try { + const parsed = JSON.parse(event.content); + const profile = radroots_profile_schema.parse(parsed); + return { ...ev, profile }; + } catch { + return undefined; + } +}; diff --git a/utils-nostr/src/events/reaction/lib.ts b/utils-nostr/src/events/reaction/lib.ts @@ -0,0 +1,21 @@ +import { NDKEvent, NDKKind } from "@nostr-dev-kit/ndk"; +import { RadrootsReaction } from "@radroots/events-bindings"; +import { NDKEventFigure } from "../../types/ndk.js"; +import { ndk_event } from "../lib.js"; +import { tags_reaction } from "./tags.js"; + +export const KIND_RADROOTS_REACTION = 7; +export type KindRadrootsReaction = typeof KIND_RADROOTS_REACTION; + +export const ndk_event_reaction = async (opts: NDKEventFigure<{ data: RadrootsReaction; }>): Promise<NDKEvent | undefined> => { + const { ndk, ndk_user, data } = opts; + return await ndk_event({ + ndk, + ndk_user, + basis: { + kind: NDKKind.Reaction, + content: data.content, + tags: tags_reaction(data) + }, + }); +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/reaction/parse.ts b/utils-nostr/src/events/reaction/parse.ts @@ -0,0 +1,19 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { RadrootsReaction, radroots_reaction_schema } from "@radroots/events-bindings"; +import { parse_nostr_event_basis } from "../lib.js"; +import { NdkEventBasis } from "../subscription.js"; +import { KIND_RADROOTS_REACTION, type KindRadrootsReaction } from "./lib.js"; + +export type RadrootsReactionNostrEvent = NdkEventBasis<KindRadrootsReaction> & { reaction: RadrootsReaction; } + +export const parse_nostr_reaction_event = (event: NDKEvent): RadrootsReactionNostrEvent | undefined => { + const ev = parse_nostr_event_basis(event, KIND_RADROOTS_REACTION); + if (!ev) return undefined; + try { + const parsed = JSON.parse(event.content); + const reaction = radroots_reaction_schema.parse(parsed); + return { ...ev, reaction }; + } catch { + return undefined; + } +}; diff --git a/utils-nostr/src/events/reaction/tags.ts b/utils-nostr/src/events/reaction/tags.ts @@ -0,0 +1,15 @@ +import { RadrootsReaction } from "@radroots/events-bindings"; +import { NostrEventTags } from "../../types/lib.js"; + +export const tags_reaction = (opts: RadrootsReaction): NostrEventTags => { + const { root } = opts; + const ref_kind = root.kind.toString(); + const ref_author = root.author; + const tags: NostrEventTags = [ + [`e`, root.id, ...root.relays || ``], + [`p`, ref_author], + [`k`, ref_kind], + ]; + if (root.d_tag) tags.push([`a`, `${ref_kind}:${ref_author}:${root.d_tag}`, ...root.relays || ``]) + return tags; +}; +\ No newline at end of file diff --git a/utils-nostr/src/events/subscription.ts b/utils-nostr/src/events/subscription.ts @@ -0,0 +1,36 @@ +import { NDKEvent } from "@nostr-dev-kit/ndk"; +import { parse_nostr_comment_event, RadrootsCommentNostrEvent } from "./comment/parse.js"; +import { parse_nostr_follow_event, RadrootsFollowNostrEvent } from "./follow/parse.js"; +import { parse_nostr_listing_event, RadrootsListingNostrEvent } from "./listing/parse.js"; +import { parse_nostr_profile_event, RadrootsProfileNostrEvent } from "./profile/parse.js"; +import { parse_nostr_reaction_event, RadrootsReactionNostrEvent } from "./reaction/parse.js"; + +export type NdkEventBasis<T extends number> = { + id: string; + published_at: number; + author: string; + kind: T; +}; + +export type NdkEventPayload = + | RadrootsProfileNostrEvent + | RadrootsListingNostrEvent + | RadrootsCommentNostrEvent + | RadrootsReactionNostrEvent + | RadrootsFollowNostrEvent + +export const on_ndk_event = (event: NDKEvent): NdkEventPayload | undefined => { + if (!event || typeof event.kind !== 'number') return undefined; + + switch (event.kind) { + case 0: return parse_nostr_profile_event(event); + case 30402: return parse_nostr_listing_event(event); + case 1111: return parse_nostr_comment_event(event); + case 7: return parse_nostr_reaction_event(event); + case 3: return parse_nostr_follow_event(event); + + default: return undefined; + } +}; + + diff --git a/utils-nostr/src/index.ts b/utils-nostr/src/index.ts @@ -0,0 +1,38 @@ +export * from "./domain/trade/lib.js" +export * from "./domain/trade/listing/accept/lib.js" +export * from "./domain/trade/listing/conveyance/lib.js" +export * from "./domain/trade/listing/fulfillment/lib.js" +export * from "./domain/trade/listing/invoice/lib.js" +export * from "./domain/trade/listing/order/lib.js" +export * from "./domain/trade/listing/payment/lib.js" +export * from "./domain/trade/listing/receipt/lib.js" +export * from "./domain/trade/listing/tags.js" +export * from "./domain/trade/tags.js" +export * from "./events/comment/lib.js" +export * from "./events/comment/parse.js" +export * from "./events/comment/tags.js" +export * from "./events/follow/lib.js" +export * from "./events/follow/parse.js" +export * from "./events/follow/tags.js" +export * from "./events/job/lib.js" +export * from "./events/job/tags.js" +export * from "./events/job/utils.js" +export * from "./events/lib.js" +export * from "./events/listing/lib.js" +export * from "./events/listing/parse.js" +export * from "./events/listing/tags.js" +export * from "./events/profile/lib.js" +export * from "./events/profile/parse.js" +export * from "./events/reaction/lib.js" +export * from "./events/reaction/parse.js" +export * from "./events/reaction/tags.js" +export * from "./events/subscription.js" +export * from "./keys/lib.js" +export * from "./relay/lib.js" +export * from "./schemas/lib.js" +export * from "./types/lib.js" +export * from "./types/ndk.js" +export * from "./utils/ndk.js" +export * from "./utils/relays.js" +export * from "./utils/tags.js" + diff --git a/utils-nostr/src/keys/lib.ts b/utils-nostr/src/keys/lib.ts @@ -0,0 +1,94 @@ +import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; +import { NDKPrivateKeySigner } from "@nostr-dev-kit/ndk"; +import { generateSecretKey, getPublicKey, nip19 } from "nostr-tools"; + +export const regex_nostr_key = /^[a-f0-9]{64}$/; + +export const lib_nostr_get_key_bytes = (hex: string): Uint8Array => { + return hexToBytes(hex); +}; + +export const lib_nostr_get_key_hex = (bytes: Uint8Array): string => { + return bytesToHex(bytes); +}; + +export const lib_nostr_key_generate = (): string => { + const bytes = generateSecretKey(); + return lib_nostr_get_key_hex(bytes); +}; + +export const lib_nostr_npub_encode = (public_key_hex?: string): string | undefined => { + try { + if (!public_key_hex) return undefined; + const npub = nip19.npubEncode(public_key_hex) + return npub; + } catch { + return undefined; + } +}; + +export const lib_nostr_npub_decode = (npub?: string): string | undefined => { + try { + if (!npub) return undefined; + const { type, data } = nip19.decode(npub); + if (type === `npub` && data) return data; + } catch { + return undefined; + } +}; + +export const lib_nostr_nsec_encode = (secret_key_hex?: string): string | undefined => { + try { + if (!secret_key_hex) return undefined; + const bytes = lib_nostr_get_key_bytes(secret_key_hex); + return nip19.nsecEncode(bytes); + } catch { + return undefined; + } +}; + +export const lib_nostr_nsec_decode = (nsec?: string): string | undefined => { + try { + if (!nsec) return undefined; + const decode = nip19.decode(nsec); + if (decode && decode.type === `nsec` && decode.data) return bytesToHex(decode.data); + return undefined; + } catch { + return undefined; + } +}; + +export const lib_nostr_nprofile_encode = (public_key_hex: string, relays: string[]): string | undefined => { + try { + if (!public_key_hex || !relays.length) return undefined; + const nprofile = nip19.nprofileEncode({ pubkey: public_key_hex, relays }) + return nprofile; + } catch { + return undefined; + } + +}; + +export const lib_nostr_nprofile_decode = (nprofile?: string): nip19.ProfilePointer | undefined => { + try { + if (!nprofile) return undefined; + const { type, data } = nip19.decode(nprofile); + if (type === `nprofile` && data) return data; + } catch { + return undefined; + } +}; + +export const lib_nostr_public_key = (secret_key_hex: string): string => { + const bytes = lib_nostr_get_key_bytes(secret_key_hex); + return getPublicKey(bytes); +}; + +export const lib_nostr_secret_key_validate = (secret_key: string): string | undefined => { + try { + const signer = new NDKPrivateKeySigner(secret_key); + return signer.privateKey; + } catch { + return undefined; + } +}; +\ No newline at end of file diff --git a/utils-nostr/src/relay/lib.ts b/utils-nostr/src/relay/lib.ts @@ -0,0 +1,32 @@ +import { NostrRelayInformationDocument, NostrRelayInformationDocumentFields } from "../types/lib.js"; + +export const lib_nostr_relay_parse_information_document = (data: any): NostrRelayInformationDocument | undefined => { + const obj = typeof data === `string` ? JSON.parse(data) : data; + return { + id: typeof obj.id === 'string' ? obj.id : undefined, + name: typeof obj.name === 'string' ? obj.name : undefined, + description: typeof obj.description === 'string' ? obj.description : undefined, + pubkey: typeof obj.pubkey === 'string' ? obj.pubkey : undefined, + contact: typeof obj.contact === 'string' ? obj.contact : undefined, + supported_nips: Array.isArray(obj.supported_nips) && obj.supported_nips.every((nip: any) => typeof nip === 'number') + ? obj.supported_nips + : undefined, + software: typeof obj.software === 'string' ? obj.software : undefined, + version: typeof obj.version === 'string' ? obj.version : undefined, + limitation_payment_required: obj.limitation && typeof obj.limitation === 'object' && typeof obj.limitation.payment_required === 'string' ? obj.limitation.payment_required : undefined, + limitation_restricted_writes: obj.limitation && typeof obj.limitation === 'object' && typeof obj.limitation.restricted_writes === 'boolean' ? obj.limitation.restricted_writes : undefined, + }; +}; + +export const lib_nostr_relay_build_information_document = (data: any): NostrRelayInformationDocumentFields | undefined => { + const doc = lib_nostr_relay_parse_information_document(data); + if (!doc) return; + const result: Partial<NostrRelayInformationDocumentFields> = {}; + Object.entries(doc).forEach(([key, value]) => { + if (typeof value === 'boolean') result[key as keyof NostrRelayInformationDocument] = value ? '1' : '0'; + else if (Array.isArray(value)) result[key as keyof NostrRelayInformationDocument] = value.join(', '); + else if (value === null || value === undefined) result[key as keyof NostrRelayInformationDocument] = ''; + else result[key as keyof NostrRelayInformationDocument] = String(value); + }); + return result; +}; +\ No newline at end of file diff --git a/utils-nostr/src/schemas/lib.ts b/utils-nostr/src/schemas/lib.ts @@ -0,0 +1,7 @@ +import { z } from 'zod'; + +export const nostr_tag_client_schema = z.object({ + name: z.string(), + pubkey: z.string(), + relay: z.string() +}); +\ No newline at end of file diff --git a/utils-nostr/src/types/lib.ts b/utils-nostr/src/types/lib.ts @@ -0,0 +1,94 @@ +import { type EventTemplate as NostrToolsEventTemplate } from "nostr-tools"; +import { z } from 'zod'; +import { nostr_tag_client_schema } from "../schemas/lib.js"; + +export type NostrTagClient = z.infer<typeof nostr_tag_client_schema>; +export type NostrEventTag = string[]; +export type NostrEventTags = NostrEventTag[]; + +export type NostrEventTagClient = { + name: string; + pubkey: string; + relay: string; +}; + +/* +export type NostrEventTagPriceDiscount = ( + { + quantity: { + ref_quantity: string; + threshold: string; + value: string; + currency: string; + } + } | + { + mass: { + unit: string; + threshold: string; + threshold_unit: string; + value: string; + currency: string; + } + } | + { + subtotal: { + threshold: string; + currency: string; + value: string; + measure: string; + } + } | + { + total: { + total_min: string; + value: string; + measure: string; + } + } +); +*/ + +export type NostrEventTagLocation = { + primary: string; + city?: string; + region?: string; + country?: string; + lat?: number; + lng?: number; +}; + +export type NostrEventTagImage = { + url: string; + size?: { + w: number; + h: number; + }; +}; + +export type NostrRelayInformationDocument = { + id?: string; + name?: string; + description?: string; + pubkey?: string; + contact?: string; + supported_nips?: number[]; + software?: string; + version?: string; + limitation_payment_required?: string; + limitation_restricted_writes?: boolean; +} + +export type NostrRelayInformationDocumentFields = { [K in keyof NostrRelayInformationDocument]: string; }; + +export type ILibNostrNeventEncode = { + id: string; + relays: string[]; + author: string; + kind: number; +}; + +export type ILibNostrEventSign = { + secret_key: string; + event: NostrToolsEventTemplate; +}; +\ No newline at end of file diff --git a/utils-nostr/src/types/ndk.ts b/utils-nostr/src/types/ndk.ts @@ -0,0 +1,10 @@ +import NDK, { NDKUser } from "@nostr-dev-kit/ndk"; +import { type NostrEventTagClient } from "./lib.js"; + +export type NDKEventFigure<T extends object> = { + ndk: NDK; + ndk_user: NDKUser; + date_published?: Date; + client?: NostrEventTagClient; +} & T; + diff --git a/utils-nostr/src/utils/ndk.ts b/utils-nostr/src/utils/ndk.ts @@ -0,0 +1,13 @@ +import NDK, { NDKCacheAdapter, NDKPrivateKeySigner } from "@nostr-dev-kit/ndk"; + +export const create_ndk = (explicitRelayUrls: string[], cacheAdapter?: NDKCacheAdapter): NDK => { + return new NDK({ + explicitRelayUrls, + enableOutboxModel: false, + cacheAdapter + }); +}; + +export const create_ndk_signer = (secret_key: string): NDKPrivateKeySigner => { + return new NDKPrivateKeySigner(secret_key); +}; +\ No newline at end of file diff --git a/utils-nostr/src/utils/relays.ts b/utils-nostr/src/utils/relays.ts @@ -0,0 +1,22 @@ +import type { RadrootsRelayDocument } from "@radroots/events-bindings"; + +const nostr_relay_form_field_record: Record<keyof RadrootsRelayDocument, true> = { + name: true, + description: true, + pubkey: true, + contact: true, + supported_nips: true, + software: true, + version: true +}; + +const is_nostr_relay_form_field = (value: string): value is keyof RadrootsRelayDocument => { + return value in nostr_relay_form_field_record; +}; + +export const nostr_relay_parse_form_keys = (value: string): keyof RadrootsRelayDocument | "" => { + if (is_nostr_relay_form_field(value)) { + return value; + } + return ""; +}; diff --git a/utils-nostr/src/utils/tags.ts b/utils-nostr/src/utils/tags.ts @@ -0,0 +1,11 @@ +import { NostrEventTag, NostrEventTagClient } from "../types/lib.js"; + +export const TAG_E = 'e'; +export const TAG_I = 'i'; + +export const tag_client = (opts: NostrEventTagClient, d_tag?: string): NostrEventTag => { + const tag = [`client`, opts.name]; + if (d_tag) tag.push(`31990:${opts.pubkey}:${d_tag}`); + tag.push(opts.relay); + return tag; +}; diff --git a/utils-nostr/tsconfig.cjs.json b/utils-nostr/tsconfig.cjs.json @@ -0,0 +1,15 @@ +{ + "extends": "@radroots/tsconfig/tsconfig.esm.json", + "compilerOptions": { + "module": "CommonJS", + "moduleResolution": "Node", + "rootDir": "./src", + "outDir": "dist/cjs", + "declaration": false, + "declarationMap": false, + "emitDeclarationOnly": false, + "tsBuildInfoFile": "node_modules/.cache/tsc.utils-nostr.cjs.tsbuildinfo" + }, + "include": ["src"], + "exclude": ["node_modules", "dist"] +} diff --git a/utils-nostr/tsconfig.esm.json b/utils-nostr/tsconfig.esm.json @@ -0,0 +1,13 @@ +{ + "extends": "@radroots/tsconfig/tsconfig.esm.json", + "compilerOptions": { + "moduleResolution": "nodenext", + "rootDir": "./src", + "outDir": "dist/esm", + "declaration": true, + "declarationMap": true, + "declarationDir": "dist/types" + }, + "include": ["src"], + "exclude": ["node_modules", "dist"] +} diff --git a/utils-nostr/tsconfig.json b/utils-nostr/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "./tsconfig.esm.json" +}