├── .eslintrc.json
├── .gitignore
├── .husky
├── pre-commit
└── pre-push
├── LICENSE
├── Makefile
├── README.md
├── __tests__
├── convertToRenderable.test.ts
├── graph.test.ts
├── parsers.test.ts
├── processObjectForDisplay.test.ts
└── removeUUIDs.test.ts
├── build.sh
├── examples
├── angular
│ ├── .editorconfig
│ ├── .gitignore
│ ├── README.md
│ ├── angular.json
│ ├── package-lock.json
│ ├── package.json
│ ├── src
│ │ ├── app
│ │ │ ├── app-routing.module.ts
│ │ │ ├── app.component.css
│ │ │ ├── app.component.html
│ │ │ ├── app.component.spec.ts
│ │ │ ├── app.component.ts
│ │ │ ├── app.module.ts
│ │ │ └── chatUI.component.ts
│ │ ├── assets
│ │ │ └── .gitkeep
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ ├── main.ts
│ │ ├── polyfills.ts
│ │ └── styles.css
│ ├── tsconfig.app.json
│ ├── tsconfig.json
│ └── tsconfig.spec.json
└── nextjs
│ ├── .gitignore
│ ├── Makefile
│ ├── README.md
│ ├── next.config.js
│ ├── package-lock.json
│ ├── package.json
│ ├── postcss.config.js
│ ├── public
│ ├── next.svg
│ └── vercel.svg
│ ├── src
│ └── app
│ │ ├── chat
│ │ ├── favicon.ico
│ │ ├── globals.css
│ │ ├── layout.tsx
│ │ └── page.tsx
│ │ ├── favicon.ico
│ │ ├── globals.css
│ │ ├── layout.tsx
│ │ └── page.tsx
│ ├── tailwind.config.js
│ └── tsconfig.json
├── index.html
├── jest.config.js
├── package-lock.json
├── package.json
├── postcss.config.cjs
├── postcss.config.js
├── rollup.config.mjs
├── sidebar-screenshot.png
├── sidebar.png
├── src
├── components
│ ├── autoGrowingTextarea.tsx
│ ├── chat.tsx
│ ├── chatItems.tsx
│ ├── followUpSuggestions.tsx
│ ├── graph.tsx
│ ├── loadingspinner.tsx
│ ├── modal.tsx
│ ├── sidebar.tsx
│ └── superflowsButton.tsx
├── development.tsx
├── index.css
├── index.tsx
└── lib
│ ├── consts.ts
│ ├── export.ts
│ ├── parser.ts
│ ├── types.ts
│ ├── useMessageCache.ts
│ └── utils.ts
├── tailwind.config.cjs
├── tsconfig.json
└── vite.config.ts
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "browser": true,
4 | "es2021": true
5 | },
6 | "extends": [
7 | "eslint:recommended",
8 | "plugin:@typescript-eslint/recommended",
9 | "plugin:react/recommended"
10 | ],
11 | "parser": "@typescript-eslint/parser",
12 | "parserOptions": {
13 | "ecmaVersion": "latest",
14 | "sourceType": "module"
15 | },
16 | "plugins": ["@typescript-eslint", "react"],
17 | "rules": {
18 | "@typescript-eslint/no-explicit-any": "off",
19 | "@typescript-eslint/no-unused-vars": "off",
20 | "@typescript-eslint/ban-ts-comment": "off",
21 | "no-prototype-builtins": "off",
22 | "no-mixed-spaces-and-tabs": "off",
23 | "no-empty": "off"
24 | },
25 | "ignorePatterns": ["dist/*", "node_modules/*", "*.config.js"]
26 | }
27 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | .idea/
4 | local/
5 |
6 | # dependencies
7 | node_modules
8 | .pnp
9 | .pnp.js
10 |
11 | # testing
12 | coverage
13 |
14 | # next.js
15 | .next/
16 | out/
17 | build
18 |
19 | # misc
20 | .DS_Store
21 | *.pem
22 | .vscode
23 |
24 | # debug
25 | npm-debug.log*
26 | yarn-debug.log*
27 | yarn-error.log*
28 | .pnpm-debug.log*
29 |
30 | # local env files
31 | .env
32 | .env.local
33 | .env.development.local
34 | .env.test.local
35 | .env.production.local
36 |
37 | # Distribution directories
38 | dist/
39 | package/
40 | storybook-static/
41 |
42 | # turbo
43 | .turbo
44 |
45 | # tar
46 | *.tgz
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npm run lint
5 |
--------------------------------------------------------------------------------
/.husky/pre-push:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npm test -- --watchAll=false --bail --ci
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: all build clean
2 |
3 | p:
4 | npx prettier --write .
5 |
6 | pc: p
7 | npm run lint
8 |
9 | run:
10 | npm run dev
11 |
12 | build:
13 | npm run build
14 |
15 | test:
16 | # Run in series to stop race condition
17 | npm test -- --runInBand
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Superflows Chat UI React
2 |
3 | Superflows Chat UI is a collection of pre-built UI components that can be used to integrate a Superflows chatbot into your software.
4 |
5 | The purpose of this library is to allow developers to easily integrate Superflows chatbot into their software.
6 |
7 |
8 |
9 |
10 |
11 | You can integrate in 3 ways:
12 |
13 | | | Approach | Description |
14 | | --- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
15 | | 1 | `SuperflowsButton` component _(recommended)_ | Easiest & fastest |
16 | | 2 | `SuperflowsChat` component | Most flexible & customizable |
17 | | 3 | The modal (`SuperflowsModal`) or sidebar (`SuperflowsSidebar`) components | (#1 but you have total control over the button that opens the chatbot) |
18 |
19 | ## Installation
20 |
21 | ```bash
22 | npm install @superflows/chat-ui-react
23 | ```
24 |
25 | ## Documentation
26 |
27 | Find the [integration guide here.](https://docs.superflows.ai/docs/category/integration-guide)
28 |
29 | Find [documentation for the Chat UI components here](https://docs.superflows.ai/docs/category/ui-components-react).
30 |
--------------------------------------------------------------------------------
/__tests__/convertToRenderable.test.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * @jest-environment jsdom
3 | */
4 | import uuid from "uuid";
5 | import { describe, expect, it } from "@jest/globals";
6 | import { convertToMarkdownTable } from "../src/lib/utils";
7 |
8 | describe("convertToRenderable", () => {
9 | it("should convert short array of numbers to a markdown table", () => {
10 | const input = [1, 2, 3, 4, 5, 6];
11 | const output = convertToMarkdownTable(input);
12 | expect(output).toEqual(
13 | `| | | | | | |
14 | |---|---|---|---|---|---|
15 | | 1 | 2 | 3 | 4 | 5 | 6 |
16 | `,
17 | );
18 | });
19 | it("should convert long array of numbers to a markdown table", () => {
20 | const input = [1, 2, 3, 4, 5, 6, 7];
21 | const output = convertToMarkdownTable(input);
22 | expect(output).toEqual(
23 | `| |
24 | |---|
25 | | 1 |
26 | | 2 |
27 | | 3 |
28 | | 4 |
29 | | 5 |
30 | | 6 |
31 | | 7 |
32 | `,
33 | );
34 | });
35 | it("should convert object with 1 key and value of long array of numbers to a markdown table", () => {
36 | const input = { whatsthedifferencebetweenmeandyou: [1, 2, 3, 4, 5, 6, 7] };
37 | const output = convertToMarkdownTable(input);
38 | expect(output).toEqual(
39 | `### Whatsthedifferencebetweenmeandyou
40 |
41 | | |
42 | |---|
43 | | 1 |
44 | | 2 |
45 | | 3 |
46 | | 4 |
47 | | 5 |
48 | | 6 |
49 | | 7 |
50 | `,
51 | );
52 | });
53 | it("should convert array of arrays to a markdown table", () => {
54 | const input = [
55 | [1, 2, 3],
56 | [4, 5, 6],
57 | [7, 8, 9],
58 | ];
59 | const output = convertToMarkdownTable(input);
60 | expect(output).toEqual(
61 | `| 0 | 1 | 2 |
62 | | :---: | :---: | :---: |
63 | | 1 | 2 | 3 |
64 | | 4 | 5 | 6 |
65 | | 7 | 8 | 9 |
66 | `,
67 | );
68 | });
69 | it("should convert an array of objects to a markdown table", () => {
70 | const input = [
71 | { a: 1, b: 2, c: 3 },
72 | { a: 4, b: 5, c: 6 },
73 | ];
74 | const output = convertToMarkdownTable(input);
75 | expect(output).toEqual(
76 | `| a | b | c |
77 | | :---: | :---: | :---: |
78 | | 1 | 2 | 3 |
79 | | 4 | 5 | 6 |
80 | `,
81 | );
82 | });
83 | it("should convert an array of objects with nested arrays to a markdown table", () => {
84 | const input = [
85 | { a: 1, b: 2, c: [1, 2, 3] },
86 | { a: 4, b: 5, c: [4, 5, 6] },
87 | ];
88 | const output = convertToMarkdownTable(input);
89 | expect(output).toEqual(
90 | `| a | b | c |
91 | | :---: | :---: | :---: |
92 | | 1 | 2 | 1,2,3 |
93 | | 4 | 5 | 4,5,6 |
94 | `,
95 | );
96 | });
97 | it("should convert an array of objects with nested objects to a markdown table", () => {
98 | const input = [
99 | { a: 1, b: 2, c: { fire: 1, sale: 2, aaaa: 3, theburning: 4 } },
100 | { a: 4, b: 5, c: { fire: 1, sale: 2, aaaa: 3, theburning: 4 } },
101 | ];
102 | const output = convertToMarkdownTable(input);
103 | expect(output)
104 | .toEqual(`| a | b | c -> Fire | c -> Sale | c -> Aaaa | c -> Theburning |
105 | | :---: | :---: | :-------: | :-------: | :-------: | :-------------: |
106 | | 1 | 2 | 1 | 2 | 3 | 4 |
107 | | 4 | 5 | 1 | 2 | 3 | 4 |
108 | `);
109 | });
110 | it("should convert object with long array of objects into a markdown table", () => {
111 | const input = {
112 | responses: [
113 | {
114 | score: 5,
115 | comment: "Very quick and easy to sort out",
116 | updated_at: "2023-08-02T14:02:18.818Z",
117 | data_source: "Trustpilot",
118 | themes: [
119 | {
120 | name: "Ease of Use / Navigation",
121 | },
122 | {
123 | name: "Speed of Use / Navigation",
124 | },
125 | ],
126 | },
127 | {
128 | score: 1,
129 | comment:
130 | "This bank has the worst customer service ever as soon as they open I'm shutting down my accounts,,,\nSHHIIIIITTTTTT SERVICE 45 MINUTES ON HOLD !!!!",
131 | updated_at: "2023-08-02T14:02:10.108Z",
132 | data_source: "Trustpilot",
133 | },
134 | {
135 | score: 5,
136 | comment: "Have been great for when abroad.",
137 | updated_at: "2023-08-02T14:02:18.945Z",
138 | data_source: "Trustpilot",
139 | themes: [
140 | {
141 | name: "General",
142 | },
143 | ],
144 | },
145 | ],
146 | };
147 | const out = convertToMarkdownTable(input);
148 | expect(out).toEqual(`### Responses
149 |
150 | | Score | Comment | Updated At | Data Source | Themes |
151 | | :---: | :----------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------: | :---------: | :--------------------------------------------------------------: |
152 | | 5 | Very quick and easy to sort out | 2023-08-02T14:02:18.818Z | Trustpilot | {name:Ease of Use / Navigation},{name:Speed of Use / Navigation} |
153 | | 1 | This bank has the worst customer service ever as soon as they open I'm shutting down my accounts,,,
SHHIIIIITTTTTT SERVICE 45 MINUTES ON HOLD !!!! | 2023-08-02T14:02:10.108Z | Trustpilot | |
154 | | 5 | Have been great for when abroad. | 2023-08-02T14:02:18.945Z | Trustpilot | {name:General} |
155 | `);
156 | });
157 | it("should convert simple object to a markdown table", () => {
158 | const input = {
159 | if: "you can keep your head",
160 | when: "all about you are losing theirs",
161 | and: "blaming it on you",
162 | };
163 | const output = convertToMarkdownTable(input);
164 | expect(output).toEqual(
165 | `| Name | Value |
166 | | :---- | :------------------------------ |
167 | | if | you can keep your head |
168 | | when | all about you are losing theirs |
169 | | and | blaming it on you |
170 | `,
171 | );
172 | });
173 | it("should convert object with 1 array field to a markdown table", () => {
174 | const input = {
175 | if: ["you ", "can ", "trust", " yourself"],
176 | when: "all men doubt you",
177 | but: "keep allowance for their doubting too",
178 | };
179 | const output = convertToMarkdownTable(input);
180 | expect(output).toEqual(
181 | `| Name | Value |
182 | | :---- | :------------------------------------ |
183 | | if | you ,can ,trust, yourself |
184 | | when | all men doubt you |
185 | | but | keep allowance for their doubting too |
186 | `,
187 | );
188 | });
189 | it("should convert object with 1 object field to a markdown table", () => {
190 | const input = {
191 | if: ["you ", "can ", "wait"],
192 | and: { not: "be", tired: "of", waiting: "." },
193 | };
194 | const output = convertToMarkdownTable(input);
195 | const expected = `| Name | Value |
196 | | :------------- | :------------- |
197 | | if | you ,can ,wait |
198 | | and -> not | be |
199 | | and -> tired | of |
200 | | and -> waiting | . |
201 | `;
202 | expect(output).toEqual(expected);
203 | });
204 |
205 | it("removes uuid from key:value pairs", () => {
206 | const input = {
207 | well: "i dreamed i saw the knights in armor coming",
208 | saying: "something about a queen",
209 | uuid: uuid.v4(),
210 | };
211 | const output = convertToMarkdownTable(input);
212 | expect(output).toEqual(
213 | `| Name | Value |
214 | | :----- | :------------------------------------------ |
215 | | well | i dreamed i saw the knights in armor coming |
216 | | saying | something about a queen |
217 | `,
218 | );
219 | });
220 |
221 | it("removes uuid from array", () => {
222 | const input = "look at mother nature on the run".split(" ");
223 | input.push(uuid.v4());
224 | const output = convertToMarkdownTable(input);
225 | const expected = `| |
226 | |---|
227 | | look |
228 | | at |
229 | | mother |
230 | | nature |
231 | | on |
232 | | the |
233 | | run |
234 | `;
235 | expect(output).toEqual(expected);
236 | });
237 | it("removes nested uuid from array", () => {
238 | const input = [
239 | ["i", "was"],
240 | ["lying", "in"],
241 | ["a", "burned"],
242 | ["out", "basement"],
243 | ["with", uuid.v4()],
244 | ];
245 | const output = convertToMarkdownTable(input);
246 | const expected = `| 0 | 1 |
247 | | :---: | :------: |
248 | | i | was |
249 | | lying | in |
250 | | a | burned |
251 | | out | basement |
252 | | with | |
253 | `;
254 | expect(output).toEqual(expected);
255 | });
256 | it("removes uuid from nested object", () => {
257 | const input = [
258 | { flying: "mother nature's silver seed", to: "a new home in the sun" },
259 | { flying: "mother nature's on the run", to: uuid.v4() },
260 | ];
261 | const output = convertToMarkdownTable(input);
262 | const expected = `| Flying | To |
263 | | :-------------------------: | :-------------------: |
264 | | mother nature's silver seed | a new home in the sun |
265 | | mother nature's on the run | |
266 | `;
267 | expect(output).toEqual(expected);
268 | });
269 | it("real world example - nested object", () => {
270 | const input = {
271 | workflow: { code: "client.sub-account" },
272 | data: {
273 | account: {
274 | id: "6e9e250d-47d9-4fda-b223-9687a71afc0b",
275 | clientId: "a800b3e5-15e0-4b3c-9d0f-e95f3aed30ba",
276 | status: "active",
277 | country: "GB",
278 | currency: "GBP",
279 | alias: "GBP Account",
280 | routingCodes: {},
281 | // @ts-ignore
282 | iban: null,
283 | // @ts-ignore
284 | accountNumber: null,
285 | ledgerNumber: "43668932",
286 | availableBalance: 0,
287 | accountHolderIdentityType: "corporate",
288 | accountHolderName: "I.F Technology Ltd",
289 | mainAccountId: "f51db37b-9da6-47e3-a20a-93e642a8fb2c",
290 | },
291 | },
292 | connect: { type: "explicit", serviceProvider: "currencycloud" },
293 | metadata: {},
294 | };
295 | const output = convertToMarkdownTable(input);
296 | const expected = `| Name | Value |
297 | | :------------------------------------------- | :----------------- |
298 | | workflow -> code | client.sub-account |
299 | | data -> account -> status | active |
300 | | data -> account -> country | GB |
301 | | data -> account -> currency | GBP |
302 | | data -> account -> alias | GBP Account |
303 | | data -> account -> ledgerNumber | 43668932 |
304 | | data -> account -> availableBalance | 0 |
305 | | data -> account -> accountHolderIdentityType | corporate |
306 | | data -> account -> accountHolderName | I.F Technology Ltd |
307 | | connect -> type | explicit |
308 | | connect -> serviceProvider | currencycloud |
309 | `;
310 | expect(output).toEqual(expected);
311 | });
312 | });
313 |
--------------------------------------------------------------------------------
/__tests__/graph.test.ts:
--------------------------------------------------------------------------------
1 | import { describe, expect, it } from "@jest/globals";
2 | import {
3 | checkStringMatch,
4 | extractGraphData,
5 | findFirstArray,
6 | possibleYlabels,
7 | } from "../src/components/graph";
8 | import { GraphData } from "../src/lib/types";
9 |
10 | describe("checkStringMatch", () => {
11 | it("basic match", () => {
12 | const possibleLabels = ["Value", "Genre", "Groups", "Label"];
13 | expect(checkStringMatch("value", possibleLabels)).toBeTruthy();
14 | });
15 | it("match plural", () => {
16 | const possibleLabels = ["Values", "Genre", "Groups", "Label"];
17 | expect(checkStringMatch("value", possibleLabels)).toBeTruthy();
18 | });
19 |
20 | it("match camel", () => {
21 | const possibleLabels = ["Values", "Genre", "TimeDays", "Label"];
22 | expect(checkStringMatch("time days", possibleLabels)).toBeTruthy();
23 | });
24 |
25 | it("no match", () => {
26 | const possibleLabels = ["Values", "Genre", "TimeDays", "Label"];
27 | expect(checkStringMatch("puppy", possibleLabels)).toBeFalsy();
28 | });
29 |
30 | it("match score", () => {
31 | expect(checkStringMatch("score", possibleYlabels)).toBeTruthy();
32 | });
33 | });
34 |
35 | describe("findFirstArray", () => {
36 | it("basic match", () => {
37 | const data = { x: [1, 2, 3] };
38 | const { result, arrayKey } = findFirstArray(data);
39 | expect(result).toEqual([1, 2, 3]);
40 | expect(arrayKey).toEqual("x");
41 | });
42 |
43 | it("data is array", () => {
44 | const data = [1, 2, 3];
45 | const { result, arrayKey } = findFirstArray(data);
46 | expect(result).toEqual([1, 2, 3]);
47 | expect(arrayKey).toBeNull();
48 | });
49 |
50 | it("array of objects", () => {
51 | const data = {
52 | x: "1",
53 | y: 200,
54 | arr: [
55 | { x: 1, y: 2 },
56 | { x: 2, y: 3 },
57 | { x: 3, y: 4 },
58 | ],
59 | xisDate: false,
60 | };
61 |
62 | const { result, arrayKey } = findFirstArray(data);
63 |
64 | expect(result).toEqual([
65 | { x: 1, y: 2 },
66 | { x: 2, y: 3 },
67 | { x: 3, y: 4 },
68 | ]);
69 | expect(arrayKey).toEqual("arr");
70 | });
71 |
72 | it("multiple arrays", () => {
73 | const data = {
74 | x: "1",
75 | y: [200, 300, 400],
76 | a: {
77 | arr2: [
78 | { x: 1, y: 2 },
79 | { x: 2, y: 3 },
80 | { x: 3, y: 4 },
81 | ],
82 | },
83 | xisDate: false,
84 | };
85 | const { result, arrayKey } = findFirstArray(data);
86 | expect(result).toEqual([200, 300, 400]);
87 | expect(arrayKey).toEqual("y");
88 | });
89 |
90 | it("no arrays", () => {
91 | const data = {
92 | April: "is",
93 | the: "cruelest",
94 | month: 100,
95 | };
96 | const { result, arrayKey } = findFirstArray(data);
97 | expect(result).toEqual(null);
98 | expect(arrayKey).toEqual(null);
99 | });
100 | });
101 |
102 | describe("extractGraphData", () => {
103 | it("basic match", () => {
104 | const data = { numberOfCustomers: [1, 2, 3] };
105 | const expected: GraphData = {
106 | type: "line",
107 | data: [
108 | { x: 0, y: 1 },
109 | { x: 1, y: 2 },
110 | { x: 2, y: 3 },
111 | ],
112 | graphTitle: "numberOfCustomers",
113 | };
114 | expect(extractGraphData(data, "line")).toEqual(expected);
115 | });
116 | it("match array of objects", () => {
117 | const data = {
118 | numberOfCustomers: [
119 | { category: 1, value: 2 },
120 | { category: 2, value: 3 },
121 | ],
122 | };
123 | const expected: GraphData = {
124 | type: "line",
125 | data: [
126 | { x: 1, y: 2 },
127 | { x: 2, y: 3 },
128 | ],
129 | xLabel: "category",
130 | yLabel: "value",
131 | graphTitle: "numberOfCustomers",
132 | xIsdate: false,
133 | };
134 | expect(extractGraphData(data, "line")).toEqual(expected);
135 | });
136 | it("match array of objects date", () => {
137 | const data = {
138 | numberOfCustomers: [
139 | { date: "2023-08-22", value: 2 },
140 | { date: "2023-08-23", value: 3 },
141 | ],
142 | };
143 | expect(extractGraphData(data, "line")?.xIsdate).toEqual(true);
144 | expect(extractGraphData(data, "line")?.data[0].y).toEqual(2);
145 | expect(extractGraphData(data, "line")?.data[1].y).toEqual(3);
146 |
147 | expect(extractGraphData(data, "line")?.data[0].x).toBeGreaterThan(19590);
148 | expect(extractGraphData(data, "line")?.data[0].x).toBeLessThan(
149 | 19590 + 365 * 100,
150 | ); // test will fail in 100 years time
151 | expect(extractGraphData(data, "line")?.data[1].x).toBeGreaterThan(
152 | extractGraphData(data, "line")?.data[0].x as number,
153 | );
154 | });
155 | it("no arrays", () => {
156 | const data = { numberOfCustomers: 100 };
157 | expect(extractGraphData(data, "line")).toEqual(null);
158 | });
159 | it("Only y axis match", () => {
160 | const data = {
161 | numberOfCustomers: [
162 | { snooker: 1, score: 2 },
163 | { snooker: 2, score: 3 },
164 | ],
165 | };
166 | const expected: GraphData = {
167 | type: "line",
168 | data: [
169 | { x: 0, y: 2 },
170 | { x: 1, y: 3 },
171 | ],
172 | yLabel: "score",
173 | graphTitle: "numberOfCustomers",
174 | };
175 | const res = extractGraphData(data, "line");
176 | expect(res).toEqual(expected);
177 | });
178 |
179 | it("No y axis match, but x axis match", () => {
180 | const data = {
181 | numberOfCustomers: [
182 | { date: 1, year: 2 },
183 | { date: 2, year: 3 },
184 | ],
185 | };
186 | expect(extractGraphData(data, "line")).toEqual(null);
187 | });
188 | it("multiple y axis match and x axis match", () => {
189 | const data = {
190 | numberOfCustomers: [
191 | { date: 1, year: 2, score: 100 },
192 | { date: 2, year: 3, score: 105 },
193 | ],
194 | };
195 | // This might be a bad test because the order of keys in a json is not guaranteed
196 | const expected: GraphData = {
197 | type: "line",
198 | data: [
199 | { x: 1, y: 100 },
200 | { x: 2, y: 105 },
201 | ],
202 | yLabel: "score",
203 | xLabel: "date",
204 | graphTitle: "numberOfCustomers",
205 | xIsdate: false,
206 | };
207 |
208 | expect(extractGraphData(data, "line")).toEqual(expected);
209 | });
210 | });
211 |
--------------------------------------------------------------------------------
/__tests__/parsers.test.ts:
--------------------------------------------------------------------------------
1 | import { describe, it, expect } from "@jest/globals";
2 | import {
3 | FunctionCall,
4 | makeDoubleExternalQuotes,
5 | parseFunctionCall,
6 | parseOutput,
7 | } from "../src/lib/parser";
8 |
9 | describe("Parse output", () => {
10 | it("should not error", () => {
11 | const output = parseOutput(
12 | "Reasoning: We have successfully retrieved the recent information about Mr. Daniel Solís Martínez's case. The most recent event is an insurance note related to water damage from a plumbing issue. The claim has not yet been completed and the case has been passed on to WekLaw.\n" +
13 | "\n" +
14 | "Plan:\n" +
15 | "- Inform the user about the retrieved information.\n" +
16 | "\n" +
17 | "Commands:\n",
18 | );
19 | expect(output).toBeDefined();
20 | expect(output.reasoning).toBe(
21 | "We have successfully retrieved the recent information about Mr. Daniel Solís Martínez's case. The most recent event is an insurance note related to water damage from a plumbing issue. The claim has not yet been completed and the case has been passed on to WekLaw.",
22 | );
23 | expect(output.plan).toBe(
24 | "- Inform the user about the retrieved information.",
25 | );
26 | expect(output.tellUser).toBe("");
27 | expect(output.commands).toStrictEqual([]);
28 | expect(output.completed).toBe(true);
29 | });
30 | it("should not error including tell user", () => {
31 | const output = parseOutput(
32 | "Reasoning:\n" +
33 | "The user's request is vague and needs clarification. We need to understand what kind of trap they are referring to, for which customer this is for, and what the context of the scheduling is about.\n" +
34 | "\n" +
35 | "Plan:\n" +
36 | "- Ask the user for more information about the type of trap, the customer involved, and any other relevant details.\n" +
37 | "\n" +
38 | "Tell user:\n" +
39 | "Could you please provide more information? Who is the customer we need to schedule a trap for and what type of trap are we talking about?\n",
40 | );
41 | expect(output).toBeDefined();
42 | expect(output.reasoning).toBe(
43 | "The user's request is vague and needs clarification. We need to understand what kind of trap they are referring to, for which customer this is for, and what the context of the scheduling is about.",
44 | );
45 | expect(output.plan).toBe(
46 | "- Ask the user for more information about the type of trap, the customer involved, and any other relevant details.",
47 | );
48 | expect(output.tellUser).toBe(
49 | "Could you please provide more information? Who is the customer we need to schedule a trap for and what type of trap are we talking about?",
50 | );
51 | expect(output.commands).toStrictEqual([]);
52 | expect(output.completed).toBe(true);
53 | });
54 | it("should not error no plan, no commands", () => {
55 | const output = parseOutput(
56 | "Reasoning: We have successfully retrieved the recent information about Mr. Nestor Alfaras's case.\n" +
57 | "\n" +
58 | "Tell user: The most recent update for Mr. Nestor Alfaras's case is an insurance note which has been completed. The subproject type was Plumbing and the details were passed on to WekLaw.\n",
59 | );
60 | expect(output).toBeDefined();
61 | expect(output.reasoning).toBe(
62 | "We have successfully retrieved the recent information about Mr. Nestor Alfaras's case.",
63 | );
64 | expect(output.plan).toBe("");
65 | expect(output.tellUser).toBe(
66 | "The most recent update for Mr. Nestor Alfaras's case is an insurance note which has been completed. The subproject type was Plumbing and the details were passed on to WekLaw.",
67 | );
68 | expect(output.commands).toStrictEqual([]);
69 | expect(output.completed).toBe(true);
70 | });
71 | it("should not error no plan, no commands", () => {
72 | const output = parseOutput(
73 | 'Reasoning: The search results show multiple individuals with the last name "Martinez". I need to clarify which Mr. Martinez the user is referring to.\n' +
74 | "\n" +
75 | "Plan:\n" +
76 | "- Ask the user to provide more information about Mr. Martinez so we can identify the correct person.\n" +
77 | "\n" +
78 | "Tell user: We have multiple customers with the last name Martinez. Could you please provide more information, such as a first name, to help identify the correct Mr. Martinez?",
79 | );
80 | expect(output).toBeDefined();
81 | expect(output.reasoning).toBe(
82 | 'The search results show multiple individuals with the last name "Martinez". I need to clarify which Mr. Martinez the user is referring to.',
83 | );
84 | expect(output.plan).toBe(
85 | "- Ask the user to provide more information about Mr. Martinez so we can identify the correct person.",
86 | );
87 | expect(output.tellUser).toBe(
88 | "We have multiple customers with the last name Martinez. Could you please provide more information, such as a first name, to help identify the correct Mr. Martinez?",
89 | );
90 | expect(output.commands).toStrictEqual([]);
91 | expect(output.completed).toBe(true);
92 | });
93 | it("should not output 'invalid input format:'", () => {
94 | const output = parseOutput(
95 | "Reasoning: The search results show multiple individuals with",
96 | );
97 | expect(output).toBeDefined();
98 | expect(output.reasoning).toBe(
99 | "The search results show multiple individuals with",
100 | );
101 | expect(output.plan).toBe("");
102 | expect(output.tellUser).toBe("");
103 | expect(output.commands).toStrictEqual([]);
104 | expect(output.completed).toBe(true);
105 | });
106 |
107 | it("tell user as command", () => {
108 | const output = parseOutput("Commands:\nTell user: i did a nice command");
109 | expect(output).toBeDefined();
110 | expect(output.reasoning).toBe("");
111 | expect(output.plan).toBe("");
112 | expect(output.tellUser).toBe("i did a nice command");
113 | expect(output.commands).toStrictEqual([]);
114 | expect(output.completed).toBe(true);
115 | });
116 |
117 | it("long output, parsing commands properly", () => {
118 | const gptOut =
119 | "Reasoning:\n" +
120 | "In order to generate a report showing the most active users in the last 30 days from the construction industry, we will need to create a segment for this specific group of users. Then, we will add necessary columns to this segment. After that, we can generate a report from this segment.\n" +
121 | "\n" +
122 | "Plan:\n" +
123 | "- Create a segment for users in the construction industry.\n" +
124 | "- Filter this segment to include only users who have been active in the last 30 days.\n" +
125 | "- Add necessary columns to this new segment (like user activity and user industry).\n" +
126 | "- Finally, create a report for this segment.\n" +
127 | "\n" +
128 | "Tell user:\n" +
129 | "I'm going to create a report that shows the most active users in the last 30 days from the construction industry. I'll start by creating and setting up a new segment for these users.\n" +
130 | "\n" +
131 | "Commands:\n" +
132 | 'create_segment(name="Active Construction Users", segmentType="user")\n' +
133 | 'create_report(reportName="Active Construction Users Report", description="Report showing most active construction industry users in last 30 days.", segmentId="{{id}}", timeframeDays=30, columns=[{"name": "User Activity","type": "number"},{"name": "User Industry","type": "string"}])';
134 | const output = parseOutput(gptOut);
135 | expect(output).toStrictEqual({
136 | reasoning:
137 | "In order to generate a report showing the most active users in the last 30 days from the construction industry, we will need to create a segment for this specific group of users. Then, we will add necessary columns to this segment. After that, we can generate a report from this segment.",
138 | plan:
139 | "- Create a segment for users in the construction industry.\n" +
140 | "- Filter this segment to include only users who have been active in the last 30 days.\n" +
141 | "- Add necessary columns to this new segment (like user activity and user industry).\n" +
142 | "- Finally, create a report for this segment.",
143 | tellUser:
144 | "I'm going to create a report that shows the most active users in the last 30 days from the construction industry. I'll start by creating and setting up a new segment for these users.",
145 | commands: [
146 | {
147 | name: "create_segment",
148 | args: {
149 | name: "Active Construction Users",
150 | segmentType: "user",
151 | },
152 | },
153 | {
154 | name: "create_report",
155 | args: {
156 | reportName: "Active Construction Users Report",
157 | description:
158 | "Report showing most active construction industry users in last 30 days.",
159 | segmentId: "{{id}}",
160 | timeframeDays: 30,
161 | columns: [
162 | {
163 | name: "User Activity",
164 | type: "number",
165 | },
166 | {
167 | name: "User Industry",
168 | type: "string",
169 | },
170 | ],
171 | },
172 | },
173 | ],
174 | completed: false,
175 | });
176 | });
177 | it("incorrectly-ordered real world output", () => {
178 | const gptOut =
179 | "Reasoning: To create a new account for the client, I will use the 'create_account' function. The required parameters are 'workflow' and 'data'. Under 'workflow', I will set the code to 'client.sub-account' as we are creating a sub-account for an existing client. Under 'data', I will provide the clientId (which in this case is 23030138) and a currency code as per ISO 4217.\n" +
180 | "\n" +
181 | "Tell user: Please provide the currency for the new account.\n" +
182 | "\n" +
183 | "Plan:\n" +
184 | '- Use create_account function with workflow code "client.sub-account" and data containing clientId and currency.';
185 | const output = parseOutput(gptOut);
186 | expect(output).toStrictEqual({
187 | reasoning:
188 | "To create a new account for the client, I will use the 'create_account' function. The required parameters are 'workflow' and 'data'. Under 'workflow', I will set the code to 'client.sub-account' as we are creating a sub-account for an existing client. Under 'data', I will provide the clientId (which in this case is 23030138) and a currency code as per ISO 4217.",
189 | plan: '- Use create_account function with workflow code "client.sub-account" and data containing clientId and currency.',
190 | tellUser: "Please provide the currency for the new account.",
191 | commands: [],
192 | completed: true,
193 | });
194 | });
195 | it("incomplete commands should not be tell user. Function ends in fullstop", () => {
196 | const output = parseOutput(
197 | "Reasoning: Some reasoning\n" +
198 | "\n" +
199 | "Plan:\n" +
200 | "- Inform the user about the retrieved information.\n" +
201 | "\n" +
202 | "Commands: function_call(arg1=1, arg2=2.",
203 | );
204 | expect(output).toBeDefined();
205 | expect(output.reasoning).toBe("Some reasoning");
206 | expect(output.plan).toBe(
207 | "- Inform the user about the retrieved information.",
208 | );
209 | expect(output.tellUser).toBe("");
210 | expect(output.commands).toStrictEqual([]);
211 | expect(output.completed).toBe(true);
212 | });
213 | it("incomplete commands should not be tell user. Function has no brackets yet", () => {
214 | const output = parseOutput(
215 | "Reasoning: Some reasoning\n" +
216 | "\n" +
217 | "Plan:\n" +
218 | "- Inform the user about the retrieved information.\n" +
219 | "\n" +
220 | "Commands: function_ca",
221 | );
222 | expect(output).toBeDefined();
223 | expect(output.reasoning).toBe("Some reasoning");
224 | expect(output.plan).toBe(
225 | "- Inform the user about the retrieved information.",
226 | );
227 | expect(output.tellUser).toBe("");
228 | expect(output.commands).toStrictEqual([
229 | {
230 | name: "function_ca",
231 | args: {},
232 | },
233 | ]);
234 | expect(output.completed).toBe(false);
235 | });
236 | it("tell user mistakenly put under commands", () => {
237 | const output = parseOutput(
238 | "Reasoning: Some reasoning\n" +
239 | "\n" +
240 | "Plan:\n" +
241 | "- Inform the user about the retrieved information.\n" +
242 | "\n" +
243 | "Commands: I have completed my job.",
244 | );
245 | expect(output).toBeDefined();
246 | expect(output.reasoning).toBe("Some reasoning");
247 | expect(output.plan).toBe(
248 | "- Inform the user about the retrieved information.",
249 | );
250 | expect(output.tellUser).toBe("I have completed my job.");
251 | expect(output.commands).toStrictEqual([]);
252 | expect(output.completed).toBe(true);
253 | });
254 | it("tell user mistakenly put under commands but tell user already exists", () => {
255 | const output = parseOutput(
256 | "Reasoning: Some reasoning\n" +
257 | "\n" +
258 | "Tell user: There's something i'd like to tell you\n" +
259 | "\n" +
260 | "Plan:\n" +
261 | "- Inform the user about the retrieved information.\n" +
262 | "\n" +
263 | "Commands: I have completed my job.",
264 | );
265 | expect(output).toBeDefined();
266 | expect(output.reasoning).toBe("Some reasoning");
267 | expect(output.plan).toBe(
268 | "- Inform the user about the retrieved information.",
269 | );
270 | expect(output.tellUser).toBe("There's something i'd like to tell you");
271 | expect(output.commands).toStrictEqual([]);
272 | expect(output.completed).toBe(true);
273 | });
274 | it("incomplete commands aren't put into tell user", () => {
275 | const output = parseOutput(
276 | "Reasoning: Some reasoning\n" +
277 | "\n" +
278 | "Tell user: There's something i'd like to tell you\n" +
279 | "\n" +
280 | "Plan:\n" +
281 | "- Inform the user about the retrieved information.\n" +
282 | "\n" +
283 | "Commands: function_call(a=1, ",
284 | );
285 | expect(output).toBeDefined();
286 | expect(output.reasoning).toBe("Some reasoning");
287 | expect(output.plan).toBe(
288 | "- Inform the user about the retrieved information.",
289 | );
290 | expect(output.tellUser).toBe("There's something i'd like to tell you");
291 | expect(output.commands).toStrictEqual([]);
292 | expect(output.completed).toBe(true);
293 | });
294 | it("Commands: None should be skipped", () => {
295 | const output = parseOutput(
296 | "Reasoning: Some reasoning\n" +
297 | "\n" +
298 | "Tell user: There's something i'd like to tell you\n" +
299 | "\n" +
300 | "Plan:\n" +
301 | "- Inform the user about the retrieved information.\n" +
302 | "\n" +
303 | "Commands:\n" +
304 | "None",
305 | );
306 | expect(output).toBeDefined();
307 | expect(output.reasoning).toBe("Some reasoning");
308 | expect(output.plan).toBe(
309 | "- Inform the user about the retrieved information.",
310 | );
311 | expect(output.tellUser).toBe("There's something i'd like to tell you");
312 | expect(output.commands).toStrictEqual([]);
313 | expect(output.completed).toBe(true);
314 | });
315 | it("When writing 'Reasoning:', it shouldn't count as Tell user", () => {
316 | const output = parseOutput("Reason");
317 | expect(output).toBeDefined();
318 | expect(output.reasoning).toBe("");
319 | expect(output.plan).toBe("");
320 | expect(output.tellUser).toBe("");
321 | expect(output.commands).toStrictEqual([]);
322 | expect(output.completed).toBe(true);
323 | });
324 | it("Bug found when required args with no choice are filled in", () => {
325 | const output = parseOutput(
326 | "Reasoning: \nTo break down the listings by the number of guests allowed, we need to fetch all the listings and then perform data analysis on them to count the number of listings that allow a certain number of guests.\n\nPlan:\n- Fetch all listings using get_listings function.\n- Perform data analysis using perform_data_analysis function to count the number of listings for each guest capacity.\n\nCommands:\nget_listings(limit=\"\", start=\"\")\nperform_data_analysis(instruction='Count the number of listings for each guest capacity', type='bar')",
327 | );
328 | expect(output).toBeDefined();
329 | expect(output.reasoning).toBe(
330 | "To break down the listings by the number of guests allowed, we need to fetch all the listings and then perform data analysis on them to count the number of listings that allow a certain number of guests.",
331 | );
332 | expect(output.plan).toBe(
333 | "- Fetch all listings using get_listings function.\n- Perform data analysis using perform_data_analysis function to count the number of listings for each guest capacity.",
334 | );
335 | expect(output.tellUser).toBe("");
336 | expect(output.commands).toStrictEqual([
337 | { name: "get_listings", args: { limit: "", start: "" } },
338 | {
339 | name: "perform_data_analysis",
340 | args: {
341 | instruction: "Count the number of listings for each guest capacity",
342 | type: "bar",
343 | },
344 | },
345 | ]);
346 | expect(output.completed).toBe(false);
347 | });
348 | it("Real world", () => {
349 | const text = `I've found a variety of healthy vegetarian recipes for different meals of the day. Here's a suggested meal plan:
350 |
351 | ### Breakfast
352 | - **Avocado Toast with Tomato and Poached Egg**: A simple yet nutritious start to the day, featuring ripe avocados, fresh tomatoes, and eggs on whole-grain bread.
353 | - **Green Smoothie Bowl**: Blend spinach, banana, almond milk, and chia seeds for a refreshing and filling breakfast bowl.
354 |
355 | ### Lunch
356 | - **Quinoa Salad with Mixed Vegetables**: A hearty salad with quinoa, cucumbers, tomatoes, bell peppers, and a lemon vinaigrette.
357 | - **Lentil Soup**: Rich in protein and fiber, this soup is both satisfying and healthy.
358 |
359 | ### Dinner
360 | - **Portobello and Poblano Enchiladas**: Stuffed flour tortillas with thinly-sliced portobellos and poblanos topped with cheddar and queso fresco. [Epicurious](URL11)
361 | - **Butternut Squash Risotto**: Creamy risotto with roasted butternut squash makes for a comforting dinner. [The Mediterranean Dish](URL12)
362 |
363 | ### Snacks
364 | - **Famous Tomato Dip**: A quick blend of canned tomatoes, almonds, garlic, and olive oil. [A Couple Cooks](URL16)
365 | - **Crispy Roasted Chickpeas**: Spiced chickpeas roasted until crunchy. [MOON and spoon and yum](URL20)
366 |
367 | This meal plan provides a balance of nutrients across different meals while keeping the dishes varied and interesting.
368 |
369 | Sources:
370 | [Epicurious](URL11)
371 | [The Mediterranean Dish](URL12)
372 | [A Couple Cooks](URL16)
373 | [MOON and spoon and yum](URL20)`;
374 | const out = parseOutput(text);
375 | expect(out).toEqual({
376 | plan: "",
377 | reasoning: "",
378 | commands: [],
379 | tellUser: text,
380 | completed: true,
381 | });
382 | });
383 | it("Real world with bad commands text", () => {
384 | const text = `I've found a variety of healthy vegetarian recipes for different meals of the day. Here's a suggested meal plan:
385 |
386 | ### Breakfast
387 | - **Avocado Toast with Tomato and Poached Egg**: A simple yet nutritious start to the day, featuring ripe avocados, fresh tomatoes, and eggs on whole-grain bread.
388 | - **Green Smoothie Bowl**: Blend spinach, banana, almond milk, and chia seeds for a refreshing and filling breakfast bowl.
389 |
390 | ### Lunch
391 | - **Quinoa Salad with Mixed Vegetables**: A hearty salad with quinoa, cucumbers, tomatoes, bell peppers, and a lemon vinaigrette.
392 | - **Lentil Soup**: Rich in protein and fiber, this soup is both satisfying and healthy.
393 |
394 | ### Dinner
395 | - **Portobello and Poblano Enchiladas**: Stuffed flour tortillas with thinly-sliced portobellos and poblanos topped with cheddar and queso fresco. [Epicurious](URL11)
396 | - **Butternut Squash Risotto**: Creamy risotto with roasted butternut squash makes for a comforting dinner. [The Mediterranean Dish](URL12)
397 |
398 | ### Snacks
399 | - **Famous Tomato Dip**: A quick blend of canned tomatoes, almonds, garlic, and olive oil. [A Couple Cooks](URL16)
400 | - **Crispy Roasted Chickpeas**: Spiced chickpeas roasted until crunchy. [MOON and spoon and yum](URL20)
401 |
402 | This meal plan provides a balance of nutrients across different meals while keeping the dishes varied and interesting.
403 |
404 | Sources:
405 | [Epicurious](URL11)
406 | [The Mediterranean Dish](URL12)
407 | [A Couple Cooks](URL16)
408 | [MOON and spoon and yum](URL20)
409 |
410 | Commands:
411 | None, I don't need to do anything here`;
412 | const out = parseOutput(text);
413 | expect(out).toEqual({
414 | plan: "",
415 | reasoning: "",
416 | commands: [],
417 | tellUser: text.split("Commands:")[0].trim(),
418 | completed: true,
419 | });
420 | });
421 | it("Real world with array of objects", () => {
422 | const text = `
423 | Reasoning:
424 | 1. The user wants to create a new active builder with specific parameters.
425 | 2. The create_builder function is used to create new builders in the ERP system.
426 | 3. The user has provided all necessary parameters for the function.
427 |
428 | Commands:
429 | create_builder(DbName="hello", Active=True, ModuleId="123", OwnerType=1, Fields=[{"Name": "bye", "Label": "bye", "Type": 1, "Required": True}], Name="hello")`;
430 | const out = parseOutput(text);
431 | expect(out).toEqual({
432 | plan: "",
433 | reasoning:
434 | "1. The user wants to create a new active builder with specific parameters.\n2. The create_builder function is used to create new builders in the ERP system.\n3. The user has provided all necessary parameters for the function.",
435 | commands: [
436 | {
437 | name: "create_builder",
438 | args: {
439 | DbName: "hello",
440 | Active: true,
441 | ModuleId: "123",
442 | OwnerType: 1,
443 | Fields: [{ Name: "bye", Label: "bye", Type: 1, Required: true }],
444 | Name: "hello",
445 | },
446 | },
447 | ],
448 | tellUser: "",
449 | completed: false,
450 | });
451 | });
452 | });
453 |
454 | describe("parseFunctionCall", () => {
455 | it("hyphenated argument name", () => {
456 | const str = `get_account(gtmhub-accountId="64b17ac6548041a751aaf2f6", id_team="64b17ac6548041a751aaf2f7")`;
457 | const output = parseFunctionCall(str);
458 | const expectedOutput = {
459 | name: "get_account",
460 | args: {
461 | "gtmhub-accountId": "64b17ac6548041a751aaf2f6",
462 | id_team: "64b17ac6548041a751aaf2f7",
463 | },
464 | };
465 | expect(output).toStrictEqual(expectedOutput);
466 | });
467 | it("argument name with dots in", () => {
468 | const str = `list_accounts(data.account.availableBalanceFrom="1000")`;
469 | const output = parseFunctionCall(str);
470 | const expectedOutput = {
471 | name: "list_accounts",
472 | args: {
473 | "data.account.availableBalanceFrom": "1000",
474 | },
475 | };
476 | expect(output).toStrictEqual(expectedOutput);
477 | });
478 | it("argument name with space in skipped", () => {
479 | const str = `list_accounts(data availableBalanceFrom="1000")`;
480 | const output = parseFunctionCall(str);
481 | const expectedOutput = {
482 | name: "list_accounts",
483 | args: {
484 | availableBalanceFrom: "1000",
485 | },
486 | };
487 | expect(output).toStrictEqual(expectedOutput);
488 | });
489 | it("object passed to function", () => {
490 | const str = `create_goal(gtmhub-accountId='64b94e50c1815107739582f9', goal={"title": "Close sales"}, ownerIds=['64b94e50c1815107739582fa'], sessionId='64b94e50c1815107739582fc')`;
491 | const output = parseFunctionCall(str);
492 | const expectedOutput = {
493 | name: "create_goal",
494 | args: {
495 | "gtmhub-accountId": "64b94e50c1815107739582f9",
496 | goal: { title: "Close sales" },
497 | ownerIds: ["64b94e50c1815107739582fa"],
498 | sessionId: "64b94e50c1815107739582fc",
499 | },
500 | };
501 | expect(output).toStrictEqual(expectedOutput);
502 | });
503 |
504 | it("correctly parses function with floating point argument", () => {
505 | const str = `set_coordinates(x=3.14, y=0.98)`;
506 | const output = parseFunctionCall(str);
507 | const expectedOutput = {
508 | name: "set_coordinates",
509 | args: { x: 3.14, y: 0.98 },
510 | };
511 | expect(output).toEqual(expectedOutput);
512 | });
513 | it("correctly parses function mixed argument types", () => {
514 | const str = `set_coordinates(x=3.14, placeName="The Moon", y=0.98)`;
515 | const output = parseFunctionCall(str);
516 | const expectedOutput = {
517 | name: "set_coordinates",
518 | args: { x: 3.14, y: 0.98, placeName: "The Moon" },
519 | };
520 | expect(output).toEqual(expectedOutput);
521 | });
522 | it("string has a comma in it", () => {
523 | const str = `set_coordinates(x=3.14, placeName="The Moon, the sun", y=0.98)`;
524 | const output = parseFunctionCall(str);
525 | const expectedOutput = {
526 | name: "set_coordinates",
527 | args: { x: 3.14, y: 0.98, placeName: "The Moon, the sun" },
528 | };
529 | expect(output).toEqual(expectedOutput);
530 | });
531 | it("string has a comma and single quotes in it", () => {
532 | const str = `set_coordinates(x=3.14, placeName="The Moon, 'very nice eh', the sun", y=0.98)`;
533 | const output = parseFunctionCall(str);
534 | const expectedOutput = {
535 | name: "set_coordinates",
536 | args: {
537 | x: 3.14,
538 | y: 0.98,
539 | placeName: "The Moon, 'very nice eh', the sun",
540 | },
541 | };
542 | expect(output).toEqual(expectedOutput);
543 | });
544 | it("string has escaped quote in it", () => {
545 | const str = `set_coordinates(x=3.14, placeName="The Moon,\\" sun ", y=0.98)`;
546 | const output = parseFunctionCall(str);
547 | const expectedOutput = {
548 | name: "set_coordinates",
549 | args: {
550 | x: 3.14,
551 | y: 0.98,
552 | placeName: 'The Moon," sun ',
553 | },
554 | };
555 | expect(output).toEqual(expectedOutput);
556 | });
557 | it("returns function with no arguments when none are provided", () => {
558 | const str = `do_something()`;
559 | const output = parseFunctionCall(str);
560 | const expectedOutput = { name: "do_something", args: {} };
561 | expect(output).toEqual(expectedOutput);
562 | });
563 | it("throws an error when function call format is invalid", () => {
564 | const str = `getAccount "64b17ac6548041a751aaf2f6" "64b17ac6548041a751aaf2f7"`;
565 | expect(() => parseFunctionCall(str)).toThrowError(
566 | "Invalid function call format: " + str,
567 | );
568 | });
569 | it("array of dictionaries", () => {
570 | const commandText =
571 | 'create_report(reportName="Active Construction Users Report", description="Report showing most active construction industry users in last 30 days.", segmentId="{{id}}", timeframeDays=30, columns=[{"name": "User Activity","type": "number"},{"name": "User Industry","type": "string"}])';
572 | const output = parseFunctionCall(commandText);
573 | const expectedOutput = {
574 | name: "create_report",
575 | args: {
576 | reportName: "Active Construction Users Report",
577 | description:
578 | "Report showing most active construction industry users in last 30 days.",
579 | segmentId: "{{id}}",
580 | timeframeDays: 30,
581 | columns: [
582 | {
583 | name: "User Activity",
584 | type: "number",
585 | },
586 | {
587 | name: "User Industry",
588 | type: "string",
589 | },
590 | ],
591 | },
592 | };
593 | expect(output).toEqual(expectedOutput);
594 | });
595 | it("nested dictionaries", () => {
596 | const commandText = `create_account(workflow={"code": "client.sub-account"}, data={"account": {"clientId": "09f42c3a-dcea-4468-a77a-40f1e6d456f1", "currency": "USD", "mainAccountId": "74ef55ef-a583-4a96-92f2-b3ad3b5c0682"}})`;
597 | const output = parseFunctionCall(commandText);
598 | const expectedOutput = {
599 | name: "create_account",
600 | args: {
601 | workflow: { code: "client.sub-account" },
602 | data: {
603 | account: {
604 | clientId: "09f42c3a-dcea-4468-a77a-40f1e6d456f1",
605 | currency: "USD",
606 | mainAccountId: "74ef55ef-a583-4a96-92f2-b3ad3b5c0682",
607 | },
608 | },
609 | },
610 | };
611 | expect(output).toEqual(expectedOutput);
612 | });
613 | it("parse escaped quotes properly", () => {
614 | const out = parseFunctionCall(
615 | `search_filings(query="formType:\\"S-4\\" AND NOT formType:(\\"4/A\\" OR \\"S-4 POS\\")", ticker="AAPL")`,
616 | );
617 | expect(out).toStrictEqual({
618 | name: "search_filings",
619 | args: {
620 | query: 'formType:"S-4" AND NOT formType:("4/A" OR "S-4 POS")',
621 | ticker: "AAPL",
622 | },
623 | });
624 | });
625 | it("parse escaped quotes properly - single quotes", () => {
626 | const out = parseFunctionCall(
627 | `search_filings(query='formType:"S-4" AND NOT formType:("4/A" OR "S-4 POS")', ticker="AAPL")`,
628 | );
629 | expect(out).toStrictEqual({
630 | name: "search_filings",
631 | args: {
632 | query: 'formType:"S-4" AND NOT formType:("4/A" OR "S-4 POS")',
633 | ticker: "AAPL",
634 | },
635 | });
636 | });
637 | it("parse escaped quotes properly - backslash", () => {
638 | const out = parseFunctionCall(
639 | `perform_data_analysis(instruction='Break down Lucas\\' closed deals in the last 6 months by value')`,
640 | );
641 | expect(out).toStrictEqual({
642 | name: "perform_data_analysis",
643 | args: {
644 | instruction:
645 | "Break down Lucas' closed deals in the last 6 months by value",
646 | },
647 | });
648 | });
649 | it("parse okay when brackets forgotten", () => {
650 | const out = parseFunctionCall(`list_users`);
651 | expect(out).toStrictEqual({
652 | name: "list_users",
653 | args: {},
654 | });
655 | });
656 | it("replace backslash underscore with underscore in fn name and arg names, but not string values", () => {
657 | const out = parseFunctionCall(
658 | `update\\_property(property\\_id="ID\\_1", bedrooms=4)`,
659 | );
660 | expect(out).toStrictEqual({
661 | name: "update_property",
662 | args: { property_id: "ID\\_1", bedrooms: 4 },
663 | });
664 | });
665 | it("True with capital T, False with capital F", () => {
666 | const out = parseFunctionCall(
667 | `update\\_property(expand=True, go_away=False)`,
668 | );
669 | expect(out).toStrictEqual({
670 | name: "update_property",
671 | args: { expand: true, go_away: false },
672 | });
673 | });
674 | it("Numbered command", () => {
675 | const out = parseFunctionCall(
676 | `1. instruct_coder(instruction="Find all deals that were closed in the past 6 months. Then, calculate the total revenue generated by each sales rep from these deals. Finally, identify and return the name of the sales rep with the highest total revenue.")`,
677 | );
678 | expect(out).toStrictEqual({
679 | name: "instruct_coder",
680 | args: {
681 | instruction:
682 | "Find all deals that were closed in the past 6 months. Then, calculate the total revenue generated by each sales rep from these deals. Finally, identify and return the name of the sales rep with the highest total revenue.",
683 | },
684 | });
685 | });
686 | it("Commas between commands", () => {
687 | const out = parseFunctionCall(`item_get(id=9),`);
688 | expect(out).toStrictEqual({
689 | name: "item_get",
690 | args: {
691 | id: 9,
692 | },
693 | });
694 | });
695 | });
696 |
697 | describe("makeDoubleExternalQuotes", () => {
698 | it("single quotes with escaped double quotes", () => {
699 | const out = makeDoubleExternalQuotes(`'hello \\"world\\"'`);
700 | expect(out).toBe(`"hello \\"world\\""`);
701 | });
702 | });
703 |
--------------------------------------------------------------------------------
/__tests__/processObjectForDisplay.test.ts:
--------------------------------------------------------------------------------
1 | import { describe, expect, it } from "@jest/globals";
2 | import { processObjectForDisplay } from "../src/lib/utils";
3 |
4 | describe("remove single key nodes", () => {
5 | it("Handles empty object", () => {
6 | const data = {};
7 | const expected = {};
8 |
9 | expect(processObjectForDisplay(data)).toEqual(expected);
10 | });
11 |
12 | it("array returns same array", () => {
13 | const data = [1, 2, 3];
14 | const expected = [1, 2, 3];
15 |
16 | const output = processObjectForDisplay(data);
17 | expect(output).toEqual(expected);
18 | });
19 |
20 | it("special case single array", () => {
21 | const data = { oldGregg: [1, 2, 3] };
22 | const expected = [1, 2, 3];
23 | const output = processObjectForDisplay(data);
24 | expect(output).toEqual(expected);
25 | });
26 | it("nested special case", () => {
27 | const data = { root: { branch: { leaf: [1, 2, 3] } } };
28 | const expected = [1, 2, 3];
29 |
30 | expect(processObjectForDisplay(data)).toEqual(expected);
31 | });
32 | it("more complex nested special case", () => {
33 | const data = {
34 | a: {
35 | b: [
36 | { nice: 1, nested: { boy: 2 } },
37 | { nice: 2, nested: { boy: 3 } },
38 | ],
39 | },
40 | };
41 |
42 | const expected = [
43 | { nice: 1, nested: { boy: 2 } },
44 | { nice: 2, nested: { boy: 3 } },
45 | ];
46 |
47 | const output = processObjectForDisplay(data);
48 | expect(output).toEqual(expected);
49 | });
50 |
51 | it("array of objects", () => {
52 | const data = [
53 | { a: 1, b: 2, c: 3 },
54 | { a: 4, b: 5, c: 6 },
55 | ];
56 | const output = processObjectForDisplay(data);
57 | expect(output).toEqual(data);
58 | });
59 |
60 | it("single node key nested inside complex object", () => {
61 | const data = {
62 | umbrella: {
63 | responses: { data: [1, 2, 3] },
64 | theHitcher: "put you in the picture",
65 | tony: { harrison: "outrage" },
66 | },
67 | };
68 |
69 | const expected = {
70 | "umbrella -> responses -> data": [1, 2, 3],
71 | "umbrella -> theHitcher": "put you in the picture",
72 | "umbrella -> tony -> harrison": "outrage",
73 | };
74 | const output = processObjectForDisplay(data);
75 | expect(output).toEqual(expected);
76 | });
77 |
78 | it("Does not lose data for multiple nested single key", () => {
79 | const data = {
80 | outer: {
81 | middle: {
82 | inner: "value",
83 | },
84 | middle2: "value2",
85 | },
86 | };
87 |
88 | const expected = {
89 | "outer -> middle -> inner": "value",
90 | "outer -> middle2": "value2",
91 | };
92 |
93 | expect(processObjectForDisplay(data)).toEqual(expected);
94 | });
95 |
96 | it("Does not lose data for deeply nested structures", () => {
97 | const data = {
98 | first: {
99 | second: {
100 | third: {
101 | fourth: { fifth: "minor fall, major lift" },
102 | },
103 | other: "value2",
104 | },
105 | third: {
106 | fifth: [
107 | "i",
108 | "remember",
109 | "you",
110 | "well",
111 | "in",
112 | "the",
113 | "chelsea",
114 | "hotel",
115 | ],
116 | },
117 | },
118 | };
119 |
120 | const expected = {
121 | "first -> second -> third -> fourth -> fifth": "minor fall, major lift",
122 | "first -> second -> other": "value2",
123 | "first -> third -> fifth": [
124 | "i",
125 | "remember",
126 | "you",
127 | "well",
128 | "in",
129 | "the",
130 | "chelsea",
131 | "hotel",
132 | ],
133 | };
134 |
135 | expect(processObjectForDisplay(data)).toEqual(expected);
136 | });
137 |
138 | it("doesnt mutate original data", () => {
139 | const data = {
140 | first: {
141 | second: {
142 | third: {
143 | fourth: "value",
144 | },
145 | other: "value2",
146 | },
147 | third: {
148 | fifth: "value3",
149 | },
150 | },
151 | };
152 |
153 | const originalData = JSON.parse(JSON.stringify(data));
154 |
155 | const result = processObjectForDisplay(data);
156 | expect(data).toEqual(originalData);
157 | expect(result).not.toBe(data);
158 | });
159 |
160 | it("Array of single key not changed", () => {
161 | const data = [
162 | { make: "Alfa Romeo" },
163 | { make: "Ferrari" },
164 | { make: "Dodge" },
165 | { make: "Subaru" },
166 | { make: "Toyota" },
167 | { make: "Volkswagen" },
168 | { make: "Volvo" },
169 | { make: "Audi" },
170 | ];
171 |
172 | const result = processObjectForDisplay(data);
173 | expect(result).toEqual(data);
174 | });
175 | });
176 |
--------------------------------------------------------------------------------
/__tests__/removeUUIDs.test.ts:
--------------------------------------------------------------------------------
1 | import { removeUUIDs } from "../src/lib/utils";
2 |
3 | describe("removeUUIDs", () => {
4 | it("empty object", () => {
5 | expect(removeUUIDs({})).toEqual({});
6 | });
7 |
8 | it("simple object with no UUIDs", () => {
9 | expect(removeUUIDs({ a: "abc", b: "def" })).toEqual({ a: "abc", b: "def" });
10 | });
11 |
12 | it("simple object with UUIDs", () => {
13 | expect(
14 | removeUUIDs({ a: "abc", b: "3b241101-e2bb-4255-8caf-4136c566a964" }),
15 | ).toEqual({ a: "abc" });
16 | });
17 |
18 | it("nested object with UUIDs", () => {
19 | expect(
20 | removeUUIDs({
21 | a: "abc",
22 | b: { c: "3b241101-e2bb-4255-8caf-4136c566a964" },
23 | }),
24 | ).toEqual({ a: "abc", b: {} });
25 | });
26 |
27 | it("simple array with no UUIDs", () => {
28 | expect(removeUUIDs(["abc", "def"])).toEqual(["abc", "def"]);
29 | });
30 |
31 | it("simple array with UUIDs", () => {
32 | expect(
33 | removeUUIDs(["abc", "3b241101-e2bb-4255-8caf-4136c566a964"]),
34 | ).toEqual(["abc"]);
35 | });
36 |
37 | it("nested array with UUIDs", () => {
38 | expect(
39 | removeUUIDs([
40 | "abc",
41 | ["3b241101-e2bb-4255-8caf-4136c566a964", "cheese is a kind of meat"],
42 | ]),
43 | ).toEqual(["abc", ["cheese is a kind of meat"]]);
44 | });
45 |
46 | it("array of objects with UUIDs", () => {
47 | expect(
48 | removeUUIDs([{ a: "abc", b: "3b241101-e2bb-4255-8caf-4136c566a964" }]),
49 | ).toEqual([{ a: "abc" }]);
50 | });
51 |
52 | it("complex object and array with UUIDs", () => {
53 | expect(
54 | removeUUIDs({
55 | a: "abc",
56 | b: "3b241101-e2bb-4255-8caf-4136c566a964",
57 | c: ["def", "3b241101-e2bb-4255-8caf-4136c566a964"],
58 | }),
59 | ).toEqual({ a: "abc", c: ["def"] });
60 | });
61 |
62 | it("null object", () => {
63 | expect(removeUUIDs(null)).toEqual(null);
64 | });
65 |
66 | it("very nested object with UUIDs", () => {
67 | const input = {
68 | a: "abc",
69 | b: {
70 | c: "3b241101-e2bb-4255-8caf-4136c566a964",
71 | d: {
72 | e: "123",
73 | f: {
74 | g: "3b241101-e2bb-4255-8caf-4136c566a964",
75 | h: "456",
76 | },
77 | },
78 | },
79 | i: "def",
80 | };
81 | const expectedOutput = {
82 | a: "abc",
83 | b: { d: { e: "123", f: { h: "456" } } },
84 | i: "def",
85 | };
86 | expect(removeUUIDs(input)).toEqual(expectedOutput);
87 | });
88 |
89 | it("very nested array with UUIDs", () => {
90 | const input = [
91 | "abc",
92 | [
93 | "def",
94 | ["ghi", ["3b241101-e2bb-4255-8caf-4136c566a964", "jkl"], "mno"],
95 | "pqr",
96 | ],
97 | "stu",
98 | ];
99 | const expectedOutput = [
100 | "abc",
101 | ["def", ["ghi", ["jkl"], "mno"], "pqr"],
102 | "stu",
103 | ];
104 | expect(removeUUIDs(input)).toEqual(expectedOutput);
105 | });
106 | });
107 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | sed_command="sed -i"
2 |
3 | if [ "$(uname)" == "Darwin" ]; then
4 | # macOS
5 | sed_command="sed -i ''"
6 | fi
7 |
8 | rollup -c
9 | mv dist/src/index.d.ts dist/index.d.ts
10 | $sed_command 's/.\/components/.\/src\/components/g' dist/index.d.ts
11 | $sed_command 's/.\/lib/.\/src\/lib/g' dist/index.d.ts
--------------------------------------------------------------------------------
/examples/angular/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see https://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.ts]
12 | quote_type = single
13 |
14 | [*.md]
15 | max_line_length = off
16 | trim_trailing_whitespace = false
17 |
--------------------------------------------------------------------------------
/examples/angular/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # Compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 | /bazel-out
8 |
9 | # Node
10 | /node_modules
11 | npm-debug.log
12 | yarn-error.log
13 |
14 | # IDEs and editors
15 | .idea/
16 | .project
17 | .classpath
18 | .c9/
19 | *.launch
20 | .settings/
21 | *.sublime-workspace
22 |
23 | # Visual Studio Code
24 | .vscode/*
25 | !.vscode/settings.json
26 | !.vscode/tasks.json
27 | !.vscode/launch.json
28 | !.vscode/extensions.json
29 | .history/*
30 |
31 | # Miscellaneous
32 | /.angular/cache
33 | .sass-cache/
34 | /connect.lock
35 | /coverage
36 | /libpeerconnection.log
37 | testem.log
38 | /typings
39 |
40 | # System files
41 | .DS_Store
42 | Thumbs.db
43 |
--------------------------------------------------------------------------------
/examples/angular/README.md:
--------------------------------------------------------------------------------
1 | # Superflows-in-Angular Example
2 |
3 |
4 | [This commit has](https://github.com/Superflows-AI/chat-ui/pull/43/commits/38c0b52dcbd5bc533d24ff1fc0a83828e02acf5b) the full list of changes to add the `SuperflowsModal` to the project.
5 |
6 | To use this for real you'll need to change the `superflowsApiKey` to your in `src/app/chatUI.component.ts`. You can get an API key [here](https://dashboard.superflows.ai/api-settings) by signing up for a free account.
7 |
8 | ## Development server
9 |
10 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
11 |
12 | ## Code scaffolding
13 |
14 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
15 |
16 | ## Build
17 |
18 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
19 |
20 | ## Running unit tests
21 |
22 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
23 |
24 | Note: This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 16.2.6.
25 |
--------------------------------------------------------------------------------
/examples/angular/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "my-angular-app": {
7 | "projectType": "application",
8 | "schematics": {},
9 | "root": "",
10 | "sourceRoot": "src",
11 | "prefix": "app",
12 | "architect": {
13 | "build": {
14 | "builder": "@angular-devkit/build-angular:browser",
15 | "options": {
16 | "outputPath": "dist/my-angular-app",
17 | "index": "src/index.html",
18 | "main": "src/main.ts",
19 | "polyfills": [
20 | "zone.js"
21 | ],
22 | "tsConfig": "tsconfig.app.json",
23 | "assets": [
24 | "src/favicon.ico",
25 | "src/assets"
26 | ],
27 | "styles": [
28 | "src/styles.css"
29 | ],
30 | "scripts": []
31 | },
32 | "configurations": {
33 | "production": {
34 | "budgets": [
35 | {
36 | "type": "initial",
37 | "maximumWarning": "500kb",
38 | "maximumError": "1mb"
39 | },
40 | {
41 | "type": "anyComponentStyle",
42 | "maximumWarning": "2kb",
43 | "maximumError": "4kb"
44 | }
45 | ],
46 | "outputHashing": "all"
47 | },
48 | "development": {
49 | "buildOptimizer": false,
50 | "optimization": false,
51 | "vendorChunk": true,
52 | "extractLicenses": false,
53 | "sourceMap": true,
54 | "namedChunks": true
55 | }
56 | },
57 | "defaultConfiguration": "production"
58 | },
59 | "serve": {
60 | "builder": "@angular-devkit/build-angular:dev-server",
61 | "configurations": {
62 | "production": {
63 | "browserTarget": "my-angular-app:build:production"
64 | },
65 | "development": {
66 | "browserTarget": "my-angular-app:build:development"
67 | }
68 | },
69 | "defaultConfiguration": "development"
70 | },
71 | "extract-i18n": {
72 | "builder": "@angular-devkit/build-angular:extract-i18n",
73 | "options": {
74 | "browserTarget": "my-angular-app:build"
75 | }
76 | },
77 | "test": {
78 | "builder": "@angular-devkit/build-angular:karma",
79 | "options": {
80 | "polyfills": [
81 | "zone.js",
82 | "zone.js/testing"
83 | ],
84 | "tsConfig": "tsconfig.spec.json",
85 | "assets": [
86 | "src/favicon.ico",
87 | "src/assets"
88 | ],
89 | "styles": [
90 | "src/styles.css"
91 | ],
92 | "scripts": []
93 | }
94 | }
95 | }
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/examples/angular/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "my-angular-app",
3 | "version": "0.0.0",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "watch": "ng build --watch --configuration development",
9 | "test": "ng test"
10 | },
11 | "private": true,
12 | "dependencies": {
13 | "@angular/animations": "^16.2.0",
14 | "@angular/common": "^16.2.0",
15 | "@angular/compiler": "^16.2.0",
16 | "@angular/core": "^16.2.0",
17 | "@angular/forms": "^16.2.0",
18 | "@angular/platform-browser": "^16.2.0",
19 | "@angular/platform-browser-dynamic": "^16.2.0",
20 | "@angular/router": "^16.2.0",
21 | "@superflows/chat-ui-react": "^1.2.61",
22 | "react-dom": "^18.2.0",
23 | "rxjs": "~7.8.0",
24 | "tslib": "^2.3.0",
25 | "zone.js": "~0.13.0"
26 | },
27 | "devDependencies": {
28 | "@angular-devkit/build-angular": "^16.2.6",
29 | "@angular/cli": "^16.2.6",
30 | "@angular/compiler-cli": "^16.2.0",
31 | "@types/jasmine": "~4.3.0",
32 | "@types/react-dom": "^18.2.13",
33 | "jasmine-core": "~4.6.0",
34 | "karma": "~6.4.0",
35 | "karma-chrome-launcher": "~3.2.0",
36 | "karma-coverage": "~2.2.0",
37 | "karma-jasmine": "~5.1.0",
38 | "karma-jasmine-html-reporter": "~2.1.0",
39 | "typescript": "~5.1.3"
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/examples/angular/src/app/app-routing.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { RouterModule, Routes } from '@angular/router';
3 | import { ReactComponentWrapperComponent } from './chatUI.component';
4 |
5 | const routes: Routes = [
6 | { path: '', component: ReactComponentWrapperComponent },
7 | ];
8 |
9 | @NgModule({
10 | imports: [RouterModule.forRoot(routes)],
11 | exports: [RouterModule],
12 | })
13 | export class AppRoutingModule {}
14 |
--------------------------------------------------------------------------------
/examples/angular/src/app/app.component.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Superflows-AI/chat-ui/81005fd7622af9c2489fb638b1ba1af0b2d73277/examples/angular/src/app/app.component.css
--------------------------------------------------------------------------------
/examples/angular/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
304 |
305 |
306 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
343 |
344 |
{{ title }} app is running!
345 |
346 |
350 |
351 |
352 |
353 |
354 |
Resources
355 |
Here are some links to help you get started:
356 |
357 |
388 |
389 |
390 |
Next Steps
391 |
What do you want to do next with your app?
392 |
393 |
394 |
395 |
396 |
400 |
401 |
405 |
406 |
410 |
411 |
415 |
416 |
420 |
421 |
425 |
426 |
427 |
428 |
429 |
ng generate component xyz
430 |
ng add @angular/material
431 |
ng add @angular/pwa
432 |
ng add _____
433 |
ng test
434 |
ng build
435 |
436 |
437 |
438 |
454 |
455 |
456 |
468 |
469 |
473 |
474 |
475 |
476 |
477 |
478 |
479 |
480 |
481 |
482 |
483 |
484 |
485 |
--------------------------------------------------------------------------------
/examples/angular/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 | import { RouterTestingModule } from '@angular/router/testing';
3 | import { AppComponent } from './app.component';
4 |
5 | describe('AppComponent', () => {
6 | beforeEach(() => TestBed.configureTestingModule({
7 | imports: [RouterTestingModule],
8 | declarations: [AppComponent]
9 | }));
10 |
11 | it('should create the app', () => {
12 | const fixture = TestBed.createComponent(AppComponent);
13 | const app = fixture.componentInstance;
14 | expect(app).toBeTruthy();
15 | });
16 |
17 | it(`should have as title 'my-angular-app'`, () => {
18 | const fixture = TestBed.createComponent(AppComponent);
19 | const app = fixture.componentInstance;
20 | expect(app.title).toEqual('my-angular-app');
21 | });
22 |
23 | it('should render title', () => {
24 | const fixture = TestBed.createComponent(AppComponent);
25 | fixture.detectChanges();
26 | const compiled = fixture.nativeElement as HTMLElement;
27 | expect(compiled.querySelector('.content span')?.textContent).toContain('my-angular-app app is running!');
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/examples/angular/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-root',
5 | templateUrl: './app.component.html',
6 | styleUrls: ['./app.component.css']
7 | })
8 | export class AppComponent {
9 | title = 'my-angular-app';
10 | }
11 |
--------------------------------------------------------------------------------
/examples/angular/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { BrowserModule } from '@angular/platform-browser';
3 |
4 | import { AppRoutingModule } from './app-routing.module';
5 | import { AppComponent } from './app.component';
6 | import { ReactComponentWrapperComponent } from './chatUI.component';
7 |
8 | @NgModule({
9 | declarations: [AppComponent, ReactComponentWrapperComponent],
10 | imports: [BrowserModule, AppRoutingModule],
11 | providers: [],
12 | bootstrap: [AppComponent],
13 | })
14 | export class AppModule {}
15 |
--------------------------------------------------------------------------------
/examples/angular/src/app/chatUI.component.ts:
--------------------------------------------------------------------------------
1 | import {
2 | AfterViewInit,
3 | Component,
4 | ElementRef,
5 | OnDestroy,
6 | ViewChild,
7 | } from '@angular/core';
8 | import * as ReactDOM from 'react-dom';
9 | import * as React from 'react';
10 | import { SuperflowsModal } from '@superflows/chat-ui-react';
11 | import { createRoot } from 'react-dom/client';
12 |
13 | @Component({
14 | selector: 'app-react-component',
15 | template: '',
16 | })
17 | export class ReactComponentWrapperComponent
18 | implements OnDestroy, AfterViewInit
19 | {
20 | @ViewChild('reactContainer', { static: true }) container!: ElementRef;
21 | // @Input() superflowsApiKey: any; // replace superflowsApiKey with actual prop names of your React component
22 | // Add more @Input() if your React component accepts more props
23 |
24 | private componentRef: any;
25 | private root: any;
26 |
27 | constructor() {}
28 |
29 | ngAfterViewInit() {
30 | this.root = createRoot(this.container.nativeElement);
31 | this.root.render(
32 | React.createElement(SuperflowsModal, {
33 | AIname: 'Superflows',
34 | open: true,
35 | setOpen: () => {},
36 | superflowsApiKey: 'A KEY',
37 | }), // replace with actual prop names
38 | );
39 | }
40 |
41 | ngOnDestroy() {
42 | this.root.unmount(this.container.nativeElement);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/examples/angular/src/assets/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Superflows-AI/chat-ui/81005fd7622af9c2489fb638b1ba1af0b2d73277/examples/angular/src/assets/.gitkeep
--------------------------------------------------------------------------------
/examples/angular/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Superflows-AI/chat-ui/81005fd7622af9c2489fb638b1ba1af0b2d73277/examples/angular/src/favicon.ico
--------------------------------------------------------------------------------
/examples/angular/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | MyAngularApp
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/examples/angular/src/main.ts:
--------------------------------------------------------------------------------
1 | import './polyfills';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 | import { AppModule } from './app/app.module';
4 |
5 | platformBrowserDynamic()
6 | .bootstrapModule(AppModule)
7 | .catch((err) => console.error(err));
8 |
--------------------------------------------------------------------------------
/examples/angular/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | (window as any).global = window;
2 |
--------------------------------------------------------------------------------
/examples/angular/src/styles.css:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 |
--------------------------------------------------------------------------------
/examples/angular/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "extends": "./tsconfig.json",
4 | "compilerOptions": {
5 | "outDir": "./out-tsc/app",
6 | "types": []
7 | },
8 | "files": [
9 | "src/main.ts"
10 | ],
11 | "include": [
12 | "src/**/*.d.ts"
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/examples/angular/tsconfig.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "compileOnSave": false,
4 | "compilerOptions": {
5 | "allowSyntheticDefaultImports": true,
6 | "baseUrl": "./",
7 | "outDir": "./dist/out-tsc",
8 | "forceConsistentCasingInFileNames": true,
9 | "strict": true,
10 | "noImplicitOverride": true,
11 | "noPropertyAccessFromIndexSignature": true,
12 | "noImplicitReturns": true,
13 | "noFallthroughCasesInSwitch": true,
14 | "sourceMap": true,
15 | "declaration": false,
16 | "downlevelIteration": true,
17 | "experimentalDecorators": true,
18 | "moduleResolution": "node",
19 | "importHelpers": true,
20 | "target": "ES2022",
21 | "module": "ES2022",
22 | "useDefineForClassFields": false,
23 | "lib": [
24 | "ES2022",
25 | "dom"
26 | ]
27 | },
28 | "angularCompilerOptions": {
29 | "enableI18nLegacyMessageIdFormat": false,
30 | "strictInjectionParameters": true,
31 | "strictInputAccessModifiers": true,
32 | "strictTemplates": true
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/examples/angular/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "extends": "./tsconfig.json",
4 | "compilerOptions": {
5 | "outDir": "./out-tsc/spec",
6 | "types": [
7 | "jasmine"
8 | ]
9 | },
10 | "include": [
11 | "src/**/*.spec.ts",
12 | "src/**/*.d.ts"
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/examples/nextjs/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | .env.*
4 |
5 | # dependencies
6 | /node_modules
7 | /.pnp
8 | .pnp.js
9 |
10 | # testing
11 | /coverage
12 |
13 | # next.js
14 | /.next/
15 | /out/
16 |
17 | # production
18 | /build
19 |
20 | # misc
21 | .DS_Store
22 | *.pem
23 |
24 | # debug
25 | npm-debug.log*
26 | yarn-debug.log*
27 | yarn-error.log*
28 |
29 | # local env files
30 | .env*.local
31 | .env.*
32 |
33 | # vercel
34 | .vercel
35 |
36 | # typescript
37 | *.tsbuildinfo
38 | next-env.d.ts
39 |
--------------------------------------------------------------------------------
/examples/nextjs/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: all build clean
2 |
3 | run:
4 | npm run dev
5 |
6 | build:
7 | npm run build
8 |
--------------------------------------------------------------------------------
/examples/nextjs/README.md:
--------------------------------------------------------------------------------
1 | This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
2 |
3 | ## Getting Started
4 |
5 | First, run the development server:
6 |
7 | ```bash
8 | npm run dev
9 | # or
10 | yarn dev
11 | # or
12 | pnpm dev
13 | ```
14 |
15 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
16 |
17 | You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
18 |
19 | This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
20 |
21 | ## Learn More
22 |
23 | To learn more about Next.js, take a look at the following resources:
24 |
25 | - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
26 | - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
27 |
28 | You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
29 |
30 | ## Deploy on Vercel
31 |
32 | The 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.
33 |
34 | Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
35 |
--------------------------------------------------------------------------------
/examples/nextjs/next.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('next').NextConfig} */
2 | const nextConfig = {};
3 |
4 | module.exports = nextConfig;
5 |
--------------------------------------------------------------------------------
/examples/nextjs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "nextjs",
3 | "version": "0.1.0",
4 | "private": true,
5 | "scripts": {
6 | "dev": "next dev",
7 | "build": "next build",
8 | "start": "next start",
9 | "lint": "next lint"
10 | },
11 | "dependencies": {
12 | "@superflows/chat-ui-react": "^1.2.61",
13 | "@types/node": "20.4.6",
14 | "@types/react": "18.2.18",
15 | "@types/react-dom": "18.2.7",
16 | "autoprefixer": "10.4.14",
17 | "next": "13.4.12",
18 | "postcss": "8.4.27",
19 | "react": "18.2.0",
20 | "react-dom": "18.2.0",
21 | "tailwindcss": "3.3.3",
22 | "typescript": "5.1.6"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/examples/nextjs/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | autoprefixer: {},
5 | },
6 | };
7 |
--------------------------------------------------------------------------------
/examples/nextjs/public/next.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/examples/nextjs/public/vercel.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/examples/nextjs/src/app/chat/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Superflows-AI/chat-ui/81005fd7622af9c2489fb638b1ba1af0b2d73277/examples/nextjs/src/app/chat/favicon.ico
--------------------------------------------------------------------------------
/examples/nextjs/src/app/chat/globals.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 | :root {
6 | --foreground-rgb: 0, 0, 0;
7 | --background-start-rgb: 214, 219, 220;
8 | --background-end-rgb: 255, 255, 255;
9 | }
10 |
11 | @media (prefers-color-scheme: dark) {
12 | :root {
13 | --foreground-rgb: 255, 255, 255;
14 | --background-start-rgb: 0, 0, 0;
15 | --background-end-rgb: 0, 0, 0;
16 | }
17 | }
18 |
19 | body {
20 | color: rgb(var(--foreground-rgb));
21 | background: linear-gradient(
22 | to bottom,
23 | transparent,
24 | rgb(var(--background-end-rgb))
25 | )
26 | rgb(var(--background-start-rgb));
27 | }
28 |
--------------------------------------------------------------------------------
/examples/nextjs/src/app/chat/layout.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import "./globals.css";
3 | import type { Metadata } from "next";
4 | import { Inter } from "next/font/google";
5 |
6 | const inter = Inter({ subsets: ["latin"] });
7 |
8 | export const metadata: Metadata = {
9 | title: "Create Next App",
10 | description: "Generated by create next app",
11 | };
12 |
13 | export default function RootLayout({
14 | children,
15 | }: {
16 | children: React.ReactNode;
17 | }) {
18 | return (
19 |
20 | {children}
21 |
22 | );
23 | }
24 |
--------------------------------------------------------------------------------
/examples/nextjs/src/app/chat/page.tsx:
--------------------------------------------------------------------------------
1 | "use client";
2 | import React from "react";
3 | import { SuperflowsButton, SuperflowsChat } from "@superflows/chat-ui-react";
4 | import { Cog6ToothIcon } from "@heroicons/react/24/outline";
5 |
6 | if (!process.env.NEXT_PUBLIC_SUPERFLOWS_API_KEY) {
7 | throw new Error(
8 | "You must provide a Superflows API key in the environment variables as NEXT_PUBLIC_SUPERFLOWS_API_KEY",
9 | );
10 | }
11 |
12 | export default function Home() {
13 | return (
14 |
15 |
33 |
34 | );
35 | }
36 |
--------------------------------------------------------------------------------
/examples/nextjs/src/app/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Superflows-AI/chat-ui/81005fd7622af9c2489fb638b1ba1af0b2d73277/examples/nextjs/src/app/favicon.ico
--------------------------------------------------------------------------------
/examples/nextjs/src/app/globals.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 | :root {
6 | --foreground-rgb: 0, 0, 0;
7 | --background-start-rgb: 214, 219, 220;
8 | --background-end-rgb: 255, 255, 255;
9 | }
10 |
11 | @media (prefers-color-scheme: dark) {
12 | :root {
13 | --foreground-rgb: 255, 255, 255;
14 | --background-start-rgb: 0, 0, 0;
15 | --background-end-rgb: 0, 0, 0;
16 | }
17 | }
18 |
19 | body {
20 | color: rgb(var(--foreground-rgb));
21 | background: linear-gradient(
22 | to bottom,
23 | transparent,
24 | rgb(var(--background-end-rgb))
25 | )
26 | rgb(var(--background-start-rgb));
27 | }
28 |
--------------------------------------------------------------------------------
/examples/nextjs/src/app/layout.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import "./globals.css";
3 | import type { Metadata } from "next";
4 | import { Inter } from "next/font/google";
5 |
6 | const inter = Inter({ subsets: ["latin"] });
7 |
8 | export const metadata: Metadata = {
9 | title: "Create Next App",
10 | description: "Generated by create next app",
11 | };
12 |
13 | export default function RootLayout({
14 | children,
15 | }: {
16 | children: React.ReactNode;
17 | }) {
18 | return (
19 |
20 | {children}
21 |
22 | );
23 | }
24 |
--------------------------------------------------------------------------------
/examples/nextjs/src/app/page.tsx:
--------------------------------------------------------------------------------
1 | "use client";
2 | import React from "react";
3 | import { SuperflowsButton } from "@superflows/chat-ui-react";
4 | import { Cog6ToothIcon } from "@heroicons/react/24/outline";
5 |
6 | if (!process.env.NEXT_PUBLIC_SUPERFLOWS_API_KEY) {
7 | throw new Error(
8 | "You must provide a Superflows API key in the environment variables as NEXT_PUBLIC_SUPERFLOWS_API_KEY",
9 | );
10 | }
11 |
12 | export default function Home() {
13 | return (
14 |
15 |
16 |
17 |
18 |
19 | A
20 |
21 |
Acme CRM
22 |
23 |
24 | {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => (
25 |
26 | {n !== 1 &&
}
27 |
30 |
31 | ))}
32 |
33 |
46 |
47 |
52 |
70 |
71 | {[1, 2, 3].map((n) => (
72 |
73 | ))}
74 |
75 |
76 |
77 |
78 | {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13].map((n) => (
79 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | ))}
90 |
91 |
92 |
93 | );
94 | }
95 |
--------------------------------------------------------------------------------
/examples/nextjs/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
5 | "./src/components/**/*.{js,ts,jsx,tsx,mdx}",
6 | "./src/app/**/*.{js,ts,jsx,tsx,mdx}",
7 | ],
8 | theme: {
9 | extend: {
10 | backgroundImage: {
11 | "gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
12 | "gradient-conic":
13 | "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
14 | },
15 | },
16 | },
17 | plugins: [],
18 | };
19 |
--------------------------------------------------------------------------------
/examples/nextjs/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": ["dom", "dom.iterable", "esnext"],
5 | "allowJs": true,
6 | "skipLibCheck": true,
7 | "strict": true,
8 | "forceConsistentCasingInFileNames": true,
9 | "noEmit": true,
10 | "esModuleInterop": true,
11 | "module": "esnext",
12 | "moduleResolution": "bundler",
13 | "resolveJsonModule": true,
14 | "isolatedModules": true,
15 | "jsx": "preserve",
16 | "incremental": true,
17 | "plugins": [
18 | {
19 | "name": "next"
20 | }
21 | ],
22 | "paths": {
23 | "@/*": ["./src/*"]
24 | }
25 | },
26 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
27 | "exclude": ["node_modules"]
28 | }
29 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: "ts-jest/presets/default-esm",
3 | testEnvironment: "node",
4 | extensionsToTreatAsEsm: [".ts"],
5 | transform: {},
6 | moduleNameMapper: {
7 | uuid: require.resolve("uuid"),
8 | },
9 | modulePathIgnorePatterns: ["/examples/"],
10 | transformIgnorePatterns: [],
11 | };
12 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@superflows/chat-ui-react",
3 | "version": "1.2.61",
4 | "main": "dist/index.js",
5 | "devDependencies": {
6 | "@babel/core": "^7.23.9",
7 | "@babel/plugin-transform-nullish-coalescing-operator": "^7.23.4",
8 | "@babel/plugin-transform-optional-chaining": "^7.23.4",
9 | "@heroicons/react": "^2.0.18",
10 | "@jest/globals": "^29.6.2",
11 | "@rollup/plugin-babel": "^6.0.4",
12 | "@rollup/plugin-commonjs": "^25.0.3",
13 | "@rollup/plugin-node-resolve": "^15.1.0",
14 | "@superflows/rollup-plugin-tailwindcss": "^1.1.0",
15 | "@types/jest": "^29.5.3",
16 | "@types/luxon": "^3.3.1",
17 | "@types/node": "^20.5.7",
18 | "@types/react": "^18.2.0",
19 | "@types/react-dom": "^18.2.7",
20 | "@types/uuid": "^9.0.2",
21 | "@typescript-eslint/eslint-plugin": "^6.5.0",
22 | "@typescript-eslint/parser": "^6.5.0",
23 | "@vitejs/plugin-react": "^4.0.4",
24 | "@vitejs/plugin-react-refresh": "^1.3.6",
25 | "eslint": "^8.48.0",
26 | "eslint-plugin-react": "^7.33.2",
27 | "husky": "^8.0.3",
28 | "jest": "^29.6.4",
29 | "jest-environment-jsdom": "^29.6.2",
30 | "postcss": "^8.4.29",
31 | "prettier": "^3.0.0",
32 | "react": "^18.2.0",
33 | "react-dom": "^18.2.0",
34 | "rollup": "^3.26.3",
35 | "rollup-plugin-dts": "^5.3.1",
36 | "rollup-plugin-polyfill-node": "^0.12.0",
37 | "rollup-plugin-postcss": "^4.0.2",
38 | "rollup-plugin-typescript2": "^0.35.0",
39 | "ts-jest": "^29.1.1",
40 | "typescript": "^5.1.6",
41 | "vite": "^4.4.9",
42 | "vite-plugin-dts": "^3.5.3",
43 | "vite-plugin-node-polyfills": "^0.12.0"
44 | },
45 | "peerDependencies": {
46 | "react": "^16 || ^17 || ^18",
47 | "react-dom": "^16 || ^17 || ^18"
48 | },
49 | "scripts": {
50 | "build": "bash build.sh",
51 | "lint": "eslint --fix . && echo 'Lint complete.'",
52 | "start": "rollup -c -w",
53 | "dev": "vite",
54 | "test": "NODE_OPTIONS=--experimental-vm-modules jest --watch",
55 | "prepare": "husky install"
56 | },
57 | "files": [
58 | "dist"
59 | ],
60 | "dependencies": {
61 | "@headlessui/react": "1.4",
62 | "@heroicons/react": "^2.0.18",
63 | "@superflows/chat-ui-react": "^1.1.20",
64 | "@tailwindcss/forms": "^0.5.4",
65 | "luxon": "^3.4.0",
66 | "react-markdown": "^8",
67 | "recharts": "^2.7.2",
68 | "remark-gfm": "^3.0.1",
69 | "tablemark": "^3.0.0",
70 | "uuid": "^9.0.0"
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/postcss.config.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/rollup.config.mjs:
--------------------------------------------------------------------------------
1 | import tailwind from "@superflows/rollup-plugin-tailwindcss";
2 | import typescript from "rollup-plugin-typescript2";
3 | import postcss from "rollup-plugin-postcss";
4 | import babel from "@rollup/plugin-babel";
5 | import resolve from "@rollup/plugin-node-resolve";
6 | import commonjs from "@rollup/plugin-commonjs";
7 | import nodePolyfills from "rollup-plugin-polyfill-node";
8 |
9 | import pkg from "./package.json" assert { type: "json" };
10 |
11 | export default {
12 | input: "src/index.tsx",
13 | output: [
14 | {
15 | file: pkg.main,
16 | format: "cjs",
17 | exports: "named",
18 | sourcemap: true,
19 | strict: false,
20 | },
21 | ],
22 | plugins: [
23 | babel(
24 | {
25 | plugins: [
26 | "@babel/plugin-transform-optional-chaining",
27 | "@babel/plugin-transform-nullish-coalescing-operator"
28 | ],
29 | }
30 | ),
31 | resolve(),
32 | nodePolyfills({ include: ["process*", "path", "url*"] }),
33 | commonjs({
34 | include: "node_modules/**",
35 | }),
36 | postcss({
37 | config: {
38 | path: "./postcss.config.js",
39 | },
40 | extensions: [".css"],
41 | minimize: true,
42 | inject: {
43 | insertAt: "top",
44 | },
45 | }),
46 | tailwind({
47 | input: "src/index.css",
48 | // Tailor the emitted stylesheet to the bundle by removing any unused CSS
49 | // (highly recommended when packaging for distribution).
50 | purge: true,
51 | }),
52 | typescript({
53 | exclude: ["src/development.tsx"]
54 | }),
55 | ],
56 | external: ["react", "react-dom", "@headlessui/react", "@heroicons/react"],
57 | };
58 |
--------------------------------------------------------------------------------
/sidebar-screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Superflows-AI/chat-ui/81005fd7622af9c2489fb638b1ba1af0b2d73277/sidebar-screenshot.png
--------------------------------------------------------------------------------
/sidebar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Superflows-AI/chat-ui/81005fd7622af9c2489fb638b1ba1af0b2d73277/sidebar.png
--------------------------------------------------------------------------------
/src/components/autoGrowingTextarea.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import { useEffect, useRef } from "react";
3 |
4 | export function AutoGrowingTextArea(props: {
5 | className: string;
6 | placeholder: string;
7 | value: string;
8 | onChange: (e: React.ChangeEvent) => void;
9 | onKeyDown?: (e: React.KeyboardEvent) => void;
10 | minHeight?: number;
11 | maxHeight?: number;
12 | onBlur?: React.FocusEventHandler;
13 | }) {
14 | const ref: React.MutableRefObject = useRef(null);
15 |
16 | useEffect(() => {
17 | if (ref.current === null) return;
18 | // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
19 | ref.current.style.height = "5px";
20 |
21 | const maxH = props.maxHeight ?? 500;
22 | const minH = props.minHeight ?? 36;
23 |
24 | // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
25 | ref.current.style.height =
26 | // eslint-disable-next-line @typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-member-access
27 | Math.max(Math.min(ref.current.scrollHeight, maxH), minH).toString() +
28 | "px";
29 | }, [ref.current, props.value]);
30 |
31 | return (
32 |
41 | );
42 | }
43 |
--------------------------------------------------------------------------------
/src/components/followUpSuggestions.tsx:
--------------------------------------------------------------------------------
1 | import { StreamingStepInput } from "../lib/types";
2 | import React, { useEffect } from "react";
3 | import { classNames, scrollToBottom } from "../lib/utils";
4 |
5 | export default function FollowUpSuggestions(props: {
6 | devChatContents: StreamingStepInput[];
7 | followUpSuggestions: string[];
8 | onClick: (text: string) => void;
9 | scrollRef: React.RefObject;
10 | width: number;
11 | }) {
12 | useEffect(() => {
13 | setTimeout(() => {
14 | scrollToBottom(props.scrollRef, "smooth");
15 | }, 50);
16 | }, [props.followUpSuggestions]);
17 |
18 | return (
19 | 640
23 | ? "sf-flex-row sf-overflow-hidden sf-flex-wrap"
24 | : "sf-flex-col",
25 | )}
26 | >
27 | {props.followUpSuggestions.map((text) => (
28 |
35 | ))}
36 |
37 | );
38 | }
39 |
--------------------------------------------------------------------------------
/src/components/graph.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import {
3 | LineChart,
4 | Label,
5 | Line,
6 | ResponsiveContainer,
7 | XAxis,
8 | YAxis,
9 | BarChart,
10 | CartesianGrid,
11 | Tooltip,
12 | Bar,
13 | } from "recharts";
14 |
15 | import { DateTime } from "luxon";
16 | import { GraphData, Json, SupportedGraphTypes } from "../lib/types";
17 |
18 | // Here due to issues with importing from ./utils in tests
19 | function classNames(
20 | ...classes: (string | undefined | null | boolean)[]
21 | ): string {
22 | return classes.filter(Boolean).join(" ");
23 | }
24 |
25 | const formats = [
26 | "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
27 | "yyyy-MM-dd'T'HH:mm:ss.SSS",
28 | "yyyy-MM-dd'T'HH:mm:ss'Z'",
29 | "yyyy-MM-dd'T'HH:mm:ss",
30 | "yyyy-MM-dd'T'HH:mm",
31 | "yyyy-MM-dd'T'HH",
32 | "yyyy-MM-dd",
33 | "yyyy/MM/dd'T'HH:mm:ss.SSS'Z'",
34 | "yyyy/MM/dd'T'HH:mm:ss.SSS",
35 | "yyyy/MM/dd'T'HH:mm:ss",
36 | "yyyy/MM/dd'T'HH:mm",
37 | "yyyy/MM/dd'T'HH",
38 | "yyyy/MM/dd",
39 | "yyyy.MM.dd'T'HH:mm:ss.SSS'Z'",
40 | "yyyy.MM.dd'T'HH:mm:ss.SSS",
41 | "yyyy.MM.dd'T'HH:mm:ss",
42 | "yyyy.MM.dd'T'HH:mm",
43 | "yyyy.MM.dd'T'HH",
44 | "yyyy.MM.dd",
45 | "yyyyMMdd'T'HHmmss.SSS'Z'",
46 | "yyyyMMdd'T'HHmmss.SSS",
47 | "yyyyMMdd'T'HHmmss",
48 | "yyyyMMdd'T'HHmm",
49 | "yyyyMMdd'T'HH",
50 | "yyyyMMdd",
51 | "MM-dd-yyyy",
52 | "dd.MM.yyyy",
53 | "MM/dd/yyyy",
54 | "dd/MM/yyyy",
55 | "h:mm a", // 1:30 PM
56 | ];
57 |
58 | const formatsToSkip = ["HH:mm:ss.SSS", "HH:mm:ss", "HH:mm"];
59 |
60 | function attemptDatetimeConversion(array: any[]): number[] | null {
61 | if (typeof array[0] !== "string") return null;
62 |
63 | let matchingFormat = null;
64 |
65 | if (
66 | formatsToSkip
67 | .map((format) => {
68 | const dt = DateTime.fromFormat(array[0], format);
69 | if (dt.isValid) return format;
70 | return null;
71 | })
72 | .filter(Boolean).length > 0
73 | ) {
74 | return null;
75 | }
76 |
77 | for (const format of formats) {
78 | const dt = DateTime.fromFormat(array[0], format);
79 | if (dt.isValid) {
80 | matchingFormat = format;
81 | break;
82 | }
83 | }
84 |
85 | if (DateTime.fromISO(array[0]).isValid) {
86 | matchingFormat = "ISO";
87 | }
88 |
89 | if (!matchingFormat) return null;
90 |
91 | const convertedArray = [];
92 |
93 | for (const str of array) {
94 | const dt =
95 | matchingFormat === "ISO"
96 | ? DateTime.fromISO(str)
97 | : DateTime.fromFormat(str, matchingFormat);
98 |
99 | if (!dt.isValid) {
100 | return null;
101 | }
102 | convertedArray.push(dt.toSeconds());
103 | }
104 |
105 | return convertedArray;
106 | }
107 |
108 | const secondsToDay = 60 * 60 * 24;
109 |
110 | export function Graph(props: GraphData & { small: boolean }) {
111 | if (props.data.length === 0) return <>>;
112 | const xIsNumber = typeof props.data[0].x === "number";
113 |
114 | let xRange: number;
115 | let offset: number;
116 | const graphData = formatGraphData(props);
117 | const data = [...graphData.data];
118 |
119 | if (xIsNumber) {
120 | xRange =
121 | Math.max(...props.data.map((obj) => obj.x as number)) -
122 | Math.min(...props.data.map((obj) => obj.x as number));
123 | offset = Math.floor(xRange * 0.1);
124 | }
125 | const nonXYLabels: string[] = [];
126 | for (const key of Object.keys(props.data[0])) {
127 | if (key !== "x" && key !== "y") {
128 | nonXYLabels.push(key);
129 | }
130 | }
131 | const yLabel = props.yLabel || "";
132 | const yUnitReg = /\((.*)\)$/.exec(yLabel);
133 | const yUnit = yUnitReg ? yUnitReg[1] : undefined;
134 |
135 | if (props.type === "value") {
136 | const value = formatValue(props.data[0].y);
137 | const valueWithUnits = includeUnits(value, yUnit);
138 | return (
139 |
144 |
149 |
150 |
151 | {valueWithUnits}
152 |
153 |
154 |
155 |
156 | );
157 | }
158 | const tickFontSize = props.small ? 10 : 12;
159 | const labelFontSize = props.small ? 12 : 15;
160 |
161 | return (
162 |
170 | {props.type === "bar" ? (
171 |
172 |
173 |
186 | 5 ? -90 : 0,
191 | fontSize: labelFontSize,
192 | position: "insideLeft",
193 | dy: yLabel.length * 3,
194 | dx: -4,
195 | }}
196 | tick={{ fontSize: tickFontSize }}
197 | />
198 | {
200 | const payload =
201 | vals.payload.length > 0 ? vals.payload[0].payload : {};
202 | const value = formatValue(payload.y);
203 | const valueWithUnits = includeUnits(value, yUnit);
204 | const splitYLabel = yLabel.split("(");
205 | return (
206 |
212 |
{payload.x}
213 |
214 | {splitYLabel[0]
215 | ? splitYLabel[0].replaceAll("_", " ").trim()
216 | : splitYLabel[0].trim()}
217 | :
218 |
219 | {valueWithUnits}
220 |
221 |
222 | {nonXYLabels.map((label) => (
223 |
227 | {capitaliseFirstLetter(
228 | label ? label.replaceAll("_", " ") : label,
229 | )}
230 | : {payload[label]}
231 |
232 | ))}
233 |
234 | );
235 | }}
236 | />
237 | {props.graphTitle}
238 |
239 |
240 | ) : (
241 |
242 |
243 |
256 | DateTime.fromSeconds(x * secondsToDay).toLocaleString(
257 | xRange < 1 / 24
258 | ? DateTime.TIME_24_WITH_SECONDS
259 | : xRange < 1
260 | ? DateTime.TIME_24_SIMPLE
261 | : DateTime.DATE_SHORT,
262 | )
263 | : undefined
264 | }
265 | >
266 |
272 |
273 | {
275 | const payload =
276 | vals.payload.length > 0 ? vals.payload[0].payload : {};
277 | const value = formatValue(payload.y);
278 | const valueWithUnits = includeUnits(value, yUnit);
279 | const splitYLabel = yLabel.split("(");
280 | return (
281 |
287 |
{payload.x}
288 |
289 | {splitYLabel[0]
290 | ? splitYLabel[0].replaceAll("_", " ").trim()
291 | : splitYLabel[0].trim()}
292 | :
293 |
294 | {valueWithUnits}
295 |
296 |
297 | {nonXYLabels.map((label) => (
298 |
302 | {capitaliseFirstLetter(
303 | label ? label.replaceAll("_", " ") : label,
304 | )}
305 | : {payload[label]}
306 |
307 | ))}
308 |
309 | );
310 | }}
311 | />
312 |
313 |
319 |
320 | {props.graphTitle}
321 |
322 |
323 | )}
324 |
325 | );
326 | }
327 |
328 | function capitaliseFirstLetter(str: string | undefined) {
329 | if (str === undefined) return undefined;
330 | return str.charAt(0).toUpperCase() + str.slice(1);
331 | }
332 |
333 | export const possibleXlabels = [
334 | "Time",
335 | "Date",
336 | "Event",
337 | "Product",
338 | "Category",
339 | "Grades",
340 | "Days",
341 | "Months",
342 | "Hours",
343 | "Teams",
344 | "State",
345 | "City",
346 | "Country",
347 | "Models",
348 | "Versions",
349 | "Classes",
350 | "Years",
351 | "Quarters",
352 | "Genre",
353 | "Groups",
354 | "Label",
355 | ];
356 |
357 | export const possibleYlabels = [
358 | "Value",
359 | "Price",
360 | "Weight",
361 | "Size",
362 | "Length",
363 | "Width",
364 | "Height",
365 | "Distance",
366 | "Quantity",
367 | "Score",
368 | "Population",
369 | "Revenue",
370 | "Sales",
371 | "GDP",
372 | "Exposure",
373 | "Temperature",
374 | "Speed",
375 | "Frequency",
376 | "numberOfCustomers",
377 | "Density",
378 | "UnitsSold",
379 | "Satisfaction",
380 | ];
381 |
382 | function formatGraphData(graphData: GraphData): GraphData {
383 | if (graphData.type === "value") {
384 | return graphData;
385 | }
386 | if (typeof graphData.data[0].x === "number") {
387 | return {
388 | ...graphData,
389 | data: graphData.data.sort((a, b) => (a.x as number) - (b.x as number)),
390 | };
391 | } else if (typeof graphData.data[0].x === "string") {
392 | const dates = attemptDatetimeConversion(graphData.data.map((obj) => obj.x));
393 | if (dates) {
394 | const xRange = Math.max(...dates) - Math.min(...dates);
395 | return {
396 | ...graphData,
397 | data: graphData.data
398 | .map((obj, index) => ({
399 | ...obj,
400 | x: dates[index],
401 | }))
402 | .sort((a, b) => a.x - b.x)
403 | .map((obj) => ({
404 | ...obj,
405 | x: DateTime.fromSeconds(obj.x).toLocaleString(
406 | xRange < 1 / 24
407 | ? DateTime.TIME_24_WITH_SECONDS
408 | : xRange < 1
409 | ? DateTime.TIME_24_SIMPLE
410 | : DateTime.DATE_SHORT,
411 | ),
412 | })),
413 | xIsdate: true,
414 | };
415 | }
416 | }
417 | return graphData;
418 | }
419 |
420 | export function extractGraphData(
421 | data: Json,
422 | type: SupportedGraphTypes,
423 | ): GraphData | null {
424 | const { result: array, arrayKey } = findFirstArray(data);
425 |
426 | if (array === null) {
427 | console.log(`no array found in data: ${data}`);
428 | return null;
429 | }
430 | if (typeof array[0] === "number")
431 | return {
432 | type,
433 | data: array.map((value, index) => ({ x: index, y: value })),
434 | graphTitle: arrayKey,
435 | };
436 |
437 | if (
438 | typeof array[0] === "string" &&
439 | // We can graph if every value in the array is a stringified number
440 | array.every((val) => !isNaN(Number(val)))
441 | )
442 | return {
443 | type,
444 | data: array.map((value, index) => ({ x: index, y: Number(value) })),
445 | graphTitle: arrayKey,
446 | };
447 |
448 | // TODO: Currently don't support arrays of arrays
449 | if (typeof array[0] === "object" && !(array[0] instanceof Array)) {
450 | // Fields that match the possible x labels and are in every object in the array
451 | // x matches are either in the possible x labels or can be converted to a date
452 | const xMatches = Object.keys(array[0])
453 | .filter(
454 | (key) =>
455 | checkStringMatch(key, possibleXlabels) ||
456 | attemptDatetimeConversion(array.map((obj) => obj[key])) !== null,
457 | )
458 | .filter((key) => array.every((obj) => key in obj));
459 |
460 | const yMatches = Object.keys(array[0])
461 | .filter((key) => checkStringMatch(key, possibleYlabels))
462 | .filter((key) => array.every((obj) => key in obj));
463 |
464 | if (xMatches.length === 0 && yMatches.length === 0) {
465 | console.log(
466 | `no x or y matches found in array keys ${Object.keys(array[0])}`,
467 | );
468 | return null;
469 | }
470 |
471 | if (yMatches.length > 0 && xMatches.length === 0) {
472 | const yLabel = yMatches[0];
473 | return {
474 | type,
475 | data: array.map((obj, index) => ({
476 | x: index,
477 | y: obj[yLabel],
478 | })),
479 | yLabel,
480 | graphTitle: arrayKey,
481 | };
482 | } else if (xMatches.length > 0 && yMatches.length > 0) {
483 | const xLabel = xMatches[0];
484 | const yLabel = yMatches[0];
485 |
486 | const dateParseRes = attemptDatetimeConversion(
487 | array.map((obj) => obj[xLabel]),
488 | );
489 |
490 | const x = dateParseRes ?? array.map((obj) => obj[xLabel]);
491 | const data = [];
492 | for (let i = 0; i < x.length; i++) {
493 | data.push({
494 | x: dateParseRes ? x[i] / secondsToDay : x[i],
495 | y: array[i][yLabel],
496 | });
497 | }
498 |
499 | return {
500 | type,
501 | data,
502 | xLabel,
503 | yLabel,
504 | graphTitle: arrayKey,
505 | xIsdate: dateParseRes !== null,
506 | };
507 | }
508 | }
509 |
510 | return null;
511 | }
512 |
513 | export function findFirstArray(
514 | json: any,
515 | key: string | number | null = null,
516 | ): { result: any[] | null; arrayKey: string | number | null } {
517 | /**
518 | * Recursively search through the object's properties for an array.
519 | * Return first array found (which will be at the highest level) of nesting
520 | **/
521 | // check if the input is an object or array
522 | if (typeof json === "object" && json !== null) {
523 | // if the input is an array, return it
524 | if (Array.isArray(json)) {
525 | return { result: json, arrayKey: key };
526 | }
527 | // otherwise, recursively search through the object's properties
528 | for (const key in json) {
529 | if (json.hasOwnProperty(key)) {
530 | const { result } = findFirstArray(json[key], key);
531 | // if this property is an array, or contains an array, return it
532 | if (result) {
533 | return { result, arrayKey: key };
534 | }
535 | }
536 | }
537 | }
538 | // no array found
539 | return { result: null, arrayKey: key };
540 | }
541 | export function checkStringMatch(
542 | fieldName: string,
543 | possibleLabels: string[],
544 | ): boolean {
545 | // Match insensitive to punctuation, spaces, case and trailing s
546 | const processStr = (str: string) => {
547 | const processed = str.toLowerCase().replace(/[\W\s]/g, "");
548 | return processed.endsWith("s") ? processed.slice(0, -1) : processed;
549 | };
550 |
551 | return possibleLabels.some((y) => processStr(fieldName) === processStr(y));
552 | }
553 |
554 | function formatValue(value: number | string): string {
555 | if (typeof value === "number") {
556 | if (Math.abs(value) >= 1000) {
557 | return numberWithCommas(Math.round(value));
558 | } else if (Math.abs(value) > 0.1) {
559 | return (Math.round(value * 100) / 100).toString();
560 | } else if (Math.abs(value) > 0) {
561 | return value.toExponential(2);
562 | } else {
563 | return "0";
564 | }
565 | }
566 | return value;
567 | }
568 |
569 | function numberWithCommas(x: number): string {
570 | /** Converts a number to a string containing commas */
571 | const parts = x.toString().split(".");
572 | parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
573 | return parts.join(".");
574 | }
575 |
576 | function includeUnits(value: string, unit: string | undefined): string {
577 | if (!unit || value === undefined || value == null) return value;
578 | if (unit in mapCurrencyNameToSymbol) {
579 | unit = mapCurrencyNameToSymbol[unit];
580 | }
581 | value = value.toString();
582 | if (["£", "$", "€"].includes(unit)) {
583 | const isNeg = value.startsWith("-");
584 | if (isNeg) {
585 | return `-${unit}${value.slice(1)}`;
586 | }
587 | return `${unit}${value}`;
588 | }
589 | return `${value}${unit}`;
590 | }
591 |
592 | const mapCurrencyNameToSymbol: Record = {
593 | USD: "$",
594 | EUR: "€",
595 | GBP: "£",
596 | };
597 |
--------------------------------------------------------------------------------
/src/components/loadingspinner.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import { classNames } from "../lib/utils";
3 |
4 | export function LoadingSpinner({ classes }: { classes: string }) {
5 | return (
6 |
26 | );
27 | }
28 |
--------------------------------------------------------------------------------
/src/components/modal.tsx:
--------------------------------------------------------------------------------
1 | import React, { Fragment } from "react";
2 | import { Dialog, Transition } from "@headlessui/react";
3 | import classNames from "classnames";
4 | import { SparklesIcon, XMarkIcon } from "@heroicons/react/24/solid";
5 | import Chat from "./chat";
6 | import { SuperflowsModalProps } from "../lib/types";
7 |
8 | export default function SuperflowsModal(props: SuperflowsModalProps) {
9 | const focusRef = React.useRef(null);
10 |
11 | return (
12 |
81 | );
82 | }
83 |
--------------------------------------------------------------------------------
/src/components/sidebar.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import {
3 | ChevronLeftIcon,
4 | ChevronRightIcon,
5 | XMarkIcon,
6 | } from "@heroicons/react/24/outline";
7 | import { Fragment, useRef } from "react";
8 | import { Dialog, Transition } from "@headlessui/react";
9 | import { classNames } from "../lib/utils";
10 | import { SuperflowsSidebarProps } from "../lib/types";
11 | import Chat from "./chat";
12 |
13 | export default function SuperflowsSidebar(props: SuperflowsSidebarProps) {
14 | const focusRef = useRef(null);
15 | return (
16 |