[
  {
    "path": ".babelrc",
    "content": "{\n    \"presets\": [\"@babel/preset-env\"],\n    \"plugins\": [[\"@babel/transform-runtime\"]]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": "dist\nnode_modules\npackage-lock.json\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   Copyright 2020- NeuML LLC\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n    <img src=\"https://raw.githubusercontent.com/neuml/txtai/master/logo.png\"/>\n</p>\n\n<p align=\"center\">\n    <b>JavaScript client for txtai</b>\n</p>\n\n<p align=\"center\">\n    <a href=\"https://github.com/neuml/txtai.js/releases\">\n        <img src=\"https://img.shields.io/github/release/neuml/txtai.js.svg?style=flat&color=success\" alt=\"Version\"/>\n    </a>\n    <a href=\"https://github.com/neuml/txtai.js/releases\">\n        <img src=\"https://img.shields.io/github/release-date/neuml/txtai.js.svg?style=flat&color=blue\" alt=\"GitHub Release Date\"/>\n    </a>\n    <a href=\"https://github.com/neuml/txtai.js/issues\">\n        <img src=\"https://img.shields.io/github/issues/neuml/txtai.js.svg?style=flat&color=success\" alt=\"GitHub Issues\"/>\n    </a>\n    <a href=\"https://github.com/neuml/txtai.js\">\n        <img src=\"https://img.shields.io/github/last-commit/neuml/txtai.js.svg?style=flat&color=blue\" alt=\"GitHub Last Commit\"/>\n    </a>\n</p>\n\n[txtai](https://github.com/neuml/txtai) is an all-in-one AI framework for semantic search, LLM orchestration and language model workflows.\n\nThis repository contains JavaScript bindings for the txtai API.\n\n## Installation\ntxtai.js can be installed via npm\n\n    npm install txtai\n\n## Examples\nThe examples directory has a series of examples that give an overview of txtai. See the list of examples below.\n\n| Example     |      Description      |\n|:----------|:-------------|\n| [Introducing txtai](https://github.com/neuml/txtai.js/blob/master/examples/node/src/embeddings.js) | Overview of the functionality provided by txtai |\n| [Extractive QA with txtai](https://github.com/neuml/txtai.js/blob/master/examples/node/src/extractor.js) | Extractive question-answering with txtai |\n| [Labeling with zero-shot classification](https://github.com/neuml/txtai.js/blob/master/examples/node/src/labels.js) | Labeling with zero-shot classification |\n| [Pipelines and workflows](https://github.com/neuml/txtai.js/blob/master/examples/node/src/pipelines.js) | Pipelines and workflows |\n\ntxtai.js connects to a txtai api instance. See [this link](https://neuml.github.io/txtai/api/) for details on how to start a new api instance.\n\nOnce an api instance is running, do the following to run the examples.\n\n```\ngit clone https://github.com/neuml/txtai.js\ncd txtai.js/examples/node\nnpm install\nnpm run build\nnode dist/embeddings.js\nnode dist/extractor.js\nnode dist/labels.js\nnode dist/pipelines.js\n```\n"
  },
  {
    "path": "examples/node/.babelrc",
    "content": "{\n    \"presets\": [\"@babel/preset-env\"],\n    \"plugins\": [[\"@babel/transform-runtime\"]]\n}\n"
  },
  {
    "path": "examples/node/package.json",
    "content": "{\n    \"name\": \"txtai-node\",\n    \"dependencies\": {\n        \"sprintf-js\": \">=1.1.2\",\n        \"txtai\": \">=9.9.0\"\n    },\n    \"devDependencies\": {\n        \"@babel/cli\": \">=7.10.5\",\n        \"@babel/core\": \">=7.10.5\",\n        \"@babel/node\": \">=7.10.5\",\n        \"@babel/plugin-transform-runtime\": \">=7.10.5\",\n        \"@babel/preset-env\": \">=7.10.5\"\n    },\n    \"scripts\": {\n        \"build\": \"node_modules/@babel/cli/bin/babel.js src -d dist -s --verbose\"\n    }\n}\n"
  },
  {
    "path": "examples/node/src/embeddings.js",
    "content": "import {Embeddings} from \"txtai\";\nimport {sprintf} from \"sprintf-js\";\n\n/**\n * Example embeddings functionality.\n * \n * Implements functionality found in this notebook: https://github.com/neuml/txtai/blob/master/examples/01_Introducing_txtai.ipynb\n */\nconst run = async () => {\n    try {\n        let embeddings = new Embeddings(\"http://localhost:8000\");\n\n        let data  = [\"US tops 5 million confirmed virus cases\",\n                     \"Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg\",\n                     \"Beijing mobilises invasion craft along coast as Taiwan tensions escalate\",\n                     \"The National Park Service warns against sacrificing slower friends in a bear attack\",\n                     \"Maine man wins $1M from $25 lottery ticket\",\n                     \"Make huge profits without work, earn up to $100,000 a day\"];\n\n        console.log(\"Running similarity queries\");\n        console.log(sprintf(\"%-20s %s\", \"Query\", \"Best Match\"));\n        console.log(\"-\".repeat(50));\n\n        for (let query of [\"feel good story\", \"climate change\", \"public health story\", \"war\", \"wildlife\", \"asia\", \"lucky\", \"dishonest junk\"]) {\n            let results = await embeddings.similarity(query, data);\n            let uid = results[0].id;\n            console.log(sprintf(\"%-20s %s\", query, data[uid]))\n        }\n\n        let documents = data.map((text, index) => ({id: index, text: text}));\n\n        await embeddings.add(documents);\n        await embeddings.index();\n\n        console.log();\n        console.log(\"Building an Embeddings index\");\n        console.log(sprintf(\"%-20s %s\", \"Query\", \"Best Match\"));\n        console.log(\"-\".repeat(50));\n\n        for (let query of [\"feel good story\", \"climate change\", \"public health story\", \"war\", \"wildlife\", \"asia\", \"lucky\", \"dishonest junk\"]) {\n            let results = await embeddings.search(query, 1);\n            let uid = results[0].id;\n            console.log(sprintf(\"%-20s %s\", query, data[uid]));\n        }\n\n        data[0] = \"See it: baby panda born\"\n\n        await embeddings.delete([5]);\n        await embeddings.add([{id: 0, text: data[0]}])\n        await embeddings.upsert();\n\n        console.log();\n        console.log(\"Test delete/upsert/count\");\n        console.log(sprintf(\"%-20s %s\", \"Query\", \"Best Match\"));\n        console.log(\"-\".repeat(50));\n\n        let query = \"feel good story\";\n        let results = await embeddings.search(query, 1);\n        let uid = results[0].id;\n        console.log(sprintf(\"%-20s %s\", query, data[uid]));\n\n        let count = await embeddings.count();\n        console.log();\n        console.log(sprintf(\"Total Count: %d\", count));\n    }\n    catch (e) {\n        console.trace(e);\n    }\n};\n\nrun();"
  },
  {
    "path": "examples/node/src/extractor.js",
    "content": "import {Extractor} from \"txtai\";\n\n/**\n * Example extractor functionality.\n * \n * Implements logic found in this notebook: https://github.com/neuml/txtai/blob/master/examples/05_Extractive_QA_with_txtai.ipynb\n */\nconst run = async () => {\n    try {\n        let extractor = new Extractor(\"http://localhost:8000\");\n\n        let data = [\"Giants hit 3 HRs to down Dodgers\",\n                    \"Giants 5 Dodgers 4 final\",\n                    \"Dodgers drop Game 2 against the Giants, 5-4\",\n                    \"Blue Jays beat Red Sox final score 2-1\",\n                    \"Red Sox lost to the Blue Jays, 2-1\",\n                    \"Blue Jays at Red Sox is over. Score: 2-1\",\n                    \"Phillies win over the Braves, 5-0\",\n                    \"Phillies 5 Braves 0 final\",\n                    \"Final: Braves lose to the Phillies in the series opener, 5-0\",\n                    \"Lightning goaltender pulled, lose to Flyers 4-1\",\n                    \"Flyers 4 Lightning 1 final\",\n                    \"Flyers win 4-1\"]\n\n        // Run series of questions\n        let questions = [\"What team won the game?\", \"What was score?\"];\n        for (let query of [\"Red Sox - Blue Jays\", \"Phillies - Braves\", \"Dodgers - Giants\", \"Flyers - Lightning\"]) {\n            console.log(\"----\" + query + \"----\");\n\n            let queue = questions.map(question => ({name: question, query: query, question: question, snippet: false}));\n            console.log(await extractor.extract(queue, data));\n        }\n\n        // Ad-hoc questions\n        let question = \"What hockey team won?\";\n        \n        console.log(\"----\" + question + \"----\");\n        console.log(await extractor.extract([{name: question, query: question, question: question, snippet: false}], data));\n    }\n    catch (e) {\n        console.trace(e);\n    }\n};\n\nrun();"
  },
  {
    "path": "examples/node/src/labels.js",
    "content": "import {Labels} from \"txtai\";\nimport {sprintf} from \"sprintf-js\";\n\n/**\n * Example labels functionality.\n * \n * Implements logic found in this notebook: https://github.com/neuml/txtai/blob/master/examples/07_Apply_labels_with_zero_shot_classification.ipynb\n */\nconst run = async () => {\n    try {\n        let labels = new Labels(\"http://localhost:8000\");\n\n        let data = [\"Dodgers lose again, give up 3 HRs in a loss to the Giants\",\n                    \"Giants 5 Cardinals 4 final in extra innings\",\n                    \"Dodgers drop Game 2 against the Giants, 5-4\",\n                    \"Flyers 4 Lightning 1 final. 45 saves for the Lightning.\",\n                    \"Slashing, penalty, 2 minute power play coming up\",\n                    \"What a stick save!\",\n                    \"Leads the NFL in sacks with 9.5\",\n                    \"UCF 38 Temple 13\",\n                    \"With the 30 yard completion, down to the 10 yard line\",\n                    \"Drains the 3pt shot!!, 0:15 remaining in the game\",\n                    \"Intercepted! Drives down the court and shoots for the win\",\n                    \"Massive dunk!!! they are now up by 15 with 2 minutes to go\"];\n\n        // List of labels\n        let tags = [\"Baseball\", \"Football\", \"Hockey\", \"Basketball\"];\n\n        console.log(sprintf(\"%-75s %s\", \"Text\", \"Label\"));\n        console.log(\"-\".repeat(100));\n\n        for (let text of data) {\n            let label = await labels.label(text, tags);\n            label = tags[label[0].id];\n\n            console.log(sprintf(\"%-75s %s\", text, label));\n        }\n\n        tags = [\"😀\", \"😡\"];\n\n        console.log();\n        console.log(sprintf(\"%-75s %s\", \"Text\", \"Label\"));\n        console.log(\"-\".repeat(100));\n\n        for (let text of data) {\n            let label = await labels.label(text, tags);\n            label = tags[label[0].id];\n\n            console.log(sprintf(\"%-75s %s\", text, label));\n        }\n    }\n    catch (e) {\n        console.trace(e);\n    }\n};\n\nrun();"
  },
  {
    "path": "examples/node/src/pipelines.js",
    "content": "import {Segmentation, Textractor, Summary, Transcription, Translation, Workflow} from \"txtai\";\n\n/**\n * Example pipeline and workflow functionality.\n *\n * Uses files from txtai unit tests: https://github.com/neuml/txtai/releases/download/v2.0.0/tests.tar.gz\n */\nconst run = async () => {\n    try {\n        let service = \"http://localhost:8000\"\n\n        let segment = new Segmentation(service);\n\n        let sentences = \"This is a test. And another test.\";\n\n        console.log(\"---- Segmented Text ----\");\n        console.log(await segment.segment(sentences));\n\n        let textractor = new Textractor(service);\n        let text = await textractor.textract(\"/tmp/txtai/article.pdf\")\n\n        console.log(\"\\n---- Extracted Text ----\");\n        console.log(text);\n\n        let summary = new Summary(service);\n        let summarytext = await summary.summary(text);\n\n        console.log(\"\\n---- Summary Text ----\");\n        console.log(summarytext);\n\n        let translate = new Translation(service);\n        let translation = await translate.translate(summarytext, \"es\");\n\n        console.log(\"\\n---- Summary Text in Spanish ----\");\n        console.log(translation);\n\n        let workflow = new Workflow(service);\n        let output = await workflow.workflow(\"sumspanish\", [\"file:///tmp/txtai/article.pdf\"]);\n\n        console.log(\"\\n---- Workflow [Extract Text->Summarize->Translate] ----\");\n        console.log(output);\n\n        let transcribe = new Transcription(service);\n        let transcription = await transcribe.transcribe(\"/tmp/txtai/Make_huge_profits.wav\")\n\n        console.log(\"\\n---- Transcribed Text ----\");\n        console.log(transcription);\n    }\n    catch (e) {\n        console.trace(e);\n    }\n};\n\nrun();"
  },
  {
    "path": "package.json",
    "content": "{\n    \"name\": \"txtai\",\n    \"version\": \"9.9.0\",\n    \"author\": \"NeuML\",\n    \"description\": \"JavaScript client for txtai\",\n    \"license\": \"Apache-2.0\",\n    \"keywords\": [\"search\", \"nlp\", \"machine-learning\", \"similarity\"],\n    \"repository\": \"neuml/txtai.js\",\n    \"main\": \"dist/index.js\",\n    \"files\": [\"dist\"],\n    \"dependencies\": {\n        \"core-js\": \">=3.6.5\",\n        \"isomorphic-fetch\": \">=2.2.1\"\n    },\n    \"devDependencies\": {\n        \"@babel/cli\": \">=7.10.5\",\n        \"@babel/core\": \">=7.10.5\",\n        \"@babel/node\": \">=7.10.5\",\n        \"@babel/plugin-transform-runtime\": \">=7.10.5\",\n        \"@babel/preset-env\": \">=7.10.5\"\n    },\n    \"scripts\": {\n        \"build\": \"node_modules/@babel/cli/bin/babel.js src -d dist -s --verbose\"\n    }\n}\n"
  },
  {
    "path": "src/api.js",
    "content": "// Backwards compatibility\nimport \"core-js/features/promise\";\nimport \"isomorphic-fetch\";\n\n/**\n * Base class for interfacing with a remote txtai service via REST API calls. \n */\nclass API {\n    /**\n     * Creates an API instance.\n     * \n     * @param url api url\n     * @param token api token\n     */\n    constructor(url, token) {\n        // API url\n        this.url = url ? url : process.env.TXTAI_API_URL\n\n        // API token\n        this.token = token ? token : process.env.TXTAI_API_TOKEN\n    }\n\n    /**\n     * Executes a get request.\n     * \n     * @param method api method\n     * @param params query parameters\n     * @return response\n     */\n    async get(method, params) {\n        // Build URL\n        let url = `${this.url}/${method}`;\n        if (params) {\n            url += `?${new URLSearchParams(params)}`;\n        }\n\n        // Execute remote call\n        let res = await fetch(url, {headers: this.headers()});\n\n        // Validate response and return JSON \n        return res.ok ? await res.json() : Promise.reject(`${res.status} ${res.statusText}`);\n    }\n\n    /**\n     * Executes a post request.\n     *\n     * @param method api method\n     * @param params post parameters\n     * @return response\n     */\n    async post(method, params) {\n        // Build URL\n        let url = `${this.url}/${method}`;\n\n        // Default headers\n        let defaults = {\"Content-Type\": \"application/json\"};\n\n        // Execute remote call\n        let res = await fetch(url, {method: \"post\",\n                                    body: JSON.stringify(params),\n                                    headers: this.headers(defaults)});\n\n        // Validate response and return JSON\n        return res.ok ? await res.json() : Promise.reject(`${res.status} ${res.statusText}`);\n    }\n\n    /**\n     * Executes a multipart form post request.\n     *\n     * @param method api method\n     * @param formData FormData object\n     * @return response\n     */\n    async postForm(method, formData) {\n        // Build URL\n        let url = `${this.url}/${method}`;\n\n        // Execute remote call (no Content-Type header - browser sets it with boundary)\n        let res = await fetch(url, {method: \"post\",\n                                    body: formData,\n                                    headers: this.headers()});\n\n        // Validate response\n        return res.ok ? Promise.resolve() : Promise.reject(`${res.status} ${res.statusText}`);\n    }\n\n    /**\n     * Creates default HTTP headers.\n     *\n     * @param base base headers\n     * @return headers\n     */\n    headers(base) {\n        let headers = base ? base : {};\n        if (this.token) {\n            headers[\"Authorization\"] = \"Bearer \" + this.token;\n        }\n\n        return headers\n    }\n}\n\nexport default API;\n"
  },
  {
    "path": "src/embeddings.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai embeddings instance. \n */\nclass Embeddings extends API {\n    /**\n     * Finds documents in the embeddings model most similar to the input query. Returns\n     * a list of {id: value, score: value} sorted by highest score, where id is the\n     * document id in the embeddings model.\n     * \n     * @param query query text\n     * @param limit maximum results (defaults to 10)\n     * @param weights hybrid score weights, if applicable\n     * @param index index name, if applicable\n     * @return list of {id: value, score: value}\n     */\n    async search(query, limit = 10, weights = null, index = null) {\n        let params = {\n            query: query,\n            limit: limit\n        }\n\n        if (weights != null) {\n            params[\"weights\"] = weights\n        }\n        if (index != null) {\n            params[\"index\"] = index\n        }\n\n        return await this.get(\"search\", params).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Finds documents in the embeddings model most similar to the input queries. Returns\n     * a list of {id: value, score: value} sorted by highest score per query, where id is\n     * the document id in the embeddings model.\n     *\n     * @param queries queries text\n     * @param limit maximum results (defaults to 10)\n     * @param weights hybrid score weights, if applicable\n     * @param index index name, if applicable\n     * @return list of {id: value, score: value} per query\n     */\n    async batchsearch(queries, limit = 10, weights = null, index = null) {\n        let params = {\n            queries: queries,\n            limit: limit\n        }\n\n        if (weights != null) {\n            params[\"weights\"] = weights\n        }\n        if (index != null) {\n            params[\"index\"] = index\n        }\n\n        return await this.post(\"batchsearch\", params).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Adds a batch of documents for indexing.\n     * \n     * @param documents list of {id: value, text: value}\n     */\n    async add(documents) {\n        await this.post(\"add\", documents).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Builds an embeddings index for previously batched documents.\n     */\n    async index() {\n        await this.get(\"index\", null).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Runs an embeddings upsert operation for previously batched documents.\n     */\n    async upsert() {\n        await this.get(\"upsert\", null).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Deletes from an embeddings index. Returns list of ids deleted.\n     *\n     * @param ids list of ids to delete\n     * @return ids deleted\n     */\n    async delete(ids) {\n        return await this.post(\"delete\", ids).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Recreates this embeddings index using config. This method only works if document content storage is enabled.\n     *\n     * @param config new config\n     * @param func optional function to prepare content for indexing\n     */\n    async reindex(config, func = null) {\n        let params = {\n            config: config,\n        }\n\n        if (func != null) {\n            params[\"function\"] = func\n        }\n\n        await this.post(\"reindex\", params).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Total number of elements in this embeddings index.\n     *\n     * @return number of elements in embeddings index\n     */\n    async count() {\n        return await this.get(\"count\", null).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Computes the similarity between query and list of text. Returns a list of\n     * {id: value, score: value} sorted by highest score, where id is the index\n     * in texts.\n     *\n     * @param query query text\n     * @param texts list of text\n     * @return list of {id: value, score: value}\n     */\n    async similarity(query, texts) {\n        return await this.post(\"similarity\", {query: query, texts: texts}).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Computes the similarity between list of queries and list of text. Returns a list\n     * of {id: value, score: value} sorted by highest score per query, where id is the\n     * index in texts.\n     * \n     * @param queries queries text\n     * @param texts list of text\n     * @return list of {id: value, score: value} per query\n     */\n    async batchsimilarity(queries, texts) {\n        return await this.post(\"batchsimilarity\", {queries: queries, texts: texts}).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Transforms text into an embeddings array.\n     *\n     * @param text input text\n     * @return embeddings array\n     */\n    async transform(text) {\n        return await this.get(\"transform\", {text: text}).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Transforms list of text into embeddings arrays.\n     *\n     * @param texts list of text\n     * @return embeddings array\n     */\n    async batchtransform(texts) {\n        return await this.post(\"batchtransform\", texts).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Adds a batch of binary objects for indexing.\n     *\n     * @param data list of binary data (Blob, File, or Buffer objects)\n     * @param uid list of corresponding ids (optional)\n     * @param field optional object field name\n     */\n    async addobject(data, uid = null, field = null) {\n        let formData = new FormData();\n\n        for (let i = 0; i < data.length; i++) {\n            formData.append(\"data\", data[i], `file${i}`);\n        }\n\n        if (uid != null) {\n            for (let id of uid) {\n                formData.append(\"uid\", id);\n            }\n        }\n\n        if (field != null) {\n            formData.append(\"field\", field);\n        }\n\n        await this.postForm(\"addobject\", formData).catch(e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Adds a batch of images for indexing.\n     *\n     * @param data list of image data (Blob, File, or Buffer objects)\n     * @param uid list of corresponding ids\n     * @param field optional object field name\n     */\n    async addimage(data, uid, field = null) {\n        let formData = new FormData();\n\n        for (let i = 0; i < data.length; i++) {\n            formData.append(\"data\", data[i], data[i].name || `image${i}`);\n        }\n\n        if (uid != null) {\n            for (let id of uid) {\n                formData.append(\"uid\", id);\n            }\n        }\n\n        if (field != null) {\n            formData.append(\"field\", field);\n        }\n\n        await this.postForm(\"addimage\", formData).catch(e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Embeddings;\n"
  },
  {
    "path": "src/extractor.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai extractor instance. \n */\nclass Extractor extends API {\n    /**\n     * Extracts answers to input questions.\n     * \n     * @param queue list of {name: value, query: value, question: value, snippet: value}\n     * @param texts list of text\n     * @return list of {name: value, answer: value}\n     */\n    async extract(queue, texts) {\n        return await this.post(\"extract\", {queue: queue, texts: texts}).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Extractor;\n"
  },
  {
    "path": "src/index.js",
    "content": "import Embeddings from \"./embeddings\";\nimport Extractor from \"./extractor\";\nimport Labels from \"./labels\";\nimport Segmentation from \"./segmentation\";\nimport Similarity from \"./similarity\";\nimport Summary from \"./summary\";\nimport Textractor from \"./textractor\";\nimport Transcription from \"./transcription\";\nimport Translation from \"./translation\";\nimport Workflow from \"./workflow\";\n\nexport {\n    Embeddings,\n    Extractor,\n    Labels,\n    Segmentation,\n    Similarity,\n    Summary,\n    Textractor,\n    Transcription,\n    Translation,\n    Workflow\n};\n"
  },
  {
    "path": "src/labels.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai labels instance. \n */\nclass Labels extends API {\n    /**\n     * Applies a zero shot classifier to text using a list of labels. Returns a list of\n     * {id: value, score: value} sorted by highest score, where id is the index in labels.\n     * \n     * @param text input text\n     * @param labels list of labels\n     * @return list of {id: value, score: value} per text element\n     */\n    async label(text, labels) {\n        return await this.post(\"label\", {text: text, labels: labels}).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Applies a zero shot classifier to list of text using a list of labels. Returns a list of\n     * {id: value, score: value} sorted by highest score, where id is the index in labels per\n     * text element.\n     *\n     * @param texts list of texts\n     * @param labels list of labels\n     * @return list of {id: value score: value} per text element\n     */\n    async batchlabel(texts, labels) {\n        return await this.post(\"batchlabel\", {texts: texts, labels: labels}).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Labels;\n"
  },
  {
    "path": "src/segmentation.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai segmentation instance. \n */\nclass Segmentation extends API {\n    /**\n     * Segments text into semantic units.\n     * \n     * @param text input text\n     * @return segmented text\n     */\n    async segment(text) {\n        return await this.get(\"segment\", {text: text}).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Segments text into semantic units.\n     * \n     * @param texts list of texts to segment\n     * @return list of segmented text\n     */\n    async batchsegment(texts) {\n        return await this.post(\"batchsegment\", texts).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Segmentation;\n"
  },
  {
    "path": "src/similarity.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai similarity instance.\n */\nclass Similarity extends API {\n    /**\n     * Computes the similarity between query and list of text. Returns a list of\n     * {id: value, score: value} sorted by highest score, where id is the index\n     * in texts.\n     *\n     * @param query query text\n     * @param texts list of text\n     * @return list of {id: value, score: value}\n     */\n    async similarity(query, texts) {\n        return await this.post(\"similarity\", {query: query, texts: texts}).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Computes the similarity between list of queries and list of text. Returns a list\n     * of {id: value, score: value} sorted by highest score per query, where id is the\n     * index in texts.\n     *\n     * @param queries queries text\n     * @param texts list of text\n     * @return list of {id: value, score: value} per query\n     */\n    async batchsimilarity(queries, texts) {\n        return await this.post(\"batchsimilarity\", {queries: queries, texts: texts}).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Similarity;\n"
  },
  {
    "path": "src/summary.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai summary instance. \n */\nclass Summary extends API {\n    /**\n     * Runs a summarization model against a block of text.\n     *\n     * @param text text to summarize\n     * @param minlength minimum length for summary\n     * @param maxlength maximum length for summary\n     * @return summary text\n     */\n    async summary(text, minlength, maxlength) {\n        let params = {text: text}\n        if (minlength) {\n            params.minlength = minlength;\n        }\n        if (maxlength) {\n            params.maxlength = maxlength;\n        }\n\n        return await this.get(\"summary\", params).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Runs a summarization model against a block of text.\n     *\n     * @param texts list of text to summarize\n     * @param minlength minimum length for summary\n     * @param maxlength maximum length for summary\n     * @return list of summary text\n     */\n    async batchsummary(texts, minlength, maxlength) {\n        let params = {texts: texts}\n        if (minlength) {\n            params.minlength = minlength;\n        }\n        if (maxlength) {\n            params.maxlength = maxlength;\n        }\n\n        return await this.post(\"batchsummary\", params).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Summary;\n"
  },
  {
    "path": "src/textractor.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai textractor instance. \n */\nclass Textractor extends API {\n    /**\n     * Extracts text from a file at path.\n     * \n     * @param file file to extract text\n     * @return extracted text\n     */\n    async textract(file) {\n        return await this.get(\"textract\", {file: file}).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Extracts text from a file at path.\n     * \n     * @param files list of files to extract text\n     * @return list of extracted text\n     */\n    async batchtextract(files) {\n        return await this.post(\"batchtextract\", files).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Textractor;\n"
  },
  {
    "path": "src/transcription.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai transcription instance. \n */\nclass Transcription extends API {\n    /**\n     * Transcribes audio files to text.\n     * \n     * @param file file to transcribe\n     * @return transcribed text\n     */\n    async transcribe(file) {\n        return await this.get(\"transcribe\", {file: file}).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Transcribes audio files to text.\n     * \n     * @param files list of files to transcribe\n     * @return list of transcribed text\n     */\n    async batchtranscribe(files) {\n        return await this.post(\"batchtranscribe\", files).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Transcription;\n"
  },
  {
    "path": "src/translation.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai translation instance. \n */\nclass Translation extends API {\n    /**\n     * Translates text from source language into target language.\n     * \n     * @param text text to translate\n     * @param target target language code, defaults to \"en\"\n     * @param source source language code, detects language if not provided\n     * @return translated text\n     */\n    async translate(text, target, source) {\n        let params = {text: text};\n        if (target) {\n            params.target = target;\n        }\n        if (source) {\n            params.source = source;\n        }\n\n        return await this.get(\"translate\", params).catch (e => {\n            throw(e);\n        });\n    }\n\n    /**\n     * Translates text from source language into target language.\n     * \n     * @param texts list of text to translate\n     * @param target target language code, defaults to \"en\"\n     * @param source source language code, detects language if not provided\n     * @return list of translated text\n     */\n    async batchtranslate(texts, target, source) {\n        let params = {texts: texts};\n        if (target) {\n            params.target = target;\n        }\n        if (source) {\n            params.source = source;\n        }\n\n        return await this.post(\"batchtranslate\", files).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Translation;\n"
  },
  {
    "path": "src/workflow.js",
    "content": "import API from \"./api\";\n\n/**\n * txtai workflow instance. \n */\nclass Workflow extends API {\n    /**\n     * Executes a named workflow using elements as input.\n     *\n     * @param name workflow name\n     * @param elements list of elements to run through workflow\n     * @return list of processed elements\n     */\n    async workflow(name, elements) {\n        return await this.post(\"workflow\", {name: name, elements: elements}).catch (e => {\n            throw(e);\n        });\n    }\n}\n\nexport default Workflow;\n"
  }
]