diff --git a/apps/cf-ai-backend/.gitignore b/apps/cf-ai-backend/.gitignore index 3b0fe33c..c51412d9 100644 --- a/apps/cf-ai-backend/.gitignore +++ b/apps/cf-ai-backend/.gitignore @@ -1,4 +1,5 @@ # Logs +wrangler.toml logs _.log diff --git a/apps/cf-ai-backend/pnpm-lock.yaml b/apps/cf-ai-backend/pnpm-lock.yaml deleted file mode 100644 index b78ececf..00000000 --- a/apps/cf-ai-backend/pnpm-lock.yaml +++ /dev/null @@ -1,790 +0,0 @@ -lockfileVersion: '6.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -devDependencies: - '@cloudflare/workers-types': - specifier: ^4.20240222.0 - version: 4.20240222.0 - typescript: - specifier: ^5.0.4 - version: 5.3.3 - wrangler: - specifier: ^3.0.0 - version: 3.29.0(@cloudflare/workers-types@4.20240222.0) - -packages: - - /@cloudflare/kv-asset-handler@0.3.1: - resolution: {integrity: sha512-lKN2XCfKCmpKb86a1tl4GIwsJYDy9TGuwjhDELLmpKygQhw8X2xR4dusgpC5Tg7q1pB96Eb0rBo81kxSILQMwA==} - dependencies: - mime: 3.0.0 - dev: true - - /@cloudflare/workerd-darwin-64@1.20240208.0: - resolution: {integrity: sha512-64qjsCUz6VtjXnUex5D6dWoJDuUBRw1ps2TEVH9wGJ4ubiLVUxKhj3bzkVy0RoJ8FhaCKzJWWRyTo4yc192UTA==} - engines: {node: '>=16'} - cpu: [x64] - os: [darwin] - requiresBuild: true - dev: true - optional: true - - /@cloudflare/workerd-darwin-arm64@1.20240208.0: - resolution: {integrity: sha512-eVQrAV200LhwLY6JZLx3l2lDrjsTC86lqnvH+RSeM43bAcdneC6lVfykHnTaOTgYFvYQbqRkn9ICWxXj1V9L5g==} - engines: {node: '>=16'} - cpu: [arm64] - os: [darwin] - requiresBuild: true - dev: true - optional: true - - /@cloudflare/workerd-linux-64@1.20240208.0: - resolution: {integrity: sha512-ivZ2UuCvi44j8JZ++XlQzSYajt5ptvAdwlh3WPpCcygtHXEh6SVo8QXEUOXhPbv861C0HZMYxLCaLqlpQDWB8g==} - engines: {node: '>=16'} - cpu: [x64] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@cloudflare/workerd-linux-arm64@1.20240208.0: - resolution: {integrity: sha512-aLfvl9kXQKbM7aLvfL0HbOt5VEgv15mEZGyFKyDldJ8+nOXH6nYPma1ccwF8BHmu8otHc420eyPr2xPKhLSJnw==} - engines: {node: '>=16'} - cpu: [arm64] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@cloudflare/workerd-windows-64@1.20240208.0: - resolution: {integrity: sha512-Y6KMukWnorsSmPx6d82IuJ4SU8sX1+2y+w1uFJ76sucSgXqUAN1fmjG+EyzRVbcbsxRGBCD9c1Pn8T1amMLEYA==} - engines: {node: '>=16'} - cpu: [x64] - os: [win32] - requiresBuild: true - dev: true - optional: true - - /@cloudflare/workers-types@4.20240222.0: - resolution: {integrity: sha512-luO0BdK3rLlCv3B240+cTrfqm+XSbHtpk+88aJtGwzyVK9QF/Xz8lBgE/oZZLN8nCTmOvxAZnszyxUuZ8GP8Cg==} - dev: true - - /@cspotcode/source-map-support@0.8.1: - resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} - engines: {node: '>=12'} - dependencies: - '@jridgewell/trace-mapping': 0.3.9 - dev: true - - /@esbuild-plugins/node-globals-polyfill@0.2.3(esbuild@0.17.19): - resolution: {integrity: sha512-r3MIryXDeXDOZh7ih1l/yE9ZLORCd5e8vWg02azWRGj5SPTuoh69A2AIyn0Z31V/kHBfZ4HgWJ+OK3GTTwLmnw==} - peerDependencies: - esbuild: '*' - dependencies: - esbuild: 0.17.19 - dev: true - - /@esbuild-plugins/node-modules-polyfill@0.2.2(esbuild@0.17.19): - resolution: {integrity: sha512-LXV7QsWJxRuMYvKbiznh+U1ilIop3g2TeKRzUxOG5X3YITc8JyyTa90BmLwqqv0YnX4v32CSlG+vsziZp9dMvA==} - peerDependencies: - esbuild: '*' - dependencies: - esbuild: 0.17.19 - escape-string-regexp: 4.0.0 - rollup-plugin-node-polyfills: 0.2.1 - dev: true - - /@esbuild/android-arm64@0.17.19: - resolution: {integrity: sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==} - engines: {node: '>=12'} - cpu: [arm64] - os: [android] - requiresBuild: true - dev: true - optional: true - - /@esbuild/android-arm@0.17.19: - resolution: {integrity: sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==} - engines: {node: '>=12'} - cpu: [arm] - os: [android] - requiresBuild: true - dev: true - optional: true - - /@esbuild/android-x64@0.17.19: - resolution: {integrity: sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==} - engines: {node: '>=12'} - cpu: [x64] - os: [android] - requiresBuild: true - dev: true - optional: true - - /@esbuild/darwin-arm64@0.17.19: - resolution: {integrity: sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==} - engines: {node: '>=12'} - cpu: [arm64] - os: [darwin] - requiresBuild: true - dev: true - optional: true - - /@esbuild/darwin-x64@0.17.19: - resolution: {integrity: sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==} - engines: {node: '>=12'} - cpu: [x64] - os: [darwin] - requiresBuild: true - dev: true - optional: true - - /@esbuild/freebsd-arm64@0.17.19: - resolution: {integrity: sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==} - engines: {node: '>=12'} - cpu: [arm64] - os: [freebsd] - requiresBuild: true - dev: true - optional: true - - /@esbuild/freebsd-x64@0.17.19: - resolution: {integrity: sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==} - engines: {node: '>=12'} - cpu: [x64] - os: [freebsd] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-arm64@0.17.19: - resolution: {integrity: sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==} - engines: {node: '>=12'} - cpu: [arm64] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-arm@0.17.19: - resolution: {integrity: sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==} - engines: {node: '>=12'} - cpu: [arm] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-ia32@0.17.19: - resolution: {integrity: sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==} - engines: {node: '>=12'} - cpu: [ia32] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-loong64@0.17.19: - resolution: {integrity: sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==} - engines: {node: '>=12'} - cpu: [loong64] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-mips64el@0.17.19: - resolution: {integrity: sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==} - engines: {node: '>=12'} - cpu: [mips64el] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-ppc64@0.17.19: - resolution: {integrity: sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==} - engines: {node: '>=12'} - cpu: [ppc64] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-riscv64@0.17.19: - resolution: {integrity: sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==} - engines: {node: '>=12'} - cpu: [riscv64] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-s390x@0.17.19: - resolution: {integrity: sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==} - engines: {node: '>=12'} - cpu: [s390x] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/linux-x64@0.17.19: - resolution: {integrity: sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==} - engines: {node: '>=12'} - cpu: [x64] - os: [linux] - requiresBuild: true - dev: true - optional: true - - /@esbuild/netbsd-x64@0.17.19: - resolution: {integrity: sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==} - engines: {node: '>=12'} - cpu: [x64] - os: [netbsd] - requiresBuild: true - dev: true - optional: true - - /@esbuild/openbsd-x64@0.17.19: - resolution: {integrity: sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==} - engines: {node: '>=12'} - cpu: [x64] - os: [openbsd] - requiresBuild: true - dev: true - optional: true - - /@esbuild/sunos-x64@0.17.19: - resolution: {integrity: sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==} - engines: {node: '>=12'} - cpu: [x64] - os: [sunos] - requiresBuild: true - dev: true - optional: true - - /@esbuild/win32-arm64@0.17.19: - resolution: {integrity: sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==} - engines: {node: '>=12'} - cpu: [arm64] - os: [win32] - requiresBuild: true - dev: true - optional: true - - /@esbuild/win32-ia32@0.17.19: - resolution: {integrity: sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==} - engines: {node: '>=12'} - cpu: [ia32] - os: [win32] - requiresBuild: true - dev: true - optional: true - - /@esbuild/win32-x64@0.17.19: - resolution: {integrity: sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==} - engines: {node: '>=12'} - cpu: [x64] - os: [win32] - requiresBuild: true - dev: true - optional: true - - /@fastify/busboy@2.1.0: - resolution: {integrity: sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==} - engines: {node: '>=14'} - dev: true - - /@jridgewell/resolve-uri@3.1.2: - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - dev: true - - /@jridgewell/sourcemap-codec@1.4.15: - resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==} - dev: true - - /@jridgewell/trace-mapping@0.3.9: - resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.4.15 - dev: true - - /@types/node-forge@1.3.11: - resolution: {integrity: sha512-FQx220y22OKNTqaByeBGqHWYz4cl94tpcxeFdvBo3wjG6XPBuZ0BNgNZRV5J5TFmmcsJ4IzsLkmGRiQbnYsBEQ==} - dependencies: - '@types/node': 20.11.20 - dev: true - - /@types/node@20.11.20: - resolution: {integrity: sha512-7/rR21OS+fq8IyHTgtLkDK949uzsa6n8BkziAKtPVpugIkO6D+/ooXMvzXxDnZrmtXVfjb1bKQafYpb8s89LOg==} - dependencies: - undici-types: 5.26.5 - dev: true - - /acorn-walk@8.3.2: - resolution: {integrity: sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==} - engines: {node: '>=0.4.0'} - dev: true - - /acorn@8.11.3: - resolution: {integrity: sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==} - engines: {node: '>=0.4.0'} - hasBin: true - dev: true - - /anymatch@3.1.3: - resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} - engines: {node: '>= 8'} - dependencies: - normalize-path: 3.0.0 - picomatch: 2.3.1 - dev: true - - /as-table@1.0.55: - resolution: {integrity: sha512-xvsWESUJn0JN421Xb9MQw6AsMHRCUknCe0Wjlxvjud80mU4E6hQf1A6NzQKcYNmYw62MfzEtXc+badstZP3JpQ==} - dependencies: - printable-characters: 1.0.42 - dev: true - - /binary-extensions@2.2.0: - resolution: {integrity: sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==} - engines: {node: '>=8'} - dev: true - - /blake3-wasm@2.1.5: - resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} - dev: true - - /braces@3.0.2: - resolution: {integrity: sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==} - engines: {node: '>=8'} - dependencies: - fill-range: 7.0.1 - dev: true - - /capnp-ts@0.7.0: - resolution: {integrity: sha512-XKxXAC3HVPv7r674zP0VC3RTXz+/JKhfyw94ljvF80yynK6VkTnqE3jMuN8b3dUVmmc43TjyxjW4KTsmB3c86g==} - dependencies: - debug: 4.3.4 - tslib: 2.6.2 - transitivePeerDependencies: - - supports-color - dev: true - - /chokidar@3.6.0: - resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} - engines: {node: '>= 8.10.0'} - dependencies: - anymatch: 3.1.3 - braces: 3.0.2 - glob-parent: 5.1.2 - is-binary-path: 2.1.0 - is-glob: 4.0.3 - normalize-path: 3.0.0 - readdirp: 3.6.0 - optionalDependencies: - fsevents: 2.3.3 - dev: true - - /cookie@0.5.0: - resolution: {integrity: sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==} - engines: {node: '>= 0.6'} - dev: true - - /data-uri-to-buffer@2.0.2: - resolution: {integrity: sha512-ND9qDTLc6diwj+Xe5cdAgVTbLVdXbtxTJRXRhli8Mowuaan+0EJOtdqJ0QCHNSSPyoXGx9HX2/VMnKeC34AChA==} - dev: true - - /debug@4.3.4: - resolution: {integrity: sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==} - engines: {node: '>=6.0'} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - dependencies: - ms: 2.1.2 - dev: true - - /esbuild@0.17.19: - resolution: {integrity: sha512-XQ0jAPFkK/u3LcVRcvVHQcTIqD6E2H1fvZMA5dQPSOWb3suUbWbfbRf94pjc0bNzRYLfIrDRQXr7X+LHIm5oHw==} - engines: {node: '>=12'} - hasBin: true - requiresBuild: true - optionalDependencies: - '@esbuild/android-arm': 0.17.19 - '@esbuild/android-arm64': 0.17.19 - '@esbuild/android-x64': 0.17.19 - '@esbuild/darwin-arm64': 0.17.19 - '@esbuild/darwin-x64': 0.17.19 - '@esbuild/freebsd-arm64': 0.17.19 - '@esbuild/freebsd-x64': 0.17.19 - '@esbuild/linux-arm': 0.17.19 - '@esbuild/linux-arm64': 0.17.19 - '@esbuild/linux-ia32': 0.17.19 - '@esbuild/linux-loong64': 0.17.19 - '@esbuild/linux-mips64el': 0.17.19 - '@esbuild/linux-ppc64': 0.17.19 - '@esbuild/linux-riscv64': 0.17.19 - '@esbuild/linux-s390x': 0.17.19 - '@esbuild/linux-x64': 0.17.19 - '@esbuild/netbsd-x64': 0.17.19 - '@esbuild/openbsd-x64': 0.17.19 - '@esbuild/sunos-x64': 0.17.19 - '@esbuild/win32-arm64': 0.17.19 - '@esbuild/win32-ia32': 0.17.19 - '@esbuild/win32-x64': 0.17.19 - dev: true - - /escape-string-regexp@4.0.0: - resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} - engines: {node: '>=10'} - dev: true - - /estree-walker@0.6.1: - resolution: {integrity: sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==} - dev: true - - /exit-hook@2.2.1: - resolution: {integrity: sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw==} - engines: {node: '>=6'} - dev: true - - /fill-range@7.0.1: - resolution: {integrity: sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==} - engines: {node: '>=8'} - dependencies: - to-regex-range: 5.0.1 - dev: true - - /fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - requiresBuild: true - dev: true - optional: true - - /function-bind@1.1.2: - resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - dev: true - - /get-source@2.0.12: - resolution: {integrity: sha512-X5+4+iD+HoSeEED+uwrQ07BOQr0kEDFMVqqpBuI+RaZBpBpHCuXxo70bjar6f0b0u/DQJsJ7ssurpP0V60Az+w==} - dependencies: - data-uri-to-buffer: 2.0.2 - source-map: 0.6.1 - dev: true - - /glob-parent@5.1.2: - resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} - engines: {node: '>= 6'} - dependencies: - is-glob: 4.0.3 - dev: true - - /glob-to-regexp@0.4.1: - resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} - dev: true - - /hasown@2.0.1: - resolution: {integrity: sha512-1/th4MHjnwncwXsIW6QMzlvYL9kG5e/CpVvLRZe4XPa8TOUNbCELqmvhDmnkNsAjwaG4+I8gJJL0JBvTTLO9qA==} - engines: {node: '>= 0.4'} - dependencies: - function-bind: 1.1.2 - dev: true - - /is-binary-path@2.1.0: - resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} - engines: {node: '>=8'} - dependencies: - binary-extensions: 2.2.0 - dev: true - - /is-core-module@2.13.1: - resolution: {integrity: sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==} - dependencies: - hasown: 2.0.1 - dev: true - - /is-extglob@2.1.1: - resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} - engines: {node: '>=0.10.0'} - dev: true - - /is-glob@4.0.3: - resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} - engines: {node: '>=0.10.0'} - dependencies: - is-extglob: 2.1.1 - dev: true - - /is-number@7.0.0: - resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} - engines: {node: '>=0.12.0'} - dev: true - - /magic-string@0.25.9: - resolution: {integrity: sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==} - dependencies: - sourcemap-codec: 1.4.8 - dev: true - - /mime@3.0.0: - resolution: {integrity: sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==} - engines: {node: '>=10.0.0'} - hasBin: true - dev: true - - /miniflare@3.20240208.0: - resolution: {integrity: sha512-NnP3MQFh2pV7iETNmJzSlMBF/KhRA+XT4A7JLCfxunadQSPbTMMgbsZo9EfLloMwHMUhZGNVot3Pvh+VnT2joQ==} - engines: {node: '>=16.13'} - hasBin: true - dependencies: - '@cspotcode/source-map-support': 0.8.1 - acorn: 8.11.3 - acorn-walk: 8.3.2 - capnp-ts: 0.7.0 - exit-hook: 2.2.1 - glob-to-regexp: 0.4.1 - stoppable: 1.1.0 - undici: 5.28.3 - workerd: 1.20240208.0 - ws: 8.16.0 - youch: 3.3.3 - zod: 3.22.4 - transitivePeerDependencies: - - bufferutil - - supports-color - - utf-8-validate - dev: true - - /ms@2.1.2: - resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} - dev: true - - /mustache@4.2.0: - resolution: {integrity: sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==} - hasBin: true - dev: true - - /nanoid@3.3.7: - resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - dev: true - - /node-forge@1.3.1: - resolution: {integrity: sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==} - engines: {node: '>= 6.13.0'} - dev: true - - /normalize-path@3.0.0: - resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} - engines: {node: '>=0.10.0'} - dev: true - - /path-parse@1.0.7: - resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - dev: true - - /path-to-regexp@6.2.1: - resolution: {integrity: sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==} - dev: true - - /picomatch@2.3.1: - resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} - engines: {node: '>=8.6'} - dev: true - - /printable-characters@1.0.42: - resolution: {integrity: sha512-dKp+C4iXWK4vVYZmYSd0KBH5F/h1HoZRsbJ82AVKRO3PEo8L4lBS/vLwhVtpwwuYcoIsVY+1JYKR268yn480uQ==} - dev: true - - /readdirp@3.6.0: - resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} - engines: {node: '>=8.10.0'} - dependencies: - picomatch: 2.3.1 - dev: true - - /resolve.exports@2.0.2: - resolution: {integrity: sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==} - engines: {node: '>=10'} - dev: true - - /resolve@1.22.8: - resolution: {integrity: sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==} - hasBin: true - dependencies: - is-core-module: 2.13.1 - path-parse: 1.0.7 - supports-preserve-symlinks-flag: 1.0.0 - dev: true - - /rollup-plugin-inject@3.0.2: - resolution: {integrity: sha512-ptg9PQwzs3orn4jkgXJ74bfs5vYz1NCZlSQMBUA0wKcGp5i5pA1AO3fOUEte8enhGUC+iapTCzEWw2jEFFUO/w==} - deprecated: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-inject. - dependencies: - estree-walker: 0.6.1 - magic-string: 0.25.9 - rollup-pluginutils: 2.8.2 - dev: true - - /rollup-plugin-node-polyfills@0.2.1: - resolution: {integrity: sha512-4kCrKPTJ6sK4/gLL/U5QzVT8cxJcofO0OU74tnB19F40cmuAKSzH5/siithxlofFEjwvw1YAhPmbvGNA6jEroA==} - dependencies: - rollup-plugin-inject: 3.0.2 - dev: true - - /rollup-pluginutils@2.8.2: - resolution: {integrity: sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==} - dependencies: - estree-walker: 0.6.1 - dev: true - - /selfsigned@2.4.1: - resolution: {integrity: sha512-th5B4L2U+eGLq1TVh7zNRGBapioSORUeymIydxgFpwww9d2qyKvtuPU2jJuHvYAwwqi2Y596QBL3eEqcPEYL8Q==} - engines: {node: '>=10'} - dependencies: - '@types/node-forge': 1.3.11 - node-forge: 1.3.1 - dev: true - - /source-map@0.6.1: - resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} - engines: {node: '>=0.10.0'} - dev: true - - /sourcemap-codec@1.4.8: - resolution: {integrity: sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==} - deprecated: Please use @jridgewell/sourcemap-codec instead - dev: true - - /stacktracey@2.1.8: - resolution: {integrity: sha512-Kpij9riA+UNg7TnphqjH7/CzctQ/owJGNbFkfEeve4Z4uxT5+JapVLFXcsurIfN34gnTWZNJ/f7NMG0E8JDzTw==} - dependencies: - as-table: 1.0.55 - get-source: 2.0.12 - dev: true - - /stoppable@1.1.0: - resolution: {integrity: sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==} - engines: {node: '>=4', npm: '>=6'} - dev: true - - /supports-preserve-symlinks-flag@1.0.0: - resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} - engines: {node: '>= 0.4'} - dev: true - - /to-regex-range@5.0.1: - resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} - engines: {node: '>=8.0'} - dependencies: - is-number: 7.0.0 - dev: true - - /tslib@2.6.2: - resolution: {integrity: sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==} - dev: true - - /typescript@5.3.3: - resolution: {integrity: sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==} - engines: {node: '>=14.17'} - hasBin: true - dev: true - - /undici-types@5.26.5: - resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} - dev: true - - /undici@5.28.3: - resolution: {integrity: sha512-3ItfzbrhDlINjaP0duwnNsKpDQk3acHI3gVJ1z4fmwMK31k5G9OVIAMLSIaP6w4FaGkaAkN6zaQO9LUvZ1t7VA==} - engines: {node: '>=14.0'} - dependencies: - '@fastify/busboy': 2.1.0 - dev: true - - /workerd@1.20240208.0: - resolution: {integrity: sha512-edFdwHU95Ww2SmjBvBJhbc7hhVXMEo6Y7qqSWCl6W9lGScTlCMCXd4AU3f/EGJ3P++FC+CWqu+XuAywebbKF2Q==} - engines: {node: '>=16'} - hasBin: true - requiresBuild: true - optionalDependencies: - '@cloudflare/workerd-darwin-64': 1.20240208.0 - '@cloudflare/workerd-darwin-arm64': 1.20240208.0 - '@cloudflare/workerd-linux-64': 1.20240208.0 - '@cloudflare/workerd-linux-arm64': 1.20240208.0 - '@cloudflare/workerd-windows-64': 1.20240208.0 - dev: true - - /wrangler@3.29.0(@cloudflare/workers-types@4.20240222.0): - resolution: {integrity: sha512-VXUUltM0/fxCF20Z3tH39zpnykDJNPH2lMWI5wA0VmRpuKG0Gffjj5lU2vJaI/PfUCo3q4JErxWcgLezBGnFyA==} - engines: {node: '>=16.17.0'} - hasBin: true - peerDependencies: - '@cloudflare/workers-types': ^4.20230914.0 - peerDependenciesMeta: - '@cloudflare/workers-types': - optional: true - dependencies: - '@cloudflare/kv-asset-handler': 0.3.1 - '@cloudflare/workers-types': 4.20240222.0 - '@esbuild-plugins/node-globals-polyfill': 0.2.3(esbuild@0.17.19) - '@esbuild-plugins/node-modules-polyfill': 0.2.2(esbuild@0.17.19) - blake3-wasm: 2.1.5 - chokidar: 3.6.0 - esbuild: 0.17.19 - miniflare: 3.20240208.0 - nanoid: 3.3.7 - path-to-regexp: 6.2.1 - resolve: 1.22.8 - resolve.exports: 2.0.2 - selfsigned: 2.4.1 - source-map: 0.6.1 - xxhash-wasm: 1.0.2 - optionalDependencies: - fsevents: 2.3.3 - transitivePeerDependencies: - - bufferutil - - supports-color - - utf-8-validate - dev: true - - /ws@8.16.0: - resolution: {integrity: sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - dev: true - - /xxhash-wasm@1.0.2: - resolution: {integrity: sha512-ibF0Or+FivM9lNrg+HGJfVX8WJqgo+kCLDc4vx6xMeTce7Aj+DLttKbxxRR/gNLSAelRc1omAPlJ77N/Jem07A==} - dev: true - - /youch@3.3.3: - resolution: {integrity: sha512-qSFXUk3UZBLfggAW3dJKg0BMblG5biqSF8M34E06o5CSsZtH92u9Hqmj2RzGiHDi64fhe83+4tENFP2DB6t6ZA==} - dependencies: - cookie: 0.5.0 - mustache: 4.2.0 - stacktracey: 2.1.8 - dev: true - - /zod@3.22.4: - resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==} - dev: true diff --git a/apps/cf-ai-backend/src/routes.ts b/apps/cf-ai-backend/src/routes.ts index 4a2d2827..841f107a 100644 --- a/apps/cf-ai-backend/src/routes.ts +++ b/apps/cf-ai-backend/src/routes.ts @@ -2,6 +2,7 @@ import { CloudflareVectorizeStore } from '@langchain/cloudflare'; import * as apiAdd from './routes/add'; import * as apiQuery from "./routes/query" import * as apiAsk from "./routes/ask" +import * as apiChat from "./routes/chat" import { OpenAIEmbeddings } from './OpenAIEmbedder'; import { GenerativeModel } from '@google/generative-ai'; import { Request } from '@cloudflare/workers-types'; @@ -17,6 +18,8 @@ routeMap.set('/query', apiQuery); routeMap.set('/ask', apiAsk); +routeMap.set('/chat', apiChat); + // Add more route mappings as needed // routeMap.set('/api/otherRoute', { ... }); diff --git a/apps/cf-ai-backend/src/routes/chat.ts b/apps/cf-ai-backend/src/routes/chat.ts new file mode 100644 index 00000000..95788d03 --- /dev/null +++ b/apps/cf-ai-backend/src/routes/chat.ts @@ -0,0 +1,113 @@ +import { Content, GenerativeModel } from "@google/generative-ai"; +import { OpenAIEmbeddings } from "../OpenAIEmbedder"; +import { CloudflareVectorizeStore } from "@langchain/cloudflare"; +import { Request } from "@cloudflare/workers-types"; + +export async function POST(request: Request, _: CloudflareVectorizeStore, embeddings: OpenAIEmbeddings, model: GenerativeModel, env?: Env) { + const queryparams = new URL(request.url).searchParams; + const query = queryparams.get("q"); + const topK = parseInt(queryparams.get("topK") ?? "5"); + const user = queryparams.get("user") + const spaces = queryparams.get("spaces") + const spacesArray = spaces ? spaces.split(",") : undefined + + const sourcesOnly = (queryparams.get("sourcesOnly") ?? "false") + + if (!user) { + return new Response(JSON.stringify({ message: "Invalid User" }), { status: 400 }); + } + + if (!query) { + return new Response(JSON.stringify({ message: "Invalid Query" }), { status: 400 }); + } + const filter: VectorizeVectorMetadataFilter = { + user + } + + const responses: VectorizeMatches = { matches: [], count: 0 }; + + if (spacesArray) { + for (const space of spacesArray) { + filter.space = space; + + const queryAsVector = await embeddings.embedQuery(query); + + const resp = await env!.VECTORIZE_INDEX.query(queryAsVector, { + topK, + filter + }); + + if (resp.count > 0) { + responses.matches.push(...resp.matches) + responses.count += resp.count + } + } + } else { + const queryAsVector = await embeddings.embedQuery(query); + const resp = await env!.VECTORIZE_INDEX.query(queryAsVector, { + topK, + filter: { + user + } + }); + + if (resp.count > 0) { + responses.matches.push(...resp.matches) + responses.count += resp.count + } + } + + // if (responses.count === 0) { + // return new Response(JSON.stringify({ message: "No Results Found" }), { status: 404 }); + // } + + const highScoreIds = responses.matches.filter(({ score }) => score > 0.35).map(({ id }) => id) + + if (sourcesOnly === "true") { + return new Response(JSON.stringify({ ids: highScoreIds }), { status: 200 }); + } + + const vec = await env!.VECTORIZE_INDEX.getByIds(highScoreIds) + + const preparedContext = vec.map(({ metadata }) => `Website title: ${metadata!.title}\nDescription: ${metadata!.description}\nURL: ${metadata!.url}\nContent: ${metadata!.text}`).join("\n\n"); + + const body = await request.json() as { + chatHistory?: Content[] + }; + + const defaultHistory = [ + { + role: "user", + parts: [{ text: `You are an agent that summarizes a page based on the query. don't say 'based on the context'. I expect you to be like a 'Second Brain'. you will be provided with the context (old saved posts) and questions. Answer accordingly. Answer in markdown format` }], + }, + { + role: "model", + parts: [{ text: "Ok, I am a personal assistant, and will act as a second brain to help with user's queries." }], + }, + ] as Content[]; + + const chat = model.startChat({ + history: [...defaultHistory, ...(body.chatHistory ?? [])], + }); + + const prompt = `Context:\n${preparedContext}\n\nQuestion: ${query}\nAnswer:`; + + const output = await chat.sendMessageStream(prompt); + + const response = new Response( + new ReadableStream({ + async start(controller) { + const converter = new TextEncoder(); + for await (const chunk of output.stream) { + const chunkText = await chunk.text(); + const encodedChunk = converter.encode("data: " + JSON.stringify({ "response": chunkText }) + "\n\n"); + controller.enqueue(encodedChunk); + } + const doneChunk = converter.encode("data: [DONE]"); + controller.enqueue(doneChunk); + controller.close(); + } + }) + ); + return response; +} diff --git a/apps/cf-ai-backend/src/routes/query.ts b/apps/cf-ai-backend/src/routes/query.ts index bf94c13e..be237d7d 100644 --- a/apps/cf-ai-backend/src/routes/query.ts +++ b/apps/cf-ai-backend/src/routes/query.ts @@ -21,15 +21,11 @@ export async function GET(request: Request, _: CloudflareVectorizeStore, embeddi } const filter: VectorizeVectorMetadataFilter = { - user: { - $eq: user - } + user } if (space) { - filter.space = { - $eq: space - } + filter.space } const queryAsVector = await embeddings.embedQuery(query); @@ -40,7 +36,7 @@ export async function GET(request: Request, _: CloudflareVectorizeStore, embeddi }); if (resp.count === 0) { - return new Response(JSON.stringify({ message: "No Results Found" }), { status: 400 }); + return new Response(JSON.stringify({ message: "No Results Found" }), { status: 404 }); } const highScoreIds = resp.matches.filter(({ score }) => score > 0.3).map(({ id }) => id) diff --git a/apps/extension/manifest.json b/apps/extension/manifest.json index 53bddb24..7b7bf460 100644 --- a/apps/extension/manifest.json +++ b/apps/extension/manifest.json @@ -18,6 +18,7 @@ ], "matches": [ "http://localhost:3000/*", + "https://opulent-funicular-94rx4v9w775f96q-3000.app.github.dev/*", "https://anycontext.dhr.wtf/*", "" ] @@ -27,6 +28,7 @@ "activeTab", "storage", "http://localhost:3000/*", + "https://opulent-funicular-94rx4v9w775f96q-3000.app.github.dev/*", "https://anycontext.dhr.wtf/*" ], "background": { diff --git a/apps/extension/src/App.tsx b/apps/extension/src/App.tsx index a442cbb9..551fb0d0 100644 --- a/apps/extension/src/App.tsx +++ b/apps/extension/src/App.tsx @@ -1,6 +1,9 @@ import { useEffect, useState } from 'react'; import { z } from 'zod'; import { userObj } from './types/zods'; +import { getEnv } from './util'; + +const backendUrl = getEnv() === "development" ? "http://localhost:3000" : "https://supermemory.dhr.wtf"; function App() { const [userData, setUserData] = useState | null>( @@ -14,7 +17,7 @@ function App() { if (loginButton) { if (jwt) { - fetch('https://supermemory.dhr.wtf/api/me', { + fetch(`${backendUrl}/api/me`, { headers: { Authorization: `Bearer ${jwt}`, }, @@ -43,7 +46,7 @@ function App() { ); } diff --git a/apps/web/src/app/api/chat/route.ts b/apps/web/src/app/api/chat/route.ts new file mode 100644 index 00000000..aec5b0ea --- /dev/null +++ b/apps/web/src/app/api/chat/route.ts @@ -0,0 +1,67 @@ +import { db } from "@/server/db"; +import { eq } from "drizzle-orm"; +import { sessions, users } from "@/server/db/schema"; +import { type NextRequest, NextResponse } from "next/server"; +import { env } from "@/env"; +import { ChatHistory } from "../../../../types/memory"; + +export const runtime = "edge"; + +export async function POST(req: NextRequest) { + const token = req.cookies.get("next-auth.session-token")?.value ?? req.cookies.get("__Secure-authjs.session-token")?.value ?? req.cookies.get("authjs.session-token")?.value ?? req.headers.get("Authorization")?.replace("Bearer ", ""); + + const sessionData = await db.select().from(sessions).where(eq(sessions.sessionToken, token!)) + + if (!sessionData || sessionData.length === 0) { + return new Response(JSON.stringify({ message: "Invalid Key, session not found." }), { status: 404 }); + } + + const user = await db.select().from(users).where(eq(users.id, sessionData[0].userId)).limit(1) + + if (!user || user.length === 0) { + return NextResponse.json({ message: "Invalid Key, session not found." }, { status: 404 }); + } + + const session = { session: sessionData[0], user: user[0] } + + const query = new URL(req.url).searchParams.get("q"); + const spaces = new URL(req.url).searchParams.get("spaces"); + + const sourcesOnly = new URL(req.url).searchParams.get("sourcesOnly") ?? "false"; + + const chatHistory = await req.json() as { + chatHistory: ChatHistory[] + }; + + console.log("CHathistory", chatHistory) + + if (!query) { + return new Response(JSON.stringify({ message: "Invalid query" }), { status: 400 }); + } + + + const resp = await fetch(`https://cf-ai-backend.dhravya.workers.dev/chat?q=${query}&user=${session.user.email ?? session.user.name}&sourcesOnly=${sourcesOnly}&spaces=${spaces}`, { + headers: { + "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY, + }, + method: "POST", + body: JSON.stringify({ + chatHistory: chatHistory.chatHistory ?? [] + }) + }) + + console.log(resp.status) + console.log(resp.statusText) + + if (resp.status !== 200 || !resp.ok) { + const errorData = await resp.json(); + console.log(errorData) + return new Response(JSON.stringify({ message: "Error in CF function", error: errorData }), { status: resp.status }); + } + + // Stream the response back to the client + const { readable, writable } = new TransformStream(); + resp && resp.body!.pipeTo(writable); + + return new Response(readable, { status: 200 }); +} \ No newline at end of file diff --git a/apps/web/src/app/api/query/route.ts b/apps/web/src/app/api/query/route.ts index 4e2f0674..28f441bc 100644 --- a/apps/web/src/app/api/query/route.ts +++ b/apps/web/src/app/api/query/route.ts @@ -21,7 +21,7 @@ export async function GET(req: NextRequest) { return NextResponse.json({ message: "Invalid Key, session not found." }, { status: 404 }); } - const session = {session: sessionData[0], user: user[0]} + const session = { session: sessionData[0], user: user[0] } const query = new URL(req.url).searchParams.get("q"); const sourcesOnly = new URL(req.url).searchParams.get("sourcesOnly") ?? "false"; @@ -36,8 +36,11 @@ export async function GET(req: NextRequest) { } }) + console.log(resp.status) + if (resp.status !== 200 || !resp.ok) { const errorData = await resp.json(); + console.log(errorData) return new Response(JSON.stringify({ message: "Error in CF function", error: errorData }), { status: resp.status }); } diff --git a/apps/web/src/app/api/store/route.ts b/apps/web/src/app/api/store/route.ts index 46e4cdfb..06db08b9 100644 --- a/apps/web/src/app/api/store/route.ts +++ b/apps/web/src/app/api/store/route.ts @@ -1,6 +1,6 @@ import { db } from "@/server/db"; -import { eq } from "drizzle-orm"; -import { sessions, storedContent, userStoredContent, users } from "@/server/db/schema"; +import { and, eq } from "drizzle-orm"; +import { contentToSpace, sessions, storedContent, users, space } from "@/server/db/schema"; import { type NextRequest, NextResponse } from "next/server"; import { env } from "@/env"; import { getMetaData } from "@/server/helpers"; @@ -31,6 +31,7 @@ export async function POST(req: NextRequest) { const data = await req.json() as { pageContent: string, url: string, + space?: string }; const metadata = await getMetaData(data.url); @@ -38,33 +39,47 @@ export async function POST(req: NextRequest) { let id: number | undefined = undefined; - const storedCont = await db.select().from(storedContent).where(eq(storedContent.url, data.url)).limit(1) - - if (storedCont.length > 0) { - id = storedCont[0].id; - } else { - const storedContentId = await db.insert(storedContent).values({ - content: data.pageContent, - title: metadata.title, - description: metadata.description, - url: data.url, - baseUrl: metadata.baseUrl, - image: metadata.image, - savedAt: new Date() - }) + let storeToSpace = data.space + + if (!storeToSpace) { + storeToSpace = 'all' + } - id = storedContentId.meta.last_row_id; + const storedContentId = await db.insert(storedContent).values({ + content: data.pageContent, + title: metadata.title, + description: metadata.description, + url: data.url, + baseUrl: metadata.baseUrl, + image: metadata.image, + savedAt: new Date(), + user: session.user.id + }) + + id = storedContentId.meta.last_row_id; + + if (!id) { + return NextResponse.json({ message: "Error", error: "Error in CF function" }, { status: 500 }); } - try { - await db.insert(userStoredContent).values({ - userId: session.user.id, - contentId: id - }); - } catch (e) { - console.log(e); + let spaceID = 0; + + const spaceData = await db.select().from(space).where(and(eq(space.name, storeToSpace), eq(space.user, session.user.id))).limit(1) + spaceID = spaceData[0]?.id + + if (!spaceData || spaceData.length === 0) { + const spaceId = await db.insert(space).values({ + name: storeToSpace, + user: session.user.id + }) + spaceID = spaceId.meta.last_row_id; } + await db.insert(contentToSpace).values({ + contentId: id as number, + spaceId: spaceID + }) + const res = await Promise.race([ fetch("https://cf-ai-backend.dhravya.workers.dev/add", { method: "POST", @@ -78,10 +93,6 @@ export async function POST(req: NextRequest) { ) ]) as Response - const _ = await res.text(); - - console.log(_) - if (res.status !== 200) { return NextResponse.json({ message: "Error", error: "Error in CF function" }, { status: 500 }); } diff --git a/apps/web/src/app/content.tsx b/apps/web/src/app/content.tsx new file mode 100644 index 00000000..39f2948d --- /dev/null +++ b/apps/web/src/app/content.tsx @@ -0,0 +1,18 @@ +'use client'; +import Main from '@/components/Main'; +import Sidebar from '@/components/Sidebar/index'; +import { SessionProvider } from 'next-auth/react'; +import { useState } from 'react'; + +export default function Content() { + const [selectedItem, setSelectedItem] = useState(null); + + return ( + +
+ +
+
+
+ ); +} diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 394bda43..f19a0b57 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -20,7 +20,7 @@ } body { - @apply bg-rgray-1 text-rgray-11; + @apply bg-rgray-2 text-rgray-11 max-h-screen overflow-y-hidden; /* color: rgb(var(--foreground-rgb)); background: linear-gradient( to bottom, @@ -30,8 +30,41 @@ body { rgb(var(--background-start-rgb)); */ } +[vaul-drawer-wrapper] { + @apply bg-rgray-2; +} + @layer utilities { .text-balance { text-wrap: balance; } } + +.sidebar { + height: 100vh; + height: 100dvh; + max-height: 100vh; + max-height: 100dvh; +} + +.DrawerContent { + padding-top: 5vh; + padding-top: 5dvh; +} + +.main-hidden { + padding-bottom: 20vh; + padding-bottom: 15dvh; +} + +.chat-answer pre { + @apply bg-rgray-3 rounded-md border border-rgray-5 p-3 text-sm my-5; +} + +.chat-answer h1 { + @apply text-rgray-11 text-xl font-medium my-5; +} + +.chat-answer img { + @apply rounded-md font-medium my-5; +} \ No newline at end of file diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx index 5464c1d3..1b204dec 100644 --- a/apps/web/src/app/layout.tsx +++ b/apps/web/src/app/layout.tsx @@ -15,8 +15,12 @@ export default function RootLayout({ children: React.ReactNode; }>) { return ( - - {children} + + +
+ {children} +
+ ); } diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 2522a25f..95e18e83 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -1,29 +1,33 @@ -import { CardContent, Card } from '@/components/ui/card'; -import { db } from '@/server/db'; +import { db } from "@/server/db"; import { + contentToSpace, sessions, + space, + StoredContent, storedContent, - userStoredContent, users, -} from '@/server/db/schema'; -import { eq, inArray } from 'drizzle-orm'; -import { cookies, headers } from 'next/headers'; -import { redirect } from 'next/navigation'; -import Image from 'next/image'; -import QueryAI from '@/components/QueryAI'; -import MessagePoster from './MessagePoster'; +} from "@/server/db/schema"; +import { eq, inArray } from "drizzle-orm"; +import { cookies, headers } from "next/headers"; +import { redirect } from "next/navigation"; +import Sidebar from "@/components/Sidebar/index"; +import Main from "@/components/Main"; +import MessagePoster from "./MessagePoster"; +import { transformContent } from "../../types/memory"; +import { MemoryProvider } from "@/contexts/MemoryContext"; +import Content from "./content"; -export const runtime = 'edge'; +export const runtime = "edge"; export default async function Home() { const token = - cookies().get('next-auth.session-token')?.value ?? - cookies().get('__Secure-authjs.session-token')?.value ?? - cookies().get('authjs.session-token')?.value ?? - headers().get('Authorization')?.replace('Bearer ', ''); + cookies().get("next-auth.session-token")?.value ?? + cookies().get("__Secure-authjs.session-token")?.value ?? + cookies().get("authjs.session-token")?.value ?? + headers().get("Authorization")?.replace("Bearer ", ""); if (!token) { - return redirect('/api/auth/signin'); + return redirect("/api/auth/signin"); } const session = await db @@ -32,104 +36,50 @@ export default async function Home() { .where(eq(sessions.sessionToken, token!)); if (!session || session.length === 0) { - return redirect('/api/auth/signin'); + return redirect("/api/auth/signin"); } - const userContent = await db - .select() - .from(userStoredContent) - .where(eq(userStoredContent.userId, session[0].userId)); - - const userData = await db + const [userData] = await db .select() .from(users) .where(eq(users.id, session[0].userId)) .limit(1); - if (!userData || userData.length === 0) { - return redirect('/api/auth/signin'); + if (!userData) { + return redirect("/api/auth/signin"); } - const listOfContent = - userContent.map((content) => content.contentId).length > 0 - ? userContent.map((content) => content.contentId) - : [1]; - - const posts = await db + // Fetch all content for the user + const contents = await db .select() .from(storedContent) - .where(inArray(storedContent.id, listOfContent)); + .where(eq(storedContent.user, userData.id)) + .all(); - return ( -
-
-
- logo -
-

SuperMemory

- Remember that one thing you read a while ago? We got you covered. - Add the extension, click a button and I'll remember it for you.{' '} - - Get the Extension - -
-
-
- - + const collectedSpaces = + contents.length > 0 ? await transformContent(contents) : []; - + collectedSpaces.push({ + id: 2, + title: "Test", + content: [ + { + id: 1, + content: "Test", + title: "Vscode", + description: "Test", + url: "https://vscode-remake.vercel.app/", + savedAt: new Date(), + baseUrl: "https://vscode-remake.vercel.app/", + image: "https://vscode-remake.vercel.app/favicon.svg", + }, + ], + }); - {/* TODO: LABEL THE WEBSITES USING A CLASSIFICATION MODEL */} - {/* */} -
- {posts.reverse().map((post) => ( - - - Not found - -

{post.title}

-

{post.baseUrl}

-

{post.description}

-
-
-
- ))} -
-
+ return ( + + + {/* */} + ); } diff --git a/apps/web/src/app/ui/page.tsx b/apps/web/src/app/ui/page.tsx deleted file mode 100644 index 2f7c6a4b..00000000 --- a/apps/web/src/app/ui/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import Sidebar from "@/components/Sidebar"; - -export default async function Home() { - return ( - <> - - - ); -} diff --git a/apps/web/src/assets/Bin.tsx b/apps/web/src/assets/Bin.tsx new file mode 100644 index 00000000..d0793cef --- /dev/null +++ b/apps/web/src/assets/Bin.tsx @@ -0,0 +1,104 @@ +import { cn } from "@/lib/utils"; +import { useEffect, useRef } from "react"; + +export const Bin: React.FC & {}> = ({ + className, + ...props +}) => { + const icon = useRef(null); + + useEffect(() => { + let timeout: ReturnType | undefined; + + const observer = new MutationObserver(function (mutations) { + mutations.forEach(function (mutation) { + if ( + mutation.type === "attributes" && + mutation.attributeName === "data-open" && + (mutation.oldValue === "false" || mutation.oldValue === null) && + icon.current?.dataset["open"] === "true" + ) { + if (timeout) clearTimeout(timeout); + timeout = setTimeout(() => { + icon.current!.dataset["open"] = "false"; + }, 2000); + } + }); + }); + + observer.observe(icon.current!, { + attributes: true, //configure it to listen to attribute changes + }); + + return () => { + observer.disconnect(); + }; + }, []); + + return ( +
[data-lid]]:rotate-[150deg] [&[data-open='true']>[data-lid]]:delay-0", + className, + )} + {...props} + > + + + + + + + + + + +
+ ); +}; diff --git a/apps/web/src/assets/Memories.tsx b/apps/web/src/assets/Memories.tsx new file mode 100644 index 00000000..3b1c177f --- /dev/null +++ b/apps/web/src/assets/Memories.tsx @@ -0,0 +1,69 @@ +export const MemoryIcon: React.FC> = ( + props, +) => ( + + + + + +); + +export const SpaceIcon: React.FC> = (props) => ( + + + + +); diff --git a/apps/web/src/assets/MemoryWithImages.tsx b/apps/web/src/assets/MemoryWithImages.tsx new file mode 100644 index 00000000..5cd6f8ca --- /dev/null +++ b/apps/web/src/assets/MemoryWithImages.tsx @@ -0,0 +1,528 @@ +import { svgId } from "@/lib/utils"; + +export const MemoryWithImage: React.FC< + { image: string; id: string } & React.SVGAttributes +> = ({ image, id: _id, ...props }) => { + const id = "space-1-" + _id; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + +export const MemoryWithImages2: React.FC< + { images: string[]; id: string } & React.SVGAttributes +> = ({ images, id: _id, ...props }) => { + const id = "space-2-" + _id; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + +export const MemoryWithImages3: React.FC< + { images: string[]; id: string } & React.SVGAttributes +> = ({ images, id: _id, ...props }) => { + const id = "space-3-" + _id; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; diff --git a/apps/web/src/components/ChatMessage.tsx b/apps/web/src/components/ChatMessage.tsx new file mode 100644 index 00000000..d25c9c48 --- /dev/null +++ b/apps/web/src/components/ChatMessage.tsx @@ -0,0 +1,105 @@ +import React, { useEffect } from "react"; +import { motion } from "framer-motion"; +import { ArrowUpRight, Globe } from "lucide-react"; +import { convertRemToPixels } from "@/lib/utils"; +import { SpaceIcon } from "@/assets/Memories"; +import Markdown from "react-markdown"; + +export function ChatAnswer({ + children: message, + sources, + loading = false, +}: { + children: string; + sources?: string[]; + loading?: boolean; +}) { + return ( +
+ {loading ? ( + + ) : ( +
+ {message} +
+ )} + {!loading && sources && sources?.length > 0 && ( + <> +

+ + Related Memories +

+
+ {sources?.map((source) => ( + + + {source} + + ))} +
+ + )} +
+ ); +} + +export function ChatQuestion({ children }: { children: string }) { + return ( +
200 ? "text-xl" : "text-2xl"}`} + > + {children} +
+ ); +} + +export function ChatMessage({ + children, + isLast = false, + index, +}: { + children: React.ReactNode | React.ReactNode[]; + isLast?: boolean; + index: number; +}) { + const messageRef = React.useRef(null); + + useEffect(() => { + if (!isLast) return; + messageRef.current?.parentElement?.scrollTo({ + top: messageRef.current?.offsetTop, + behavior: "smooth", + }); + }, []); + + return ( + + {children} + + ); +} + +function MessageSkeleton() { + return ( +
+
+
+
+
+
+
+ ); +} diff --git a/apps/web/src/components/Main.tsx b/apps/web/src/components/Main.tsx new file mode 100644 index 00000000..c621c68f --- /dev/null +++ b/apps/web/src/components/Main.tsx @@ -0,0 +1,444 @@ +"use client"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { FilterCombobox } from "./Sidebar/FilterCombobox"; +import { Textarea2 } from "./ui/textarea"; +import { ArrowRight, ArrowUp } from "lucide-react"; +import { MemoryDrawer } from "./MemoryDrawer"; +import useViewport from "@/hooks/useViewport"; +import { AnimatePresence, motion } from "framer-motion"; +import { cn, countLines } from "@/lib/utils"; +import { ChatHistory } from "../../types/memory"; +import { ChatAnswer, ChatMessage, ChatQuestion } from "./ChatMessage"; +import { useRouter, useSearchParams } from "next/navigation"; +import { useMemory } from "@/contexts/MemoryContext"; + +function supportsDVH() { + try { + return CSS.supports("height: 100dvh"); + } catch { + return false; + } +} + +const failResponse = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In volutpat bibendum ligula, nec consectetur purus iaculis eu. Sed venenatis magna at lacus efficitur, vel faucibus sem lobortis. Sed sit amet imperdiet eros, nec vestibulum ante. Integer ut eros pulvinar, tempus augue a, blandit nisl. Nulla ut ligula molestie, tincidunt ligula vitae, rhoncus tellus. Vestibulum molestie, orci nec scelerisque finibus, mauris eros convallis urna, vitae vehicula metus nisi id urna. Phasellus non metus et lectus sollicitudin convallis a sit amet turpis. Donec id lacinia sapien. + +Donec eget eros diam. Ut enim nunc, placerat vitae augue vel, rutrum dapibus felis. Nulla et ultrices ex. In sed arcu eget lectus scelerisque semper. Nullam aliquam luctus ultrices. Morbi finibus nec dolor vitae mattis. Quisque ligula dui, ullamcorper sed blandit et, maximus vel quam. Nunc id eros id sapien tempor feugiat sit amet sed mi. Quisque feugiat hendrerit libero non cursus. Praesent convallis, diam eget ullamcorper bibendum, est tellus blandit velit, vel cursus diam turpis sed nisi. + +Cras dictum tortor ex, id ullamcorper nibh mollis quis. Fusce mollis, massa vel sodales consectetur, lorem mi vehicula erat, id tincidunt lorem libero at augue. Suspendisse vitae enim varius, molestie augue ut, lobortis ipsum. Nam lobortis leo eget velit auctor, ac consequat nisl malesuada. Donec sed dapibus nunc. Curabitur euismod erat a erat viverra vestibulum lacinia quis nisl. Aenean rhoncus suscipit maximus. Aliquam vitae lectus est. + +Sed rhoncus sem sapien, at posuere libero imperdiet eget. Maecenas in egestas quam. Duis non faucibus eros, nec sodales sem. Proin felis urna, dapibus eget ante vitae, porttitor bibendum nunc. Integer nec augue eget diam pulvinar vestibulum. Nulla lobortis libero tellus, eu commodo elit ullamcorper in. Sed semper ultricies turpis ac dignissim. Morbi at ligula non urna mollis interdum vitae sed nisi. Quisque mattis arcu eu nisl placerat ullamcorper. Cras aliquet risus sed hendrerit faucibus. Donec vitae ex quis magna cursus ultricies ut nec urna. + +Integer molestie nulla interdum enim suscipit malesuada. Nullam eget ipsum et elit sagittis imperdiet sed dignissim sem. Fusce vitae tellus ligula. Donec eget mi varius, consequat eros sed, consectetur urna. Suspendisse potenti. Praesent posuere ullamcorper tincidunt. Donec bibendum, magna nec mollis posuere, nisi risus dictum mauris, sed gravida metus sapien vel ipsum. Etiam ultrices nulla tincidunt erat lacinia, sit amet bibendum libero posuere. Vestibulum vehicula lectus dolor, sit amet vehicula arcu ultricies nec. Proin blandit risus diam, vel finibus erat efficitur in. Suspendisse lacinia eros luctus posuere fermentum. Etiam sed lacus aliquam, vulputate est sed, venenatis ex. Aenean at nulla rhoncus, sollicitudin elit quis, auctor tortor. Donec semper, augue lacinia pharetra imperdiet, metus purus bibendum ex, et venenatis enim purus vitae nulla. Duis eu felis porta ligula laoreet viverra. +Answer +It seems like you've used placeholder text commonly known as "Lorem Ipsum," which is often used in design and publishing to simulate the appearance of written text. If you have any specific questions or need assistance with something related to this text, feel free to ask! +what is its purpose? +Sources +solopress.com favicon +typingpal.com favicon +View 2 more +Answer +The purpose of Lorem Ipsum, a commonly used placeholder text in design and publishing, is to create a natural-looking block of text that doesn't distract from the layout. It allows designers to visualize how text will appear in a design without the need for actual content to be written and approved. Lorem Ipsum helps in planning out where the content will sit on a page, focusing on the design rather than the specific content. This practice is particularly useful when the main emphasis is on the visual layout, allowing designers and clients to review templates without being distracted by the actual copy on the page +4 +5 +. +hello +`; + +export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) { + const searchParams = useSearchParams(); + const router = useRouter(); + + const [hide, setHide] = useState(false); + const [layout, setLayout] = useState<"chat" | "initial">("initial"); + const [value, setValue] = useState(""); + const { width } = useViewport(); + const [isAiLoading, setIsAiLoading] = useState(false); + + const { spaces } = useMemory(); + + // Variable to keep track of the chat history in this session + const [chatHistory, setChatHistory] = useState([]); + + const [toBeParsed, setToBeParsed] = useState(""); + + const textArea = useRef(null); + const main = useRef(null); + + const [selectedSpaces, setSelectedSpaces] = useState([]); + + useEffect(() => { + const search = searchParams.get("q"); + if (search && search.trim().length > 0) { + setValue(search); + onSend(); + router.push("/"); + } + }, []); + + useEffect(() => { + function onResize() { + if (!main.current || !window.visualViewport) return; + if ( + window.visualViewport.height < window.innerHeight + 20 && + window.visualViewport.height > window.innerHeight - 20 + ) { + setHide(false); + window.scrollTo(0, 0); + } else { + setHide(true); + window.scrollTo(0, document.body.scrollHeight); + } + } + + window.visualViewport?.addEventListener("resize", onResize); + return () => { + window.visualViewport?.removeEventListener("resize", onResize); + }; + }, []); + + useEffect(() => { + // Define a function to try parsing the accumulated data + const tryParseAccumulatedData = () => { + // Attempt to parse the "toBeParsed" state as JSON + try { + // Split the accumulated data by the known delimiter "\n\n" + const parts = toBeParsed.split("\n\n"); + let remainingData = ""; + + // Process each part to extract JSON objects + parts.forEach((part, index) => { + try { + const parsedPart = JSON.parse(part.replace("data: ", "")); // Try to parse the part as JSON + + // If the part is the last one and couldn't be parsed, keep it to accumulate more data + if (index === parts.length - 1 && !parsedPart) { + remainingData = part; + } else if (parsedPart && parsedPart.response) { + // Append to chat history in this way: + // If the last message was from the model, append to that message + // Otherwise, Start a new message from the model and append to that + if (chatHistory.length > 0) { + setChatHistory((prev: ChatHistory[]) => { + const lastMessage = prev[prev.length - 1]; + const newParts = [ + ...lastMessage.answer.parts, + { text: parsedPart.response }, + ]; + return [ + ...prev.slice(0, prev.length - 1), + { + ...lastMessage, + answer: { + parts: newParts, + sources: lastMessage.answer.sources, + }, + }, + ]; + }); + } else { + } + } + } catch (error) { + // If parsing fails and it's not the last part, it's a malformed JSON + if (index !== parts.length - 1) { + console.error("Malformed JSON part: ", part); + } else { + // If it's the last part, it may be incomplete, so keep it + remainingData = part; + } + } + }); + + // Update the toBeParsed state to only contain the unparsed remainder + if (remainingData !== toBeParsed) { + setToBeParsed(remainingData); + } + } catch (error) { + console.error("Error parsing accumulated data: ", error); + } + }; + + // Call the parsing function if there's data to be parsed + if (toBeParsed) { + tryParseAccumulatedData(); + } + }, [toBeParsed]); + + const modifyChatHistory = useCallback((old: ChatHistory[]) => { + const final: { role: "user" | "model"; parts: { text: string }[] }[] = []; + old.forEach((chat) => { + final.push({ + role: "user", + parts: [{ text: chat.question }], + }); + final.push({ + role: "model", + parts: chat.answer.parts.map((part) => ({ text: part.text })), + }); + }); + + return final; + }, []); + + const getSearchResults = async () => { + setIsAiLoading(true); + + const _value = value.trim(); + setValue(""); + + setChatHistory((prev) => [ + ...prev, + { + question: _value, + answer: { + parts: [], + sources: [], + }, + }, + ]); + + const sourcesResponse = await fetch( + `/api/chat?sourcesOnly=true&q=${_value}`, + { + method: "POST", + body: JSON.stringify({ + chatHistory: modifyChatHistory(chatHistory), + }), + }, + ); + + const sourcesInJson = (await sourcesResponse.json()) as { + ids: string[]; + }; + + setIsAiLoading(false); + setChatHistory((prev) => { + const lastMessage = prev[prev.length - 1]; + return [ + ...prev.slice(0, prev.length - 1), + { + ...lastMessage, + answer: { + parts: lastMessage.answer.parts, + sources: sourcesInJson.ids ?? [], + }, + }, + ]; + }); + + const actualSelectedSpaces = selectedSpaces.map( + (space) => spaces.find((s) => s.id === space)?.title ?? "", + ); + + const response = await fetch( + `/api/chat?q=${_value}&spaces=${actualSelectedSpaces.join(",")}`, + { + method: "POST", + body: JSON.stringify({ + chatHistory: modifyChatHistory(chatHistory), + }), + }, + ); + + if (response.status !== 200) { + setIsAiLoading(false); + return; + } + + if (response.body) { + let reader = response.body?.getReader(); + let decoder = new TextDecoder("utf-8"); + let result = ""; + + // @ts-ignore + reader.read().then(function processText({ done, value }) { + if (done) { + setIsAiLoading(false); + setToBeParsed(""); + setValue(""); + + return; + } + setToBeParsed((prev) => prev + decoder.decode(value)); + + return reader?.read().then(processText); + }); + } + }; + + const onSend = async () => { + setLayout("chat"); + await getSearchResults(); + }; + + return ( + <> + + {layout === "chat" ? ( + + ) : ( +
+

+ Ask your Second brain +

+ + setValue(e.target.value), + onKeyDown: (e) => { + console.log(e.key, e.ctrlKey, e.metaKey); + if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { + onSend(); + } + }, + }} + > +
+ { + textArea.current?.querySelector("textarea")?.focus(); + }} + className="hidden md:flex" + selectedSpaces={selectedSpaces} + setSelectedSpaces={setSelectedSpaces} + /> + +
+
+ {width <= 768 && } +
+ )} +
+ + ); +} + +export function Chat({ + sidebarOpen, + chatHistory, + isLoading = false, + askQuestion, + setValue, + value, +}: { + sidebarOpen: boolean; + isLoading?: boolean; + chatHistory: ChatHistory[]; + askQuestion: () => void; + setValue: (value: string) => void; + value: string; +}) { + const textArea = useRef(null); + + function onValueChange(e: React.ChangeEvent) { + const value = e.target.value; + setValue(value); + const lines = countLines(e.target); + e.target.rows = Math.min(5, lines); + } + + return ( +
+
+ {chatHistory.map((msg, i) => ( + + {msg.question} + + {msg.answer.parts.map((part) => part.text).join(" ")} + + + ))} +
+
+
+
+ { + textArea.current?.querySelector("textarea")?.focus(); + }} + side="top" + align="start" + className="bg-[#252525]" + // TODO: SPACES FILTER HERE + selectedSpaces={[]} + setSelectedSpaces={(spaces) => {}} + /> + { + if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { + askQuestion(); + } + }, + }} + > +
+ +
+
+
+
+
+ ); +} diff --git a/apps/web/src/components/MemoryDrawer.tsx b/apps/web/src/components/MemoryDrawer.tsx new file mode 100644 index 00000000..f1ca5d47 --- /dev/null +++ b/apps/web/src/components/MemoryDrawer.tsx @@ -0,0 +1,49 @@ +import { useRef, useState } from "react"; +import { Drawer, DrawerContent, DrawerOverlay } from "./ui/drawer"; +import { MemoryIcon } from "@/assets/Memories"; +import { cn } from "@/lib/utils"; +import { MemoriesBar } from "./Sidebar/MemoriesBar"; + +export interface Props extends React.ButtonHTMLAttributes { + hide?: boolean; +} + +export function MemoryDrawer({ className, hide = false, ...props }: Props) { + const [activeSnapPoint, setActiveSnapPoint] = useState< + number | null | string + >(0.1); + + return ( + + + + + + + + ); +} diff --git a/apps/web/src/components/QueryAI.tsx b/apps/web/src/components/QueryAI.tsx deleted file mode 100644 index 3cb14178..00000000 --- a/apps/web/src/components/QueryAI.tsx +++ /dev/null @@ -1,139 +0,0 @@ -'use client'; - -import { Label } from './ui/label'; -import React, { useEffect, useState } from 'react'; -import { Input } from './ui/input'; -import { Button } from './ui/button'; -import SearchResults from './SearchResults'; - -function QueryAI() { - const [searchResults, setSearchResults] = useState([]); - const [isAiLoading, setIsAiLoading] = useState(false); - - const [aiResponse, setAIResponse] = useState(''); - const [input, setInput] = useState(''); - const [toBeParsed, setToBeParsed] = useState(''); - - const handleStreamData = (newChunk: string) => { - // Append the new chunk to the existing data to be parsed - setToBeParsed((prev) => prev + newChunk); - }; - - useEffect(() => { - // Define a function to try parsing the accumulated data - const tryParseAccumulatedData = () => { - // Attempt to parse the "toBeParsed" state as JSON - try { - // Split the accumulated data by the known delimiter "\n\n" - const parts = toBeParsed.split('\n\n'); - let remainingData = ''; - - // Process each part to extract JSON objects - parts.forEach((part, index) => { - try { - const parsedPart = JSON.parse(part.replace('data: ', '')); // Try to parse the part as JSON - - // If the part is the last one and couldn't be parsed, keep it to accumulate more data - if (index === parts.length - 1 && !parsedPart) { - remainingData = part; - } else if (parsedPart && parsedPart.response) { - // If the part is parsable and has the "response" field, update the AI response state - setAIResponse((prev) => prev + parsedPart.response); - } - } catch (error) { - // If parsing fails and it's not the last part, it's a malformed JSON - if (index !== parts.length - 1) { - console.error('Malformed JSON part: ', part); - } else { - // If it's the last part, it may be incomplete, so keep it - remainingData = part; - } - } - }); - - // Update the toBeParsed state to only contain the unparsed remainder - if (remainingData !== toBeParsed) { - setToBeParsed(remainingData); - } - } catch (error) { - console.error('Error parsing accumulated data: ', error); - } - }; - - // Call the parsing function if there's data to be parsed - if (toBeParsed) { - tryParseAccumulatedData(); - } - }, [toBeParsed]); - - const getSearchResults = async (e: React.FormEvent) => { - e.preventDefault(); - setIsAiLoading(true); - - const sourcesResponse = await fetch( - `/api/query?sourcesOnly=true&q=${input}`, - ); - - const sourcesInJson = (await sourcesResponse.json()) as { - ids: string[]; - }; - - setSearchResults(sourcesInJson.ids); - - const response = await fetch(`/api/query?q=${input}`); - - if (response.status !== 200) { - setIsAiLoading(false); - return; - } - - if (response.body) { - let reader = response.body.getReader(); - let decoder = new TextDecoder('utf-8'); - let result = ''; - - // @ts-ignore - reader.read().then(function processText({ done, value }) { - if (done) { - // setSearchResults(JSON.parse(result.replace('data: ', ''))); - // setIsAiLoading(false); - return; - } - - handleStreamData(decoder.decode(value)); - - return reader.read().then(processText); - }); - } - }; - - return ( -
-
await getSearchResults(e)} className="mt-8"> - -
- setInput(e.target.value)} - placeholder="Search using AI... ✨" - id="searchInput" - /> - -
-
- - {searchResults && ( - - )} -
- ); -} - -export default QueryAI; diff --git a/apps/web/src/components/SearchResults.tsx b/apps/web/src/components/SearchResults.tsx deleted file mode 100644 index 0445d0b4..00000000 --- a/apps/web/src/components/SearchResults.tsx +++ /dev/null @@ -1,38 +0,0 @@ -'use client' - -import React from 'react'; -import { Card, CardContent } from './ui/card'; -import Markdown from 'react-markdown'; -import remarkGfm from 'remark-gfm' - -function SearchResults({ - aiResponse, - sources, -}: { - aiResponse: string; - sources: string[]; -}) { - return ( -
-
-
- {aiResponse.replace('', '')} -
-
-
- {sources.map((value, index) => ( - - {value} - - ))} -
-
- ); -} - -export default SearchResults; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 1af37025..66ca1652 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -26,8 +26,7 @@ export default function Sidebar() { description: '', image: 'https://code.visualstudio.com/favicon.ico', baseUrl: 'https://code.visualstudio.com', - savedAt: new Date(), - space: 'Development', + savedAt: new Date() }, { id: 1, @@ -37,8 +36,7 @@ export default function Sidebar() { description: '', image: 'https://github.com/favicon.ico', baseUrl: 'https://github.com', - savedAt: new Date(), - space: 'Development', + savedAt: new Date() }, ]; diff --git a/apps/web/src/components/Sidebar/CategoryItem.tsx b/apps/web/src/components/Sidebar/CategoryItem.tsx new file mode 100644 index 00000000..0cf8a70c --- /dev/null +++ b/apps/web/src/components/Sidebar/CategoryItem.tsx @@ -0,0 +1,298 @@ +'use client'; +import { cleanUrl } from '@/lib/utils'; +import { StoredContent } from '@/server/db/schema'; +import { + DropdownMenu, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuItem, +} from '../ui/dropdown-menu'; +import { Label } from '../ui/label'; +import { + ArrowUpRight, + MoreHorizontal, + Tags, + ChevronDown, + Edit3, + Trash2, + Save, + ChevronRight, + Plus, + Minus, +} from 'lucide-react'; +import { useState } from 'react'; +import { + Drawer, + DrawerContent, + DrawerHeader, + DrawerTitle, + DrawerDescription, + DrawerFooter, + DrawerClose, +} from '../ui/drawer'; +import { Input } from '../ui/input'; +import { Textarea } from '../ui/textarea'; +import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'; +import { + AnimatePresence, + motion, + Reorder, + useMotionValue, +} from 'framer-motion'; + +const pages: StoredContent[] = [ + { + id: 1, + content: '', + title: 'Visual Studio Code', + url: 'https://code.visualstudio.com', + description: '', + image: 'https://code.visualstudio.com/favicon.ico', + baseUrl: 'https://code.visualstudio.com', + savedAt: new Date(), + }, + { + id: 2, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, + { + id: 3, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, + { + id: 4, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, + { + id: 5, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, + { + id: 6, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, + { + id: 7, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, + { + id: 8, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, + { + id: 9, + content: '', + title: "yxshv/vscode: An unofficial remake of vscode's landing page", + url: 'https://github.com/yxshv/vscode', + description: '', + image: 'https://github.com/favicon.ico', + baseUrl: 'https://github.com', + savedAt: new Date(), + }, +]; +export const CategoryItem: React.FC<{ item: StoredContent }> = ({ item }) => { + const [isExpanded, setIsExpanded] = useState(false); + const [isEditDrawerOpen, setIsEditDrawerOpen] = useState(false); + + const [items, setItems] = useState(pages); + + return ( + <> +
+ + + + + + Edit Page Details + + Change the page details + + + {cleanUrl(item.url)} + + + +
+ + +
+
+ +