[
  {
    "path": ".gitattributes",
    "content": "bundle/**/* filter=lfs diff=lfs merge=binary\n**/*.onnx filter=lfs diff=lfs merge=binary\n**/*.ort filter=lfs diff=lfs merge=binary\n**/*.{jpeg,jpg} filter=lfs diff=lfs merge=binary\n**/*.png filter=lfs diff=lfs merge=binary\n**/*.webp filter=lfs diff=lfs merge=binary\n**/*.avif filter=lfs diff=lfs merge=binary\n**/*.heic filter=lfs diff=lfs merge=binary\n**/*.heif filter=lfs diff=lfs merge=binary\n**/*.pdf filter=lfs diff=lfs merge=binary\n**/*.psd filter=lfs diff=lfs merge=binary\n**/*.mp4 filter=lfs diff=lfs merge=binary\n**/*.mov filter=lfs diff=lfs merge=binary\n**/*.m4v filter=lfs diff=lfs merge=binary\n**/*.mp3 filter=lfs diff=lfs merge=binary\n**/*.wav filter=lfs diff=lfs merge=binary\n**/*.aif filter=lfs diff=lfs merge=binary\n**/*.aiff filter=lfs diff=lfs merge=binary\n"
  },
  {
    "path": ".github/workflows/pnpm-pr-check.yml",
    "content": "name: Build and test pnpm workspace\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\njobs:\n  build-and-test:\n    name: Build and test\n    uses: imgly/github-workflows/.github/workflows/pnpm-pr-check.yml@v1\n    secrets: inherit\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\nreleases\ndist\ntmp\n.DS_Store\n.vscode\n.parcel-cache\n.env"
  },
  {
    "path": ".husky/pre-commit",
    "content": "\n"
  },
  {
    "path": ".npmrc",
    "content": "; Allow transitive dependency type access\nshamefully-hoist = true\n; Hard error on unsatisfied peer dependency requirements\nstrict-peer-dependencies = true\n; Prevent accidents when running actions with outdated node_modules\nverify-deps-before-run = error\n; Fix sync-dependencies-meta-injected crashing due to some dependencies not respecting the injected flag as an optimization\ndedupe-injected-deps = false\n"
  },
  {
    "path": ".nvmrc",
    "content": "v20.17.0\n"
  },
  {
    "path": ".prettierignore",
    "content": "**/node_modules\n**/dist\n**/tmp\nbuild\n**/package-lock.json\n.vscode/\n**/public/**\nCHANGELOG.md"
  },
  {
    "path": ".prettierrc.js",
    "content": "module.exports = {\n  singleQuote: true,\n  arrowParens: 'always',\n  trailingComma: 'none'\n};\n"
  },
  {
    "path": "LICENSE.md",
    "content": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_\n\nEveryone is permitted to copy and distribute verbatim copies\nof this license document, but changing it is not allowed.\n\n## Preamble\n\nThe GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nDevelopers that use our General Public Licenses protect your rights\nwith two steps: **(1)** assert copyright on the software, and **(2)** offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\nA secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate. Many developers of free software are heartened and\nencouraged by the resulting cooperation. However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\nThe GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community. It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server. Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\nAn older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals. This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n## TERMS AND CONDITIONS\n\n### 0. Definitions\n\n“This License” refers to version 3 of the GNU Affero General Public License.\n\n“Copyright” also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n“The Program” refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as “you”. “Licensees” and\n“recipients” may be individuals or organizations.\n\nTo “modify” a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a “modified version” of the\nearlier work or a work “based on” the earlier work.\n\nA “covered work” means either the unmodified Program or a work based\non the Program.\n\nTo “propagate” a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo “convey” a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays “Appropriate Legal Notices”\nto the extent that it includes a convenient and prominently visible\nfeature that **(1)** displays an appropriate copyright notice, and **(2)**\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n### 1. Source Code\n\nThe “source code” for a work means the preferred form of the work\nfor making modifications to it. “Object code” means any non-source\nform of a work.\n\nA “Standard Interface” means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe “System Libraries” of an executable work include anything, other\nthan the work as a whole, that **(a)** is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and **(b)** serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n“Major Component”, in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe “Corresponding Source” for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\nThe Corresponding Source for a work in source code form is that\nsame work.\n\n### 2. Basic Permissions\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n### 3. Protecting Users' Legal Rights From Anti-Circumvention Law\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n### 4. Conveying Verbatim Copies\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n### 5. Conveying Modified Source Versions\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n- **a)** The work must carry prominent notices stating that you modified\n  it, and giving a relevant date.\n- **b)** The work must carry prominent notices stating that it is\n  released under this License and any conditions added under section 7.\n  This requirement modifies the requirement in section 4 to\n  “keep intact all notices”.\n- **c)** You must license the entire work, as a whole, under this\n  License to anyone who comes into possession of a copy. This\n  License will therefore apply, along with any applicable section 7\n  additional terms, to the whole of the work, and all its parts,\n  regardless of how they are packaged. This License gives no\n  permission to license the work in any other way, but it does not\n  invalidate such permission if you have separately received it.\n- **d)** If the work has interactive user interfaces, each must display\n  Appropriate Legal Notices; however, if the Program has interactive\n  interfaces that do not display Appropriate Legal Notices, your\n  work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n“aggregate” if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n### 6. Conveying Non-Source Forms\n\nYou may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n- **a)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by the\n  Corresponding Source fixed on a durable physical medium\n  customarily used for software interchange.\n- **b)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by a\n  written offer, valid for at least three years and valid for as\n  long as you offer spare parts or customer support for that product\n  model, to give anyone who possesses the object code either **(1)** a\n  copy of the Corresponding Source for all the software in the\n  product that is covered by this License, on a durable physical\n  medium customarily used for software interchange, for a price no\n  more than your reasonable cost of physically performing this\n  conveying of source, or **(2)** access to copy the\n  Corresponding Source from a network server at no charge.\n- **c)** Convey individual copies of the object code with a copy of the\n  written offer to provide the Corresponding Source. This\n  alternative is allowed only occasionally and noncommercially, and\n  only if you received the object code with such an offer, in accord\n  with subsection 6b.\n- **d)** Convey the object code by offering access from a designated\n  place (gratis or for a charge), and offer equivalent access to the\n  Corresponding Source in the same way through the same place at no\n  further charge. You need not require recipients to copy the\n  Corresponding Source along with the object code. If the place to\n  copy the object code is a network server, the Corresponding Source\n  may be on a different server (operated by you or a third party)\n  that supports equivalent copying facilities, provided you maintain\n  clear directions next to the object code saying where to find the\n  Corresponding Source. Regardless of what server hosts the\n  Corresponding Source, you remain obligated to ensure that it is\n  available for as long as needed to satisfy these requirements.\n- **e)** Convey the object code using peer-to-peer transmission, provided\n  you inform other peers where the object code and Corresponding\n  Source of the work are being offered to the general public at no\n  charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA “User Product” is either **(1)** a “consumer product”, which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or **(2)** anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, “normally used” refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n“Installation Information” for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n### 7. Additional Terms\n\n“Additional permissions” are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n- **a)** Disclaiming warranty or limiting liability differently from the\n  terms of sections 15 and 16 of this License; or\n- **b)** Requiring preservation of specified reasonable legal notices or\n  author attributions in that material or in the Appropriate Legal\n  Notices displayed by works containing it; or\n- **c)** Prohibiting misrepresentation of the origin of that material, or\n  requiring that modified versions of such material be marked in\n  reasonable ways as different from the original version; or\n- **d)** Limiting the use for publicity purposes of names of licensors or\n  authors of the material; or\n- **e)** Declining to grant rights under trademark law for use of some\n  trade names, trademarks, or service marks; or\n- **f)** Requiring indemnification of licensors and authors of that\n  material by anyone who conveys the material (or modified versions of\n  it) with contractual assumptions of liability to the recipient, for\n  any liability that these contractual assumptions directly impose on\n  those licensors and authors.\n\nAll other non-permissive additional terms are considered “further\nrestrictions” within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n### 8. Termination\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated **(a)**\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and **(b)** permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n### 9. Acceptance Not Required for Having Copies\n\nYou are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n### 10. Automatic Licensing of Downstream Recipients\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn “entity transaction” is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n### 11. Patents\n\nA “contributor” is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's “contributor version”.\n\nA contributor's “essential patent claims” are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, “control” includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a “patent license” is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To “grant” such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either **(1)** cause the Corresponding Source to be so\navailable, or **(2)** arrange to deprive yourself of the benefit of the\npatent license for this particular work, or **(3)** arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. “Knowingly relying” means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is “discriminatory” if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license **(a)** in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or **(b)** primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n### 12. No Surrender of Others' Freedom\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n### 13. Remote Network Interaction; Use with the GNU General Public License\n\nNotwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software. This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n### 14. Revised Versions of this License\n\nThe Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License “or any later version” applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n### 15. Disclaimer of Warranty\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n### 16. Limitation of Liability\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n### 17. Interpretation of Sections 15 and 16\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n_END OF TERMS AND CONDITIONS_\n\n## How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe “copyright” line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source. For example, if your program is a web application, its\ninterface could display a “Source” link that leads users to an archive\nof the code. There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\nYou should also get your employer (if you work as a programmer) or school,\nif any, to sign a “copyright disclaimer” for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n&lt;<http://www.gnu.org/licenses/>&gt;.\n"
  },
  {
    "path": "README.md",
    "content": "# Background Removal in the Browser & Node.js\n\n### 🚨 We are hiring 🚨\n\nWe are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**\n\n<p align=\"center\">\n<img src=\"https://storage.googleapis.com/imgly-static-assets/static/blog/github-releases/background-removal-free-plugin-app.jpg\" alt=\"background removal js showcase\" />\n\n</p>\n\nRemove backgrounds from images directly in the browser or Node.js environment with ease and no additional costs or privacy concerns.\nExplore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).\n\n## Overview\n\n`@imgly/background-removal` is a powerful npm package that allows developers to seamlessly remove the background from images directly in the browser.\n\n`@imgly/background-removal-node` is a powerful npm package that allows developers to remove the background from images in Node.js.\n\nWith its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy.\n\n## Who is it for?\n\n`@imgly/background-removal` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser or Node.js. It caters to a wide range of use cases, including but not limited to:\n\n- _E-commerce applications_ that need to remove backgrounds from product images in real time.\n\n- _Image editing applications_ that require background removal capabilities for enhancing user experience.\n\n- _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal.\n\nWhether you are a professional developer or a hobbyist, `@imgly/background-removal` empowers you to deliver impressive applications and services with ease.\n\n## License\n\nThe software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal%20License) for questions about other licensing options.\n\n## Authors & Contributors\n\nThis library is made by IMG.LY shipping the world's premier SDKs for building creative applications.\nStart your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).\n"
  },
  {
    "path": "TODOS.md",
    "content": "# Todos\n\n## Todo 2.0\n\n- [ ] use logger/telemetry callback instead of custom debug output\n- [ ] use resolver callback instead of publicPath as such we can allow various\n  ```\n      resolve: (path: string) => Response\n  ```\n- [ ] default to `gpu`\n- [ ] remove image encode and decode\n- [ ] removebg should get `ImageData` and return raw `ImageData`\n"
  },
  {
    "path": "bundle/models/isnet",
    "content": "version https://git-lfs.github.com/spec/v1\noid sha256:cc2c9f5c1751b9737cb81e708ff0c5e9542c2205daed22418a4fd2ab5d4c481a\nsize 176149806\n"
  },
  {
    "path": "bundle/models/isnet_fp16",
    "content": "version https://git-lfs.github.com/spec/v1\noid sha256:2eb4b5dda7ec41c617e59706e5aafa1f978c9a5f983d2518d9f0ae4d6eb04f20\nsize 88152708\n"
  },
  {
    "path": "bundle/models/isnet_quint8",
    "content": "version https://git-lfs.github.com/spec/v1\noid sha256:d1ca3535c21b53d08fa3b640e5949389f82e764f6376a0502d44982c35cae482\nsize 44348940\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"version\": \"1.7.0\",\n  \"name\": \"workspace\",\n  \"private\": true,\n  \"bin\": {\n    \"changelog-create\": \"./scripts/changelog/changelog-create.mjs\",\n    \"changelog-generate\": \"./scripts/changelog/changelog-generate.mjs\"\n  },\n  \"files\": [],\n  \"scripts\": {\n    \"start\": \"pnpm run watch\",\n    \"watch\": \"concurrently \\\"pnpm run watch --prefix packages/web\\\" \\\"pnpm run watch --prefix packages/node\\\"\",\n    \"build\": \"pnpm recursive run build\",\n    \"lint:fix\": \"npx prettier -c -w --ignore-unknown .\",\n    \"lint:check\": \"npx prettier -c --ignore-unknown .\",\n    \"publish:latest\": \"pnpm run publish:latest --workspaces --if-present && pnpm run deploy-assets\",\n    \"publish:next\": \"pnpm run publish:next --workspaces --if-present && pnpm run deploy-assets\",\n    \"package:version\": \"node ./scripts/package-version.mjs\",\n    \"deploy-assets\": \"node -r dotenv/config ./scripts/deploy-assets.mjs\",\n    \"tag\": \"git tag $npm_package_version & git push origin $npm_package_version\",\n    \"package:pack\": \"pnpm run package:pack --workspaces --if-present\",\n    \"prepare\": \"husky\"\n  },\n  \"devDependencies\": {\n    \"chalk\": \"~5.3.0\",\n    \"concurrently\": \"~8.2.2\",\n    \"dotenv\": \"~16.3.1\",\n    \"ejs\": \"~3.1.9\",\n    \"es-main\": \"~1.3.0\",\n    \"esbuild\": \"^0.21.1\",\n    \"glob\": \"~10.3.3\",\n    \"husky\": \"^9.0.11\",\n    \"lint-staged\": \"^15.2.2\",\n    \"meow\": \"~13.0.0\",\n    \"moment\": \"~2.29.4\",\n    \"onchange\": \"~7.1.0\",\n    \"prettier\": \"^3.5.3\",\n    \"rimraf\": \"^6.0.1\",\n    \"yaml\": \"~2.3.4\"\n  },\n  \"packageManager\": \"pnpm@10.6.5+sha512.cdf928fca20832cd59ec53826492b7dc25dc524d4370b6b4adbf65803d32efaa6c1c88147c0ae4e8d579a6c9eec715757b50d4fa35eea179d868eada4ed043af\"\n}"
  },
  {
    "path": "packages/node/.resources.mjs",
    "content": "export default [\n  {\n    path: '/models/',\n    source: '../../bundle/models/*',\n    mime: 'application/octet-steam'\n  }\n];\n"
  },
  {
    "path": "packages/node/CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [1.4.5]\n\n### Added\n\n- Added ThirdPartyLicenses.json\n\n## [1.4.0]\n\n### Added\n\n- Bumped onnx runtime to 1.17 Changed\n\n- Changed license from GPL to AGPL Changed\n\n- Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.\n\n### Changed\n\n- Typescript bindings are generated with tsc\n\n## [1.3.0]\n\n### Added\n\n- Resources are now chunked to 4MB for better caching performance and download restart.\n\n- Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.\n\n- Config option to export 'x-alpha8' format to get receive single channel alpha mask.\n\n### Removed\n\n- Configuration options to specify if background, foreground or mask is exported.\n\n### Changed\n\n- Changed the return value type of the progress callback from undefined to void\n\n- Output is now in the original image size. Mask is upscaled and applied to the original image.\n\n## [1.2.1]\n\n### Added\n\n- `CHANGELOG.md` for an better overview of the changes.\n\n- support for raw `rgba8` export formats.\n\n## [1.2.0]\n\n### Added\n\n- Support `foreground`, `background` and `mask` export type.\n- Added support for `webp` and `jpeg` export formats.\n"
  },
  {
    "path": "packages/node/LICENSE.md",
    "content": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_\n\nEveryone is permitted to copy and distribute verbatim copies\nof this license document, but changing it is not allowed.\n\n## Preamble\n\nThe GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nDevelopers that use our General Public Licenses protect your rights\nwith two steps: **(1)** assert copyright on the software, and **(2)** offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\nA secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate. Many developers of free software are heartened and\nencouraged by the resulting cooperation. However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\nThe GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community. It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server. Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\nAn older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals. This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n## TERMS AND CONDITIONS\n\n### 0. Definitions\n\n“This License” refers to version 3 of the GNU Affero General Public License.\n\n“Copyright” also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n“The Program” refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as “you”. “Licensees” and\n“recipients” may be individuals or organizations.\n\nTo “modify” a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a “modified version” of the\nearlier work or a work “based on” the earlier work.\n\nA “covered work” means either the unmodified Program or a work based\non the Program.\n\nTo “propagate” a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo “convey” a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays “Appropriate Legal Notices”\nto the extent that it includes a convenient and prominently visible\nfeature that **(1)** displays an appropriate copyright notice, and **(2)**\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n### 1. Source Code\n\nThe “source code” for a work means the preferred form of the work\nfor making modifications to it. “Object code” means any non-source\nform of a work.\n\nA “Standard Interface” means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe “System Libraries” of an executable work include anything, other\nthan the work as a whole, that **(a)** is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and **(b)** serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n“Major Component”, in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe “Corresponding Source” for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\nThe Corresponding Source for a work in source code form is that\nsame work.\n\n### 2. Basic Permissions\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n### 3. Protecting Users' Legal Rights From Anti-Circumvention Law\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n### 4. Conveying Verbatim Copies\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n### 5. Conveying Modified Source Versions\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n- **a)** The work must carry prominent notices stating that you modified\n  it, and giving a relevant date.\n- **b)** The work must carry prominent notices stating that it is\n  released under this License and any conditions added under section 7.\n  This requirement modifies the requirement in section 4 to\n  “keep intact all notices”.\n- **c)** You must license the entire work, as a whole, under this\n  License to anyone who comes into possession of a copy. This\n  License will therefore apply, along with any applicable section 7\n  additional terms, to the whole of the work, and all its parts,\n  regardless of how they are packaged. This License gives no\n  permission to license the work in any other way, but it does not\n  invalidate such permission if you have separately received it.\n- **d)** If the work has interactive user interfaces, each must display\n  Appropriate Legal Notices; however, if the Program has interactive\n  interfaces that do not display Appropriate Legal Notices, your\n  work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n“aggregate” if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n### 6. Conveying Non-Source Forms\n\nYou may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n- **a)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by the\n  Corresponding Source fixed on a durable physical medium\n  customarily used for software interchange.\n- **b)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by a\n  written offer, valid for at least three years and valid for as\n  long as you offer spare parts or customer support for that product\n  model, to give anyone who possesses the object code either **(1)** a\n  copy of the Corresponding Source for all the software in the\n  product that is covered by this License, on a durable physical\n  medium customarily used for software interchange, for a price no\n  more than your reasonable cost of physically performing this\n  conveying of source, or **(2)** access to copy the\n  Corresponding Source from a network server at no charge.\n- **c)** Convey individual copies of the object code with a copy of the\n  written offer to provide the Corresponding Source. This\n  alternative is allowed only occasionally and noncommercially, and\n  only if you received the object code with such an offer, in accord\n  with subsection 6b.\n- **d)** Convey the object code by offering access from a designated\n  place (gratis or for a charge), and offer equivalent access to the\n  Corresponding Source in the same way through the same place at no\n  further charge. You need not require recipients to copy the\n  Corresponding Source along with the object code. If the place to\n  copy the object code is a network server, the Corresponding Source\n  may be on a different server (operated by you or a third party)\n  that supports equivalent copying facilities, provided you maintain\n  clear directions next to the object code saying where to find the\n  Corresponding Source. Regardless of what server hosts the\n  Corresponding Source, you remain obligated to ensure that it is\n  available for as long as needed to satisfy these requirements.\n- **e)** Convey the object code using peer-to-peer transmission, provided\n  you inform other peers where the object code and Corresponding\n  Source of the work are being offered to the general public at no\n  charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA “User Product” is either **(1)** a “consumer product”, which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or **(2)** anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, “normally used” refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n“Installation Information” for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n### 7. Additional Terms\n\n“Additional permissions” are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n- **a)** Disclaiming warranty or limiting liability differently from the\n  terms of sections 15 and 16 of this License; or\n- **b)** Requiring preservation of specified reasonable legal notices or\n  author attributions in that material or in the Appropriate Legal\n  Notices displayed by works containing it; or\n- **c)** Prohibiting misrepresentation of the origin of that material, or\n  requiring that modified versions of such material be marked in\n  reasonable ways as different from the original version; or\n- **d)** Limiting the use for publicity purposes of names of licensors or\n  authors of the material; or\n- **e)** Declining to grant rights under trademark law for use of some\n  trade names, trademarks, or service marks; or\n- **f)** Requiring indemnification of licensors and authors of that\n  material by anyone who conveys the material (or modified versions of\n  it) with contractual assumptions of liability to the recipient, for\n  any liability that these contractual assumptions directly impose on\n  those licensors and authors.\n\nAll other non-permissive additional terms are considered “further\nrestrictions” within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n### 8. Termination\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated **(a)**\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and **(b)** permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n### 9. Acceptance Not Required for Having Copies\n\nYou are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n### 10. Automatic Licensing of Downstream Recipients\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn “entity transaction” is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n### 11. Patents\n\nA “contributor” is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's “contributor version”.\n\nA contributor's “essential patent claims” are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, “control” includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a “patent license” is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To “grant” such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either **(1)** cause the Corresponding Source to be so\navailable, or **(2)** arrange to deprive yourself of the benefit of the\npatent license for this particular work, or **(3)** arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. “Knowingly relying” means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is “discriminatory” if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license **(a)** in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or **(b)** primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n### 12. No Surrender of Others' Freedom\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n### 13. Remote Network Interaction; Use with the GNU General Public License\n\nNotwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software. This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n### 14. Revised Versions of this License\n\nThe Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License “or any later version” applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n### 15. Disclaimer of Warranty\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n### 16. Limitation of Liability\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n### 17. Interpretation of Sections 15 and 16\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n_END OF TERMS AND CONDITIONS_\n\n## How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe “copyright” line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source. For example, if your program is a web application, its\ninterface could display a “Source” link that leads users to an archive\nof the code. There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\nYou should also get your employer (if you work as a programmer) or school,\nif any, to sign a “copyright disclaimer” for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n&lt;<http://www.gnu.org/licenses/>&gt;.\n"
  },
  {
    "path": "packages/node/README.md",
    "content": "# Background Removal in NodeJs\n\n### 🚨 We are hiring 🚨\n\nWe are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**\n\n<p align=\"center\">\n<img src=\"https://img.ly/showcases/cesdk/web/s/case-thumbnail/background-removal/background-removal-0.png?utm_source=github&utm_medium=project&utm_campaign=background-removal-js\" alt=\"background removal js showcase\" />\n\n</p>\n\nRemove backgrounds from images in NodeJs environment with ease and no additional costs or privacy concerns.\nExplore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).\n\n## News\n\n- **`July 18th, 2025`:** Updated to use stable ONNX runtime version 1.21.0 instead of dev version.\n- **`November 8th, 2023`:** Added support for raw `rgba8` export formats.\n- **`November 6th, 2023`:** Added support `foreground`, `background` and `mask` export type\n- **`November 6th, 2023`:** Added support for `webp` and `jpeg` export formats.\n- **`September 12th, 2023`:** We released the code of Background Removal NodeJS.\n\nFor more detail information please refer to the [CHANGELOG](./CHANGELOG.md).\n\n## Overview\n\n`@imgly/background-removal-node` is a powerful npm package that allows developers to seamlessly remove the background from images in NodeJs. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy.\n\nThe key features of `@imgly/background-removal-node` are:\n\n- **Seamless Integration with IMG.LY's CE.SDK**: `@imgly/background-removal-node` provides seamless integration with [IMG.LY's CE.SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), allowing developers to easily incorporate powerful NodeJS image matting and background removal capabilities into their projects.\n\nThe Neural Network model files ([ONNX model](https://onnx.ai/)) are hosted by [IMG.LY](https://img.ly/), making it readily available for download to all users of the library. See the section Custom Asset Serving if you want to host data on your own servers.\n\n## Installation\n\nYou can install `@imgly/background-removal-node` via npm or yarn. Use the following commands to install the package:\n\n### NPM\n\n```shell\nnpm install @imgly/background-removal-node\n```\n\n## Usage\n\n```typescript\nimport {removeBackground} from \"@imgly/background-removal-node\";\n// const {removeBackground} = require(\"@imgly/background-removal-node\");\n\nlet image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...;\n\nremoveBackground(image_src).then((blob: Blob) => {\n  // The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src\n})\n```\n\nNote: On the first run the wasm and onnx model files are fetched. This might, depending on the bandwidth, take time. Therefore, the first run takes proportionally longer than each consecutive run. Also, all files are cached by the browser and an additional model cache.\n\n## Advanced Configuration\n\nThe library does not need any configuration to get started. However, there are optional parameters that influence the behaviour and give more control over the library.\n\n```typescript\ntype Config = {\n  publicPath: string; // The public path used for model and wasm files. Default: '`file://${path.resolve(`node_modules/${pkg.name}/dist/`)}/`.\n  debug: bool; // enable or disable useful console.log outputs\n  model: 'small' | 'medium'; // The model to use. (Default \"medium\")\n  output: {\n    format: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/x-rgba8'; // The output format. (Default \"image/png\")\n    quality: number; // The quality. (Default: 0.8)\n    type: 'foreground' | 'background' | 'mask'; // The output type. (Default \"foreground\")\n  };\n};\n```\n\n### Download Size vs Quality\n\nThe onnx model is shipped in various sizes and needs.\n\n- small (~40 MB) is the smallest model and is in most cases working fine but sometimes shows some artifacts. It's a quantized model.\n- medium (~80MB) is the default model.\n\n### Download Progress Monitoring\n\nOn the first run, the necessary data will be fetched and stored in the browser cache. Since the download might take some time, you have the option to tap into the download progress.\n\n```typescript\nlet config: Config = {\n  progress: (key, current, total) => {\n    console.log(`Downloading ${key}: ${current} of ${total}`);\n  }\n};\n```\n\n### Custom Asset Serving\n\nThe wasm and onnx neural networks are hosted by IMG.LY by default. For production use, we advise you to host them yourself. Therefore, copy all .wasm and .onnx files to your public path `$PUBLIC_PATH` and reconfigure the library.\n\n```shell\ncp node_modules/@imgly/background-removal-node/dist/*.* $PUBLIC_PATH\n```\n\n```typescript\nimport { removeBackground, Config} from \"@imgly/background-removal-node\"\n\nconst public_path = \"file://${ASSET_PATH}\" ; // the path on the local file system\n\n//const public_path = \"https://example.com/assets/\" ; // the path assets are served from\n\nlet config: Config =  {\n  publicPath: public_path, // path to the wasm files\n};\n\nlet image_src: Buffer | ArrayBuffer | Uint8Array | Blob | URL | string = ...;\n\nremoveBackground(image_src, config).then((blob: Blob) => {\n  // result is a blob encoded as PNG.\n  // It can be converted to an URL to be used as HTMLImage.src\n  const url = URL.createObjectURL(blob);\n})\n```\n\n### Debug Outputs\n\nEnable debug outputs and logging to the console\n\n```typescript\nlet config: Config = {\n  debug: true\n};\n```\n\n### Cross-Origin Resource Sharing (CORS)\n\nIf you are running into CORS issues you might want to pass additional parameters to the fetch function via\n\n```typescript\nlet config: Config = {\n  fetchArgs: {\n    mode: 'no-cors'\n  }\n};\n```\n\n`fetchArgs` are passed as second parameters to the fetch function as described in [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).\n\n## Who is it for?\n\n`@imgly/background-removal-node` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser. It caters to a wide range of use cases, including but not limited to:\n\n- _E-commerce applications_ that need to remove backgrounds from product images in real time.\n\n- _Image editing applications_ that require background removal capabilities for enhancing user experience.\n\n- _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal.\n\nWhether you are a professional developer or a hobbyist, `@imgly/background-removal-node` empowers you to deliver impressive applications and services with ease.\n\n## License\n\nThe software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal-Node%20License) for questions about other licensing options.\n\n## Authors & Contributors\n\nThis library is made by IMG.LY shipping the world's premier SDKs for building creative applications.\nStart your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node).\n"
  },
  {
    "path": "packages/node/ThirdPartyLicenses.json",
    "content": "{\n  \"onnxruntime-web\": {\n    \"source\": \"https://www.npmjs.com/package/onnxruntime-node\",\n    \"type\": \"code\",\n    \"license\": \"MIT\"\n  },\n  \"ISNET\": {\n    \"source\": \"https://github.com/xuebinqin/DIS\",\n    \"type\": \"model\",\n    \"license\": \"MIT\"\n  }\n}\n"
  },
  {
    "path": "packages/node/changelog/1.2.0/20230811184244-export_type_and_formats.yml",
    "content": "---\ntype: Added\ndescription: Support `foreground`, `background` and `mask` export type.\n---\ntype: Added\ndescription: Added support for `webp` and `jpeg` export formats.\n"
  },
  {
    "path": "packages/node/changelog/1.2.1/20230811184244-Changelog_item.yml",
    "content": "---\ntype: Added\ndescription: |\n  `CHANGELOG.md` for an better overview of the changes.\n---\ntype: Added\ndescription: |\n  support for raw `rgba8` export formats.\n"
  },
  {
    "path": "packages/node/changelog/1.3.0/20230612112304-progress_return_type.yaml",
    "content": "---\ntype: Changed\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Changed the return value type of the progress callback from undefined to void\n"
  },
  {
    "path": "packages/node/changelog/1.3.0/20231512181521-resource_data_chunking.yaml",
    "content": "---\ntype: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Resources are now chunked to 4MB for better caching performance and download restart.\n"
  },
  {
    "path": "packages/node/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml",
    "content": "---\ntype: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Output is now in the original image size. Mask is upscaled and applied to the original image.\n---\ntype: Added\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.\n\n---\ntype: Removed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Configuration options to specify if background, foreground or mask is exported.\n---\ntype: Added\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Config option to export 'x-alpha8' format to get receive single channel alpha mask.\n"
  },
  {
    "path": "packages/node/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Bumped onnx runtime to 1.17 Changed\n"
  },
  {
    "path": "packages/node/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Changed license from GPL to AGPL Changed\n"
  },
  {
    "path": "packages/node/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.\n"
  },
  {
    "path": "packages/node/changelog/1.4.0/20242301155647-Typescript_bindings_are_generated_with_tsc.yaml",
    "content": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Typescript bindings are generated with tsc\n"
  },
  {
    "path": "packages/node/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added ThirdPartyLicenses.json\n"
  },
  {
    "path": "packages/node/changelog/Unreleased/.keep",
    "content": ""
  },
  {
    "path": "packages/node/changelog/info.yml",
    "content": "---\ndescription: |\n  All notable changes to this project will be documented in this file.\n\n  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n"
  },
  {
    "path": "packages/node/package.json",
    "content": "{\n  \"name\": \"@imgly/background-removal-node\",\n  \"version\": \"1.7.0\",\n  \"description\": \"Background Removal in NodeJS\",\n  \"resources\": \"@imgly/background-removal-node\",\n  \"keywords\": [\n    \"background-removal\",\n    \"nodejs\",\n    \"image-segmentation\",\n    \"image-matting\",\n    \"onnx\"\n  ],\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/imgly/background-removal-js.git\"\n  },\n  \"license\": \"SEE LICENSE IN LICENSE.md\",\n  \"author\": {\n    \"name\": \"IMG.LY GmbH\",\n    \"email\": \"support@img.ly\",\n    \"url\": \"https://img.ly\"\n  },\n  \"bugs\": {\n    \"email\": \"support@img.ly\"\n  },\n  \"homepage\": \"https://img.ly/showcases/cesdk/web/background-removal\",\n  \"source\": \"./src/index.ts\",\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.mjs\",\n  \"types\": \"./dist/index.d.ts\",\n  \"exports\": {\n    \".\": {\n      \"require\": \"./dist/index.cjs\",\n      \"import\": \"./dist/index.mjs\",\n      \"types\": \"./dist/index.d.ts\"\n    }\n  },\n  \"files\": [\n    \"LICENSE.md\",\n    \"README.md\",\n    \"CHANGELOG.md\",\n    \"ThirdPartyLicenses.json\",\n    \"dist/\",\n    \"bin/\"\n  ],\n  \"scripts\": {\n    \"start\": \"pnpm run watch\",\n    \"clean\": \"npx rimraf dist\",\n    \"test\": \"true\",\n    \"resources\": \"node ../../scripts/package-resources.mjs\",\n    \"changelog:create\": \"node ../../scripts/changelog/changelog-create.mjs\",\n    \"changelog:generate\": \"node ../../scripts/changelog/changelog-generate.mjs\",\n    \"build\": \"pnpm run clean && pnpm run resources && pnpm run types && pnpm run changelog:generate && node scripts/build.mjs\",\n    \"types\": \"tsc --declaration --emitDeclarationOnly --declarationDir dist --declarationMap\",\n    \"watch\": \"pnpm run clean && pnpm run resources && pnpm run changelog:generate && node scripts/watch.mjs\",\n    \"check:all\": \"pnpm run check:pretty\",\n    \"check:pretty\": \"prettier --list-different './src/**/*.{ts,tsx}'\",\n    \"pretty\": \"prettier --write './src/**/*.{ts,tsx}'\",\n    \"publish:latest\": \"pnpm publish --tag latest --access public\",\n    \"publish:next\": \"pnpm publish --tag next --access public\",\n    \"package:pack\": \"pnpm pack . --pack-destination ../../releases\"\n  },\n  \"dependencies\": {\n    \"@types/lodash\": \"~4.14.195\",\n    \"@types/ndarray\": \"~1.0.14\",\n    \"@types/node\": \"~20.3.1\",\n    \"lodash\": \"~4.17.21\",\n    \"ndarray\": \"~1.0.19\",\n    \"onnxruntime-node\": \"1.21.0\",\n    \"sharp\": \"~0.32.4\",\n    \"zod\": \"^3.23.8\"\n  },\n  \"devDependencies\": {\n    \"assert\": \"~2.0.0\",\n    \"esbuild\": \"~0.18.18\",\n    \"npm-dts\": \"~1.3.12\",\n    \"os-browserify\": \"~0.3.0\",\n    \"path-browserify\": \"~1.0.1\",\n    \"process\": \"~0.11.10\",\n    \"stream-browserify\": \"~3.0.0\",\n    \"ts-loader\": \"~9.4.3\",\n    \"tslib\": \"~2.5.3\",\n    \"typescript\": \"~5.1.6\",\n    \"util\": \"~0.12.5\",\n    \"webpack\": \"~5.85.1\",\n    \"webpack-cli\": \"~5.1.4\"\n  }\n}"
  },
  {
    "path": "packages/node/scripts/build.mjs",
    "content": "export { configs };\nimport * as esbuild from 'esbuild';\nimport { readFileSync } from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n  readFileSync(path.resolve(__dirname, '../package.json'))\n);\n\nconst dependencies = Object.keys(pkg.dependencies);\n\nconst configs = [\n  {\n    entryPoints: ['src/index.ts'],\n    bundle: true,\n    sourcemap: true,\n    platform: 'node',\n    format: 'cjs',\n    external: dependencies,\n    outfile: 'dist/index.cjs'\n  },\n\n  {\n    entryPoints: ['src/index.ts'],\n    bundle: true,\n    sourcemap: true,\n    external: dependencies,\n    platform: 'node',\n    format: 'esm',\n    outfile: 'dist/index.mjs'\n  }\n];\n\nawait configs.map(async (config) => await esbuild.build(config));\n"
  },
  {
    "path": "packages/node/scripts/watch.mjs",
    "content": "import * as esbuild from 'esbuild';\nimport { configs } from './build.mjs';\nimport dts from 'npm-dts';\n\nnew dts.Generator({\n  entry: 'src/index.ts',\n  output: 'dist/index.d.ts'\n}).generate();\n\nconst contexts = await Promise.all(\n  configs.map((config) => esbuild.context(config))\n);\n\nawait Promise.any(contexts.map((ctx) => ctx.watch()));\nconsole.log('watching...');\n"
  },
  {
    "path": "packages/node/src/codecs.ts",
    "content": "export { imageEncode, imageDecode, MimeType };\n\nimport sharp, { FormatEnum } from 'sharp';\nimport ndarray, { NdArray } from 'ndarray';\n\nasync function imageDecode(blob: Blob): Promise<NdArray<Uint8Array>> {\n  const buffer = await blob.arrayBuffer();\n\n  const mime = MimeType.fromString(blob.type);\n  switch (mime.type) {\n    case 'image/x-alpha8': {\n      const width = parseInt(mime.params['width']);\n      const height = parseInt(mime.params['height']);\n      return ndarray(new Uint8Array(await blob.arrayBuffer()), [\n        height,\n        width,\n        1\n      ]);\n    }\n    case 'image/x-rgba8': {\n      const width = parseInt(mime.params['width']);\n      const height = parseInt(mime.params['height']);\n      return ndarray(new Uint8Array(await blob.arrayBuffer()), [\n        height,\n        width,\n        4\n      ]);\n    }\n    case 'application/octet-stream':\n    case `image/png`:\n    case `image/jpeg`:\n    case `image/jpg`:\n    case `image/webp`: {\n      const decoded = sharp(buffer);\n      let { width, height, channels } = await decoded.metadata();\n\n      if (channels === 3) {\n        decoded.ensureAlpha();\n        channels = 4;\n      }\n\n      const outBuffer = await decoded.raw().toBuffer();\n      const array = ndarray(outBuffer, [height!, width!, channels!]);\n      await sharp(array.data, {\n        raw: { width: width!, height: height!, channels: channels! }\n      });\n      return array;\n    }\n    default:\n      throw new Error(`Unsupported format: ${mime.type}`);\n  }\n}\n\nasync function imageEncode(\n  imageTensor: NdArray<Uint8Array>,\n  quality: number = 0.8,\n  type: string = 'image/png'\n): Promise<Blob> {\n  const [height, width, channels] = imageTensor.shape;\n  if (channels !== 4) throw new Error('Only 4-channel images are supported');\n  const image = sharp(imageTensor.data, { raw: { height, width, channels } });\n  type Keys = keyof FormatEnum;\n\n  switch (type) {\n    case 'image/x-alpha8':\n    case 'image/x-rgba8': {\n      const mime = MimeType.create(type, {\n        width: width.toString(),\n        height: height.toString()\n      });\n      return new Blob([imageTensor.data], { type: mime.toString() });\n    }\n    case `image/png`:\n    case `image/jpeg`:\n    case `image/webp`:\n      const format = type.split('/').pop()! as Keys;\n      const buffer = await image\n        .toFormat(format, { quality: quality * 100 })\n        .toBuffer();\n      return new Blob([buffer], { type: type });\n    default:\n      throw new Error(`Invalid format: ${format}`);\n  }\n}\n\nclass MimeType {\n  type: string = 'application/octet-stream';\n  params: Record<string, string> = {};\n\n  private constructor(type: string, params: Record<string, string>) {\n    this.type = type;\n    this.params = params;\n  }\n\n  toString(): string {\n    const paramsStr = [];\n    for (const key in this.params) {\n      const value = this.params[key];\n      paramsStr.push(`${key}=${value}`);\n    }\n    return [this.type, ...paramsStr].join(';');\n  }\n\n  static create(type, params: Record<string, string>): MimeType {\n    return new MimeType(type, params);\n  }\n\n  isIdentical(other: MimeType): Boolean {\n    return this.type === other.type && this.params === other.params;\n  }\n\n  isEqual(other: MimeType): Boolean {\n    return this.type === other.type;\n  }\n\n  static fromString(mimeType: string): MimeType {\n    const [type, ...paramsArr] = mimeType.split(';');\n    const params: Record<string, string> = {};\n\n    for (const param of paramsArr) {\n      const [key, value] = param.split('=');\n      params[key.trim()] = value.trim();\n    }\n    return new MimeType(type, params);\n  }\n}\n"
  },
  {
    "path": "packages/node/src/index.ts",
    "content": "export default removeBackground;\nexport {\n  removeBackground,\n  removeForeground,\n  segmentForeground,\n  applySegmentationMask\n};\nexport type { Config, ImageSource };\n\nimport lodash from 'lodash';\nimport ndarray from 'ndarray';\nimport { initInference, runInference } from './inference';\nimport { Config, validateConfig } from './schema';\nimport * as utils from './utils';\nimport { ImageSource } from './utils';\n\nconst { memoize } = lodash;\nconst init = memoize(initInference, (config) => JSON.stringify(config));\n\n/**\n * Removes the background from an image.\n *\n * @param image - The image to remove the background from.\n * @param configuration - Optional configuration for the background removal process.\n * @returns A Promise that resolves to the resulting image with the background removed.\n */\nasync function removeBackground(\n  image: ImageSource,\n  configuration?: Config\n): Promise<Blob> {\n  const { config, session } = await init(configuration);\n\n  const imageTensor = await utils.imageSourceToImageData(image, config);\n  const [width, height, channels] = imageTensor.shape;\n\n  const alphamask = await runInference(imageTensor, config, session);\n  const stride = width * height;\n\n  const outImageTensor = imageTensor;\n  for (let i = 0; i < stride; i += 1) {\n    outImageTensor.data[4 * i + 3] = alphamask.data[i];\n  }\n\n  const outImage = await utils.imageEncode(\n    outImageTensor,\n    config.output.quality,\n    config.output.format\n  );\n\n  return outImage;\n}\n\n/**\n * Removes the foreground from an image.\n *\n * @param image - The image to remove the foreground from.\n * @param configuration - Optional configuration for the foreground removal process.\n * @returns A Promise that resolves to the resulting image with the foreground removed.\n */\nasync function removeForeground(\n  image: ImageSource,\n  configuration?: Config\n): Promise<Blob> {\n  const { config, session } = await init(configuration);\n\n  const imageTensor = await utils.imageSourceToImageData(image, config);\n  const [width, height, channels] = imageTensor.shape;\n\n  const alphamask = await runInference(imageTensor, config, session);\n  const stride = width * height;\n  const outImageTensor = imageTensor;\n  for (let i = 0; i < stride; i += 1) {\n    outImageTensor.data[4 * i + 3] = 255 - alphamask.data[i];\n  }\n\n  const outImage = await utils.imageEncode(\n    outImageTensor,\n    config.output.quality,\n    config.output.format\n  );\n\n  return outImage;\n}\n\n/**\n * Segments the foreground of an image using a given configuration.\n *\n * @param image - The image source to segment.\n * @param configuration - The optional configuration for the segmentation.\n * @returns A Promise that resolves to the segmented foreground as a Blob.\n */\nasync function segmentForeground(\n  image: ImageSource,\n  configuration?: Config\n): Promise<Blob> {\n  const { config, session } = await init(configuration);\n\n  const imageTensor = await utils.imageSourceToImageData(image, config);\n  const [height, width, channels] = imageTensor.shape;\n\n  const alphamask = await runInference(imageTensor, config, session);\n  const stride = width * height;\n\n  if (config.output.format === 'image/x-alpha8') {\n    const outImage = await utils.imageEncode(\n      alphamask,\n      config.output.quality,\n      config.output.format\n    );\n    return outImage;\n  } else {\n    const outImageTensor = ndarray(new Uint8Array(channels * stride), [\n      height,\n      width,\n      channels\n    ]);\n    for (let i = 0; i < stride; i += 1) {\n      const index = 4 * i + 3;\n      outImageTensor.data[index] = alphamask.data[i]; //Red\n      outImageTensor.data[index + 1] = alphamask.data[i]; //Green\n      outImageTensor.data[index + 2] = alphamask.data[i]; // Blue\n      outImageTensor.data[index + 3] = 255;\n    }\n\n    const outImage = await utils.imageEncode(\n      outImageTensor,\n      config.output.quality,\n      config.output.format\n    );\n\n    return outImage;\n  }\n}\n\nasync function applySegmentationMask(\n  image,\n  mask,\n  config?: Config\n): Promise<Blob> {\n  config = validateConfig(config);\n  const imageTensor = await utils.imageSourceToImageData(image, config);\n  const [imageHeight, imageWidth, imageChannels] = imageTensor.shape;\n  const maskTensor = await utils.imageSourceToImageData(mask, config);\n  const [maskHeight, maskWidth, maskChannels] = maskTensor.shape;\n\n  const alphaMask =\n    maskHeight !== imageHeight || maskWidth !== imageWidth\n      ? utils.tensorResizeBilinear(maskTensor, imageWidth, imageHeight)\n      : maskTensor;\n  const stride = imageWidth * imageHeight;\n  for (let i = 0; i < stride; i += 1) {\n    const idxImage = imageChannels * i;\n    const idxMask = maskChannels * i;\n    imageTensor.data[idxImage + 3] = alphaMask.data[idxMask]; // alpha information it always in the first (sometimes also in the others)\n  }\n\n  const outImage = await utils.imageEncode(\n    imageTensor,\n    config.output.quality,\n    config.output.format\n  );\n\n  return outImage;\n}\n"
  },
  {
    "path": "packages/node/src/inference.ts",
    "content": "export { initInference, runInference };\n\nimport { tensorResizeBilinear, tensorHWCtoBCHW } from './utils';\nimport { createOnnxSession, runOnnxSession } from './onnx';\nimport { Config, validateConfig } from './schema';\n\nimport { loadAsBlob } from './resource';\nimport ndarray, { NdArray } from 'ndarray';\nimport { convertFloat32ToUint8 } from './utils';\n\nasync function initInference(config?: Config) {\n  config = validateConfig(config);\n\n  if (config.debug) console.debug('Loading model...');\n  const model = config.model;\n  const blob = await loadAsBlob(`/models/${model}`, config);\n  const arrayBuffer = await blob.arrayBuffer();\n  const session = await createOnnxSession(arrayBuffer, config);\n  return { config, session };\n}\n\nasync function runInference(\n  imageTensor: NdArray<Uint8Array>,\n  config: Config,\n  session: any\n): Promise<NdArray<Uint8Array>> {\n  if (config.progress) config.progress('compute:inference', 0, 1);\n  const resolution = 1024;\n  const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;\n\n  let tensorImage = tensorResizeBilinear(imageTensor, resolution, resolution);\n  const inputTensor = tensorHWCtoBCHW(tensorImage); // this converts also from float to rgba\n\n  // run\n  const predictionsDict = await runOnnxSession(\n    session,\n    [['input', inputTensor]],\n    ['output']\n  );\n\n  let alphamask = ndarray(predictionsDict[0].data, [resolution, resolution, 1]);\n  let alphamaskU8 = convertFloat32ToUint8(alphamask);\n  alphamaskU8 = tensorResizeBilinear(alphamaskU8, srcWidth, srcHeight);\n\n  if (config.progress) config.progress('compute:inference', 1, 1);\n  return alphamaskU8;\n}\n"
  },
  {
    "path": "packages/node/src/onnx.ts",
    "content": "export { createOnnxSession, runOnnxSession };\n\nimport ndarray, { NdArray } from 'ndarray';\nimport * as ort from 'onnxruntime-node';\n// import * as ort from 'onnxruntime-node-gpu';\nimport { Config } from './schema';\n\nasync function createOnnxSession(model: any, config: Config) {\n  if (config.debug) {\n    ort.env.debug = true;\n    ort.env.logLevel = 'verbose';\n    console.debug('ort.env.wasm:', ort.env.wasm);\n  }\n\n  const ort_config: ort.InferenceSession.SessionOptions = {\n    graphOptimizationLevel: 'all',\n    executionMode: 'parallel'\n  };\n\n  const session = await ort.InferenceSession.create(model, ort_config).catch(\n    (e: any) => {\n      throw new Error(\n        `Failed to create session: ${e}. Please check if the publicPath is set correctly.`\n      );\n    }\n  );\n  return session;\n}\n\nasync function runOnnxSession(\n  session: any,\n  inputs: [string, NdArray<Float32Array>][],\n  outputs: [string]\n) {\n  const feeds: Record<string, any> = {};\n  for (const [key, tensor] of inputs) {\n    feeds[key] = new ort.Tensor(\n      'float32',\n      new Float32Array(tensor.data),\n      tensor.shape\n    );\n  }\n  const outputData = await session.run(feeds, {});\n  const outputKVPairs: NdArray<Float32Array>[] = [];\n\n  for (const key of outputs) {\n    const output: ort.Tensor = outputData[key];\n    const shape: number[] = output.dims as number[];\n    const data: Float32Array = output.data as Float32Array;\n    const tensor = ndarray(data, shape);\n    outputKVPairs.push(tensor);\n  }\n\n  return outputKVPairs;\n}\n"
  },
  {
    "path": "packages/node/src/resource.ts",
    "content": "export { loadAsBlob, loadAsUrl, loadFromURI };\n\nimport { Config } from './schema';\nimport { ensureAbsoluteURI } from './url';\nimport { readFile } from 'fs/promises';\nimport { fileURLToPath } from 'url';\n\nasync function loadAsUrl(url: string, config: Config) {\n  return URL.createObjectURL(await loadAsBlob(url, config));\n}\n\nasync function loadFromURI(\n  uri: URL,\n  config = { headers: { 'Content-Type': 'application/octet-stream' } }\n) {\n  switch (uri.protocol) {\n    case 'http:':\n      return await fetch(uri);\n    case 'https:':\n      return await fetch(uri);\n    case 'file:': {\n      const buffer = await readFile(fileURLToPath(uri));\n      return new Response(buffer, { status: 200, headers: config.headers });\n    }\n    default:\n      throw new Error(`Unsupported protocol: ${uri.protocol}`);\n  }\n}\n\nasync function loadAsBlob(key: string, config: Config) {\n  // load resource metadata\n\n  const resourceUri = ensureAbsoluteURI('./resources.json', config.publicPath);\n\n  const resourceResponse = await loadFromURI(resourceUri);\n\n  if (!resourceResponse.ok) {\n    throw new Error(\n      `Resource metadata not found. Ensure that the config.publicPath is configured correctly.`\n    );\n  }\n  const resourceMap = await resourceResponse.json();\n  const entry = resourceMap[key];\n\n  if (!entry) {\n    throw new Error(\n      `Resource ${key} not found. Ensure that the config.publicPath is configured correctly.`\n    );\n  }\n\n  const chunks = entry.chunks; // list of entries\n\n  let downloadedSize = 0;\n  const responses = chunks.map(async (chunk) => {\n    const url = ensureAbsoluteURI(chunk.hash, config.publicPath);\n    const chunkSize = chunk.offsets[1] - chunk.offsets[0];\n    const response = await loadFromURI(url, {\n      headers: { 'Content-Type': entry.mime }\n    });\n    const blob = await response.blob();\n\n    if (chunkSize !== blob.size) {\n      throw new Error(\n        `Failed to fetch ${key} with size ${chunkSize} but got ${blob.size}`\n      );\n    }\n\n    if (config.progress) {\n      downloadedSize += chunkSize;\n      config.progress(`fetch:${key}`, downloadedSize, entry.size);\n    }\n    return blob;\n  });\n\n  // we could create a new buffer here and use the chunk entries and combine the file instead\n\n  const allChunkData = await Promise.all(responses);\n\n  const data = new Blob(allChunkData, { type: entry.mime });\n  if (data.size !== entry.size) {\n    throw new Error(\n      `Failed to fetch ${key} with size ${entry.size} but got ${data.size}`\n    );\n  }\n  return data;\n}\n"
  },
  {
    "path": "packages/node/src/schema.ts",
    "content": "export { ConfigSchema, Config, validateConfig };\nimport { z } from 'zod';\nimport path from 'node:path';\nimport pkg from '../package.json';\n\nfunction isURI(s: string) {\n  try {\n    new URL(s);\n    return true;\n  } catch (err) {\n    return false;\n  }\n}\n\nconst ConfigSchema = z\n  .object({\n    publicPath: z\n      .string()\n      .optional()\n      .describe('The public path to the wasm files and the onnx model.')\n      .default(`file://${path.resolve(`node_modules/${pkg.name}/dist/`)}/`)\n      .transform((val) => {\n        return val\n          .replace('${PACKAGE_NAME}', pkg.name)\n          .replace('${PACKAGE_VERSION}', pkg.version);\n      })\n      .refine((val) => isURI(val), {\n        message: 'String must be a valid uri'\n      }),\n    debug: z\n      .boolean()\n      .default(false)\n      .describe('Whether to enable debug logging.'),\n    proxyToWorker: z\n      .boolean()\n      .default(true)\n      .describe('Whether to proxy inference to a web worker.'),\n    fetchArgs: z\n      .any({})\n      .default({})\n      .describe('Arguments to pass to fetch when loading the model.'),\n    progress: z\n      .function()\n      .args(z.string(), z.number(), z.number())\n      .returns(z.void())\n      .describe('Progress callback.')\n      .optional(),\n    model: z\n      .preprocess(\n        (val) => {\n          switch (val) {\n            case 'large':\n              return 'isnet';\n            case 'small':\n              return 'isnet_quint8';\n            case 'medium':\n              return 'isnet_fp16';\n            default:\n              return val;\n          }\n        },\n        z.enum(['isnet', 'isnet_fp16', 'isnet_quint8'])\n      )\n      .default('medium'),\n    output: z\n      .object({\n        format: z\n          .enum([\n            'image/png',\n            'image/jpeg',\n            'image/webp',\n            'image/x-rgba8',\n            'image/x-alpha8'\n          ])\n          .default('image/png'),\n        quality: z.number().default(0.8)\n      })\n      .default({})\n  })\n  .default({})\n  .transform((config) => {\n    if (config.debug) console.log('Config:', config);\n    if (config.debug && !config.progress) {\n      config.progress =\n        config.progress ??\n        ((key, current, total) => {\n          console.debug(`Downloading ${key}: ${current} of ${total}`);\n        });\n    }\n    return config;\n  });\n\ntype Config = z.infer<typeof ConfigSchema>;\n\nfunction validateConfig(configuration?: Config): Config {\n  return ConfigSchema.parse(configuration ?? {});\n}\n"
  },
  {
    "path": "packages/node/src/url.ts",
    "content": "export { ensureAbsoluteURI };\n\nfunction isAbsoluteURI(url: string): boolean {\n  const regExp = new RegExp('^(?:[a-z+]+:)?//', 'i');\n  return regExp.test(url); // true - regular http absolute URL\n}\n\nfunction ensureAbsoluteURI(url: string, baseUrl: string): URL {\n  if (isAbsoluteURI(url)) {\n    return new URL(url);\n  } else {\n    return new URL(url, baseUrl);\n  }\n}\n"
  },
  {
    "path": "packages/node/src/utils.ts",
    "content": "export {\n  imageDecode,\n  imageEncode,\n  tensorResizeBilinear,\n  tensorHWCtoBCHW,\n  calculateProportionalSize,\n  imageSourceToImageData,\n  ImageSource,\n  convertFloat32ToUint8\n};\n\nimport { Config } from './schema';\nimport * as codecs from './codecs';\nimport { ensureAbsoluteURI } from './url';\nimport { loadFromURI } from './resource';\n\nimport ndarray, { NdArray } from 'ndarray';\nimport { imageDecode, imageEncode } from './codecs';\n\ntype ImageSource =\n  | ArrayBuffer\n  | Uint8Array\n  | Blob\n  | URL\n  | string\n  | NdArray<Uint8Array>;\n\nfunction tensorResizeBilinear(\n  imageTensor: NdArray<Uint8Array>,\n  newWidth: number,\n  newHeight: number\n): NdArray<Uint8Array> {\n  const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;\n  // Calculate the scaling factors\n  const scaleX = srcWidth / newWidth;\n  const scaleY = srcHeight / newHeight;\n\n  // Create a new NdArray to store the resized image\n  const resizedImageData = ndarray(\n    new Uint8Array(srcChannels * newWidth * newHeight),\n    [newHeight, newWidth, srcChannels]\n  );\n  // Perform interpolation to fill the resized NdArray\n  for (let y = 0; y < newHeight; y++) {\n    for (let x = 0; x < newWidth; x++) {\n      const srcX = x * scaleX;\n      const srcY = y * scaleY;\n      const x1 = Math.max(Math.floor(srcX), 0);\n      const x2 = Math.min(Math.ceil(srcX), srcWidth - 1);\n      const y1 = Math.max(Math.floor(srcY), 0);\n      const y2 = Math.min(Math.ceil(srcY), srcHeight - 1);\n\n      const dx = srcX - x1;\n      const dy = srcY - y1;\n\n      for (let c = 0; c < srcChannels; c++) {\n        const p1 = imageTensor.get(y1, x1, c);\n        const p2 = imageTensor.get(y1, x2, c);\n        const p3 = imageTensor.get(y2, x1, c);\n        const p4 = imageTensor.get(y2, x2, c);\n\n        // Perform bilinear interpolation\n        const interpolatedValue =\n          (1 - dx) * (1 - dy) * p1 +\n          dx * (1 - dy) * p2 +\n          (1 - dx) * dy * p3 +\n          dx * dy * p4;\n\n        resizedImageData.set(y, x, c, Math.round(interpolatedValue));\n      }\n    }\n  }\n\n  return resizedImageData;\n}\n\nfunction tensorHWCtoBCHW(\n  imageTensor: NdArray<Uint8Array>,\n  mean: number[] = [128, 128, 128],\n  std: number[] = [256, 256, 256]\n): NdArray<Float32Array> {\n  var imageBufferData = imageTensor.data;\n  const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;\n  const stride = srcHeight * srcWidth;\n  const float32Data = new Float32Array(3 * stride);\n\n  // r_0, r_1, .... g_0,g_1, .... b_0\n  for (let i = 0, j = 0; i < imageBufferData.length; i += 4, j += 1) {\n    float32Data[j] = (imageBufferData[i] - mean[0]) / std[0];\n    float32Data[j + stride] = (imageBufferData[i + 1] - mean[1]) / std[1];\n    float32Data[j + stride + stride] =\n      (imageBufferData[i + 2] - mean[2]) / std[2];\n  }\n\n  return ndarray(float32Data, [1, 3, srcHeight, srcWidth]);\n}\n\nfunction calculateProportionalSize(\n  originalWidth: number,\n  originalHeight: number,\n  maxWidth: number,\n  maxHeight: number\n): [number, number] {\n  const widthRatio = maxWidth / originalWidth;\n  const heightRatio = maxHeight / originalHeight;\n  const scalingFactor = Math.min(widthRatio, heightRatio);\n  const newWidth = Math.floor(originalWidth * scalingFactor);\n  const newHeight = Math.floor(originalHeight * scalingFactor);\n  return [newWidth, newHeight];\n}\n\nasync function imageSourceToImageData(\n  image: ImageSource,\n  _: Config\n): Promise<NdArray<Uint8Array>> {\n  if (typeof image === 'string') {\n    image = ensureAbsoluteURI(image, `file://${process.cwd()}/`);\n  }\n  if (image instanceof URL) {\n    image = await (await loadFromURI(image)).blob();\n  }\n  if (image instanceof ArrayBuffer || ArrayBuffer.isView(image)) {\n    image = new Blob([image]);\n  }\n  if (image instanceof Blob) {\n    image = await codecs.imageDecode(image);\n  }\n\n  return image as NdArray<Uint8Array>;\n}\n\nfunction convertFloat32ToUint8(\n  float32Array: NdArray<Float32Array>\n): NdArray<Uint8Array> {\n  const uint8Array = new Uint8Array(float32Array.data.length);\n  for (let i = 0; i < float32Array.data.length; i++) {\n    uint8Array[i] = float32Array.data[i] * 255;\n  }\n  return ndarray(uint8Array, float32Array.shape);\n}\n"
  },
  {
    "path": "packages/node/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"lib\": [\"DOM\", \"ES2015\"],\n    \"resolveJsonModule\": true,\n    \"esModuleInterop\": true,\n    \"emitDeclarationOnly\": true,\n    \"declaration\": true,\n    \"target\": \"ES6\",\n    \"moduleResolution\": \"Node16\"\n  }\n}\n"
  },
  {
    "path": "packages/node-e2e/fixtures/images/img2img.sh",
    "content": "filename=\"photo-1686002359940-6a51b0d64f68.jpeg\"\nbasename=\"${filename%.*}\"\n\ncp \"$filename\" \"$filename\".orig\nmagick \"$filename\" \"$basename\".png\nmagick \"$filename\" \"$basename\".webp\nmagick \"$filename\" \"$basename\".jpg\nmagick \"$filename\" \"$basename\".avif\nmagick \"$filename\" \"$basename\".heif\n\n# Raw RGB\nmagick \"$filename\" -depth 8 \"$basename\".rgb\nmagick \"$filename\" -depth 8 \"$basename\".cmyk\n\n# rgb to tensor \n\nmagick \"$filename\" \"$basename\".pdf\nmagick \"$filename\" \"$basename\".psd\n\n\n"
  },
  {
    "path": "packages/node-e2e/package.json",
    "content": "{\n  \"name\": \"e2e\",\n  \"private\": true,\n  \"scripts\": {},\n  \"devDependencies\": {\n    \"@imgly/background-removal-node\": \"workspace:*\",\n    \"jest\": \"^29.6.2\"\n  },\n  \"version\": \"1.7.0\"\n}"
  },
  {
    "path": "packages/node-e2e/src/example.test.js",
    "content": "// const pkg = require('@imgly/background-removal-node');\n// const removeBackground = pkg.default;\n\n// Test case to ensure the system doesn't crash with valid inputs\n// test('removeBackground should not crash with valid inputs', async () => {\n//   const image = 'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1024&q=80';\n//   const result = await removeBackground(image, { debug: true })\n//   await expect(result).resolves.toBeInstanceOf(Blob);\n// });\n"
  },
  {
    "path": "packages/node-examples/package.json",
    "content": "{\n  \"name\": \"examples-node-cli\",\n  \"private\": true,\n  \"main\": \"index.mjs\",\n  \"scripts\": {\n    \"start\": \"node src/example_001.cjs\"\n  },\n  \"dependencies\": {\n    \"@imgly/background-removal-node\": \"workspace:*\",\n    \"uuidv4\": \"^6.2.13\"\n  },\n  \"version\": \"1.7.0\"\n}"
  },
  {
    "path": "packages/node-examples/src/example_001.cjs",
    "content": "const {\n  removeBackground,\n  segmentForeground,\n  applySegmentationMask\n} = require('@imgly/background-removal-node');\nconst fs = require('fs');\nconst uuidv4 = require('uuid').v4;\n\nconst images = [\n  // 'files/photo-1686002359940-6a51b0d64f68.jpeg',\n  'files/photo-1686002359940-hires.webp'\n  // 'files/photo-1590523278191-hires.webp'\n  // 'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&q=80'\n  // 'https://images.unsplash.com/photo-1590523278191-995cbcda646b?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9'\n];\n\nasync function run() {\n  const randomImage = images[Math.floor(Math.random() * images.length)];\n  console.log('Random image: ' + randomImage);\n  const config = {\n    debug: false,\n    // publicPath:  ...\n    progress: (key, current, total) => {\n      const [type, subtype] = key.split(':');\n      console.log(\n        `${type} ${subtype} ${((current / total) * 100).toFixed(0)}%`\n      );\n    },\n    // model: 'small',\n    model: 'isnet',\n    output: {\n      quality: 0.8,\n      format: 'image/webp' //image/jpeg, image/webp\n    }\n  };\n  console.time();\n  const blob = await removeBackground(randomImage, config);\n\n  // const mask = await segmentForeground(randomImage, config);\n  // const blob = await applySegmentationMask(randomImage, mask, config);\n  console.timeEnd();\n  const buffer = await blob.arrayBuffer();\n  try {\n    const format = config.output.format.split('/').pop();\n    const outFile = `tmp/${uuidv4()}.${format}`;\n    await fs.promises.mkdir('tmp', { recursive: true });\n    await fs.promises.writeFile(outFile, Buffer.from(buffer));\n    console.log(`Image saved to ${outFile}`);\n  } catch (error) {\n    console.error(error);\n  }\n}\n\nrun();\n"
  },
  {
    "path": "packages/web/CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [1.5.6]\n\n### Changed\n\n- Upgrade onnx-runtime\n\n## [1.5.0]\n\n### Added\n\n- Added option to execute on gpu (webgpu) and cpu. Enable by setting `device: \"gpu\"`\n\n- Added isnet model for webgpu\n\n## [1.4.5]\n\n### Added\n\n- Added ThirdPartyLicenses.json\n\n## [1.4.0]\n\n### Added\n\n- Moved all data into it's own package. Therefore, reducing the main package size for the general case.\n\n- Bumped onnx runtime to 1.17 Changed\n\n- Changed license from GPL to AGPL Changed\n\n- Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.\n\n- Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.\n\n### Changed\n\n- Fallback to Canvas if OffscreenCanvas is not available\n\n- Typescript bindings are generated with tsc\n\n## [1.3.0]\n\n### Added\n\n- Resources are now chunked to 4MB for better caching performance and download restart.\n\n- Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.\n\n- Config option to export 'x-alpha8' format to get receive single channel alpha mask.\n\n### Removed\n\n- Configuration options to specify if background, foreground or mask is exported.\n\n### Changed\n\n- Changed the return value type of the progress callback from undefined to void\n\n- Output is now in the original image size. Mask is upscaled and applied to the original image.\n\n## [1.2.1]\n\n### Added\n\n- `CHANGELOG.md` for an better overview of the changes.\n\n- support for raw `rgba8` export formats.\n\n## [1.2.0]\n\n### Added\n\n- Support `foreground`, `background` and `mask` export type.\n- Added support for `webp` and `jpeg` export formats.\n"
  },
  {
    "path": "packages/web/LICENSE.md",
    "content": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_\n\nEveryone is permitted to copy and distribute verbatim copies\nof this license document, but changing it is not allowed.\n\n## Preamble\n\nThe GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nDevelopers that use our General Public Licenses protect your rights\nwith two steps: **(1)** assert copyright on the software, and **(2)** offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\nA secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate. Many developers of free software are heartened and\nencouraged by the resulting cooperation. However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\nThe GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community. It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server. Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\nAn older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals. This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n## TERMS AND CONDITIONS\n\n### 0. Definitions\n\n“This License” refers to version 3 of the GNU Affero General Public License.\n\n“Copyright” also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n“The Program” refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as “you”. “Licensees” and\n“recipients” may be individuals or organizations.\n\nTo “modify” a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a “modified version” of the\nearlier work or a work “based on” the earlier work.\n\nA “covered work” means either the unmodified Program or a work based\non the Program.\n\nTo “propagate” a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo “convey” a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays “Appropriate Legal Notices”\nto the extent that it includes a convenient and prominently visible\nfeature that **(1)** displays an appropriate copyright notice, and **(2)**\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n### 1. Source Code\n\nThe “source code” for a work means the preferred form of the work\nfor making modifications to it. “Object code” means any non-source\nform of a work.\n\nA “Standard Interface” means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe “System Libraries” of an executable work include anything, other\nthan the work as a whole, that **(a)** is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and **(b)** serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n“Major Component”, in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe “Corresponding Source” for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\nThe Corresponding Source for a work in source code form is that\nsame work.\n\n### 2. Basic Permissions\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n### 3. Protecting Users' Legal Rights From Anti-Circumvention Law\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n### 4. Conveying Verbatim Copies\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n### 5. Conveying Modified Source Versions\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n- **a)** The work must carry prominent notices stating that you modified\n  it, and giving a relevant date.\n- **b)** The work must carry prominent notices stating that it is\n  released under this License and any conditions added under section 7.\n  This requirement modifies the requirement in section 4 to\n  “keep intact all notices”.\n- **c)** You must license the entire work, as a whole, under this\n  License to anyone who comes into possession of a copy. This\n  License will therefore apply, along with any applicable section 7\n  additional terms, to the whole of the work, and all its parts,\n  regardless of how they are packaged. This License gives no\n  permission to license the work in any other way, but it does not\n  invalidate such permission if you have separately received it.\n- **d)** If the work has interactive user interfaces, each must display\n  Appropriate Legal Notices; however, if the Program has interactive\n  interfaces that do not display Appropriate Legal Notices, your\n  work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n“aggregate” if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n### 6. Conveying Non-Source Forms\n\nYou may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n- **a)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by the\n  Corresponding Source fixed on a durable physical medium\n  customarily used for software interchange.\n- **b)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by a\n  written offer, valid for at least three years and valid for as\n  long as you offer spare parts or customer support for that product\n  model, to give anyone who possesses the object code either **(1)** a\n  copy of the Corresponding Source for all the software in the\n  product that is covered by this License, on a durable physical\n  medium customarily used for software interchange, for a price no\n  more than your reasonable cost of physically performing this\n  conveying of source, or **(2)** access to copy the\n  Corresponding Source from a network server at no charge.\n- **c)** Convey individual copies of the object code with a copy of the\n  written offer to provide the Corresponding Source. This\n  alternative is allowed only occasionally and noncommercially, and\n  only if you received the object code with such an offer, in accord\n  with subsection 6b.\n- **d)** Convey the object code by offering access from a designated\n  place (gratis or for a charge), and offer equivalent access to the\n  Corresponding Source in the same way through the same place at no\n  further charge. You need not require recipients to copy the\n  Corresponding Source along with the object code. If the place to\n  copy the object code is a network server, the Corresponding Source\n  may be on a different server (operated by you or a third party)\n  that supports equivalent copying facilities, provided you maintain\n  clear directions next to the object code saying where to find the\n  Corresponding Source. Regardless of what server hosts the\n  Corresponding Source, you remain obligated to ensure that it is\n  available for as long as needed to satisfy these requirements.\n- **e)** Convey the object code using peer-to-peer transmission, provided\n  you inform other peers where the object code and Corresponding\n  Source of the work are being offered to the general public at no\n  charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA “User Product” is either **(1)** a “consumer product”, which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or **(2)** anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, “normally used” refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n“Installation Information” for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n### 7. Additional Terms\n\n“Additional permissions” are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n- **a)** Disclaiming warranty or limiting liability differently from the\n  terms of sections 15 and 16 of this License; or\n- **b)** Requiring preservation of specified reasonable legal notices or\n  author attributions in that material or in the Appropriate Legal\n  Notices displayed by works containing it; or\n- **c)** Prohibiting misrepresentation of the origin of that material, or\n  requiring that modified versions of such material be marked in\n  reasonable ways as different from the original version; or\n- **d)** Limiting the use for publicity purposes of names of licensors or\n  authors of the material; or\n- **e)** Declining to grant rights under trademark law for use of some\n  trade names, trademarks, or service marks; or\n- **f)** Requiring indemnification of licensors and authors of that\n  material by anyone who conveys the material (or modified versions of\n  it) with contractual assumptions of liability to the recipient, for\n  any liability that these contractual assumptions directly impose on\n  those licensors and authors.\n\nAll other non-permissive additional terms are considered “further\nrestrictions” within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n### 8. Termination\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated **(a)**\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and **(b)** permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n### 9. Acceptance Not Required for Having Copies\n\nYou are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n### 10. Automatic Licensing of Downstream Recipients\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn “entity transaction” is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n### 11. Patents\n\nA “contributor” is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's “contributor version”.\n\nA contributor's “essential patent claims” are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, “control” includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a “patent license” is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To “grant” such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either **(1)** cause the Corresponding Source to be so\navailable, or **(2)** arrange to deprive yourself of the benefit of the\npatent license for this particular work, or **(3)** arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. “Knowingly relying” means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is “discriminatory” if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license **(a)** in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or **(b)** primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n### 12. No Surrender of Others' Freedom\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n### 13. Remote Network Interaction; Use with the GNU General Public License\n\nNotwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software. This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n### 14. Revised Versions of this License\n\nThe Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License “or any later version” applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n### 15. Disclaimer of Warranty\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n### 16. Limitation of Liability\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n### 17. Interpretation of Sections 15 and 16\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n_END OF TERMS AND CONDITIONS_\n\n## How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe “copyright” line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source. For example, if your program is a web application, its\ninterface could display a “Source” link that leads users to an archive\nof the code. There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\nYou should also get your employer (if you work as a programmer) or school,\nif any, to sign a “copyright disclaimer” for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n&lt;<http://www.gnu.org/licenses/>&gt;.\n"
  },
  {
    "path": "packages/web/README.md",
    "content": "# Background Removal in the Browser\n\nWe are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**\n\n&lt;p align=\"center\"&gt; &lt;img src=\"https://img.ly/showcases/cesdk/web/s/case-thumbnail/background-removal/background-removal-0.png?utm_source=github&utm_medium=project&utm_campaign=background-removal-js\" alt=\"background removal js showcase\" /&gt; &lt;/p&gt;\n\nRemove backgrounds from images directly in the browser environment with ease and no additional costs or privacy concerns. Explore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).\n\n## News\n\nFor more detail information please refer to the [CHANGELOG](./CHANGELOG.md).\n\n## Overview\n\n`@imgly/background-removal` is a powerful npm package that allows developers to seamlessly remove the background from images directly in the browser. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy.\n\nThe key features of `@imgly/background-removal` are:\n\n- **In-Browser Background Removal**: Our one-of-a-kind solution performs the entire background removal process directly in the user's browser, eliminating the need for additional server costs. By leveraging the computing power of the local device, users can enjoy a fast and efficient background removal process.\n\n- **Data Protection**: As `@imgly/background-removal` runs entirely in the browser, users can have peace of mind knowing that their images and sensitive information remain secure within their own devices. With no data transfers to external servers, data privacy concerns are effectively mitigated.\n\n- **Seamless Integration with IMG.LY's CE.SDK**: `@imgly/background-removal` provides seamless integration with [IMG.LY's CE.SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), allowing developers to easily incorporate powerful in-browser image matting and background removal capabilities into their projects.\n\nThe Neural Network ([ONNX model](https://onnx.ai/)) and WASM files used by `@imgly/background-removal` are hosted by [IMG.LY](https://img.ly/) by default. See the section Custom Asset Serving if you want to host them on your own servers.\n\n## Installation\n\nYou can install `@imgly/background-removal` via npm or yarn. You also need to install the onnxruntime-web peer dependency. Use the following commands to install the packages:\n\n### NPM\n\n```shell\nnpm install @imgly/background-removal onnxruntime-web@1.21.0-dev.20250206-d981b153d3\n```\n\n## Usage\n\n```typescript\nimport imglyRemoveBackground from \"@imgly/background-removal\"\n\nlet image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...;\n\nimglyRemoveBackground(image_src).then((blob: Blob) => {\n  // The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src\n  const url = URL.createObjectURL(blob);\n})\n```\n\nNote: On the first run the wasm and onnx model files are fetched. This might, depending on the bandwidth, take time. Therefore, the first run takes proportionally longer than each consecutive run. Also, all files are cached by the browser and an additional model cache.\n\n## Advanced Configuration\n\nThe library does not need any configuration to get started. However, there are optional parameters that influence the behaviour and give more control over the library.\n\n```typescript\ntype Config = {\n  publicPath: string; // The public path used for model and wasm files. Default: 'https://staticimgly.com/${PACKAGE_NAME}-data/${PACKAGE_VERSION}/dist/'\n  debug: bool; // enable or disable useful console.log outputs\n  device: 'cpu' | 'gpu'; // choose the execution device. gpu will use webgpu if available\n  model: 'isnet' | 'isnet_fp16' | 'isnet_quint8'; // The model to use. (Default \"isnet_fp16\")\n  output: {\n    format: 'image/png' | 'image/jpeg' | 'image/webp'; // The output format. (Default \"image/png\")\n    quality: number; // The quality. (Default: 0.8)\n    type: 'foreground' | 'background' | 'mask'; // The output type. (Default \"foreground\")\n  };\n};\n```\n\n### NextJS\n\nNote that currently only NextJS 15 is supported.\n\n### Download Size vs Quality\n\nThe onnx model is shipped in various sizes and needs.\n\n- small (\\~40 MB) is the smallest model and is in most cases working fine but sometimes shows some artifacts. It's a quantized model.\n- medium (\\~80MB) is the default model.\n\n### Preloading Assets\n\nPer default, assets are downloaded on demand. You might enforce downloading all assets at once at any time by preloading them:\n\n```typescript\nimport removeBackground, { preload, Config } from '@imgly/background-removal';\n\nconst config: Configuration = ...;\npreload(config).then(() => {\n  console.log(\"Asset preloading succeeded\")\n})\n```\n\n### Download Progress Monitoring\n\nOn the first run, the necessary data will be fetched and stored in the browser cache. Since the download might take some time, you have the option to tap into the download progress.\n\n```typescript\nlet config: Config = {\n  progress: (key, current, total) => {\n    console.log(`Downloading ${key}: ${current} of ${total}`);\n  }\n};\n```\n\n### Performance\n\nThe performance is largely dependent on the feature set available. Most prominently, ensure that `SharedArrayBuffer` is available [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer). Due to the security requirements of `SharedArrayBuffer` two headers need to be set to cross-origin isolate your site:\n\n```typescript\n'Cross-Origin-Opener-Policy': 'same-origin',\n'Cross-Origin-Embedder-Policy': 'require-corp'\n```\n\n### Custom Asset Serving\n\nThe wasm and onnx neural networks are hosted by IMG.LY by default. For production use, we advise you to host them yourself:\n\n- Download the following package with the package version that matches your `@imgly/background-removal` version from the IMG.LY CDN and decompress it. Note that you need to replace `YOUR_PACKAGE_VERSION` with the actual version of the package you are using. The URL is `https://staticimgly.com/@imgly/background-removal-data/YOUR_PACKAGE_VERSION/package.tgz`.\n- Move the content of the `package/dist` folder to be served by your web server. This often is the `/public` folder.\n\n```typescript\nimport imglyRemoveBackground, {Config} from \"@imgly/background-removal\"\n\nconst public_path = \"https://example.com/assets/\" ; // the path assets are served from\n\nlet config: Config =  {\n  publicPath: public_path, // path to the wasm files\n};\n\nlet image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...;\n\nimglyRemoveBackground(image_src, config).then((blob: Blob) => {\n  // result is a blob encoded as PNG.\n  // It can be converted to an URL to be used as HTMLImage.src\n  const url = URL.createObjectURL(blob);\n})\n```\n\n### Debug Outputs\n\nEnable debug outputs and logging to the console\n\n```typescript\nlet config: Config = {\n  debug: true\n};\n```\n\n### Cross-Origin Resource Sharing (CORS)\n\nIf you are running into CORS issues you might want to pass additional parameters to the fetch function via\n\n```typescript\nlet config: Config = {\n  fetchArgs: {\n    mode: 'no-cors'\n  }\n};\n```\n\n### Fetch Args\n\n`fetchArgs` are passed as second parameters to the fetch function as described in [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).\n\n## Who is it for?\n\n`@imgly/background-removal` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser. It caters to a wide range of use cases, including but not limited to:\n\n- _E-commerce applications_ that need to remove backgrounds from product images in real time.\n\n- _Image editing applications_ that require background removal capabilities for enhancing user experience.\n\n- _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal.\n\nWhether you are a professional developer or a hobbyist, `@imgly/background-removal` empowers you to deliver impressive applications and services with ease.\n\n## License\n\nThe software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal%20License) for questions about other licensing options.\n\n## Authors & Contributors\n\nThis library is made by IMG.LY shipping the world's premier SDKs for building creative applications. Start your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).\n"
  },
  {
    "path": "packages/web/ThirdPartyLicenses.json",
    "content": "{\n  \"onnxruntime-web\": {\n    \"source\": \"https://www.npmjs.com/package/onnxruntime-web\",\n    \"type\": \"code\",\n    \"license\": \"MIT\"\n  },\n  \"ISNET\": {\n    \"source\": \"https://github.com/xuebinqin/DIS\",\n    \"type\": \"model\",\n    \"license\": \"MIT\"\n  },\n  \"lodash-es\": {\n    \"source\": \"https://lodash.com/\",\n    \"type\": \"code\",\n    \"license\": \"MIT\"\n  },\n  \"ndarray\": {\n    \"source\": \"https://www.npmjs.com/package/ndarray\",\n    \"type\": \"code\",\n    \"license\": \"MIT\"\n  },\n  \"zod\": {\n    \"source\": \"https://www.npmjs.com/package/zod\",\n    \"type\": \"code\",\n    \"license\": \"MIT\"\n  }\n}\n"
  },
  {
    "path": "packages/web/changelog/1.2.0/20230811184244-export_type_and_formats.yml",
    "content": "---\ntype: Added\ndescription: Support `foreground`, `background` and `mask` export type.\n---\ntype: Added\ndescription: Added support for `webp` and `jpeg` export formats.\n"
  },
  {
    "path": "packages/web/changelog/1.2.1/20230811184244-Changelog_item.yml",
    "content": "---\ntype: Added\ndescription: |\n  `CHANGELOG.md` for an better overview of the changes.\n---\ntype: Added\ndescription: |\n  support for raw `rgba8` export formats.\n"
  },
  {
    "path": "packages/web/changelog/1.3.0/20230612112148-progress_return_type.yaml",
    "content": "---\ntype: Changed\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Changed the return value type of the progress callback from undefined to void\n"
  },
  {
    "path": "packages/web/changelog/1.3.0/20231512181521-resource_data_chunking.yaml",
    "content": "---\ntype: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Resources are now chunked to 4MB for better caching performance and download restart.\n"
  },
  {
    "path": "packages/web/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml",
    "content": "---\ntype: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Output is now in the original image size. Mask is upscaled and applied to the original image.\n---\ntype: Added\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.\n\n---\ntype: Removed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Configuration options to specify if background, foreground or mask is exported.\n---\ntype: Added\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Config option to export 'x-alpha8' format to get receive single channel alpha mask.\n"
  },
  {
    "path": "packages/web/changelog/1.4.0/20233012103509-Moved.yaml",
    "content": "---\ntype: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Moved all data into it's own package. Therefore, reducing the main package size for the general case.\n"
  },
  {
    "path": "packages/web/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Bumped onnx runtime to 1.17 Changed\n"
  },
  {
    "path": "packages/web/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Changed license from GPL to AGPL Changed\n"
  },
  {
    "path": "packages/web/changelog/1.4.0/20241601144157-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.\n"
  },
  {
    "path": "packages/web/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.\n"
  },
  {
    "path": "packages/web/changelog/1.4.0/20241601175908-Fallback_to_Canvas_if_OffscreenCanvas_is_not_available.yaml",
    "content": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Fallback to Canvas if OffscreenCanvas is not available\n"
  },
  {
    "path": "packages/web/changelog/1.4.0/20242301155639-Typescript_bindings_are_generated_with_tsc.yaml",
    "content": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Typescript bindings are generated with tsc\n"
  },
  {
    "path": "packages/web/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added ThirdPartyLicenses.json\n"
  },
  {
    "path": "packages/web/changelog/1.5.0/20242403201534-Added_option_to_execute_on_gpu_webgpu_and_cpu_Added.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added option to execute on gpu (webgpu) and cpu. Enable by setting `device: \"gpu\"`\n"
  },
  {
    "path": "packages/web/changelog/1.5.0/20242503170808-Added_isnet_model_for_webgpu_Added.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added isnet model for webgpu\n"
  },
  {
    "path": "packages/web/changelog/1.5.6/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
    "content": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Upgrade onnx-runtime\n"
  },
  {
    "path": "packages/web/changelog/Unreleased/.keep",
    "content": ""
  },
  {
    "path": "packages/web/changelog/info.yml",
    "content": "---\ndescription: |\n  All notable changes to this project will be documented in this file.\n\n  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n"
  },
  {
    "path": "packages/web/package.json",
    "content": "{\n  \"name\": \"@imgly/background-removal\",\n  \"version\": \"1.7.0\",\n  \"description\": \"Background Removal in the Browser\",\n  \"keywords\": [\n    \"background-removal\",\n    \"client-side\",\n    \"data-privacy\",\n    \"image-segmentation\",\n    \"image-matting\",\n    \"onnx\"\n  ],\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/imgly/background-removal-js.git\"\n  },\n  \"license\": \"SEE LICENSE IN LICENSE.md\",\n  \"author\": {\n    \"name\": \"IMG.LY GmbH\",\n    \"email\": \"support@img.ly\",\n    \"url\": \"https://img.ly\"\n  },\n  \"bugs\": {\n    \"email\": \"support@img.ly\"\n  },\n  \"source\": \"./src/index.ts\",\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.mjs\",\n  \"types\": \"./dist/src/index.d.ts\",\n  \"exports\": {\n    \".\": {\n      \"require\": \"./dist/index.cjs\",\n      \"import\": \"./dist/index.mjs\",\n      \"types\": \"./dist/src/index.d.ts\"\n    }\n  },\n  \"homepage\": \"https://img.ly/showcases/cesdk/web/background-removal\",\n  \"files\": [\n    \"LICENSE.md\",\n    \"README.md\",\n    \"CHANGELOG.md\",\n    \"ThirdPartyLicenses.json\",\n    \"dist/\",\n    \"bin/\"\n  ],\n  \"scripts\": {\n    \"start\": \"pnpm run watch\",\n    \"clean\": \"npx rimraf dist\",\n    \"test\": \"true\",\n    \"resources\": \"node ../../scripts/package-resources.mjs\",\n    \"changelog:create\": \"node ../../scripts/changelog/changelog-create.mjs\",\n    \"changelog:generate\": \"node ../../scripts/changelog/changelog-generate.mjs\",\n    \"build\": \"pnpm run clean && pnpm run types && pnpm run resources && pnpm run changelog:generate && node scripts/build.mjs\",\n    \"types\": \" npx tsc --declaration --emitDeclarationOnly --declarationDir dist --declarationMap\",\n    \"watch\": \"pnpm run clean && pnpm run resources && pnpm run changelog:generate && node scripts/watch.mjs\",\n    \"publish:latest\": \"pnpm publish --tag latest --access public\",\n    \"publish:next\": \"pnpm publish --tag next --access public\",\n    \"package:pack\": \"pnpm pack . --pack-destination ../../releases\",\n    \"check:all\": \"pnpm run check:pretty\",\n    \"check:pretty\": \"prettier --list-different './src/**/*.{ts,tsx}'\",\n    \"pretty\": \"prettier --write './src/**/*.{ts,tsx}'\"\n  },\n  \"dependencies\": {\n    \"lodash-es\": \"^4.17.21\",\n    \"ndarray\": \"~1.0.0\",\n    \"zod\": \"^3.23.8\"\n  },\n  \"peerDependencies\": {\n    \"onnxruntime-web\": \"1.21.0\"\n  },\n  \"devDependencies\": {\n    \"@types/lodash-es\": \"^4.17.12\",\n    \"@types/ndarray\": \"~1.0.14\",\n    \"@types/node\": \"~20.3.0\",\n    \"assert\": \"~2.0.0\",\n    \"esbuild\": \"~0.18.0\",\n    \"glob\": \"~10.3.0\",\n    \"npm-dts\": \"~1.3.0\",\n    \"process\": \"~0.11.0\",\n    \"ts-loader\": \"~9.4.0\",\n    \"tslib\": \"~2.5.0\",\n    \"typescript\": \"~5.1.0\",\n    \"util\": \"~0.12.0\",\n    \"webpack\": \"~5.85.0\",\n    \"webpack-cli\": \"~5.1.0\"\n  }\n}"
  },
  {
    "path": "packages/web/scripts/build.mjs",
    "content": "export { configs };\n\nimport * as esbuild from 'esbuild';\nimport { readFileSync } from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n  readFileSync(path.resolve(__dirname, '../package.json'))\n);\n\nconst dependencies = [Object.keys(pkg.peerDependencies)].flat();\n\nconst configs = [\n  {\n    entryPoints: ['src/index.ts'],\n    bundle: true,\n    sourcemap: true,\n    platform: 'browser',\n    external: dependencies,\n    format: 'cjs',\n    outfile: 'dist/index.cjs'\n  },\n  {\n    entryPoints: ['src/index.ts'],\n    bundle: true,\n    sourcemap: true,\n    external: dependencies,\n    platform: 'browser',\n    format: 'esm',\n    outfile: 'dist/index.mjs'\n  }\n];\n\nawait configs.map(async (config) => await esbuild.build(config));\n"
  },
  {
    "path": "packages/web/scripts/watch.mjs",
    "content": "import * as esbuild from 'esbuild';\nimport { configs } from './build.mjs';\nimport dts from 'npm-dts';\n\nnew dts.Generator({\n  entry: 'src/index.ts',\n  output: 'dist/index.d.ts'\n}).generate();\n\nconst contexts = await Promise.all(\n  configs.map((config) => esbuild.context(config))\n);\n\nawait Promise.any(contexts.map((ctx) => ctx.watch()));\nconsole.log('watching...');\n"
  },
  {
    "path": "packages/web/src/MimeType.ts",
    "content": "export class MimeType {\n  type: string = 'application/octet-stream';\n  params: Record<string, string> = {};\n\n  private constructor(type: string, params: Record<string, string>) {\n    this.type = type;\n    this.params = params;\n  }\n\n  toString(): string {\n    const paramsStr = [];\n    for (const key in this.params) {\n      const value = this.params[key];\n      paramsStr.push(`${key}=${value}`);\n    }\n    return [this.type, ...paramsStr].join(';');\n  }\n\n  static create(type, params: Record<string, string>): MimeType {\n    return new MimeType(type, params);\n  }\n\n  isIdentical(other: MimeType): Boolean {\n    return this.type === other.type && this.params === other.params;\n  }\n\n  isEqual(other: MimeType): Boolean {\n    return this.type === other.type;\n  }\n\n  static fromString(mimeType: string): MimeType {\n    const [type, ...paramsArr] = mimeType.split(';');\n    const params: Record<string, string> = {};\n\n    for (const param of paramsArr) {\n      const [key, value] = param.split('=');\n      params[key.trim()] = value.trim();\n    }\n    return new MimeType(type, params);\n  }\n}\n"
  },
  {
    "path": "packages/web/src/api/v1.ts",
    "content": "export default removeBackground;\nexport {\n  preload,\n  removeBackground,\n  removeForeground,\n  alphamask,\n  segmentForeground,\n  applySegmentationMask\n};\nexport type { Config, ImageSource };\n\nimport memoize from 'lodash-es/memoize';\n\nimport { initInference, runInference } from '../inference';\nimport { Config, validateConfig } from '../schema';\nimport * as utils from '../utils';\nimport { ImageSource } from '../utils';\n\nconst init = memoize(initInference, (config) => JSON.stringify(config));\n\nasync function preload(configuration?: Config): Promise<void> {\n  await init(configuration);\n  return;\n}\n\n/**\n * Removes the background from an image.\n *\n * @param image - The image to remove the background from.\n * @param configuration - Optional configuration for the background removal process.\n * @returns A Promise that resolves to the resulting image with the background removed.\n */\nasync function removeBackground(\n  image: ImageSource,\n  configuration?: Config\n): Promise<Blob> {\n  const { config, session } = await init(configuration);\n\n  if (config.progress) config.progress('compute:decode', 0, 4);\n\n  const inputImageTensor = await utils.imageSourceToImageData(image, config);\n\n  config.progress?.('compute:inference', 1, 4);\n  const [alphamask, imageTensor] = await runInference(\n    inputImageTensor,\n    config,\n    session\n  );\n\n  config.progress?.('compute:mask', 2, 4);\n  const outImageTensor = imageTensor;\n  const [width, height] = outImageTensor.shape;\n  const stride = width * height;\n  for (let i = 0; i < stride; i += 1) {\n    outImageTensor.data[4 * i + 3] = alphamask.data[i];\n  }\n  config.progress?.('compute:encode', 3, 4);\n  const outImage = await utils.imageEncode(\n    outImageTensor,\n    config.output.quality,\n    config.output.format\n  );\n  config.progress?.('compute:encode', 4, 4);\n\n  return outImage;\n}\n\n/**\n * Removes the foreground from an image.\n *\n * @param image - The image to remove the foreground from.\n * @param configuration - Optional configuration for the foreground removal process.\n * @returns A Promise that resolves to the resulting image with the foreground removed.\n */\nasync function removeForeground(\n  image: ImageSource,\n  configuration?: Config\n): Promise<Blob> {\n  const { config, session } = await init(configuration);\n\n  const imageTensor = await utils.imageSourceToImageData(image, config);\n  const [alphamask, imageInput] = await runInference(\n    imageTensor,\n    config,\n    session\n  );\n\n  const outImageTensor = imageInput;\n  const [width, height, channels] = outImageTensor.shape;\n  const stride = width * height;\n  for (let i = 0; i < stride; i += 1) {\n    outImageTensor.data[4 * i + 3] = 255 - alphamask.data[i];\n  }\n\n  const outImage = await utils.imageEncode(\n    outImageTensor,\n    config.output.quality,\n    config.output.format\n  );\n\n  return outImage;\n}\n\n/**\n * Segments the foreground of an image using a given configuration.\n *\n * @param image - The image source to segment.\n * @param configuration - The optional configuration for the segmentation.\n * @returns A Promise that resolves to the segmented foreground as a Blob.\n */\n\nconst alphamask = segmentForeground;\nasync function segmentForeground(\n  image: ImageSource,\n  configuration?: Config\n): Promise<Blob> {\n  const { config, session } = await init(configuration);\n\n  const imageTensor = await utils.imageSourceToImageData(image, config);\n  let [height, width, channels] = imageTensor.shape;\n\n  const [alphamask, imageInput] = await runInference(\n    imageTensor,\n    config,\n    session\n  );\n\n  const stride = width * height;\n  const outImageTensor = imageTensor;\n  for (let i = 0; i < stride; i += 1) {\n    const index = 4 * i;\n\n    let alpha = alphamask.data[i];\n\n    outImageTensor.data[index] = 255;\n    outImageTensor.data[index + 1] = 255;\n    outImageTensor.data[index + 2] = 255;\n    outImageTensor.data[index + 3] = alpha;\n  }\n\n  const outImage = await utils.imageEncode(\n    outImageTensor,\n    config.output.quality,\n    config.output.format\n  );\n  return outImage;\n}\n\nasync function applySegmentationMask(\n  image,\n  mask,\n  config?: Config\n): Promise<Blob> {\n  config = validateConfig(config);\n  const imageTensor = await utils.imageSourceToImageData(image, config);\n  const [imageHeight, imageWidth, imageChannels] = imageTensor.shape;\n  const maskTensor = await utils.imageSourceToImageData(mask, config);\n  const [maskHeight, maskWidth, maskChannels] = maskTensor.shape;\n\n  const alphaMask =\n    maskHeight !== imageHeight || maskWidth !== imageWidth\n      ? utils.tensorResizeBilinear(maskTensor, imageWidth, imageHeight)\n      : maskTensor;\n  const stride = imageWidth * imageHeight;\n  for (let i = 0; i < stride; i += 1) {\n    const idxImage = imageChannels * i;\n    const idxMask = maskChannels * i;\n    imageTensor.data[idxImage + 3] = alphaMask.data[idxMask + 3];\n  }\n\n  const outImage = await utils.imageEncode(\n    imageTensor,\n    config.output.quality,\n    config.output.format\n  );\n\n  return outImage;\n}\n"
  },
  {
    "path": "packages/web/src/capabilities.js",
    "content": "export const bigInt = () =>\n    (async (e) => {\n      try {\n        return (\n          (await WebAssembly.instantiate(e)).instance.exports.b(BigInt(0)) ===\n          BigInt(0)\n        );\n      } catch (e) {\n        return !1;\n      }\n    })(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 1, 126, 1, 126, 3, 2, 1, 0, 7,\n        5, 1, 1, 98, 0, 0, 10, 6, 1, 4, 0, 32, 0, 11\n      ])\n    ),\n  bulkMemory = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 3, 1, 0,\n        1, 10, 14, 1, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11\n      ])\n    ),\n  exceptions = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6,\n        0, 6, 64, 25, 11, 11\n      ])\n    ),\n  extendedConst = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 0, 1, 11, 9, 1, 0, 65, 1, 65, 2,\n        106, 11, 0\n      ])\n    ),\n  gc = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 10, 2, 95, 1, 125, 0, 96, 0, 1, 107, 0,\n        3, 2, 1, 1, 10, 12, 1, 10, 0, 67, 0, 0, 0, 0, 251, 7, 0, 11\n      ])\n    ),\n  memory64 = () =>\n    WebAssembly.validate(\n      new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 4, 1])\n    ),\n  multiValue = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 0, 2, 127, 127, 3, 2, 1, 0,\n        10, 8, 1, 6, 0, 65, 0, 65, 0, 11\n      ])\n    ),\n  mutableGlobals = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 2, 8, 1, 1, 97, 1, 98, 3, 127, 1, 6, 6, 1,\n        127, 1, 65, 0, 11, 7, 5, 1, 1, 97, 3, 1\n      ])\n    ),\n  referenceTypes = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 7, 1, 5,\n        0, 208, 112, 26, 11\n      ])\n    ),\n  relaxedSimd = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 15,\n        1, 13, 0, 65, 1, 253, 15, 65, 2, 253, 15, 253, 128, 2, 11\n      ])\n    ),\n  saturatedFloatToInt = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 12, 1,\n        10, 0, 67, 0, 0, 0, 0, 252, 0, 26, 11\n      ])\n    ),\n  signExtensions = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6,\n        0, 65, 0, 192, 26, 11\n      ])\n    ),\n  simd = () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10,\n        1, 8, 0, 65, 0, 253, 15, 253, 98, 11\n      ])\n    ),\n  streamingCompilation = () =>\n    (async () => 'compileStreaming' in WebAssembly)(),\n  tailCall = async () =>\n    WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 6, 1, 4,\n        0, 18, 0, 11\n      ])\n    ),\n  threads = () =>\n    (async (e) => {\n      try {\n        return (\n          'undefined' != typeof MessageChannel &&\n            new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),\n          WebAssembly.validate(e)\n        );\n      } catch (e) {\n        return !1;\n      }\n    })(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3,\n        1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11\n      ])\n    );\n\nexport const webgpu = async () => {\n  if (navigator.gpu === undefined) return false;\n  const adapter = await navigator.gpu.requestAdapter();\n  return adapter !== null;\n};\nexport const maxNumThreads = () => navigator.hardwareConcurrency ?? 4;\n"
  },
  {
    "path": "packages/web/src/codecs.ts",
    "content": "export { imageEncode, imageDecode, MimeType };\nimport { MimeType } from './MimeType';\nimport { imageBitmapToImageData, createCanvas } from './utils';\nimport ndarray, { NdArray } from 'ndarray';\n\nasync function imageDecode(blob: Blob): Promise<NdArray<Uint8Array>> {\n  const mime = MimeType.fromString(blob.type);\n\n  switch (mime.type) {\n    case 'image/x-alpha8': {\n      const width = parseInt(mime.params['width']);\n      const height = parseInt(mime.params['height']);\n      return ndarray(new Uint8Array(await blob.arrayBuffer()), [\n        height,\n        width,\n        1\n      ]);\n    }\n    case 'image/x-rgba8': {\n      const width = parseInt(mime.params['width']);\n      const height = parseInt(mime.params['height']);\n      return ndarray(new Uint8Array(await blob.arrayBuffer()), [\n        height,\n        width,\n        4\n      ]);\n    }\n    case 'application/octet-stream': // this is an unknwon type\n    case `image/png`:\n    case `image/jpeg`:\n    case `image/jpg`:\n    case `image/webp`: {\n      const imageBitmap = await createImageBitmap(blob);\n      const imageData = imageBitmapToImageData(imageBitmap);\n      return ndarray(new Uint8Array(imageData.data), [\n        imageData.height,\n        imageData.width,\n        4\n      ]);\n    }\n    default:\n      throw new Error(\n        `Invalid format: ${mime.type} with params: ${mime.params}`\n      );\n  }\n}\n\nasync function imageEncode(\n  imageTensor: NdArray<Uint8Array>,\n  quality: number = 0.8,\n  format: string = 'image/png'\n): Promise<Blob> {\n  const [height, width, channels] = imageTensor.shape;\n\n  switch (format) {\n    case 'image/x-alpha8':\n    case 'image/x-rgba8': {\n      const mime = MimeType.create(format, {\n        width: width.toString(),\n        height: height.toString()\n      });\n      return new Blob([imageTensor.data], { type: mime.toString() });\n    }\n    case `image/png`:\n    case `image/jpeg`:\n    case `image/webp`: {\n      const imageData = new ImageData(\n        new Uint8ClampedArray(imageTensor.data),\n        width,\n        height\n      );\n      var canvas = createCanvas(imageData.width, imageData.height);\n      var ctx = canvas.getContext('2d')!;\n      ctx.putImageData(imageData, 0, 0);\n      return canvas.convertToBlob({ quality, type: format });\n    }\n    default:\n      throw new Error(`Invalid format: ${format}`);\n  }\n}\n"
  },
  {
    "path": "packages/web/src/index.ts",
    "content": "export * from './api/v1';\n// export * as next from './api/v2';\n"
  },
  {
    "path": "packages/web/src/inference.ts",
    "content": "export { initInference, runInference };\n\nimport { tensorResizeBilinear, tensorHWCtoBCHW } from './utils';\nimport { createOnnxSession, runOnnxSession } from './onnx';\nimport { Config, validateConfig } from './schema';\n\nimport { loadAsBlob } from './resource';\nimport ndarray, { NdArray } from 'ndarray';\nimport { convertFloat32ToUint8 } from './utils';\n\nasync function initBase(config: Config): Promise<unknown> {\n  if (config.debug) console.debug('Loading model...', config.model);\n  const model = config.model;\n  const blob = await loadAsBlob(`/models/${model}`, config);\n  const arrayBuffer = await blob.arrayBuffer();\n  const session = await createOnnxSession(arrayBuffer, config);\n  return session;\n}\n\nasync function initInference(\n  config?: Config\n): Promise<{ config: Config; session: { base: unknown } }> {\n  config = validateConfig(config);\n  const base = await initBase(config);\n  return { config, session: { base } };\n}\n\nasync function runInference(\n  imageTensor: NdArray<Uint8Array>,\n  config: Config,\n  session: { base: unknown }\n): Promise<[NdArray<Uint8Array>, NdArray<Uint8Array>]> {\n  const resolution = 1024;\n  const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;\n  const keepAspect = false;\n\n  let resizedImageTensor = tensorResizeBilinear(\n    imageTensor,\n    resolution,\n    resolution,\n    keepAspect\n  );\n\n  const inputTensor = tensorHWCtoBCHW(resizedImageTensor); // this converts also from float to rgba\n\n  let predictionsDict = await runOnnxSession(\n    session.base,\n    [['input', inputTensor]],\n    ['output'],\n    config\n  );\n\n  let alphamask = ndarray(predictionsDict[0].data, [resolution, resolution, 1]);\n\n  let alphamaskU8 = convertFloat32ToUint8(alphamask);\n  if (config.rescale) {\n    alphamaskU8 = tensorResizeBilinear(\n      alphamaskU8,\n      srcWidth,\n      srcHeight,\n      keepAspect\n    );\n    return [alphamaskU8, imageTensor];\n  } else {\n    return [alphamaskU8, resizedImageTensor];\n  }\n}\n"
  },
  {
    "path": "packages/web/src/onnx.ts",
    "content": "export { createOnnxSession, runOnnxSession };\n\nimport ndarray, { NdArray } from 'ndarray';\nimport { InferenceSession, Tensor } from 'onnxruntime-web';\nimport * as caps from './capabilities';\nimport { loadAsUrl } from './resource';\nimport { Config } from './schema';\n\ntype ORT = typeof import('onnxruntime-web');\n// use a dynamic import to avoid bundling the entire onnxruntime-web package\nlet ort: ORT | null = null;\nconst getOrt = async (useWebGPU: boolean): Promise<ORT> => {\n  if (ort !== null) {\n    return ort;\n  }\n  if (useWebGPU) {\n    ort = (await import('onnxruntime-web/webgpu')).default;\n  } else {\n    ort = (await import('onnxruntime-web')).default;\n  }\n  return ort;\n};\n\nasync function createOnnxSession(model: any, config: Config) {\n  const useWebGPU = config.device === 'gpu' && (await caps.webgpu());\n  // BUG: proxyToWorker is not working for WASM/CPU Backend for now\n  const proxyToWorker = useWebGPU && config.proxyToWorker;\n  const executionProviders = [useWebGPU ? 'webgpu' : 'wasm'];\n  const ort = await getOrt(useWebGPU);\n\n  if (config.debug) {\n    console.debug('\\tUsing WebGPU:', useWebGPU);\n    console.debug('\\tProxy to Worker:', proxyToWorker);\n\n    ort.env.debug = true;\n    ort.env.logLevel = 'verbose';\n  }\n\n  ort.env.wasm.numThreads = caps.maxNumThreads();\n  ort.env.wasm.proxy = proxyToWorker;\n\n  // The path inside the resource bundle\n  const baseFilePath = useWebGPU\n    ? '/onnxruntime-web/ort-wasm-simd-threaded.jsep'\n    : '/onnxruntime-web/ort-wasm-simd-threaded';\n\n  const wasmPath = await loadAsUrl(`${baseFilePath}.wasm`, config);\n  const mjsPath = await loadAsUrl(`${baseFilePath}.mjs`, config);\n\n  ort.env.wasm.wasmPaths = {\n    mjs: mjsPath,\n    wasm: wasmPath\n  };\n\n  if (config.debug) {\n    console.debug('ort.env.wasm:', ort.env.wasm);\n  }\n\n  const ortConfig: InferenceSession.SessionOptions = {\n    executionProviders: executionProviders,\n    graphOptimizationLevel: 'all',\n    executionMode: 'parallel',\n    enableCpuMemArena: true\n  };\n\n  const session = await ort.InferenceSession.create(model, ortConfig).catch(\n    (e: any) => {\n      throw new Error(\n        `Failed to create session: \"${e}\". Please check if the publicPath is set correctly.`\n      );\n    }\n  );\n  return session;\n}\n\nasync function runOnnxSession(\n  session: any,\n  inputs: [string, NdArray<Float32Array>][],\n  outputs: [string],\n  config: Config\n) {\n  const useWebGPU = config.device === 'gpu' && (await caps.webgpu());\n  const ort = await getOrt(useWebGPU);\n\n  const feeds: Record<string, any> = {};\n  for (const [key, tensor] of inputs) {\n    feeds[key] = new ort.Tensor(\n      'float32',\n      new Float32Array(tensor.data),\n      tensor.shape\n    );\n  }\n  const outputData = await session.run(feeds, {});\n  const outputKVPairs: NdArray<Float32Array>[] = [];\n  for (const key of outputs) {\n    const output: Tensor = outputData[key];\n    const shape: number[] = output.dims as number[];\n    const data: Float32Array = output.data as Float32Array;\n    const tensor = ndarray(data, shape);\n    outputKVPairs.push(tensor);\n  }\n\n  return outputKVPairs;\n}\n"
  },
  {
    "path": "packages/web/src/resource.ts",
    "content": "export { loadAsBlob, loadAsUrl, loadAsArrayBuffer, preload, resolveChunkUrls };\n\nimport { Config } from './schema';\n\nasync function preload(config: Config): Promise<void> {\n  // load resource metadata\n  const resourceUrl = new URL('resources.json', config.publicPath);\n  const resourceResponse = await fetch(resourceUrl);\n  if (!resourceResponse.ok) {\n    throw new Error(\n      `Resource metadata not found. Ensure that the config.publicPath is configured correctly: ${config.publicPath}`\n    );\n  }\n  const resourceMap = await resourceResponse.json();\n  const keys = Object.keys(resourceMap);\n\n  await Promise.all(\n    keys.map(async (key) => {\n      return loadAsBlob(key, config);\n    })\n  );\n}\n\nasync function loadAsUrl(url: string, config: Config): Promise<string> {\n  return URL.createObjectURL(await loadAsBlob(url, config));\n}\nasync function loadAsArrayBuffer(\n  url: string,\n  config: Config\n): Promise<ArrayBuffer> {\n  return await (await loadAsBlob(url, config)).arrayBuffer();\n}\n\nasync function loadAsBlob(key: string, config: Config) {\n  // load resource metadata\n  const resourceUrl = new URL('resources.json', config.publicPath);\n  const resourceResponse = await fetch(resourceUrl);\n  if (!resourceResponse.ok) {\n    throw new Error(\n      `Resource metadata not found. Ensure that the config.publicPath is configured correctly.`\n    );\n  }\n  const resourceMap = await resourceResponse.json();\n  const entry = resourceMap[key];\n\n  if (!entry) {\n    throw new Error(\n      `Resource ${key} not found. Ensure that the config.publicPath is configured correctly.`\n    );\n  }\n\n  const chunks = entry.chunks; // list of entries\n\n  let downloadedSize = 0;\n  const responses = chunks.map(async (chunk) => {\n    const chunkSize = chunk.offsets[1] - chunk.offsets[0];\n    const url = config.publicPath\n      ? new URL(chunk.name, config.publicPath).toString()\n      : chunk.name;\n    const response = await fetch(url, config.fetchArgs);\n    const blob = await response.blob();\n\n    if (chunkSize !== blob.size) {\n      throw new Error(\n        `Failed to fetch ${key} with size ${chunkSize} but got ${blob.size}`\n      );\n    }\n\n    if (config.progress) {\n      downloadedSize += chunkSize;\n      config.progress(`fetch:${key}`, downloadedSize, entry.size);\n    }\n    return blob;\n  });\n\n  // we could create a new buffer here and use the chunk entries and combine the file instead\n\n  const allChunkData = await Promise.all(responses);\n\n  const data = new Blob(allChunkData, { type: entry.mime });\n  if (data.size !== entry.size) {\n    throw new Error(\n      `Failed to fetch ${key} with size ${entry.size} but got ${data.size}`\n    );\n  }\n  return data;\n}\n\nasync function resolveChunkUrls(key: string, config: Config) {\n  // load resource metadata\n  const resourceUrl = new URL('resources.json', config.publicPath);\n  const resourceResponse = await fetch(resourceUrl);\n  if (!resourceResponse.ok) {\n    throw new Error(\n      `Resource metadata not found. Ensure that the config.publicPath is configured correctly.`\n    );\n  }\n  const resourceMap = await resourceResponse.json();\n  const entry = resourceMap[key];\n\n  if (!entry) {\n    throw new Error(\n      `Resource ${key} not found. Ensure that the config.publicPath is configured correctly.`\n    );\n  }\n\n  const chunks = entry.chunks; // list of entries\n\n  const responses = chunks.map(async (chunk) => {\n    const url = config.publicPath\n      ? new URL(chunk.name, config.publicPath).toString()\n      : chunk.name;\n\n    return url;\n  });\n  // we could create a new buffer here and use the chunk entries and combine the file instead\n\n  const allUrls = await Promise.all(responses);\n  return allUrls;\n}\n"
  },
  {
    "path": "packages/web/src/schema.ts",
    "content": "export { Config, ConfigSchema, validateConfig };\n\nimport { z } from 'zod';\n\nimport pkg from '../package.json';\n\nconst ConfigSchema = z\n  .object({\n    publicPath: z\n      .string()\n      .optional()\n      .describe('The public path to the wasm files and the onnx model.')\n      .default(\n        'https://staticimgly.com/@imgly/background-removal-data/${PACKAGE_VERSION}/dist/'\n      )\n      .transform((val) => {\n        return val\n          .replace('${PACKAGE_NAME}', pkg.name)\n          .replace('${PACKAGE_VERSION}', pkg.version);\n      }),\n    debug: z\n      .boolean()\n      .default(false)\n      .describe('Whether to enable debug logging.'),\n    rescale: z\n      .boolean()\n      .default(true)\n      .describe('Whether to rescale the image.'),\n    device: z\n      .enum(['cpu', 'gpu'])\n      .default('cpu')\n      .describe('The device to run the model on.'),\n    proxyToWorker: z\n      .boolean()\n      .default(false)\n      .describe('Whether to proxy inference to a web worker.'),\n    fetchArgs: z\n      .any()\n      .default({})\n      .describe('Arguments to pass to fetch when loading the model.'),\n    progress: z\n      .function()\n      .args(z.string(), z.number(), z.number())\n      .returns(z.void())\n      .describe('Progress callback.')\n      .optional(),\n    model: z\n      .preprocess(\n        (val) => {\n          switch (val) {\n            case 'large':\n              return 'isnet';\n            case 'small':\n              return 'isnet_quint8';\n            case 'medium':\n              return 'isnet_fp16';\n            default:\n              return val;\n          }\n        },\n        z.enum(['isnet', 'isnet_fp16', 'isnet_quint8'])\n      )\n      .default('medium'),\n    output: z\n      .object({\n        format: z\n          .enum([\n            'image/png',\n            'image/jpeg',\n            'image/webp',\n            'image/x-rgba8',\n            'image/x-alpha8'\n          ])\n          .default('image/png'),\n        quality: z.number().default(0.8)\n      })\n      .default({})\n  })\n  .default({})\n  .transform((config) => {\n    if (config.debug) console.log('Config:', config);\n    if (config.debug && !config.progress) {\n      config.progress =\n        config.progress ??\n        ((key, current, total) => {\n          console.debug(`Downloading ${key}: ${current} of ${total}`);\n        });\n\n      if (!crossOriginIsolated) {\n        if (config.debug)\n          console.debug(\n            'Cross-Origin-Isolated is not enabled. Performance will be degraded. Please see  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer.'\n          );\n      }\n    }\n\n    return config;\n  });\n\ntype Config = z.infer<typeof ConfigSchema>;\n\nfunction validateConfig(configuration?: Config): Config {\n  return ConfigSchema.parse(configuration ?? {});\n}\n"
  },
  {
    "path": "packages/web/src/types.d.ts",
    "content": "interface Navigator {\n  gpu: any;\n}\n"
  },
  {
    "path": "packages/web/src/url.ts",
    "content": "export { isAbsoluteURI, ensureAbsoluteURI };\n\nfunction isAbsoluteURI(url: string): boolean {\n  const regExp = new RegExp('^(?:[a-z+]+:)?//', 'i');\n  return regExp.test(url); // true - regular http absolute URL\n}\n\nconst isNode = typeof window === 'undefined';\nconst isBrowser = typeof window !== 'undefined';\n\nfunction ensureAbsoluteURI(url: string, baseUrl: string): string {\n  if (isAbsoluteURI(url)) {\n    return url;\n  } else {\n    return new URL(url, baseUrl).href;\n  }\n}\n"
  },
  {
    "path": "packages/web/src/utils.ts",
    "content": "export {\n  imageDecode,\n  imageEncode,\n  tensorResizeBilinear,\n  tensorHWCtoBCHW,\n  imageBitmapToImageData,\n  imageSourceToImageData,\n  type ImageSource,\n  createCanvas\n};\n\nimport ndarray, { NdArray, TypedArray } from 'ndarray';\nimport { imageDecode, imageEncode } from './codecs';\nimport { ensureAbsoluteURI } from './url';\nimport { Config } from './schema';\n\ntype ImageSource =\n  | ImageData\n  | ArrayBuffer\n  | Uint8Array\n  | Blob\n  | URL\n  | string\n  | NdArray<Uint8Array>;\n\nfunction imageBitmapToImageData(imageBitmap: ImageBitmap): ImageData {\n  var canvas = createCanvas(imageBitmap.width, imageBitmap.height);\n  var ctx = canvas.getContext('2d')!;\n  ctx.drawImage(imageBitmap, 0, 0);\n  return ctx.getImageData(0, 0, canvas.width, canvas.height);\n}\n\nfunction createTypeArray<T extends TypedArray>(length: number) {\n  if (typeof Uint8Array !== 'undefined') {\n    return new Uint8Array(length) as T;\n  } else if (typeof Uint8ClampedArray !== 'undefined') {\n    return new Uint8ClampedArray(length) as T;\n  } else if (typeof Uint16Array !== 'undefined') {\n    return new Uint16Array(length) as T;\n  } else if (typeof Uint32Array !== 'undefined') {\n    return new Uint32Array(length) as T;\n  } else if (typeof Float32Array !== 'undefined') {\n    return new Float32Array(length) as T;\n  } else if (typeof Float64Array !== 'undefined') {\n    return new Float64Array(length) as T;\n  } else {\n    throw new Error('TypedArray not supported');\n  }\n}\nfunction tensorResizeBilinear<T extends TypedArray>(\n  imageTensor: NdArray<T>,\n  newWidth: number,\n  newHeight: number,\n  proportional: boolean = false\n): NdArray<T> {\n  const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;\n\n  let scaleX = srcWidth / newWidth;\n  let scaleY = srcHeight / newHeight;\n\n  if (proportional) {\n    const downscaling = Math.max(scaleX, scaleY) > 1.0;\n    scaleX = scaleY = downscaling\n      ? Math.max(scaleX, scaleY)\n      : Math.min(scaleX, scaleY);\n  }\n\n  // Create a new NdArray to store the resized image\n  const resizedImageData = ndarray(\n    createTypeArray<T>(srcChannels * newWidth * newHeight),\n    [newHeight, newWidth, srcChannels]\n  );\n  // Perform interpolation to fill the resized NdArray\n  for (let y = 0; y < newHeight; y++) {\n    for (let x = 0; x < newWidth; x++) {\n      const srcX = x * scaleX;\n      const srcY = y * scaleY;\n      const x1 = Math.max(Math.floor(srcX), 0);\n      const x2 = Math.min(Math.ceil(srcX), srcWidth - 1);\n      const y1 = Math.max(Math.floor(srcY), 0);\n      const y2 = Math.min(Math.ceil(srcY), srcHeight - 1);\n\n      const dx = srcX - x1;\n      const dy = srcY - y1;\n\n      for (let c = 0; c < srcChannels; c++) {\n        const p1 = imageTensor.get(y1, x1, c);\n        const p2 = imageTensor.get(y1, x2, c);\n        const p3 = imageTensor.get(y2, x1, c);\n        const p4 = imageTensor.get(y2, x2, c);\n\n        // Perform bilinear interpolation\n        const interpolatedValue =\n          (1 - dx) * (1 - dy) * p1 +\n          dx * (1 - dy) * p2 +\n          (1 - dx) * dy * p3 +\n          dx * dy * p4;\n        // console.log(interpolatedValue);\n        resizedImageData.set(y, x, c, interpolatedValue);\n      }\n    }\n  }\n\n  return resizedImageData;\n}\n\nfunction tensorHWCtoBCHW(\n  imageTensor: NdArray<Uint8Array>,\n  mean: number[] = [128, 128, 128],\n  std: number[] = [256, 256, 256]\n): NdArray<Float32Array> {\n  var imageBufferData = imageTensor.data;\n  const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;\n  const stride = srcHeight * srcWidth;\n  const float32Data = new Float32Array(3 * stride);\n\n  // r_0, r_1, .... g_0,g_1, .... b_0\n  for (let i = 0, j = 0; i < imageBufferData.length; i += 4, j += 1) {\n    float32Data[j] = (imageBufferData[i] - mean[0]) / std[0];\n    float32Data[j + stride] = (imageBufferData[i + 1] - mean[1]) / std[1];\n    float32Data[j + stride + stride] =\n      (imageBufferData[i + 2] - mean[2]) / std[2];\n  }\n\n  return ndarray(float32Data, [1, 3, srcHeight, srcWidth]);\n}\n\nasync function imageSourceToImageData(\n  image: ImageSource,\n  config: Config\n): Promise<NdArray<Uint8Array>> {\n  if (typeof image === 'string') {\n    image = ensureAbsoluteURI(image, config.publicPath);\n    image = new URL(image);\n  }\n  if (image instanceof URL) {\n    const response = await fetch(image, {});\n    image = await response.blob();\n  }\n  if (image instanceof ArrayBuffer || ArrayBuffer.isView(image)) {\n    image = new Blob([image]);\n  }\n  if (image instanceof Blob) {\n    image = await imageDecode(image);\n  }\n\n  return image as NdArray<Uint8Array>;\n}\nexport function convertFloat32ToUint8(\n  float32Array: NdArray<Float32Array>\n): NdArray<Uint8Array> {\n  const uint8Array = new Uint8Array(float32Array.data.length);\n  for (let i = 0; i < float32Array.data.length; i++) {\n    uint8Array[i] = float32Array.data[i] * 255;\n  }\n  return ndarray(uint8Array, float32Array.shape);\n}\n\nfunction createCanvas(width, height) {\n  let canvas = undefined;\n  if (typeof OffscreenCanvas !== 'undefined') {\n    canvas = new OffscreenCanvas(width, height);\n  } else {\n    canvas = document.createElement('canvas');\n  }\n\n  if (!canvas) {\n    throw new Error(\n      `Canvas nor OffscreenCanvas are available in the current context.`\n    );\n  }\n  return canvas;\n}\n"
  },
  {
    "path": "packages/web/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"lib\": [\"DOM\", \"ESNext\"],\n    \"resolveJsonModule\": true,\n    \"esModuleInterop\": true,\n    \"emitDeclarationOnly\": true,\n    \"declaration\": true,\n    \"allowJs\": true,\n    \"target\": \"ES6\",\n    \"moduleResolution\": \"bundler\",\n    \"module\": \"es2020\"\n  }\n}\n"
  },
  {
    "path": "packages/web-data/.resources.mjs",
    "content": "export default [\n  {\n    path: '/onnxruntime-web/',\n    source:\n      '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm',\n    mime: 'application/wasm'\n  },\n  {\n    path: '/onnxruntime-web/',\n    source:\n      '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.wasm',\n    mime: 'application/wasm'\n  },\n  {\n    path: '/onnxruntime-web/',\n    source:\n      '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.mjs',\n    mime: 'text/javascript'\n  },\n  {\n    path: '/onnxruntime-web/',\n    source:\n      '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.mjs',\n    mime: 'text/javascript'\n  },\n  {\n    path: '/models/',\n    source: '../../bundle/models/*',\n    mime: 'application/octet-steam'\n  }\n];\n"
  },
  {
    "path": "packages/web-data/LICENSE.md",
    "content": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_\n\nEveryone is permitted to copy and distribute verbatim copies\nof this license document, but changing it is not allowed.\n\n## Preamble\n\nThe GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nDevelopers that use our General Public Licenses protect your rights\nwith two steps: **(1)** assert copyright on the software, and **(2)** offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\nA secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate. Many developers of free software are heartened and\nencouraged by the resulting cooperation. However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\nThe GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community. It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server. Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\nAn older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals. This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n## TERMS AND CONDITIONS\n\n### 0. Definitions\n\n“This License” refers to version 3 of the GNU Affero General Public License.\n\n“Copyright” also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n“The Program” refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as “you”. “Licensees” and\n“recipients” may be individuals or organizations.\n\nTo “modify” a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a “modified version” of the\nearlier work or a work “based on” the earlier work.\n\nA “covered work” means either the unmodified Program or a work based\non the Program.\n\nTo “propagate” a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo “convey” a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays “Appropriate Legal Notices”\nto the extent that it includes a convenient and prominently visible\nfeature that **(1)** displays an appropriate copyright notice, and **(2)**\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n### 1. Source Code\n\nThe “source code” for a work means the preferred form of the work\nfor making modifications to it. “Object code” means any non-source\nform of a work.\n\nA “Standard Interface” means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe “System Libraries” of an executable work include anything, other\nthan the work as a whole, that **(a)** is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and **(b)** serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n“Major Component”, in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe “Corresponding Source” for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\nThe Corresponding Source for a work in source code form is that\nsame work.\n\n### 2. Basic Permissions\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n### 3. Protecting Users' Legal Rights From Anti-Circumvention Law\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n### 4. Conveying Verbatim Copies\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n### 5. Conveying Modified Source Versions\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n- **a)** The work must carry prominent notices stating that you modified\n  it, and giving a relevant date.\n- **b)** The work must carry prominent notices stating that it is\n  released under this License and any conditions added under section 7.\n  This requirement modifies the requirement in section 4 to\n  “keep intact all notices”.\n- **c)** You must license the entire work, as a whole, under this\n  License to anyone who comes into possession of a copy. This\n  License will therefore apply, along with any applicable section 7\n  additional terms, to the whole of the work, and all its parts,\n  regardless of how they are packaged. This License gives no\n  permission to license the work in any other way, but it does not\n  invalidate such permission if you have separately received it.\n- **d)** If the work has interactive user interfaces, each must display\n  Appropriate Legal Notices; however, if the Program has interactive\n  interfaces that do not display Appropriate Legal Notices, your\n  work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n“aggregate” if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n### 6. Conveying Non-Source Forms\n\nYou may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n- **a)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by the\n  Corresponding Source fixed on a durable physical medium\n  customarily used for software interchange.\n- **b)** Convey the object code in, or embodied in, a physical product\n  (including a physical distribution medium), accompanied by a\n  written offer, valid for at least three years and valid for as\n  long as you offer spare parts or customer support for that product\n  model, to give anyone who possesses the object code either **(1)** a\n  copy of the Corresponding Source for all the software in the\n  product that is covered by this License, on a durable physical\n  medium customarily used for software interchange, for a price no\n  more than your reasonable cost of physically performing this\n  conveying of source, or **(2)** access to copy the\n  Corresponding Source from a network server at no charge.\n- **c)** Convey individual copies of the object code with a copy of the\n  written offer to provide the Corresponding Source. This\n  alternative is allowed only occasionally and noncommercially, and\n  only if you received the object code with such an offer, in accord\n  with subsection 6b.\n- **d)** Convey the object code by offering access from a designated\n  place (gratis or for a charge), and offer equivalent access to the\n  Corresponding Source in the same way through the same place at no\n  further charge. You need not require recipients to copy the\n  Corresponding Source along with the object code. If the place to\n  copy the object code is a network server, the Corresponding Source\n  may be on a different server (operated by you or a third party)\n  that supports equivalent copying facilities, provided you maintain\n  clear directions next to the object code saying where to find the\n  Corresponding Source. Regardless of what server hosts the\n  Corresponding Source, you remain obligated to ensure that it is\n  available for as long as needed to satisfy these requirements.\n- **e)** Convey the object code using peer-to-peer transmission, provided\n  you inform other peers where the object code and Corresponding\n  Source of the work are being offered to the general public at no\n  charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA “User Product” is either **(1)** a “consumer product”, which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or **(2)** anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, “normally used” refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n“Installation Information” for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n### 7. Additional Terms\n\n“Additional permissions” are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n- **a)** Disclaiming warranty or limiting liability differently from the\n  terms of sections 15 and 16 of this License; or\n- **b)** Requiring preservation of specified reasonable legal notices or\n  author attributions in that material or in the Appropriate Legal\n  Notices displayed by works containing it; or\n- **c)** Prohibiting misrepresentation of the origin of that material, or\n  requiring that modified versions of such material be marked in\n  reasonable ways as different from the original version; or\n- **d)** Limiting the use for publicity purposes of names of licensors or\n  authors of the material; or\n- **e)** Declining to grant rights under trademark law for use of some\n  trade names, trademarks, or service marks; or\n- **f)** Requiring indemnification of licensors and authors of that\n  material by anyone who conveys the material (or modified versions of\n  it) with contractual assumptions of liability to the recipient, for\n  any liability that these contractual assumptions directly impose on\n  those licensors and authors.\n\nAll other non-permissive additional terms are considered “further\nrestrictions” within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n### 8. Termination\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated **(a)**\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and **(b)** permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n### 9. Acceptance Not Required for Having Copies\n\nYou are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n### 10. Automatic Licensing of Downstream Recipients\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn “entity transaction” is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n### 11. Patents\n\nA “contributor” is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's “contributor version”.\n\nA contributor's “essential patent claims” are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, “control” includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a “patent license” is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To “grant” such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either **(1)** cause the Corresponding Source to be so\navailable, or **(2)** arrange to deprive yourself of the benefit of the\npatent license for this particular work, or **(3)** arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. “Knowingly relying” means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is “discriminatory” if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license **(a)** in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or **(b)** primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n### 12. No Surrender of Others' Freedom\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n### 13. Remote Network Interaction; Use with the GNU General Public License\n\nNotwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software. This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n### 14. Revised Versions of this License\n\nThe Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License “or any later version” applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n### 15. Disclaimer of Warranty\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n### 16. Limitation of Liability\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n### 17. Interpretation of Sections 15 and 16\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n_END OF TERMS AND CONDITIONS_\n\n## How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe “copyright” line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source. For example, if your program is a web application, its\ninterface could display a “Source” link that leads users to an archive\nof the code. There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\nYou should also get your employer (if you work as a programmer) or school,\nif any, to sign a “copyright disclaimer” for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n&lt;<http://www.gnu.org/licenses/>&gt;.\n"
  },
  {
    "path": "packages/web-data/ThirdPartyLicenses.json",
    "content": "{\n  \"onnxruntime-web\": {\n    \"source\": \"https://www.npmjs.com/package/onnxruntime-web\",\n    \"type\": \"code\",\n    \"license\": \"MIT\"\n  },\n  \"ISNET\": {\n    \"source\": \"https://github.com/xuebinqin/DIS\",\n    \"type\": \"model\",\n    \"license\": \"MIT\"\n  }\n}\n"
  },
  {
    "path": "packages/web-data/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
    "content": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Added ThirdPartyLicenses.json\n"
  },
  {
    "path": "packages/web-data/changelog/1.5.6/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
    "content": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n  Upgrade onnx-runtime\n"
  },
  {
    "path": "packages/web-data/package.json",
    "content": "{\n  \"name\": \"@imgly/background-removal-data\",\n  \"version\": \"1.7.0\",\n  \"description\": \"Background Removal Data\",\n  \"keywords\": [\n    \"background-removal\",\n    \"image-segmentation\",\n    \"image-matting\",\n    \"onnx\"\n  ],\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/imgly/background-removal-js.git\"\n  },\n  \"license\": \"SEE LICENSE IN LICENSE.md\",\n  \"author\": {\n    \"name\": \"IMG.LY GmbH\",\n    \"email\": \"support@img.ly\",\n    \"url\": \"https://img.ly\"\n  },\n  \"bugs\": {\n    \"email\": \"support@img.ly\"\n  },\n  \"homepage\": \"https://img.ly/showcases/cesdk/web/background-removal\",\n  \"files\": [\n    \"LICENSE.md\",\n    \"README.md\",\n    \"CHANGELOG.md\",\n    \"NOTICE.md\",\n    \"ThirdPartyLicenses.json\",\n    \"dist/\",\n    \"bin/\"\n  ],\n  \"scripts\": {\n    \"start\": \"pnpm run watch\",\n    \"serve\": \"npx http-server dist --cors\",\n    \"clean\": \"npx rimraf dist\",\n    \"test\": \"true\",\n    \"resources\": \"node ../../scripts/package-resources.mjs\",\n    \"changelog:create\": \"node ../../scripts/changelog/changelog-create.mjs\",\n    \"changelog:generate\": \"node ../../scripts/changelog/changelog-generate.mjs\",\n    \"build\": \"pnpm run clean && pnpm run resources\",\n    \"watch\": \"pnpm run clean && pnpm run resources\",\n    \"publish:latest\": \"pnpm publish --tag latest --access public\",\n    \"publish:next\": \"pnpm publish --tag next --access public\",\n    \"package:pack\": \"pnpm pack . --pack-destination ../../releases\"\n  },\n  \"dependencies\": {\n    \"onnxruntime-web\": \"1.21.0-dev.20250206-d981b153d3\"\n  }\n}"
  },
  {
    "path": "packages/web-examples/next-example/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.*\n.yarn/*\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/versions\n\n# testing\n/coverage\n\n# next.js\n/.next/\n/out/\n\n# production\n/build\n\n# misc\n.DS_Store\n*.pem\n\n# debug\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n.pnpm-debug.log*\n\n# env files (can opt-in for committing if needed)\n.env*\n\n# vercel\n.vercel\n\n# typescript\n*.tsbuildinfo\nnext-env.d.ts\n"
  },
  {
    "path": "packages/web-examples/next-example/README.md",
    "content": "This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).\n\n## Getting Started\n\nFirst, run the development server:\n\n```bash\nnpm run dev\n# or\nyarn dev\n# or\npnpm dev\n# or\nbun dev\n```\n\nOpen [http://localhost:3000](http://localhost:3000) with your browser to see the result.\n\nYou can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.\n\nThis project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.\n\n## Learn More\n\nTo learn more about Next.js, take a look at the following resources:\n\n- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.\n- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.\n\nYou can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!\n\n## Deploy on Vercel\n\nThe easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.\n\nCheck out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.\n"
  },
  {
    "path": "packages/web-examples/next-example/eslint.config.mjs",
    "content": "import { dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { FlatCompat } from '@eslint/eslintrc';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst compat = new FlatCompat({\n  baseDirectory: __dirname\n});\n\nconst eslintConfig = [\n  ...compat.extends('next/core-web-vitals', 'next/typescript')\n];\n\nexport default eslintConfig;\n"
  },
  {
    "path": "packages/web-examples/next-example/next.config.ts",
    "content": "import type { NextConfig } from 'next';\n\nconst nextConfig: NextConfig = {\n  /* config options here */\n};\n\nexport default nextConfig;\n"
  },
  {
    "path": "packages/web-examples/next-example/package.json",
    "content": "{\n  \"name\": \"next-example\",\n  \"version\": \"1.7.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next build\",\n    \"start\": \"next start\",\n    \"check:all\": \"next lint\"\n  },\n  \"dependencies\": {\n    \"@cesdk/cesdk-js\": \"^1.41.1\",\n    \"next\": \"15.1.3\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"@imgly/background-removal\": \"workspace:*\",\n    \"onnxruntime-web\": \"1.21.0\"\n  },\n  \"devDependencies\": {\n    \"@eslint/eslintrc\": \"^3\",\n    \"@types/node\": \"^20\",\n    \"@types/react\": \"^19\",\n    \"@types/react-dom\": \"^19\",\n    \"eslint\": \"^9\",\n    \"eslint-config-next\": \"15.1.3\",\n    \"typescript\": \"^5\"\n  }\n}"
  },
  {
    "path": "packages/web-examples/next-example/src/app/BackgroundRemoval.tsx",
    "content": "'use client';\n\nimport {\n  applySegmentationMask,\n  Config,\n  preload,\n  removeBackground,\n  segmentForeground\n} from '@imgly/background-removal';\nimport { useEffect, useRef, useState } from 'react';\n\nconst images = [\n  'https://images.unsplash.com/photo-1656408308602-05835d990fb1?q=80&w=3200&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D',\n  'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1024&q=80',\n  'https://images.unsplash.com/photo-1590523278191-995cbcda646b?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9',\n  'https://images.unsplash.com/photo-1709248835088-03bb0946d6ab?q=80&w=3387&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'\n];\n\nconst BackgroundRemoval = () => {\n  const [imageUrl, setImageUrl] = useState('');\n  const [isRunning, setIsRunning] = useState(false);\n  const [seconds, setSeconds] = useState('0');\n  const [startDate, setStartDate] = useState(Date.now());\n  const [caption, setCaption] = useState('Click me to remove background');\n  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);\n\n  const config: Config = {\n    debug: false,\n    progress: (key, current, total) => {\n      const [type, subtype] = key.split(':');\n      setCaption(`${type} ${subtype} ${((current / total) * 100).toFixed(0)}%`);\n    },\n    rescale: true,\n    device: 'gpu',\n    output: {\n      quality: 0.8,\n      format: 'image/png'\n    }\n  };\n\n  const calculateSecondsBetweenDates = (start: number, end: number) => {\n    const milliseconds = end - start;\n    return (milliseconds / 1000.0).toFixed(1);\n  };\n\n  useEffect(() => {\n    const url = new URL(window.location.href);\n    const params = new URLSearchParams(url.search);\n    const imageParam = params.get('image');\n    const auto = params.get('auto') || false;\n\n    const randomImage =\n      imageParam || images[Math.floor(Math.random() * images.length)];\n    setImageUrl(randomImage);\n\n    const preloadAssets = async () => {\n      try {\n        await preload(config);\n        console.log('Asset preloading succeeded');\n        if (auto) load('remove');\n      } catch (error) {\n        console.error('Asset preloading failed:', error);\n      }\n    };\n\n    preloadAssets();\n\n    return () => {\n      if (intervalRef.current) {\n        clearInterval(intervalRef.current);\n      }\n    };\n  }, []);\n\n  useEffect(() => {\n    if (isRunning) {\n      intervalRef.current = setInterval(() => {\n        setSeconds(calculateSecondsBetweenDates(startDate, Date.now()));\n      }, 100);\n    } else if (intervalRef.current) {\n      clearInterval(intervalRef.current);\n    }\n\n    return () => {\n      if (intervalRef.current) {\n        clearInterval(intervalRef.current);\n      }\n    };\n  }, [isRunning, startDate]);\n\n  const resetTimer = () => {\n    setIsRunning(true);\n    setStartDate(Date.now());\n    setSeconds('0');\n  };\n\n  const stopTimer = () => {\n    setIsRunning(false);\n  };\n\n  const load = async (type: string) => {\n    const params = new URLSearchParams(window.location.search);\n    const imageParam = params.get('image');\n    const randomImage =\n      imageParam || images[Math.floor(Math.random() * images.length)];\n\n    setIsRunning(true);\n    resetTimer();\n    setImageUrl(randomImage);\n\n    try {\n      let imageBlob;\n      if (type === 'remove') {\n        imageBlob = await removeBackground(randomImage, config);\n      } else {\n        const maskBlob = await segmentForeground(randomImage, config);\n        imageBlob = await applySegmentationMask(randomImage, maskBlob, config);\n      }\n\n      const url = URL.createObjectURL(imageBlob);\n      setImageUrl(url);\n    } catch (error) {\n      console.error('Processing failed:', error);\n      setCaption('Processing failed');\n    } finally {\n      setIsRunning(false);\n      stopTimer();\n    }\n  };\n\n  return (\n    <div id=\"app\">\n      <header>\n        {/* // eslint-disable-next-line @next/next/no-img-element */}\n        {imageUrl && <img src={imageUrl} alt=\"logo\" />}\n        <p>{caption}</p>\n        <p>Processing: {seconds} s</p>\n        <button disabled={isRunning} onClick={() => load('remove')}>\n          Click me (removeBackground)\n        </button>\n        <button disabled={isRunning} onClick={() => load('segment')}>\n          Click me (applySegmentationMask)\n        </button>\n      </header>\n    </div>\n  );\n};\n\nexport default BackgroundRemoval;\n"
  },
  {
    "path": "packages/web-examples/next-example/src/app/BackgroundRemovalNoSSR.tsx",
    "content": "'use client';\nimport dynamic from 'next/dynamic';\n\nconst BackgroundRemovalNoSSR = dynamic(() => import('./BackgroundRemoval'), {\n  ssr: false\n});\n\nexport default BackgroundRemovalNoSSR;\n"
  },
  {
    "path": "packages/web-examples/next-example/src/app/globals.css",
    "content": ":root {\n  --background: #ffffff;\n  --foreground: #171717;\n}\n\n@media (prefers-color-scheme: dark) {\n  :root {\n    --background: #0a0a0a;\n    --foreground: #ededed;\n  }\n}\n\nhtml,\nbody {\n  max-width: 100vw;\n  overflow-x: hidden;\n}\n\nbody {\n  color: var(--foreground);\n  background: var(--background);\n  font-family: Arial, Helvetica, sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\n* {\n  box-sizing: border-box;\n  padding: 0;\n  margin: 0;\n}\n\na {\n  color: inherit;\n  text-decoration: none;\n}\n\n@media (prefers-color-scheme: dark) {\n  html {\n    color-scheme: dark;\n  }\n}\n\na {\n  font-weight: 500;\n  color: #646cff;\n  text-decoration: inherit;\n}\n\na:hover {\n  color: #535bf2;\n}\n\nimg {\n  max-height: 60vh;\n}\n\nbody {\n  margin: 0;\n  display: flex;\n  place-items: center;\n  /* min-width: 320px; */\n  /* max-height: 1vh; */\n}\n\nh1 {\n  font-size: 3.2em;\n  line-height: 1.1;\n}\n\nbutton {\n  border-radius: 8px;\n  border: 1px solid transparent;\n  padding: 0.6em 1.2em;\n  font-size: 1em;\n  font-weight: 500;\n  font-family: inherit;\n  background-color: #1a1a1a;\n  cursor: pointer;\n  transition: border-color 0.25s;\n}\n\nbutton:hover {\n  border-color: #646cff;\n}\n\nbutton:focus,\nbutton:focus-visible {\n  outline: 4px auto -webkit-focus-ring-color;\n}\n\n.card {\n  padding: 2em;\n}\n\n#app {\n  margin: 0 auto;\n  padding: 2rem;\n  text-align: center;\n}\n\n@media (prefers-color-scheme: light) {\n  :root {\n    color: #213547;\n    background-color: #ffffff;\n  }\n\n  a:hover {\n    color: #747bff;\n  }\n\n  button {\n    background-color: #f9f9f9;\n  }\n}\n"
  },
  {
    "path": "packages/web-examples/next-example/src/app/layout.tsx",
    "content": "import type { Metadata } from 'next';\nimport './globals.css';\n\nexport const metadata: Metadata = {\n  title: 'Create Next App',\n  description: 'Generated by create next app'\n};\n\nexport default function RootLayout({\n  children\n}: Readonly<{\n  children: React.ReactNode;\n}>) {\n  return (\n    <html lang=\"en\">\n      <body>{children}</body>\n    </html>\n  );\n}\n"
  },
  {
    "path": "packages/web-examples/next-example/src/app/page.tsx",
    "content": "import BackgroundRemovalNoSSR from './BackgroundRemovalNoSSR';\n\nexport default function Home() {\n  return <BackgroundRemovalNoSSR />;\n}\n"
  },
  {
    "path": "packages/web-examples/next-example/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2017\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"noEmit\": true,\n    \"esModuleInterop\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"bundler\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"preserve\",\n    \"incremental\": true,\n    \"plugins\": [\n      {\n        \"name\": \"next\"\n      }\n    ],\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  },\n  \"include\": [\"next-env.d.ts\", \"**/*.ts\", \"**/*.tsx\", \".next/types/**/*.ts\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "packages/web-examples/vite-project/.gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndist-ssr\n*.local\n\n# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n"
  },
  {
    "path": "packages/web-examples/vite-project/.vercel/README.txt",
    "content": "> Why do I have a folder named \".vercel\" in my project?\nThe \".vercel\" folder is created when you link a directory to a Vercel project.\n\n> What does the \"project.json\" file contain?\nThe \"project.json\" file contains:\n- The ID of the Vercel project that you linked (\"projectId\")\n- The ID of the user or team your Vercel project is owned by (\"orgId\")\n\n> Should I commit the \".vercel\" folder?\nNo, you should not share the \".vercel\" folder with anyone.\nUpon creation, it will be automatically added to your \".gitignore\" file.\n"
  },
  {
    "path": "packages/web-examples/vite-project/.vercel/project.json",
    "content": "{\n  \"orgId\": \"team_JFznad5UXNe4xKmEfdbZq5jl\",\n  \"projectId\": \"prj_jLTn0qO7rU5v6MEyaNREE9gIk3l2\"\n}\n"
  },
  {
    "path": "packages/web-examples/vite-project/README.md",
    "content": "# Vue 3 + TypeScript + Vite\n\nThis template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.\n\n## Recommended IDE Setup\n\n- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).\n\n## Type Support For `.vue` Imports in TS\n\nTypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.\n\nIf the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:\n\n1. Disable the built-in TypeScript Extension\n   1. Run `Extensions: Show Built-in Extensions` from VSCode's command palette\n   2. Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`\n2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.\n"
  },
  {
    "path": "packages/web-examples/vite-project/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite + Vue + TS</title>\n  </head>\n  <body>\n    <div id=\"app\"></div>\n    <script type=\"module\" src=\"/src/main.ts\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "packages/web-examples/vite-project/package.json",
    "content": "{\n  \"name\": \"vite-project\",\n  \"private\": true,\n  \"version\": \"1.7.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"start\": \"pnpm run dev\",\n    \"dev\": \"vite\",\n    \"build\": \"vue-tsc && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@imgly/background-removal\": \"workspace:*\",\n    \"@imgly/background-removal-data\": \"workspace:*\",\n    \"vue\": \"^3.2.47\",\n    \"onnxruntime-web\": \"1.21.0\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^4.1.0\",\n    \"typescript\": \"^5.0.2\",\n    \"vite\": \"^4.3.9\",\n    \"vue-tsc\": \"^1.4.2\"\n  }\n}"
  },
  {
    "path": "packages/web-examples/vite-project/src/App.vue",
    "content": "<script>\nimport { ref, watch, onMounted, onUnmounted } from 'vue';\n\nimport {\n  preload,\n  removeBackground,\n  removeForeground,\n  segmentForeground,\n  alphamask,\n  applySegmentationMask\n} from '@imgly/background-removal';\n\nexport default {\n  name: 'App',\n  setup() {\n    const images = [\n      'https://images.unsplash.com/photo-1656408308602-05835d990fb1?q=80&w=3200&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D',\n      'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1024&q=80',\n      'https://images.unsplash.com/photo-1590523278191-995cbcda646b?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9',\n      'https://images.unsplash.com/photo-1709248835088-03bb0946d6ab?q=80&w=3387&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'\n    ];\n\n    const url = new URL(window.location.href);\n    const params = new URLSearchParams(url.search);\n    const image = params.get('image');\n    const auto = params.get('auto') || false;\n    const randomImage = image\n      ? image\n      : images[Math.floor(Math.random() * images.length)];\n\n    const imageUrl = ref(randomImage);\n    const isRunning = ref(false);\n    const seconds = ref(0);\n    const startDate = ref(Date.now());\n    const caption = ref('Click me to remove background');\n    let interval = null;\n\n    const publicPath = new URL(import.meta.url);\n    publicPath.pathname = '/js/';\n    const config = {\n      debug: false,\n      publicPath: publicPath.href,\n      progress: (key, current, total) => {\n        const [type, subtype] = key.split(':');\n        caption.value = `${type} ${subtype} ${((current / total) * 100).toFixed(\n          0\n        )}%`;\n      },\n      // rescale: false,\n      rescale: true,\n      device: 'gpu',\n      // device: 'cpu',\n      // model: 'isnet',\n      // model: 'isnet_fp16',\n      // model: 'isnet_quint8',\n      output: {\n        quality: 0.8,\n        format: 'image/png'\n        // format: 'image/jpeg'\n        // format: 'image/webp'\n        //format: 'image/x-rgba8'\n        //format: 'image/x-alpha8'\n      }\n    };\n\n    const calculateSecondsBetweenDates = (startDate, endDate) => {\n      const milliseconds = endDate - startDate;\n      const seconds = (milliseconds / 1000.0).toFixed(1);\n      return seconds;\n    };\n\n    watch(\n      () => isRunning.value,\n      (newVal) => {\n        if (newVal) {\n          interval = setInterval(() => {\n            seconds.value = calculateSecondsBetweenDates(\n              startDate.value,\n              Date.now()\n            );\n          }, 100);\n        } else {\n          clearInterval(interval);\n        }\n      }\n    );\n\n    onMounted(async () => {\n      // Optional Preload all assets\n      await preload(config).then(() => {\n        console.log('Asset preloading succeeded');\n      });\n      if (isRunning.value) {\n        interval = setInterval(() => {\n          seconds.value = calculateSecondsBetweenDates(\n            startDate.value,\n            Date.now()\n          );\n        }, 100);\n      }\n    });\n\n    onUnmounted(() => {\n      clearInterval(interval);\n    });\n\n    const resetTimer = () => {\n      isRunning.value = true;\n      startDate.value = Date.now();\n      seconds.value = 0;\n    };\n\n    const stopTimer = () => {\n      isRunning.value = false;\n    };\n\n    const load = async (type) => {\n      const randomImage = image\n        ? image\n        : images[Math.floor(Math.random() * images.length)];\n\n      isRunning.value = true;\n      resetTimer();\n\n      imageUrl.value = randomImage;\n      let imageBlob;\n      if (type === 'remove') {\n        imageBlob = await removeBackground(randomImage, config);\n      } else {\n        const maskBlob = await segmentForeground(randomImage, config);\n        console.log(maskBlob);\n        imageBlob = await applySegmentationMask(randomImage, maskBlob, config);\n      }\n      console.log(imageBlob);\n\n      // const imageBlob = await removeBackground(randomImage, config);\n      // const imageBlob = await alphamask(randomImage, config)\n      // const maskBlob = await trimap(randomImage, config)\n      // const imageBlob = await removeForeground(randomImage, config);\n      // const imageBlob = await segmentForeground(randomImage, config);\n\n      const url = URL.createObjectURL(imageBlob);\n      imageUrl.value = url;\n      isRunning.value = false;\n      stopTimer();\n    };\n\n    if (auto) load();\n\n    return { imageUrl, isRunning, seconds, caption, load };\n  }\n};\n</script>\n\n<style scoped>\n/* Add your styles here */\n</style>\n\n<template>\n  <div id=\"app\">\n    <header>\n      <img :src=\"imageUrl\" alt=\"logo\" />\n      <p>{{ caption }}</p>\n      <p>Processing: {{ seconds }} s</p>\n\n      <button :disabled=\"isRunning\" @click=\"load('remove')\">\n        Click me (removeBackground)\n      </button>\n      <button :disabled=\"isRunning\" @click=\"load('segment')\">\n        Click me (applySegmentationMask)\n      </button>\n    </header>\n  </div>\n</template>\n\n<style scoped>\n.logo {\n  height: 6em;\n  padding: 1.5em;\n  will-change: filter;\n  transition: filter 300ms;\n}\n\n.logo:hover {\n  filter: drop-shadow(0 0 2em #646cffaa);\n}\n\n.logo.vue:hover {\n  filter: drop-shadow(0 0 2em #42b883aa);\n}\n\nbutton:not(:last-child) {\n  margin-right: 1em;\n}\n</style>\n"
  },
  {
    "path": "packages/web-examples/vite-project/src/main.ts",
    "content": "import { createApp } from 'vue';\nimport './style.css';\nimport App from './App.vue';\n\ncreateApp(App).mount('#app');\n"
  },
  {
    "path": "packages/web-examples/vite-project/src/style.css",
    "content": ":root {\n  font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;\n  line-height: 1.5;\n  font-weight: 400;\n\n  color-scheme: light dark;\n  color: rgba(255, 255, 255, 0.87);\n  background-color: #242424;\n\n  font-synthesis: none;\n  text-rendering: optimizeLegibility;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n  -webkit-text-size-adjust: 100%;\n}\n\na {\n  font-weight: 500;\n  color: #646cff;\n  text-decoration: inherit;\n}\na:hover {\n  color: #535bf2;\n}\n\nimg {\n  max-height: 60vh;\n}\nbody {\n  margin: 0;\n  display: flex;\n  place-items: center;\n  /* min-width: 320px; */\n  /* max-height: 1vh; */\n}\n\nh1 {\n  font-size: 3.2em;\n  line-height: 1.1;\n}\n\nbutton {\n  border-radius: 8px;\n  border: 1px solid transparent;\n  padding: 0.6em 1.2em;\n  font-size: 1em;\n  font-weight: 500;\n  font-family: inherit;\n  background-color: #1a1a1a;\n  cursor: pointer;\n  transition: border-color 0.25s;\n}\nbutton:hover {\n  border-color: #646cff;\n}\nbutton:focus,\nbutton:focus-visible {\n  outline: 4px auto -webkit-focus-ring-color;\n}\n\n.card {\n  padding: 2em;\n}\n\n#app {\n  margin: 0 auto;\n  padding: 2rem;\n  text-align: center;\n}\n\n@media (prefers-color-scheme: light) {\n  :root {\n    color: #213547;\n    background-color: #ffffff;\n  }\n  a:hover {\n    color: #747bff;\n  }\n  button {\n    background-color: #f9f9f9;\n  }\n}\n"
  },
  {
    "path": "packages/web-examples/vite-project/src/vite-env.d.ts",
    "content": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "packages/web-examples/vite-project/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"module\": \"ESNext\",\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"skipLibCheck\": true,\n    \"allowJs\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"preserve\",\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true\n  },\n  \"include\": [\"src/**/*.ts\", \"src/**/*.d.ts\", \"src/**/*.tsx\", \"src/**/*.vue\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "packages/web-examples/vite-project/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "packages/web-examples/vite-project/vite.config.ts",
    "content": "import { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  server: {\n    headers: {\n      'Cross-Origin-Opener-Policy': 'same-origin',\n      'Cross-Origin-Embedder-Policy': 'require-corp'\n    }\n  }\n});\n"
  },
  {
    "path": "pnpm-workspace.yaml",
    "content": "packages:\n  - packages/*\n  - packages/web-examples/*\nonlyBuiltDependencies:\n  - esbuild\n  - onnxruntime-node\n  - protobufjs\n  - sharp\n"
  },
  {
    "path": "scripts/changelog/changelog-create.mjs",
    "content": "#!/usr/bin/env node\n\nimport moment from 'moment';\nimport ejs from 'ejs';\nimport meow from 'meow';\nimport chalk from 'chalk';\nimport esMain from 'es-main';\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { dirname } from 'node:path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst AllowedTypes = ['Added', 'Changed', 'Removed', 'Security'];\n\nconst scriptName = process.argv[1].split(path.sep).pop();\n\nconst flags = {\n  message: {\n    type: 'string',\n    shortFlag: 'm',\n    isMultiple: false,\n    description: 'Message for the changelog entry'\n  },\n  version: {\n    type: 'boolean',\n    shortFlag: 'v',\n    isMultiple: false,\n    description: 'Show version number'\n  },\n  help: {\n    type: 'boolean',\n    shortFlag: 'h',\n    isMultiple: false,\n    description: 'Display this help message'\n  },\n  type: {\n    type: 'string',\n    shortFlag: 't',\n    default: 'Added',\n    isMultiple: false,\n    choices: ['Added', 'Changed', 'Removed', 'Security'],\n    description: `Type of the changelog entry`\n  }\n};\n\nconst examples = [\n  { prompt: `name` },\n  { prompt: `name --message \"Message\"` },\n  { prompt: `name --type \"Added\"` },\n  { prompt: `name --help` },\n  { prompt: `name --version` }\n];\n\nfunction parseStringToArgs(str) {\n  return str.match(/(?:[^\\s\"]+|\"[^\"]*\")+/g);\n}\n\nfunction parseExample(prompt) {\n  const args = parseStringToArgs(prompt);\n  const parser = meow('', {\n    argv: args,\n    importMeta: import.meta,\n    flags\n  });\n}\nfunction parsePrompt(prompt, flags) {\n  // how do I parse the prompt\n  const inputArgs =\n    prompt instanceof Array ? prompt : parseStringToArgs(prompt);\n\n  const flagText = (str) => chalk.yellow(str);\n  const exampleText = (str) => chalk.white(str);\n\n  const cliOptionsText = (flags, padding = 16) => {\n    const lines = [];\n    for (const [key, value] of Object.entries(flags)) {\n      const {\n        type,\n        shortFlag,\n        description,\n        default: defaultValue,\n        choices\n      } = value;\n      const defaultText = defaultValue\n        ? chalk.white(` (default: ${defaultValue})`)\n        : '';\n      const choicesText = choices\n        ? chalk.white(` [choices: ${choices.join(', ')}]`)\n        : '';\n      lines.push(\n        `${flagText(\n          `--${key}, -${shortFlag}`.padEnd(padding)\n        )}  ${description}${defaultText}${choicesText}`\n      );\n    }\n    return lines.join('\\n      ');\n  };\n\n  const cliUsageText = (flags) => {\n    const lines = [];\n    for (const [key, value] of Object.entries(flags)) {\n      const { type, shortFlag, description, default: defaultValue } = value;\n\n      const valueStr = type === 'string' ? `=<${key}>` : '';\n\n      const flagStr = `[${flagText(\n        `--${key}${valueStr} | -${shortFlag}${valueStr}`\n      )}]`;\n      lines.push(flagStr);\n    }\n    return lines.join(' ');\n  };\n\n  const cli = meow(\n    `\n    Usage\n      $ ${chalk.white(scriptName)} name ${cliUsageText(flags)}\n\n    Options\n      ${cliOptionsText(flags)}\n      \n    Examples\n      $ ${exampleText(scriptName)} name\n      $ ${exampleText(scriptName)} name ${flagText('--message')} \"Message\"\n      $ ${exampleText(scriptName)} ${flagText('--message')} \"Message\"\n      $ ${exampleText(scriptName)} ${flagText('--type')} \"Added\"\n      $ ${exampleText(scriptName)} ${flagText('--help')}\n      $ ${exampleText(scriptName)} ${flagText('--version')}\n  `,\n    {\n      argv: inputArgs.slice(2),\n      importMeta: import.meta,\n      flags\n    }\n  );\n  if (!flags.type.choices.includes(cli.flags.type)) {\n    console.error(`Invalid type: ${cli.flags.type}`);\n    console.error(`Allowed types are: ${flags.type.choices.join(', ')}`);\n    cli.showHelp();\n    process.exit(1);\n  }\n\n  return cli;\n}\n\nfunction main(argv) {\n  try {\n    const cli = parsePrompt(argv, flags);\n\n    if (cli.flags.help) {\n      cli.showHelp();\n      process.exit();\n    }\n    if (cli.flags.version) {\n      console.log('1.0.0');\n      process.exit();\n    }\n\n    const version = 'Unreleased';\n    const type = cli.flags.type;\n    const templatePath = path.resolve(__dirname, 'template.yml.ejs');\n    const changeLogDir = path.resolve('./changelog', `${version}`);\n\n    const input = cli.input.join(' ');\n\n    if (!input || input.length === 0) {\n      cli.showHelp();\n      process.exit();\n    }\n\n    const message = cli.flags.message || cli.input.join(' ');\n    const name = cli.input.join(' ').replace(/(\\W+)/gi, '_');\n\n    const dateFormat = 'YYYYDDMMHHmmss';\n\n    const date = Date.now();\n    const prefix = moment(date).format(dateFormat);\n    const filename = `${prefix}-${name}.yaml`;\n\n    const outFilePath = path.resolve(changeLogDir, filename);\n    fs.mkdirSync(changeLogDir, { recursive: true });\n\n    const template = fs.readFileSync(templatePath, 'utf-8');\n    const data = { message, type };\n    const renderedTemplate = ejs.render(template, data);\n\n    fs.writeFileSync(outFilePath, renderedTemplate);\n\n    console.info(`${chalk.grey(outFilePath)} has been created successfully.`);\n  } catch (error) {\n    console.error(chalk.red(error.message));\n    process.exit(1);\n  }\n}\n\nif (esMain(import.meta)) {\n  main(process.argv);\n}\n\nexport { main };\n"
  },
  {
    "path": "scripts/changelog/changelog-generate.mjs",
    "content": "#!/usr/bin/env node\n\n/**\n * https://keepachangelog.com/en/1.1.0/\n * Idea is simple we have a directory of yaml files. The subdirectory defines the version name.\n */\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { dirname } from 'node:path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nimport yaml from 'yaml';\n\nconst types = ['Infos', 'Added', 'Fixed', 'Removed', 'Changed', 'Security'];\n\nconst changeLogDir = path.resolve('./changelog');\n\nconst enumerateFilesInDirectory = (dir) => {\n  return fs\n    .readdirSync(dir)\n    .map((entry) => {\n      const fullPath = path.join(dir, entry);\n      const stat = fs.statSync(fullPath);\n      if (stat.isFile()) {\n        return fullPath;\n      }\n      return null;\n    })\n    .filter((entry) => entry !== null);\n};\n\nconst enumerateDirectoriesInDirectory = (dir) => {\n  return fs\n    .readdirSync(dir)\n    .map((entry) => {\n      const fullPath = path.join(dir, entry);\n      const stat = fs.statSync(fullPath);\n      if (stat.isDirectory()) {\n        return entry;\n      }\n      return null;\n    })\n    .filter((entry) => entry !== null);\n};\n\nfunction parseChangelogItems(entries) {\n  const changelog = {};\n  entries.forEach((entry) => {\n    const fileContent = fs.readFileSync(entry, 'utf8');\n    const changelogItems = yaml.parseAllDocuments(fileContent);\n    changelogItems.forEach((document) => {\n      const changelogItem = document.toJS();\n      const { type = 'Infos', description } = changelogItem;\n\n      if (changelogItem.private) return;\n\n      if (!(type in changelog)) {\n        changelog[type] = [];\n      }\n      const message = `${description}`;\n      changelog[type].push(message);\n    });\n  });\n  return changelog;\n}\n\n// Write file\nconst outFile = path.resolve('./CHANGELOG.md');\nconst outStream = fs.createWriteStream(outFile, { encoding: 'utf8' });\n\n// Root entries\nconst entries = enumerateFilesInDirectory(changeLogDir);\nconst changelogItems = parseChangelogItems(entries);\n\noutStream.write(`# Changelog\\n\\n`);\n\nchangelogItems['Infos']?.forEach((info) => {\n  outStream.write(`${info}\\n`);\n});\n\nconst versionSorter = (a, b) => {\n  return a < b ? +1 : -1;\n};\n\nconst versions = enumerateDirectoriesInDirectory(changeLogDir)\n  .map((directory) => path.basename(directory))\n  .sort(versionSorter);\n\nversions.forEach((version) => {\n  const versionDir = path.join(changeLogDir, version);\n  const entries = enumerateFilesInDirectory(versionDir);\n  const changelogItems = parseChangelogItems(entries);\n\n  const hasItems = Object.keys(changelogItems).length > 0;\n  hasItems && outStream.write(`## [${version}]\\n\\n`);\n  types.forEach((type) => {\n    if (changelogItems[type]) {\n      const messages = changelogItems[type];\n      if (type === 'Infos') {\n        messages.forEach((message) => {\n          outStream.write(`${message}\\n`);\n        });\n      } else {\n        outStream.write(`### ${type}\\n\\n`);\n        messages.forEach((message) => {\n          outStream.write(`- ${message}\\n`);\n        });\n      }\n      // outStream.write(`\\n`)\n    }\n  });\n});\n\noutStream.end();\n"
  },
  {
    "path": "scripts/changelog/template.yml.ejs",
    "content": "---\ntype: <%= type %>\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n    <%= message %>\n"
  },
  {
    "path": "scripts/deploy-assets.mjs",
    "content": "import chalk from 'chalk';\nimport { exec } from 'child_process';\nimport { readFile } from 'node:fs/promises';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nconst execAsyncWithErrors = async (command, options) => {\n  try {\n    const { stdout, stderr } = await execAsync(command, options);\n  } catch (error) {\n    throw error;\n  }\n};\n\nasync function syncToS3() {\n  try {\n    // Load package.json\n    const packageJson = JSON.parse(await readFile('./package.json', 'utf8'));\n    const version = process.argv[2] || packageJson.version;\n\n    if (!version || version === 'next') {\n      throw new Error(`Version \"${version}\" is invalid.`);\n    }\n\n    // Get the endpoint URL from an environment variable\n    const endpointUrl = process.env.S3_ENDPOINT_URL;\n    if (!endpointUrl) {\n      throw new Error('S3_ENDPOINT_URL environment variable is not set.');\n    }\n    const bucketName = process.env.S3_BUCKET_NAME;\n    if (!bucketName) {\n      throw new Error('S3_BUCKET_NAME environment variable is not set.');\n    }\n\n    const packageNames = {\n      'packages/node': '@imgly/background-removal-node',\n      'packages/web': '@imgly/background-removal',\n      'packages/web-data': '@imgly/background-removal-data'\n    };\n\n    await Promise.allSettled(\n      Object.entries(packageNames).map(async ([path, packageName]) => {\n        console.error(\n          `${chalk.red(\n            `NOTE: Syncing might fail when aws client ist not installed nor configured in silence!`\n          )}`\n        );\n        // cwd based on package name:\n        const cwd = path;\n        // npm packing:\n        await execAsyncWithErrors(\n          `rm -rf ./${path}/tmp && mkdir -p ./${path}/tmp`\n        );\n        // we pack the package to also publish the package.tgz to s3\n        const packCommand = `npm pack . --pack-destination ./tmp`;\n        console.log(`Packing ${packageName} using ${packCommand}...`);\n        await execAsyncWithErrors(packCommand, { cwd });\n        // rename the .tgz from e.g imgly-background-removal-data-1.5.3.tgz to package.tgz to have a stable name\n        await execAsyncWithErrors('mv ./tmp/*.tgz ./tmp/package.tgz', { cwd });\n        // npm extract:\n        const extractCommand = `tar -xvzf ./tmp/* -C ./tmp --strip-components=1`;\n        console.log(`Extracting ${packageName} using ${extractCommand}...`);\n        await execAsyncWithErrors(extractCommand, { cwd });\n        // sync to s3:\n        console.log(`Syncing ${packageName} to S3...`);\n        const command = `aws s3 sync --endpoint-url ${endpointUrl} ./${path}/tmp s3://${bucketName}/${packageName}/${version}`;\n        console.log(`Command: ${command}`);\n        return await execAsyncWithErrors(command);\n      })\n    );\n\n    console.log('S3 sync complete.');\n  } catch (error) {\n    console.error('Error during S3 sync:', error);\n  }\n}\n\nsyncToS3();\n"
  },
  {
    "path": "scripts/package-resources.mjs",
    "content": "export default main;\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { globSync } from 'glob';\n\n// All paths are relative to the directory of this file\nconst BaseDir = path.resolve('.');\nconst DefaultOutDir = path.resolve('./dist');\nconst DefaultEntry = {\n  mime: 'application/octet-stream'\n};\n\nasync function calculateSHA256(filePath) {\n  return new Promise((resolve, reject) => {\n    const hash = crypto.createHash('sha256');\n    const stream = fs.createReadStream(filePath);\n\n    stream.on('data', (data) => hash.update(data));\n    stream.on('end', () => resolve(hash.digest('hex')));\n    stream.on('error', (error) => reject(error));\n  });\n}\n\nasync function copyFile(sourcePath, destinationPath) {\n  return new Promise((resolve, reject) => {\n    const readStream = fs.createReadStream(sourcePath);\n    const writeStream = fs.createWriteStream(destinationPath);\n\n    readStream.on('error', (error) => reject(error));\n    writeStream.on('error', (error) => reject(error));\n    writeStream.on('finish', () => resolve());\n    readStream.pipe(writeStream);\n  });\n}\n\nasync function linkFile(sourcePath, destinationPath) {\n  return new Promise((resolve, reject) => {\n    fs.symlink(sourcePath, destinationPath, (error) => {\n      if (error) {\n        reject(error);\n      } else {\n        resolve();\n      }\n    });\n  });\n}\n\nasync function deleteFile(filePath) {\n  return new Promise((resolve, reject) => {\n    fs.unlink(filePath, (error) => {\n      if (error) {\n        if (error.code === 'ENOENT') {\n          // File doesn't exist, resolve without an error.\n          resolve();\n        } else {\n          // Other error occurred, reject with the error.\n          reject(error);\n        }\n      } else {\n        // File deleted successfully.\n        resolve();\n      }\n    });\n  });\n}\n\nfunction isFileHidden(filePath) {\n  const fileName = path.basename(filePath);\n  return fileName.startsWith('.'); // || isHiddenOnWindows(filePath);\n}\n\nasync function listAllFiles(dir) {\n  return new Promise((resolve, reject) => {\n    const allFiles = [];\n\n    function traverse(currentDir) {\n      fs.readdirSync(currentDir).forEach((file) => {\n        const filePath = path.join(currentDir, file);\n        const stat = fs.statSync(filePath);\n\n        if (stat.isFile()) {\n          allFiles.push(filePath);\n        } else if (stat.isDirectory()) {\n          traverse(filePath);\n        }\n      });\n    }\n\n    try {\n      traverse(dir);\n      resolve(allFiles);\n    } catch (error) {\n      reject(error);\n    }\n  });\n}\n\nfunction fileExists(filePath) {\n  return fs.existsSync(filePath);\n}\n\nasync function sizeFile(filePath) {\n  return new Promise((resolve, reject) => {\n    fs.stat(filePath, (error, stats) => {\n      if (error) {\n        reject(error);\n      } else {\n        resolve(stats.size);\n      }\n    });\n  });\n}\n\nfunction isFunction(variable) {\n  return typeof variable === 'function';\n}\n\nasync function transform(fileName, entry) {\n  const DefaultChunkSize = 4 * 1024 * 1024; // 4 MB chunks\n\n  const chunkSize = entry.chunkSize || DefaultChunkSize;\n  const buffer = Buffer.alloc(chunkSize);\n\n  const fileSize = await sizeFile(fileName);\n  const fileHandle = fs.openSync(fileName);\n  const chunks = [];\n  for (let offset = 0; offset < fileSize; offset += chunkSize) {\n    const bytesRead = fs.readSync(fileHandle, buffer, 0, chunkSize, offset);\n\n    const data = buffer.subarray(0, bytesRead);\n    const hash = crypto.createHash('sha256');\n    hash.update(data);\n    const chunkHash = hash.digest('hex');\n    const name = entry.name ? entry.name : chunkHash;\n    const destFile = path.resolve(DefaultOutDir, name);\n    fs.writeFileSync(destFile, data);\n    chunks.push({\n      hash: chunkHash,\n      name: name,\n      offsets: [offset, offset + bytesRead]\n    });\n  }\n\n  return {\n    chunks: chunks,\n    size: fileSize,\n    mime: entry.mime\n  };\n}\n\nasync function loadConfig() {\n  if (fileExists(path.resolve(BaseDir, '.resources.mjs'))) {\n    const resources = await import(path.resolve(BaseDir, '.resources.mjs'));\n    const entries = resources.default;\n    return entries;\n  }\n  return [];\n}\n\nasync function main() {\n  fs.mkdirSync(DefaultOutDir, { recursive: true });\n  const resources = await generateFiles();\n\n  await saveResourceMetadata(resources);\n}\n\nasync function generateFiles() {\n  const filesToProcess = {};\n  const entries = await loadConfig();\n  for (const entry of entries) {\n    const entryPath = path.resolve(BaseDir, entry.source);\n    const candidates = await globSync(entryPath, { nodir: true });\n    if (candidates.length === 0) {\n      console.error(`No files found for ${entry.source}`);\n      process.exit(-1);\n    }\n\n    for (const candidate of candidates) {\n      filesToProcess[candidate] = { ...DefaultEntry, ...entry };\n    }\n  }\n  return filesToProcess;\n}\nasync function loadResourceMetadata() {\n  const resourceMetadataFile = path.resolve(DefaultOutDir, 'resources.json');\n  if (fileExists(resourceMetadataFile)) {\n    return JSON.parse(fs.readFileSync(resourceMetadataFile, 'utf8'));\n  }\n  return [];\n}\nasync function saveResourceMetadata(filesToProcess) {\n  const resourcesMetadata = {};\n  for (const fileToProcess of Object.keys(filesToProcess)) {\n    const entry = filesToProcess[fileToProcess];\n    const metadata = await transform(fileToProcess, entry, DefaultOutDir);\n    const key = path.join(entry.path, fileToProcess.split('/').pop());\n    resourcesMetadata[key] = metadata;\n  }\n  fs.writeFileSync(\n    path.resolve(DefaultOutDir, 'resources.json'),\n    JSON.stringify(resourcesMetadata, null, 2)\n  );\n}\n\nmain(process.argv);\n"
  },
  {
    "path": "scripts/package-version.mjs",
    "content": "import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'glob';\n\nconst workspaceManifest = JSON.parse(fs.readFileSync('./package.json', 'utf8'));\nconst newVersion = process.argv[2] || workspaceManifest.version || undefined;\n\nfunction getFiles(dir) {\n  return globSync(path.join(dir, '**/package.json'), {\n    nodir: true,\n    ignore: ['**/node_modules/**']\n  });\n}\n\nfor (let file of getFiles('./')) {\n  const fileContent = fs.readFileSync(file, 'utf8').toString();\n  const manifest = JSON.parse(fileContent, 'utf8');\n\n  if (newVersion && manifest.version !== newVersion) {\n    console.info(\n      `${manifest.name}@${manifest.version} => ${manifest.name}@${newVersion}`\n    );\n    manifest.version = newVersion;\n    fs.writeFileSync(file, JSON.stringify(manifest, null, 2));\n  } else {\n    console.info(`${manifest.name}@${manifest.version}`);\n  }\n}\n"
  }
]