diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8d12f8134..6cbad1acf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,39 +22,34 @@ jobs: with: node-version: 20 - - name: Set up Deno - uses: denoland/setup-deno@v2 - with: - deno-version: v2.x - - name: Install deps run: yarn - # edgedb + # gel - name: Copy readme run: cp README.md packages/driver/README.md - - name: Build edgedb - run: yarn workspace edgedb run build + - name: Build gel + run: yarn workspace gel run build - id: check_publish_driver - name: Dry-run publish 'edgedb' to npm + name: Dry-run publish 'gel' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/driver/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If 'edgedb' version unchanged + - name: If 'gel' version unchanged if: steps.check_publish_driver.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace edgedb version --no-git-tag-version --minor + yarn workspace gel version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/driver/package.json').version") - yarn workspace edgedb version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace gel version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish 'edgedb' + - name: Publish 'gel' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/driver/package.json @@ -62,39 +57,39 @@ jobs: access: public tag: ${{ steps.check_publish_driver.outputs.type == '' && 'canary' || 'latest' }} - - name: Create 'edgedb' GitHub Release + - name: Create 'gel' GitHub Release if: steps.check_publish_driver.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: v${{ steps.check_publish_driver.outputs.version }} - name: edgedb-js v${{ steps.check_publish_driver.outputs.version }} + name: gel-js v${{ steps.check_publish_driver.outputs.version }} draft: true prerelease: false - # @edgedb/generate + # @gel/generate - - name: Build @edgedb/generate - run: yarn workspace @edgedb/generate run build + - name: Build @gel/generate + run: yarn workspace @gel/generate run build - id: check_publish_generate - name: Dry-run publish '@edgedb/generate' to npm + name: Dry-run publish '@gel/generate' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: - package: packages/generate/package.json + package: packages/gel/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/generate' version unchanged + - name: If '@gel/generate' version unchanged if: steps.check_publish_generate.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/generate version --no-git-tag-version --minor + yarn workspace @gel/generate version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/generate/package.json').version") - yarn workspace @edgedb/generate version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/generate version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/generate' + - name: Publish '@gel/generate' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/generate/package.json @@ -102,39 +97,39 @@ jobs: access: public tag: ${{ steps.check_publish_generate.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/generate' GitHub Release + - name: Create '@gel/generate' GitHub Release if: steps.check_publish_generate.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: generate-v${{ steps.check_publish_generate.outputs.version }} - name: "@edgedb/generate v${{ steps.check_publish_generate.outputs.version }}" + name: "@gel/generate v${{ steps.check_publish_generate.outputs.version }}" draft: true prerelease: false - # @edgedb/auth-core + # @gel/auth-core - - name: Build @edgedb/auth-core - run: yarn workspace @edgedb/auth-core run build + - name: Build @gel/auth-core + run: yarn workspace @gel/auth-core run build - id: check_publish_auth_core - name: Dry-run publish '@edgedb/auth-core' to npm + name: Dry-run publish '@gel/auth-core' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-core/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/auth-core' version unchanged + - name: If '@gel/auth-core' version unchanged if: steps.check_publish_auth_core.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/auth-core version --no-git-tag-version --minor + yarn workspace @gel/auth-core version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/auth-core/package.json').version") - yarn workspace @edgedb/auth-core version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/auth-core version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/auth-core' + - name: Publish '@gel/auth-core' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-core/package.json @@ -142,39 +137,39 @@ jobs: access: public tag: ${{ steps.check_publish_auth_core.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/auth-core' Release + - name: Create '@gel/auth-core' Release if: steps.check_publish_auth_core.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: auth-core-v${{ steps.check_publish_auth_core.outputs.version }} - name: "@edgedb/auth-core v${{ steps.check_publish_auth_core.outputs.version }}" + name: "@gel/auth-core v${{ steps.check_publish_auth_core.outputs.version }}" draft: true prerelease: false - # @edgedb/auth-nextjs + # @gel/auth-nextjs - - name: Build @edgedb/auth-nextjs - run: yarn workspace @edgedb/auth-nextjs run build + - name: Build @gel/auth-nextjs + run: yarn workspace @gel/auth-nextjs run build - id: check_publish_auth_nextjs - name: Dry-run publish '@edgedb/auth-nextjs' to npm + name: Dry-run publish '@gel/auth-nextjs' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-nextjs/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/auth-nextjs' version unchanged + - name: If '@gel/auth-nextjs' version unchanged if: steps.check_publish_auth_nextjs.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/auth-nextjs version --no-git-tag-version --minor + yarn workspace @gel/auth-nextjs version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/auth-nextjs/package.json').version") - yarn workspace @edgedb/auth-nextjs version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/auth-nextjs version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/auth-nextjs' + - name: Publish '@gel/auth-nextjs' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-nextjs/package.json @@ -182,39 +177,39 @@ jobs: access: public tag: ${{ steps.check_publish_auth_nextjs.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/auth-nextjs' Release + - name: Create '@gel/auth-nextjs' Release if: steps.check_publish_auth_nextjs.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: auth-nextjs-v${{ steps.check_publish_auth_nextjs.outputs.version }} - name: "@edgedb/auth-nextjs v${{ steps.check_publish_auth_nextjs.outputs.version }}" + name: "@gel/auth-nextjs v${{ steps.check_publish_auth_nextjs.outputs.version }}" draft: true prerelease: false - # @edgedb/auth-express + # @gel/auth-express - - name: Build @edgedb/auth-express - run: yarn workspace @edgedb/auth-express run build + - name: Build @gel/auth-express + run: yarn workspace @gel/auth-express run build - id: check_publish_auth_express - name: Dry-run publish '@edgedb/auth-express' to npm + name: Dry-run publish '@gel/auth-express' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-express/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/auth-express' version unchanged + - name: If '@gel/auth-express' version unchanged if: steps.check_publish_auth_express.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/auth-express version --no-git-tag-version --minor + yarn workspace @gel/auth-express version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/auth-express/package.json').version") - yarn workspace @edgedb/auth-express version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/auth-express version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/auth-express' + - name: Publish '@gel/auth-express' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-express/package.json @@ -222,39 +217,39 @@ jobs: access: public tag: ${{ steps.check_publish_auth_express.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/auth-express' Release + - name: Create '@gel/auth-express' Release if: steps.check_publish_auth_express.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: auth-express-v${{ steps.check_publish_auth_express.outputs.version }} - name: "@edgedb/auth-express v${{ steps.check_publish_auth_express.outputs.version }}" + name: "@gel/auth-express v${{ steps.check_publish_auth_express.outputs.version }}" draft: true prerelease: false - # @edgedb/auth-remix + # @gel/auth-remix - - name: Build @edgedb/auth-remix - run: yarn workspace @edgedb/auth-remix run build + - name: Build @gel/auth-remix + run: yarn workspace @gel/auth-remix run build - id: check_publish_auth_remix - name: Dry-run publish '@edgedb/auth-remix' to npm + name: Dry-run publish '@gel/auth-remix' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-remix/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/auth-remix' version unchanged + - name: If '@gel/auth-remix' version unchanged if: steps.check_publish_auth_remix.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/auth-remix version --no-git-tag-version --minor + yarn workspace @gel/auth-remix version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/auth-remix/package.json').version") - yarn workspace @edgedb/auth-remix version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/auth-remix version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/auth-remix' + - name: Publish '@gel/auth-remix' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-remix/package.json @@ -262,39 +257,39 @@ jobs: access: public tag: ${{ steps.check_publish_auth_remix.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/auth-remix' Release + - name: Create '@gel/auth-remix' Release if: steps.check_publish_auth_remix.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: auth-remix-v${{ steps.check_publish_auth_remix.outputs.version }} - name: "@edgedb/auth-remix v${{ steps.check_publish_auth_remix.outputs.version }}" + name: "@gel/auth-remix v${{ steps.check_publish_auth_remix.outputs.version }}" draft: true prerelease: false - # @edgedb/auth-sveltekit + # @gel/auth-sveltekit - - name: Build @edgedb/auth-sveltekit - run: yarn workspace @edgedb/auth-sveltekit run build + - name: Build @gel/auth-sveltekit + run: yarn workspace @gel/auth-sveltekit run build - id: check_publish_auth_sveltekit - name: Dry-run publish '@edgedb/auth-sveltekit' to npm + name: Dry-run publish '@gel/auth-sveltekit' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-sveltekit/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/auth-sveltekit' version unchanged + - name: If '@gel/auth-sveltekit' version unchanged if: steps.check_publish_auth_sveltekit.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/auth-sveltekit version --no-git-tag-version --minor + yarn workspace @gel/auth-sveltekit version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/auth-sveltekit/package.json').version") - yarn workspace @edgedb/auth-sveltekit version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/auth-sveltekit version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/auth-sveltekit' + - name: Publish '@gel/auth-sveltekit' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/auth-sveltekit/package.json @@ -302,39 +297,39 @@ jobs: access: public tag: ${{ steps.check_publish_auth_sveltekit.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/auth-sveltekit' Release + - name: Create '@gel/auth-sveltekit' Release if: steps.check_publish_auth_sveltekit.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: auth-sveltekit-v${{ steps.check_publish_auth_sveltekit.outputs.version }} - name: "@edgedb/auth-sveltekit v${{ steps.check_publish_auth_sveltekit.outputs.version }}" + name: "@gel/auth-sveltekit v${{ steps.check_publish_auth_sveltekit.outputs.version }}" draft: true prerelease: false - # @edgedb/create + # @gel/create - - name: Build @edgedb/create - run: yarn workspace @edgedb/create run build + - name: Build @gel/create + run: yarn workspace @gel/create run build - id: check_publish_create - name: Dry-run publish '@edgedb/create' to npm + name: Dry-run publish '@gel/create' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/create/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/create' version unchanged + - name: If '@gel/create' version unchanged if: steps.check_publish_create.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/create version --no-git-tag-version --minor + yarn workspace @gel/create version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/create/package.json').version") - yarn workspace @edgedb/create version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/create version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/create' + - name: Publish '@gel/create' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/create/package.json @@ -342,39 +337,39 @@ jobs: access: public tag: ${{ steps.check_publish_create.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/create' Release + - name: Create '@gel/create' Release if: steps.check_publish_create.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: create-v${{ steps.check_publish_create.outputs.version }} - name: "@edgedb/create v${{ steps.check_publish_create.outputs.version }}" + name: "@gel/create v${{ steps.check_publish_create.outputs.version }}" draft: true prerelease: false - # @edgedb/ai + # @gel/ai - - name: Build @edgedb/ai - run: yarn workspace @edgedb/ai run build + - name: Build @gel/ai + run: yarn workspace @gel/ai run build - id: check_publish_ai - name: Dry-run publish '@edgedb/ai' to npm + name: Dry-run publish '@gel/ai' to npm uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/ai/package.json token: ${{ secrets.NPM_TOKEN }} dry-run: true - - name: If '@edgedb/ai' version unchanged + - name: If '@gel/ai' version unchanged if: steps.check_publish_ai.outputs.type == '' run: | echo "Version in package.json has not changed. Creating canary release." - yarn workspace @edgedb/ai version --no-git-tag-version --minor + yarn workspace @gel/ai version --no-git-tag-version --minor CURRENT_VERSION=$(node -p "require('./packages/ai/package.json').version") - yarn workspace @edgedb/ai version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" + yarn workspace @gel/ai version --no-git-tag-version --new-version "${CURRENT_VERSION}-canary.$(date +'%Y%m%dT%H%M%S')" - - name: Publish '@edgedb/ai' + - name: Publish '@gel/ai' uses: JS-DevTools/npm-publish@4b07b26a2f6e0a51846e1870223e545bae91c552 with: package: packages/ai/package.json @@ -382,13 +377,13 @@ jobs: access: public tag: ${{ steps.check_publish_ai.outputs.type == '' && 'canary' || 'latest' }} - - name: Create '@edgedb/ai' Release + - name: Create '@gel/ai' Release if: steps.check_publish_ai.outputs.type != '' uses: softprops/action-gh-release@v2.0.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ai-v${{ steps.check_publish_ai.outputs.version }} - name: "@edgedb/ai v${{ steps.check_publish_ai.outputs.version }}" + name: "@gel/ai v${{ steps.check_publish_ai.outputs.version }}" draft: true prerelease: false diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 626d93035..5060ac09e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,24 +18,24 @@ jobs: matrix: node-version: ["18", "20", "22"] os: [ubuntu-latest] - edgedb-version: ["stable"] + gel-version: ["stable"] include: - os: ubuntu-latest node-version: "20" - edgedb-version: "nightly" + gel-version: "nightly" - os: ubuntu-latest node-version: "20" - edgedb-version: "5" + gel-version: "5" - os: ubuntu-latest node-version: "20" - edgedb-version: "4" + gel-version: "4" # - os: ubuntu-latest # node-version: "20" - # edgedb-version: "3" + # gel-version: "3" # XXX: macOS is currently unsupported by setup-edgedb # - os: macos-latest # node-version: "20" - # edgedb-version: "stable" + # gel-version: "stable" steps: - uses: actions/checkout@v4 @@ -77,35 +77,35 @@ jobs: run: | yarn format - - name: Install EdgeDB + - name: Install Gel uses: edgedb/setup-edgedb@6763b6de72782d9c2e5ecc1095986a1c707da68f with: instance-name: test - server-version: ${{ matrix.edgedb-version }} + server-version: ${{ matrix.gel-version }} - - name: Show actual EdgeDB server version + - name: Show actual Gel server version run: | - echo ACTIVE_EDGEDB_VERSION=$(edgedb query 'select sys::get_version_as_str()' -I test) >> $GITHUB_ENV + echo ACTIVE_GEL_VERSION=$(gel query 'select sys::get_version_as_str()' -I test) >> $GITHUB_ENV - name: Run package tests run: | yarn ci:test - name: Run query builder integration tests lts - if: ${{ matrix.edgedb-version == '3' || matrix.edgedb-version == '4' || matrix.edgedb-version == 'stable' || matrix.edgedb-version == 'nightly' }} + if: ${{ matrix.gel-version == '3' || matrix.gel-version == '4' || matrix.gel-version == 'stable' || matrix.gel-version == 'nightly' }} run: | - turbo run ci:integration-test --filter=@edgedb/integration-lts - turbo run bench:types --filter=@edgedb/integration-lts || echo "Benchmark types script failed, proceeding anyway." + turbo run ci:integration-test --filter=@gel/integration-lts + turbo run bench:types --filter=@gel/integration-lts || echo "Benchmark types script failed, proceeding anyway." - name: Run query builder integration tests stable - if: ${{ matrix.edgedb-version == 'stable' || matrix.edgedb-version == 'nightly' }} + if: ${{ matrix.gel-version == 'stable' || matrix.gel-version == 'nightly' }} run: | - turbo run ci:integration-test --filter=@edgedb/integration-stable + turbo run ci:integration-test --filter=@gel/integration-stable - name: Run query builder integration tests nightly - if: ${{ matrix.edgedb-version == 'nightly' }} + if: ${{ matrix.gel-version == 'nightly' }} run: | - turbo run ci:integration-test --filter=@edgedb/integration-nightly + turbo run ci:integration-test --filter=@gel/integration-nightly - name: Typecheck other packages run: | @@ -144,8 +144,8 @@ jobs: - name: Build and pack CLI wrapper run: | - yarn workspace edgedb run build - yarn workspace edgedb pack --filename=${{ github.workspace }}/edgedb-cli.tar.gz + yarn workspace gel run build + yarn workspace gel pack --filename=${{ github.workspace }}/edgedb-cli.tar.gz - name: Test CLI wrapper with npm run: | @@ -153,9 +153,9 @@ jobs: cd ${{ runner.temp }}/temp-npm npm init -y npm install ${{ github.workspace }}/edgedb-cli.tar.gz - npm exec edgedb -- project init --non-interactive - npm exec edgedb -- --version - npm exec edgedb -- query 'select sys::get_version_as_str()' + npm exec gel -- project init --non-interactive + npm exec gel -- --version + npm exec gel -- query 'select sys::get_version_as_str()' - name: Test CLI wrapper with yarn run: | @@ -163,9 +163,9 @@ jobs: cd ${{ runner.temp }}/temp-yarn yarn init -y yarn add ${{ github.workspace}}/edgedb-cli.tar.gz - yarn edgedb project init --non-interactive - yarn edgedb --version - yarn edgedb query 'select sys::get_version_as_str()' + yarn gel project init --non-interactive + yarn gel --version + yarn gel query 'select sys::get_version_as_str()' - uses: threeal/setup-yarn-action@ec8c075e62bc497968de40011c2b766f5e8f1ac5 with: @@ -179,9 +179,9 @@ jobs: yarn init -y touch yarn.lock yarn add ${{ github.workspace }}/edgedb-cli.tar.gz - yarn edgedb project init --non-interactive - yarn edgedb --version - yarn edgedb query 'select sys::get_version_as_str()' + yarn gel project init --non-interactive + yarn gel --version + yarn gel query 'select sys::get_version_as_str()' - uses: pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d with: @@ -193,9 +193,9 @@ jobs: cd ${{ runner.temp}}/temp-pnpm pnpm init pnpm add ${{ github.workspace }}/edgedb-cli.tar.gz - pnpm exec edgedb project init --non-interactive - pnpm exec edgedb --version - pnpm exec edgedb query 'select sys::get_version_as_str()' + pnpm exec gel project init --non-interactive + pnpm exec gel --version + pnpm exec gel query 'select sys::get_version_as_str()' - uses: oven-sh/setup-bun@8f24390df009a496891208e5e36b8a1de1f45135 - name: Test CLI wrapper with bun @@ -204,6 +204,6 @@ jobs: cd temp-bun bun init bun add ${{ github.workspace }}/edgedb-cli.tar.gz - bun edgedb project init --non-interactive - bun edgedb --version - bun edgedb query 'select sys::get_version_as_str()' + bun gel project init --non-interactive + bun gel --version + bun gel query 'select sys::get_version_as_str()' diff --git a/.gitignore b/.gitignore index 140976d86..c87245aef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ dist -packages/deno /.bench /.vscode node_modules diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..e21156fac --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +packages/driver/test/shared-client-testcases/ diff --git a/README.md b/README.md index aed174682..50e5ed4a6 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,39 @@
-

The official Node.js client library for EdgeDB

+

The official Node.js client library for Gel

- - Build status + + Build status - - NPM version + + NPM version - - Stars + + Stars - +

- Quickstart + Quickstart   •   - Website + Website   •   - Docs + Docs   •   Discord   •   - Twitter + Twitter
-This is the official [EdgeDB](https://github.com/edgedb/edgedb) client library +This is the official [Gel](https://github.com/geldata/gel) client library for JavaScript and TypeScript. -If you're just getting started with EdgeDB, we recommend going through the -[EdgeDB Quickstart](https://www.edgedb.com/docs/quickstart) first. This walks -you through the process of installing EdgeDB, creating a simple schema, and +If you're just getting started with Gel, we recommend going through the +[Gel Quickstart](https://www.geldata.com/docs/quickstart) first. This walks +you through the process of installing Gel, creating a simple schema, and writing some simple queries. ### Requirements @@ -46,16 +46,16 @@ writing some simple queries. ### Installation ```bash -npm install edgedb # npm users -yarn add edgedb # yarn users +npm install gel # npm users +yarn add gel # yarn users ``` -> EdgeDB 2.x requires `v0.21.0` or later +> Gel 2.x requires `v0.21.0` or later ## Basic usage > The examples below demonstrate only the most fundamental use cases for this -> library. **[Go to the complete documentation site. >](https://www.edgedb.com/docs/clients/js/index)** +> library. **[Go to the complete documentation site. >](https://www.geldata.com/docs/clients/js/index)** ### Create a client @@ -65,39 +65,39 @@ connections to your database and provides methods for executing queries. _For TypeScript (and Node.js+ESM)_ ```ts -import * as edgedb from "edgedb"; +import * as gel from "gel"; -const client = edgedb.createClient(); +const client = gel.createClient(); ``` _For Node.js (CommonJS)_ ```js -const edgedb = require("edgedb"); +const gel = require("gel"); -const client = edgedb.createClient(); +const client = gel.createClient(); ``` ### Configuring the connection -The call to `edgedb.createClient()` doesn't require arguments, as the library +The call to `gel.createClient()` doesn't require arguments, as the library can determine how to connect to your database using the following mechanisms. -1. _For local development_: initialize a project with the `edgedb project init` +1. _For local development_: initialize a project with the `gel project init` command. As long as the file is within a project directory, `createClient` will be able to auto-discover the connection information of the project's associated instance. For more information on projects, follow the - [Using projects](https://www.edgedb.com/docs/guides/projects) guide. + [Using projects](https://www.geldata.com/docs/guides/projects) guide. 2. _In production_: configure the connection using **environment variables**. (This can also be used during local development if you prefer.) The easiest - way is to set the `EDGEDB_DSN` variable; a DSN (also known as a "connection + way is to set the `GEL_DSN` variable; a DSN (also known as a "connection string") is a string of the form - `edgedb://USERNAME:PASSWORD@HOSTNAME:PORT/DATABASE`. + `gel://USERNAME:PASSWORD@HOSTNAME:PORT/DATABASE`. For advanced cases, see the -[DSN specification](https://www.edgedb.com/docs/reference/dsn) and -[Reference > Connection Parameters](https://www.edgedb.com/docs/reference/connection). +[DSN specification](https://www.geldata.com/docs/reference/dsn) and +[Reference > Connection Parameters](https://www.geldata.com/docs/reference/connection). ### Run a query @@ -105,9 +105,9 @@ For advanced cases, see the > syntax. ```ts -import * as edgedb from "edgedb"; +import * as gel from "gel"; -const client = edgedb.createClient(); +const client = gel.createClient(); await client.query("select 2 + 2"); // => [4] ``` @@ -131,17 +131,17 @@ await client.querySingle( ## Generators -Install the `@edgedb/generate` package as a dev dependency to take advantage of EdgeDB's built-in code generators. +Install the `@gel/generate` package as a dev dependency to take advantage of Gel's built-in code generators. ```bash -npm install @edgedb/generate --save-dev # npm users -yarn add @edgedb/generate --dev # yarn users +npm install @gel/generate --save-dev # npm users +yarn add @gel/generate --dev # yarn users ``` Then run a generator with the following command: ```bash -$ npx @edgedb/generate [FLAGS] +$ npx @gel/generate [FLAGS] ``` The following ``s are currently supported: @@ -155,7 +155,7 @@ The following ``s are currently supported: Run the following command to generate a source file for each `*.edgeql` system in your project. ```bash -$ npx @edgedb/generate queries +$ npx @gel/generate queries ``` Assume you have a file called `getUser.edgeql` in your project directory. @@ -172,12 +172,12 @@ filter .email = $email; This generator will generate a `getUser.query.ts` file alongside it that exports a function called `getUser`. ```ts -import {createClient} from "edgedb"; -import {myQuery} from "./myQuery.query"; +import { createClient } from "gel"; +import { myQuery } from "./myQuery.query"; const client = createClient(); -const user = await myQuery(client, {name: "Timmy"}); +const user = await myQuery(client, { name: "Timmy" }); user; // {name: string; email: string} ``` @@ -187,19 +187,19 @@ The first argument is a `Client`, the second is the set of _parameters_. Both th The query builder lets you write queries in a code-first way. It automatically infers the return type of your queries. -To generate the query builder, install the `edgedb` package, initialize a project (if you haven't already), then run the following command: +To generate the query builder, install the `gel` package, initialize a project (if you haven't already), then run the following command: ```bash -$ npx @edgedb/generate edgeql-js +$ npx @gel/generate edgeql-js ``` This will generate an EdgeQL query builder into the `./dbschema/edgeql-js` directory, as defined relative to your project root. -For details on generating the query builder, refer to the [complete documentation](https://www.edgedb.com/docs/clients/js/generation). Below is a simple `select` query as an example. +For details on generating the query builder, refer to the [complete documentation](https://www.geldata.com/docs/clients/js/generation). Below is a simple `select` query as an example. ```ts -import { createClient } from "edgedb"; +import { createClient } from "gel"; import e from "./dbschema/edgeql-js"; const client = createClient(); @@ -215,30 +215,30 @@ const result = await query.run(client); result.actors[0].name; // => Timothee Chalamet ``` -For details on using the query builder, refer to the full [query builder docs](https://www.edgedb.com/docs/clients/js/querybuilder). +For details on using the query builder, refer to the full [query builder docs](https://www.geldata.com/docs/clients/js/querybuilder). ## Contribute -Contributing to this library requires a local installation of EdgeDB. Install -EdgeDB from [here](https://www.edgedb.com/download) or -[build it from source](https://www.edgedb.com/docs/reference/dev). +Contributing to this library requires a local installation of Gel. Install +Gel from [here](https://www.geldata.com/download) or +[build it from source](https://www.geldata.com/docs/reference/dev). ```bash -$ git clone git@github.com:edgedb/edgedb-js.git -$ cd edgedb-js +$ git clone git@github.com:gel/gel-js.git +$ cd gel-js $ yarn # install dependencies $ yarn run build # build all packages $ yarn run test # run tests for all packages ``` -> In order to be able to run all tests you need to have `edgedb-server` in your +> In order to be able to run all tests you need to have `gel-server` in your > path. This can be done by either running tests from within a Python 3.12 -> virtual environment (you will have it if you built EdgeDB locally), or by -> [installing](https://docs.edgedb.com/cli/edgedb_server/edgedb_server_install#ref-cli-edgedb-server-install) -> specific EdgeDB version and then adding its binary path to the `EDGEDB_SERVER_BIN` environment variable. -> Check [here](https://docs.edgedb.com/cli/edgedb_server/edgedb_server_info#ref-cli-edgedb-server-info) +> virtual environment (you will have it if you built Gel locally), or by +> [installing](https://docs.geldata.com/cli/gel_server/gel_server_install#ref-cli-gel-server-install) +> specific Gel version and then adding its binary path to the `GEL_SERVER_BIN` environment variable. +> Check [here](https://docs.geldata.com/cli/gel_server/gel_server_info#ref-cli-gel-server-info) > to find how to get the binary path. ## License -`edgedb-js` is developed and distributed under the Apache 2.0 license. +`gel-js` is developed and distributed under the Apache 2.0 license. diff --git a/integration-tests/legacy/.gitignore b/integration-tests/legacy/.gitignore index 339e9b967..34652dda7 100644 --- a/integration-tests/legacy/.gitignore +++ b/integration-tests/legacy/.gitignore @@ -2,7 +2,6 @@ trace trace/* mts/edgeql-js esm/edgeql-js -deno/edgeql-js cjs/edgeql-js db/schema/edgeql-js db/schema/queries.ts diff --git a/integration-tests/legacy/edgedb.toml b/integration-tests/legacy/gel.toml similarity index 100% rename from integration-tests/legacy/edgedb.toml rename to integration-tests/legacy/gel.toml diff --git a/integration-tests/legacy/globalSetup.ts b/integration-tests/legacy/globalSetup.ts index 4692a7fbb..bd0f5d693 100644 --- a/integration-tests/legacy/globalSetup.ts +++ b/integration-tests/legacy/globalSetup.ts @@ -1,9 +1,9 @@ -import createClient from "edgedb"; +import createClient from "gel"; export default async () => { const client = createClient(); - process.env._JEST_EDGEDB_VERSION = await client.queryRequiredSingleJSON( + process.env._JEST_GEL_VERSION = await client.queryRequiredSingleJSON( `select sys::get_version()`, ); }; diff --git a/integration-tests/legacy/jest.config.js b/integration-tests/legacy/jest.config.js index 2c22ce297..6817887ef 100644 --- a/integration-tests/legacy/jest.config.js +++ b/integration-tests/legacy/jest.config.js @@ -1,7 +1,7 @@ module.exports = { preset: "ts-jest", testEnvironment: "node", - testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs", "./deno"], + testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs"], globalSetup: "./globalSetup.ts", transform: {}, globals: {}, diff --git a/integration-tests/legacy/package.json b/integration-tests/legacy/package.json index 720cbc302..72574335a 100644 --- a/integration-tests/legacy/package.json +++ b/integration-tests/legacy/package.json @@ -1,6 +1,6 @@ { "private": true, - "name": "@edgedb/integration-legacy", + "name": "@gel/integration-legacy", "version": "0.0.0", "scripts": { "typecheck": "echo 'Integration tests - legacy, skipping typecheck...'", @@ -10,12 +10,12 @@ "ci:integration-test": "tsx ./testRunner.ts" }, "devDependencies": { - "@edgedb/generate": "*", + "@gel/generate": "*", "@tsconfig/node-lts": "^20.1.3", "@types/jest": "^29.5.12", "@types/node": "^20.12.13", "conditional-type-checks": "^1.0.6", - "edgedb": "*", + "gel": "*", "jest": "^29.7.0", "ts-jest": "^29.1.4", "typescript": "^5.5.2" diff --git a/integration-tests/legacy/setupTeardown.ts b/integration-tests/legacy/setupTeardown.ts index 094a05012..19f50daa3 100644 --- a/integration-tests/legacy/setupTeardown.ts +++ b/integration-tests/legacy/setupTeardown.ts @@ -1,5 +1,5 @@ import * as tc from "conditional-type-checks"; -import { type Client, createClient } from "edgedb"; +import { type Client, createClient } from "gel"; export { tc }; @@ -25,7 +25,7 @@ export async function teardownTests(client: Client) { } export const versionGTE = (majorVer: number) => { - const version = JSON.parse(process.env._JEST_EDGEDB_VERSION!); + const version = JSON.parse(process.env._JEST_GEL_VERSION!); return version.major >= majorVer; }; diff --git a/integration-tests/legacy/smoke.test.ts b/integration-tests/legacy/smoke.test.ts index 0fb729a77..43269e514 100644 --- a/integration-tests/legacy/smoke.test.ts +++ b/integration-tests/legacy/smoke.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { type Client } from "edgedb"; +import { type Client } from "gel"; import e from "./db/schema/edgeql-js"; import { setupTests, teardownTests } from "./setupTeardown"; diff --git a/integration-tests/legacy/testRunner.ts b/integration-tests/legacy/testRunner.ts index 685628640..85971465c 100644 --- a/integration-tests/legacy/testRunner.ts +++ b/integration-tests/legacy/testRunner.ts @@ -1,4 +1,4 @@ -import createClient from "edgedb"; +import createClient from "gel"; import { shutdown, @@ -12,7 +12,7 @@ import { } from "../../packages/driver/test/testUtil"; (async function main() { - console.log("\nStarting EdgeDB test cluster..."); + console.log("\nStarting Gel test cluster..."); const statusFile = generateStatusFileName("node"); console.log("Node status file:", statusFile); @@ -21,7 +21,7 @@ import { const { proc, config } = await startServer(args, statusFile); - console.log(`EdgeDB test cluster is up [port: ${config.port}]...`); + console.log(`Gel test cluster is up [port: ${config.port}]...`); const managementConn = await createClient(config).ensureConnected(); @@ -33,8 +33,8 @@ import { console.error(err); process.exit(1); } finally { - console.log("Shutting down EdgeDB test cluster..."); + console.log("Shutting down Gel test cluster..."); await shutdown(proc, managementConn); - console.log("EdgeDB test cluster is down..."); + console.log("Gel test cluster is down..."); } })(); diff --git a/integration-tests/lts/.gitignore b/integration-tests/lts/.gitignore index e06bbfdd7..b56b97529 100644 --- a/integration-tests/lts/.gitignore +++ b/integration-tests/lts/.gitignore @@ -2,7 +2,6 @@ trace trace/* mts/edgeql-js esm/edgeql-js -deno/edgeql-js cjs/edgeql-js dbschema/edgeql-js dbschema/queries.ts diff --git a/integration-tests/lts/cardinality.test.ts b/integration-tests/lts/cardinality.test.ts index 79a3d03db..2ccf3f7f0 100644 --- a/integration-tests/lts/cardinality.test.ts +++ b/integration-tests/lts/cardinality.test.ts @@ -1,4 +1,4 @@ -import type { $ } from "edgedb"; +import type { $ } from "gel"; import type { cardutil } from "../../packages/generate/src/syntax/cardinality"; import { tc } from "./setupTeardown"; diff --git a/integration-tests/lts/casts.test.ts b/integration-tests/lts/casts.test.ts index 20743fde8..dbd8136c8 100644 --- a/integration-tests/lts/casts.test.ts +++ b/integration-tests/lts/casts.test.ts @@ -3,7 +3,7 @@ import e from "./dbschema/edgeql-js"; import type { $Movie } from "./dbschema/edgeql-js/modules/default"; import { setupTests, tc, teardownTests } from "./setupTeardown"; -import type { Client, $ } from "edgedb"; +import type { Client, $ } from "gel"; describe("casts", () => { let client: Client; diff --git a/integration-tests/lts/cjs/test.js b/integration-tests/lts/cjs/test.js index 4973b5cde..9eeb3349b 100644 --- a/integration-tests/lts/cjs/test.js +++ b/integration-tests/lts/cjs/test.js @@ -1,14 +1,14 @@ // tslint:disable:no-console -const {createClient} = require("edgedb"); +const { createClient } = require("gel"); const e = require("./edgeql-js").default; -const {freeShape, scalarQuery} = require("./queries"); +const { freeShape, scalarQuery } = require("./queries"); async function run() { try { const client = createClient(); const query = e.select({ num: e.int64(35), - msg: e.str("Hello world") + msg: e.str("Hello world"), }); const result = await query.run(client); @@ -16,7 +16,7 @@ async function run() { throw new Error(); } await scalarQuery(client); - const movies = await freeShape(client, {data: "hello world"}); + const movies = await freeShape(client, { data: "hello world" }); if (movies.data !== "hello world") { throw new Error("Failure: --cjs"); diff --git a/integration-tests/lts/cjs/test.mts b/integration-tests/lts/cjs/test.mts index 9aeab027c..71ec36874 100644 --- a/integration-tests/lts/cjs/test.mts +++ b/integration-tests/lts/cjs/test.mts @@ -1,7 +1,7 @@ // tslint:disable:no-console // import {setupTests} from "./test/setupTeardown"; -import {createClient} from "edgedb"; +import { createClient } from "gel"; import e from "./edgeql-js/index.js"; const client = createClient(); diff --git a/integration-tests/lts/collections.test.ts b/integration-tests/lts/collections.test.ts index c4c8a6b28..b34ce0904 100644 --- a/integration-tests/lts/collections.test.ts +++ b/integration-tests/lts/collections.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import type { Client } from "edgedb"; +import type { Client } from "gel"; import * as $ from "../../packages/generate/src/syntax/reflection"; import e, { type $infer, objectTypeToTupleType } from "./dbschema/edgeql-js"; import type { sys } from "./dbschema/interfaces"; diff --git a/integration-tests/lts/dbschema/default.esdl b/integration-tests/lts/dbschema/default.esdl index d3fb6dc7b..649606df4 100644 --- a/integration-tests/lts/dbschema/default.esdl +++ b/integration-tests/lts/dbschema/default.esdl @@ -153,7 +153,7 @@ module default { } # Unicode handling - # https://github.com/edgedb/edgedb/blob/master/tests/schemas/dump02_default.esdl + # https://github.com/geldata/gel/blob/master/tests/schemas/dump02_default.esdl abstract annotation `🍿`; diff --git a/integration-tests/lts/delete.test.ts b/integration-tests/lts/delete.test.ts index 33d0e0db9..10e3c0b24 100644 --- a/integration-tests/lts/delete.test.ts +++ b/integration-tests/lts/delete.test.ts @@ -1,11 +1,11 @@ import assert from "node:assert/strict"; -import type * as edgedb from "edgedb"; +import type * as gel from "gel"; import e from "./dbschema/edgeql-js"; import { setupTests, teardownTests, tc, type TestData } from "./setupTeardown"; describe("delete", () => { - let client: edgedb.Client; + let client: gel.Client; let data: TestData; beforeAll(async () => { @@ -48,10 +48,7 @@ describe("delete", () => { const deleteAll = e.delete(e.Hero); tc.assert< - tc.IsExact< - (typeof deleteAll)["__cardinality__"], - edgedb.$.Cardinality.Many - > + tc.IsExact<(typeof deleteAll)["__cardinality__"], gel.$.Cardinality.Many> >(true); }); diff --git a/integration-tests/lts/detached.test.ts b/integration-tests/lts/detached.test.ts index 0a35e46a1..14b20b47f 100644 --- a/integration-tests/lts/detached.test.ts +++ b/integration-tests/lts/detached.test.ts @@ -1,10 +1,10 @@ import assert from "node:assert/strict"; -import type * as edgedb from "edgedb"; +import type * as gel from "gel"; import e from "./dbschema/edgeql-js"; import { setupTests, tc, teardownTests, type TestData } from "./setupTeardown"; describe("detached", () => { - let client: edgedb.Client; + let client: gel.Client; let data: TestData; beforeAll(async () => { diff --git a/integration-tests/lts/esm.test.mjs b/integration-tests/lts/esm.test.mjs index f1e230f9a..bdbdf6d79 100644 --- a/integration-tests/lts/esm.test.mjs +++ b/integration-tests/lts/esm.test.mjs @@ -1,6 +1,6 @@ import path from "path"; -import {execSync} from "child_process"; -import {createClient} from "edgedb"; +import { execSync } from "child_process"; +import { createClient } from "gel"; const QBDIR = "./dbschema/qbout"; @@ -10,7 +10,7 @@ const CMD = [ `yarn generate edgeql-js`, `--output-dir ./dbschema/qbout`, `--force-overwrite`, - "--target esm" + "--target esm", ]; async function run() { @@ -22,7 +22,7 @@ async function run() { } execSync(CMD.join(" ")); const indexFilePath = path.posix.join(QBDIR, "index.mjs"); - const {default: e} = await import(indexFilePath); + const { default: e } = await import(indexFilePath); const result = await e.str("Hello world!").run(client); if (result !== "Hello world!") throw new Error(); console.log(`ESM tests successful.`); diff --git a/integration-tests/lts/esm/test.js b/integration-tests/lts/esm/test.js index 1444605c7..fa9eee232 100644 --- a/integration-tests/lts/esm/test.js +++ b/integration-tests/lts/esm/test.js @@ -1,6 +1,6 @@ -import {createClient} from "edgedb"; +import { createClient } from "gel"; import e from "./edgeql-js/index.mjs"; -import {freeShape, scalarQuery} from "./queries.mjs"; +import { freeShape, scalarQuery } from "./queries.mjs"; const client = createClient(); @@ -9,14 +9,14 @@ async function run() { const result = await e .select({ num: e.int64(35), - msg: e.str("sup") + msg: e.str("sup"), }) .run(client); if (result.num !== 35) throw new Error(); if (result.msg !== "sup") throw new Error(); await scalarQuery(client); - const movies = await freeShape(client, {data: "hi mom"}); + const movies = await freeShape(client, { data: "hi mom" }); if (movies.data !== "hi mom") { throw new Error("Failure: --esm"); diff --git a/integration-tests/lts/edgedb.toml b/integration-tests/lts/gel.toml similarity index 100% rename from integration-tests/lts/edgedb.toml rename to integration-tests/lts/gel.toml diff --git a/integration-tests/lts/globalSetup.ts b/integration-tests/lts/globalSetup.ts index 4692a7fbb..bd0f5d693 100644 --- a/integration-tests/lts/globalSetup.ts +++ b/integration-tests/lts/globalSetup.ts @@ -1,9 +1,9 @@ -import createClient from "edgedb"; +import createClient from "gel"; export default async () => { const client = createClient(); - process.env._JEST_EDGEDB_VERSION = await client.queryRequiredSingleJSON( + process.env._JEST_GEL_VERSION = await client.queryRequiredSingleJSON( `select sys::get_version()`, ); }; diff --git a/integration-tests/lts/globals.test.ts b/integration-tests/lts/globals.test.ts index 15e565a5d..fee84d504 100644 --- a/integration-tests/lts/globals.test.ts +++ b/integration-tests/lts/globals.test.ts @@ -1,13 +1,13 @@ import assert from "node:assert/strict"; -import type * as edgedb from "edgedb"; -import { $ } from "edgedb"; +import type * as gel from "gel"; +import { $ } from "gel"; import e from "./dbschema/edgeql-js"; import { setupTests, teardownTests } from "./setupTeardown"; describe("globals", () => { - let client: edgedb.Client; + let client: gel.Client; beforeAll(async () => { const setup = await setupTests(); diff --git a/integration-tests/lts/group.test.ts b/integration-tests/lts/group.test.ts index 307947b25..d9882fb51 100644 --- a/integration-tests/lts/group.test.ts +++ b/integration-tests/lts/group.test.ts @@ -1,12 +1,12 @@ import assert from "node:assert/strict"; -import type * as edgedb from "edgedb"; +import type * as gel from "gel"; import * as tc from "conditional-type-checks"; import e, { type $infer } from "./dbschema/edgeql-js"; import { setupTests, teardownTests, type TestData } from "./setupTeardown"; describe("group", () => { - let client: edgedb.Client; + let client: gel.Client; let data: TestData; beforeAll(async () => { diff --git a/integration-tests/lts/insert.test.ts b/integration-tests/lts/insert.test.ts index 1e173c289..4c0185031 100644 --- a/integration-tests/lts/insert.test.ts +++ b/integration-tests/lts/insert.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { type Client, $ } from "edgedb"; +import { type Client, $ } from "gel"; import type { Villain } from "./dbschema/edgeql-js/modules/default"; import type { InsertShape } from "./dbschema/edgeql-js/insert"; import e from "./dbschema/edgeql-js"; diff --git a/integration-tests/lts/jest.config.js b/integration-tests/lts/jest.config.js index 2c22ce297..6817887ef 100644 --- a/integration-tests/lts/jest.config.js +++ b/integration-tests/lts/jest.config.js @@ -1,7 +1,7 @@ module.exports = { preset: "ts-jest", testEnvironment: "node", - testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs", "./deno"], + testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs"], globalSetup: "./globalSetup.ts", transform: {}, globals: {}, diff --git a/integration-tests/lts/json.test.ts b/integration-tests/lts/json.test.ts index 0eaae5382..a6a71568e 100644 --- a/integration-tests/lts/json.test.ts +++ b/integration-tests/lts/json.test.ts @@ -1,11 +1,11 @@ import assert from "node:assert/strict"; -import * as edgedb from "edgedb"; +import * as gel from "gel"; import e from "./dbschema/edgeql-js"; import { setupTests, teardownTests, tc } from "./setupTeardown"; describe("json", () => { - let client: edgedb.Client; + let client: gel.Client; beforeAll(async () => { const setup = await setupTests(); @@ -92,12 +92,12 @@ describe("json", () => { test("serialize data classes", async () => { const datum = [ new Date("2022-07-18T21:42:46.569Z"), - new edgedb.LocalDate(2020, 1, 1), - new edgedb.LocalDateTime(2020, 1, 1), - new edgedb.LocalTime(2, 22), - new edgedb.Duration(3), - new edgedb.RelativeDuration(3), - new edgedb.DateDuration(1), + new gel.LocalDate(2020, 1, 1), + new gel.LocalDateTime(2020, 1, 1), + new gel.LocalTime(2, 22), + new gel.Duration(3), + new gel.RelativeDuration(3), + new gel.DateDuration(1), ]; assert.deepEqual(await e.json(datum).run(client), [ "2022-07-18T21:42:46.569Z", diff --git a/integration-tests/lts/literals.test.ts b/integration-tests/lts/literals.test.ts index a9e5e165a..2965a585d 100644 --- a/integration-tests/lts/literals.test.ts +++ b/integration-tests/lts/literals.test.ts @@ -1,17 +1,17 @@ import assert from "node:assert/strict"; -import * as edgedb from "edgedb"; -import { TypeKind } from "edgedb/dist/reflection"; +import * as gel from "gel"; +import { TypeKind } from "gel/dist/reflection"; import e from "./dbschema/edgeql-js"; import { setupTests, versionGTE } from "./setupTeardown"; describe("literals", () => { test("literals", () => { - const duration = new edgedb.Duration(0, 0, 0, 0, 5, 6, 7, 8, 9, 10); - const localdate = new edgedb.LocalDate(2021, 10, 31); - const localdatetime = new edgedb.LocalDateTime(2021, 10, 31, 21, 45, 30); - const localtime = new edgedb.LocalTime(15, 15, 0); - const relduration = new edgedb.RelativeDuration(1, 2, 3); - const dateduration = new edgedb.DateDuration(1, 2, 3, 4); + const duration = new gel.Duration(0, 0, 0, 0, 5, 6, 7, 8, 9, 10); + const localdate = new gel.LocalDate(2021, 10, 31); + const localdatetime = new gel.LocalDateTime(2021, 10, 31, 21, 45, 30); + const localtime = new gel.LocalTime(15, 15, 0); + const relduration = new gel.RelativeDuration(1, 2, 3); + const dateduration = new gel.DateDuration(1, 2, 3, 4); const uuid = "317fee4c-0da5-45aa-9980-fedac211bfb6"; assert.equal( @@ -129,7 +129,7 @@ describe("literals", () => { const horror = e.Genre.Horror; assert.deepEqual(e.Genre.Horror.__element__.__kind__, TypeKind.enum); assert.deepEqual(horror.__element__, e.Genre); - assert.deepEqual(horror.__cardinality__, edgedb.$.Cardinality.One); + assert.deepEqual(horror.__cardinality__, gel.$.Cardinality.One); assert.equal( e.literal(e.Genre, "Horror").toEdgeQL(), `default::Genre.Horror`, diff --git a/integration-tests/lts/mts/test.ts b/integration-tests/lts/mts/test.ts index 3907655e3..d3ce51c24 100644 --- a/integration-tests/lts/mts/test.ts +++ b/integration-tests/lts/mts/test.ts @@ -1,7 +1,7 @@ // tslint:disable:no-console // import {setupTests} from "./test/setupTeardown"; -import { createClient } from "edgedb"; +import { createClient } from "gel"; import e from "./edgeql-js/index.mjs"; import { freeShape, scalarQuery } from "./queries.mjs"; diff --git a/integration-tests/lts/operators.test.ts b/integration-tests/lts/operators.test.ts index c1b40d006..58bbf2f8d 100644 --- a/integration-tests/lts/operators.test.ts +++ b/integration-tests/lts/operators.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import superjson from "superjson"; -import type { Client } from "edgedb"; +import type { Client } from "gel"; import fc from "fast-check"; import e from "./dbschema/edgeql-js"; import * as $ from "../../packages/generate/src/syntax/reflection"; diff --git a/integration-tests/lts/package.json b/integration-tests/lts/package.json index e529b4bb8..3a46b57bd 100644 --- a/integration-tests/lts/package.json +++ b/integration-tests/lts/package.json @@ -1,6 +1,6 @@ { "private": true, - "name": "@edgedb/integration-lts", + "name": "@gel/integration-lts", "version": "0.0.0", "scripts": { "typecheck": "echo 'Integration tests - lts, skipping typecheck...'", @@ -18,7 +18,7 @@ }, "devDependencies": { "@arktype/attest": "^0.7.8", - "@edgedb/generate": "*", + "@gel/generate": "*", "@tsconfig/node-lts": "^20.1.3", "@types/jest": "^29.5.12", "@types/node": "^20.12.13", @@ -29,7 +29,7 @@ "typescript": "^5.5.2" }, "dependencies": { - "edgedb": "*", + "gel": "*", "fast-check": "^3.19.0" } } diff --git a/integration-tests/lts/params.test.ts b/integration-tests/lts/params.test.ts index 44ce54247..be6177a41 100644 --- a/integration-tests/lts/params.test.ts +++ b/integration-tests/lts/params.test.ts @@ -1,9 +1,9 @@ import assert from "node:assert/strict"; -import * as edgedb from "edgedb"; +import * as gel from "gel"; import e from "./dbschema/edgeql-js"; import { setupTests, teardownTests, tc, versionGTE } from "./setupTeardown"; -let client: edgedb.Client; +let client: gel.Client; describe("params", () => { beforeAll(async () => { @@ -225,13 +225,13 @@ SELECT (SELECT __param__test)`, datetime: new Date(), genre: "Action" as const, - duration: new edgedb.Duration(0, 0, 0, 0, 1), - local_date: new edgedb.LocalDate(2021, 11, 25), - local_time: new edgedb.LocalTime(12, 34), - local_datetime: new edgedb.LocalDateTime(2021, 11, 25, 1, 2, 3), - relative_duration: new edgedb.RelativeDuration(1, 2, 3), - date_duration: new edgedb.DateDuration(1, 2, 3, 4), - memory: new edgedb.ConfigMemory(BigInt(125952)), + duration: new gel.Duration(0, 0, 0, 0, 1), + local_date: new gel.LocalDate(2021, 11, 25), + local_time: new gel.LocalTime(12, 34), + local_datetime: new gel.LocalDateTime(2021, 11, 25, 1, 2, 3), + relative_duration: new gel.RelativeDuration(1, 2, 3), + date_duration: new gel.DateDuration(1, 2, 3, 4), + memory: new gel.ConfigMemory(BigInt(125952)), }; const result = await query.run(client, args); @@ -254,13 +254,13 @@ SELECT (SELECT __param__test)`, uuid: string; datetime: Date; genre: "Horror" | "Action" | "RomCom" | "Science Fiction" | "Select"; - duration: edgedb.Duration; - local_date: edgedb.LocalDate; - local_time: edgedb.LocalTime; - local_datetime: edgedb.LocalDateTime; - relative_duration: edgedb.RelativeDuration; - date_duration: edgedb.DateDuration; - memory: edgedb.ConfigMemory; + duration: gel.Duration; + local_date: gel.LocalDate; + local_time: gel.LocalTime; + local_datetime: gel.LocalDateTime; + relative_duration: gel.RelativeDuration; + date_duration: gel.DateDuration; + memory: gel.ConfigMemory; } > >(true); @@ -289,7 +289,7 @@ SELECT (SELECT __param__test)`, const query = e.params(params, (p) => e.select(p)); const args = { - date_duration: new edgedb.DateDuration(1, 2, 3, 4), + date_duration: new gel.DateDuration(1, 2, 3, 4), }; const result = await query.run(client, args); @@ -298,7 +298,7 @@ SELECT (SELECT __param__test)`, tc.IsExact< typeof result, { - date_duration: edgedb.DateDuration; + date_duration: gel.DateDuration; } > >(true); diff --git a/integration-tests/lts/pgvector.test.ts b/integration-tests/lts/pgvector.test.ts index 0dcc01415..ed05ba498 100644 --- a/integration-tests/lts/pgvector.test.ts +++ b/integration-tests/lts/pgvector.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { type Client } from "edgedb"; +import { type Client } from "gel"; import e from "./dbschema/edgeql-js"; import { setupTests, tc, teardownTests } from "./setupTeardown"; diff --git a/integration-tests/lts/primitives.test.ts b/integration-tests/lts/primitives.test.ts index 093d449ae..120e84f43 100644 --- a/integration-tests/lts/primitives.test.ts +++ b/integration-tests/lts/primitives.test.ts @@ -1,11 +1,11 @@ import assert from "node:assert/strict"; -import * as edgedb from "edgedb"; +import * as gel from "gel"; import e from "./dbschema/edgeql-js"; import type { getSharedParentPrimitiveVariadic } from "./dbschema/edgeql-js/syntax"; import { setupTests, tc, teardownTests } from "./setupTeardown"; describe("primitives", () => { - let client: edgedb.Client; + let client: gel.Client; beforeAll(async () => { const setup = await setupTests(); ({ client } = setup); @@ -48,10 +48,10 @@ describe("primitives", () => { }); test("range primitives", async () => { - const range = new edgedb.Range(3, 8); - const lowerRange = new edgedb.Range(3, null); - const upperRange = new edgedb.Range(null, 8); - const dateRange = new edgedb.Range( + const range = new gel.Range(3, 8); + const lowerRange = new gel.Range(3, null); + const upperRange = new gel.Range(null, 8); + const dateRange = new gel.Range( new Date("2022-07-05T14:00:00Z"), new Date("2022-07-05T16:00:00Z"), ); @@ -80,8 +80,8 @@ describe("primitives", () => { `std::range({}, 8)`, ); - assert.throws(() => e.range(new edgedb.Range(null, null))); - assert.throws(() => e.range(edgedb.Range.empty())); + assert.throws(() => e.range(new gel.Range(null, null))); + assert.throws(() => e.range(gel.Range.empty())); const res = await e .select({ @@ -96,10 +96,10 @@ describe("primitives", () => { tc.IsExact< typeof res, { - range: edgedb.Range; - lowerRange: edgedb.Range; - upperRange: edgedb.Range; - dateRange: edgedb.Range; + range: gel.Range; + lowerRange: gel.Range; + upperRange: gel.Range; + dateRange: gel.Range; } > >(true); @@ -107,7 +107,7 @@ describe("primitives", () => { assert.deepEqual(res, { range: range, lowerRange: lowerRange, - upperRange: new edgedb.Range(null, 8, false), + upperRange: new gel.Range(null, 8, false), dateRange: dateRange, }); @@ -135,7 +135,7 @@ describe("primitives", () => { tc.assert< tc.IsExact< typeof res2, - { range: edgedb.Range; rangeArray: edgedb.Range[] } + { range: gel.Range; rangeArray: gel.Range[] } > >(true); @@ -158,7 +158,7 @@ describe("primitives", () => { const res3 = await e.select(e.Bag.rangeField).run(client); - tc.assert[]>>(true); + tc.assert[]>>(true); assert.deepEqual(res3, [lowerRange]); diff --git a/integration-tests/lts/queries.test.ts b/integration-tests/lts/queries.test.ts index c5944ac53..18a9374dc 100644 --- a/integration-tests/lts/queries.test.ts +++ b/integration-tests/lts/queries.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import type * as edgedb from "edgedb"; +import type * as gel from "gel"; import * as tc from "conditional-type-checks"; import { @@ -16,7 +16,7 @@ import { import { type TestData, setupTests, teardownTests } from "./setupTeardown"; describe("queries", () => { - let client: edgedb.Client; + let client: gel.Client; let data: TestData; beforeAll(async () => { @@ -55,8 +55,8 @@ describe("queries", () => { stage_no: number; local: string[]; }; - range: edgedb.Range; - local_date: edgedb.LocalDate; + range: gel.Range; + local_date: gel.LocalDate; }[] > >(true); diff --git a/integration-tests/lts/select-current.test.ts b/integration-tests/lts/select-current.test.ts index e09a15e2b..046ba1815 100644 --- a/integration-tests/lts/select-current.test.ts +++ b/integration-tests/lts/select-current.test.ts @@ -1,11 +1,11 @@ import assert from "node:assert/strict"; -import type * as edgedb from "edgedb"; +import type * as gel from "gel"; import * as $ from "./dbschema/edgeql-js/reflection"; import e, { type $infer } from "./dbschema/edgeql-js"; import { setupTests, teardownTests, tc, type TestData } from "./setupTeardown"; -let client: edgedb.Client; +let client: gel.Client; let data: TestData; describe("select", () => { diff --git a/integration-tests/lts/select.test.ts b/integration-tests/lts/select.test.ts index 9d4777cd8..664424fb3 100644 --- a/integration-tests/lts/select.test.ts +++ b/integration-tests/lts/select.test.ts @@ -1,12 +1,12 @@ import assert from "node:assert/strict"; -import * as edgedb from "edgedb"; +import * as gel from "gel"; import * as fc from "fast-check"; import * as $ from "./dbschema/edgeql-js/reflection"; import e, { type $infer } from "./dbschema/edgeql-js"; import { setupTests, teardownTests, tc, type TestData } from "./setupTeardown"; -let client: edgedb.Client; +let client: gel.Client; let data: TestData; describe("select", () => { @@ -56,32 +56,32 @@ describe("select", () => { assert.equal(dateSelect.__element__, e.datetime); assert.equal(dateSelect.__cardinality__, $.Cardinality.One); - const durationSelect = e.select(new edgedb.Duration()); + const durationSelect = e.select(new gel.Duration()); assert.equal(durationSelect.__kind__, $.ExpressionKind.Select); assert.equal(durationSelect.__element__, e.duration); assert.equal(durationSelect.__cardinality__, $.Cardinality.One); - const ldrSelect = e.select(new edgedb.LocalDateTime(1, 2, 3)); + const ldrSelect = e.select(new gel.LocalDateTime(1, 2, 3)); assert.equal(ldrSelect.__kind__, $.ExpressionKind.Select); assert.equal(ldrSelect.__element__, e.cal.local_datetime); assert.equal(ldrSelect.__cardinality__, $.Cardinality.One); - const ldSelect = e.select(new edgedb.LocalDate(1, 2, 3)); + const ldSelect = e.select(new gel.LocalDate(1, 2, 3)); assert.equal(ldSelect.__kind__, $.ExpressionKind.Select); assert.equal(ldSelect.__element__, e.cal.local_date); assert.equal(ldSelect.__cardinality__, $.Cardinality.One); - const ltSelect = e.select(new edgedb.LocalTime(1, 2, 3)); + const ltSelect = e.select(new gel.LocalTime(1, 2, 3)); assert.equal(ltSelect.__kind__, $.ExpressionKind.Select); assert.equal(ltSelect.__element__, e.cal.local_time); assert.equal(ltSelect.__cardinality__, $.Cardinality.One); - const rdSelect = e.select(new edgedb.RelativeDuration(1, 2, 3)); + const rdSelect = e.select(new gel.RelativeDuration(1, 2, 3)); assert.equal(rdSelect.__kind__, $.ExpressionKind.Select); assert.equal(rdSelect.__element__, e.cal.relative_duration); assert.equal(rdSelect.__cardinality__, $.Cardinality.One); - const memSelect = e.select(new edgedb.ConfigMemory(BigInt(1234))); + const memSelect = e.select(new gel.ConfigMemory(BigInt(1234))); assert.equal(memSelect.__kind__, $.ExpressionKind.Select); assert.equal(memSelect.__element__, e.cfg.memory); assert.equal(memSelect.__cardinality__, $.Cardinality.One); @@ -1602,7 +1602,7 @@ SELECT __scope_0_defaultPerson { filter_single: e.op(movie.genre, "=", e.Genre.Action), })); - assert.rejects(() => query.run(client), edgedb.CardinalityViolationError); + assert.rejects(() => query.run(client), gel.CardinalityViolationError); }); test("type union links", async () => { @@ -1695,7 +1695,7 @@ SELECT __scope_0_defaultPerson { } const q = e.select(e.json(testString)); - assert.rejects(() => q.run(client), edgedb.InputDataError); + assert.rejects(() => q.run(client), gel.InputDataError); }); test("arbitrary json literal", async () => { diff --git a/integration-tests/lts/sets.test.ts b/integration-tests/lts/sets.test.ts index f682ad91e..5d0279b7c 100644 --- a/integration-tests/lts/sets.test.ts +++ b/integration-tests/lts/sets.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { $, type Client } from "edgedb"; +import { $, type Client } from "gel"; import e, { type $infer } from "./dbschema/edgeql-js"; import { setupTests, teardownTests, tc } from "./setupTeardown"; import { TypeKind } from "../../packages/generate/src/syntax/reflection"; diff --git a/integration-tests/lts/setupTeardown.ts b/integration-tests/lts/setupTeardown.ts index c28727ee4..caf186598 100644 --- a/integration-tests/lts/setupTeardown.ts +++ b/integration-tests/lts/setupTeardown.ts @@ -1,5 +1,5 @@ import * as tc from "conditional-type-checks"; -import { type Client, createClient } from "edgedb"; +import { type Client, createClient } from "gel"; export { tc }; @@ -134,7 +134,7 @@ export async function teardownTests(client: Client) { } export const versionGTE = (majorVer: number) => { - const version = JSON.parse(process.env._JEST_EDGEDB_VERSION!); + const version = JSON.parse(process.env._JEST_GEL_VERSION!); return version.major >= majorVer; }; diff --git a/integration-tests/lts/testRunner.ts b/integration-tests/lts/testRunner.ts index 56e271f76..b9fa9dbaa 100644 --- a/integration-tests/lts/testRunner.ts +++ b/integration-tests/lts/testRunner.ts @@ -1,4 +1,4 @@ -import createClient from "edgedb"; +import createClient from "gel"; import { shutdown, @@ -12,7 +12,7 @@ import { } from "../../packages/driver/test/testUtil"; (async function main() { - console.log("\nStarting EdgeDB test cluster..."); + console.log("\nStarting Gel test cluster..."); const statusFile = generateStatusFileName("node"); console.log("Node status file:", statusFile); @@ -21,7 +21,7 @@ import { const { proc, config } = await startServer(args, statusFile); - console.log(`EdgeDB test cluster is up [port: ${config.port}]...`); + console.log(`Gel test cluster is up [port: ${config.port}]...`); const managementConn = await createClient(config).ensureConnected(); @@ -34,8 +34,8 @@ import { console.error(err); process.exit(1); } finally { - console.log("Shutting down EdgeDB test cluster..."); + console.log("Shutting down Gel test cluster..."); await shutdown(proc, managementConn); - console.log("EdgeDB test cluster is down..."); + console.log("Gel test cluster is down..."); } })(); diff --git a/integration-tests/lts/update.test.ts b/integration-tests/lts/update.test.ts index f8ba7f09e..ee6ec2010 100644 --- a/integration-tests/lts/update.test.ts +++ b/integration-tests/lts/update.test.ts @@ -1,12 +1,12 @@ import assert from "node:assert/strict"; -import type * as edgedb from "edgedb"; +import type * as gel from "gel"; import e from "./dbschema/edgeql-js"; import type { UpdateShape } from "./dbschema/edgeql-js/syntax"; import { setupTests, tc, teardownTests, type TestData } from "./setupTeardown"; describe("update", () => { - let client: edgedb.Client; + let client: gel.Client; let data: TestData; const $Hero = e.Hero.__element__; diff --git a/integration-tests/nightly/.gitignore b/integration-tests/nightly/.gitignore index e06bbfdd7..b56b97529 100644 --- a/integration-tests/nightly/.gitignore +++ b/integration-tests/nightly/.gitignore @@ -2,7 +2,6 @@ trace trace/* mts/edgeql-js esm/edgeql-js -deno/edgeql-js cjs/edgeql-js dbschema/edgeql-js dbschema/queries.ts diff --git a/integration-tests/nightly/globalSetup.ts b/integration-tests/nightly/globalSetup.ts index 4692a7fbb..bd0f5d693 100644 --- a/integration-tests/nightly/globalSetup.ts +++ b/integration-tests/nightly/globalSetup.ts @@ -1,9 +1,9 @@ -import createClient from "edgedb"; +import createClient from "gel"; export default async () => { const client = createClient(); - process.env._JEST_EDGEDB_VERSION = await client.queryRequiredSingleJSON( + process.env._JEST_GEL_VERSION = await client.queryRequiredSingleJSON( `select sys::get_version()`, ); }; diff --git a/integration-tests/nightly/jest.config.js b/integration-tests/nightly/jest.config.js index 2c22ce297..6817887ef 100644 --- a/integration-tests/nightly/jest.config.js +++ b/integration-tests/nightly/jest.config.js @@ -1,7 +1,7 @@ module.exports = { preset: "ts-jest", testEnvironment: "node", - testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs", "./deno"], + testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs"], globalSetup: "./globalSetup.ts", transform: {}, globals: {}, diff --git a/integration-tests/nightly/package.json b/integration-tests/nightly/package.json index cb7b5b0fe..ceb713267 100644 --- a/integration-tests/nightly/package.json +++ b/integration-tests/nightly/package.json @@ -1,6 +1,6 @@ { "private": true, - "name": "@edgedb/integration-nightly", + "name": "@gel/integration-nightly", "version": "0.0.0", "scripts": { "typecheck": "echo 'Integration tests - nightly, skipping typecheck...'", @@ -10,12 +10,12 @@ "ci:integration-test": "tsx ./testRunner.ts" }, "devDependencies": { - "@edgedb/generate": "*", + "@gel/generate": "*", "@tsconfig/node-lts": "^20.1.3", "@types/jest": "^29.5.12", "@types/node": "^20.12.13", "conditional-type-checks": "^1.0.6", - "edgedb": "*", + "gel": "*", "jest": "^29.7.0", "ts-jest": "^29.1.4", "typescript": "^5.5.2" diff --git a/integration-tests/nightly/setupTeardown.ts b/integration-tests/nightly/setupTeardown.ts index a862416b2..8826c50d2 100644 --- a/integration-tests/nightly/setupTeardown.ts +++ b/integration-tests/nightly/setupTeardown.ts @@ -1,5 +1,5 @@ import * as tc from "conditional-type-checks"; -import { type Client, createClient } from "edgedb"; +import { type Client, createClient } from "gel"; export { tc }; @@ -28,7 +28,7 @@ export async function teardownTests(client: Client) { } export const versionGTE = (majorVer: number) => { - const version = JSON.parse(process.env._JEST_EDGEDB_VERSION!); + const version = JSON.parse(process.env._JEST_GEL_VERSION!); return version.major >= majorVer; }; diff --git a/integration-tests/nightly/testRunner.ts b/integration-tests/nightly/testRunner.ts index 685628640..85971465c 100644 --- a/integration-tests/nightly/testRunner.ts +++ b/integration-tests/nightly/testRunner.ts @@ -1,4 +1,4 @@ -import createClient from "edgedb"; +import createClient from "gel"; import { shutdown, @@ -12,7 +12,7 @@ import { } from "../../packages/driver/test/testUtil"; (async function main() { - console.log("\nStarting EdgeDB test cluster..."); + console.log("\nStarting Gel test cluster..."); const statusFile = generateStatusFileName("node"); console.log("Node status file:", statusFile); @@ -21,7 +21,7 @@ import { const { proc, config } = await startServer(args, statusFile); - console.log(`EdgeDB test cluster is up [port: ${config.port}]...`); + console.log(`Gel test cluster is up [port: ${config.port}]...`); const managementConn = await createClient(config).ensureConnected(); @@ -33,8 +33,8 @@ import { console.error(err); process.exit(1); } finally { - console.log("Shutting down EdgeDB test cluster..."); + console.log("Shutting down Gel test cluster..."); await shutdown(proc, managementConn); - console.log("EdgeDB test cluster is down..."); + console.log("Gel test cluster is down..."); } })(); diff --git a/integration-tests/stable/.gitignore b/integration-tests/stable/.gitignore index e06bbfdd7..b56b97529 100644 --- a/integration-tests/stable/.gitignore +++ b/integration-tests/stable/.gitignore @@ -2,7 +2,6 @@ trace trace/* mts/edgeql-js esm/edgeql-js -deno/edgeql-js cjs/edgeql-js dbschema/edgeql-js dbschema/queries.ts diff --git a/integration-tests/stable/auth.test.ts b/integration-tests/stable/auth.test.ts index e2ca6c28a..177d01d05 100644 --- a/integration-tests/stable/auth.test.ts +++ b/integration-tests/stable/auth.test.ts @@ -1,4 +1,4 @@ -import type { Client } from "edgedb"; +import type { Client } from "gel"; import e, { type $infer } from "./dbschema/edgeql-js"; import { setupTests, tc, teardownTests } from "./setupTeardown"; diff --git a/integration-tests/stable/edgedb.toml b/integration-tests/stable/gel.toml similarity index 100% rename from integration-tests/stable/edgedb.toml rename to integration-tests/stable/gel.toml diff --git a/integration-tests/stable/globalSetup.ts b/integration-tests/stable/globalSetup.ts index 4692a7fbb..bd0f5d693 100644 --- a/integration-tests/stable/globalSetup.ts +++ b/integration-tests/stable/globalSetup.ts @@ -1,9 +1,9 @@ -import createClient from "edgedb"; +import createClient from "gel"; export default async () => { const client = createClient(); - process.env._JEST_EDGEDB_VERSION = await client.queryRequiredSingleJSON( + process.env._JEST_GEL_VERSION = await client.queryRequiredSingleJSON( `select sys::get_version()`, ); }; diff --git a/integration-tests/stable/jest.config.js b/integration-tests/stable/jest.config.js index 2c22ce297..6817887ef 100644 --- a/integration-tests/stable/jest.config.js +++ b/integration-tests/stable/jest.config.js @@ -1,7 +1,7 @@ module.exports = { preset: "ts-jest", testEnvironment: "node", - testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs", "./deno"], + testPathIgnorePatterns: ["./dist", "./esm", "./mts", "./cjs"], globalSetup: "./globalSetup.ts", transform: {}, globals: {}, diff --git a/integration-tests/stable/multirange.test.ts b/integration-tests/stable/multirange.test.ts index 9d6e5db32..8e81d5514 100644 --- a/integration-tests/stable/multirange.test.ts +++ b/integration-tests/stable/multirange.test.ts @@ -1,4 +1,4 @@ -import type { Client, MultiRange } from "edgedb"; +import type { Client, MultiRange } from "gel"; import e from "./dbschema/edgeql-js"; import { setupTests, tc, teardownTests } from "./setupTeardown"; diff --git a/integration-tests/stable/package.json b/integration-tests/stable/package.json index a24a0df2a..71d0dcbf5 100644 --- a/integration-tests/stable/package.json +++ b/integration-tests/stable/package.json @@ -1,6 +1,6 @@ { "private": true, - "name": "@edgedb/integration-stable", + "name": "@gel/integration-stable", "version": "0.0.0", "scripts": { "typecheck": "echo 'Integration tests - stable, skipping typecheck...'", @@ -10,12 +10,12 @@ "ci:integration-test": "tsx ./testRunner.ts" }, "devDependencies": { - "@edgedb/generate": "*", + "@gel/generate": "*", "@tsconfig/node-lts": "^20.1.3", "@types/jest": "^29.5.12", "@types/node": "^20.12.13", "conditional-type-checks": "^1.0.6", - "edgedb": "*", + "gel": "*", "jest": "^29.7.0", "ts-jest": "^29.1.4", "typescript": "^5.5.2" diff --git a/integration-tests/stable/select.test.ts b/integration-tests/stable/select.test.ts index 42b9c426d..d58588cb6 100644 --- a/integration-tests/stable/select.test.ts +++ b/integration-tests/stable/select.test.ts @@ -1,10 +1,10 @@ -import type * as edgedb from "edgedb"; +import type * as gel from "gel"; import assert from "node:assert/strict"; import e, { type $infer } from "./dbschema/edgeql-js"; import { setupTests, teardownTests, tc } from "./setupTeardown"; -let client: edgedb.Client; +let client: gel.Client; describe("select", () => { beforeAll(async () => { diff --git a/integration-tests/stable/setupTeardown.ts b/integration-tests/stable/setupTeardown.ts index 5d1848413..2eb620bbb 100644 --- a/integration-tests/stable/setupTeardown.ts +++ b/integration-tests/stable/setupTeardown.ts @@ -1,5 +1,5 @@ import * as tc from "conditional-type-checks"; -import { type Client, createClient } from "edgedb"; +import { type Client, createClient } from "gel"; export { tc }; @@ -47,7 +47,7 @@ export async function teardownTests(client: Client) { } export const versionGTE = (majorVer: number) => { - const version = JSON.parse(process.env._JEST_EDGEDB_VERSION!); + const version = JSON.parse(process.env._JEST_GEL_VERSION!); return version.major >= majorVer; }; diff --git a/integration-tests/stable/testRunner.ts b/integration-tests/stable/testRunner.ts index 685628640..85971465c 100644 --- a/integration-tests/stable/testRunner.ts +++ b/integration-tests/stable/testRunner.ts @@ -1,4 +1,4 @@ -import createClient from "edgedb"; +import createClient from "gel"; import { shutdown, @@ -12,7 +12,7 @@ import { } from "../../packages/driver/test/testUtil"; (async function main() { - console.log("\nStarting EdgeDB test cluster..."); + console.log("\nStarting Gel test cluster..."); const statusFile = generateStatusFileName("node"); console.log("Node status file:", statusFile); @@ -21,7 +21,7 @@ import { const { proc, config } = await startServer(args, statusFile); - console.log(`EdgeDB test cluster is up [port: ${config.port}]...`); + console.log(`Gel test cluster is up [port: ${config.port}]...`); const managementConn = await createClient(config).ensureConnected(); @@ -33,8 +33,8 @@ import { console.error(err); process.exit(1); } finally { - console.log("Shutting down EdgeDB test cluster..."); + console.log("Shutting down Gel test cluster..."); await shutdown(proc, managementConn); - console.log("EdgeDB test cluster is down..."); + console.log("Gel test cluster is down..."); } })(); diff --git a/packages/ai/README.md b/packages/ai/README.md index 3eb72df05..810fd6d1e 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -1,41 +1,41 @@ -# @edgedb/ai +# @gel/ai ## Installation -You can install the `@edgedb/ai` package using npm, yarn, or pnpm. Choose the command corresponding to your package manager: +You can install the `@gel/ai` package using npm, yarn, or pnpm. Choose the command corresponding to your package manager: ```bash -npm install @edgedb/ai -yarn add @edgedb/ai -pnpm add @edgedb/ai +npm install @gel/ai +yarn add @gel/ai +pnpm add @gel/ai ``` -## EdgeDB Configuration +## Gel Configuration See the AI documentation for detailed guidance on setting up the AI extension and creating a schema for use with the specialized indexes it includes. ## API Reference -### `createAI(client: Client, options: Partial = {}): EdgeDBAI` +### `createAI(client: Client, options: Partial = {}): GelAI` -Creates an instance of `EdgeDBAI` with the specified client and options. +Creates an instance of `GelAI` with the specified client and options. -- `client`: An EdgeDB client instance. +- `client`: An Gel client instance. - `options`: Configuration options for the AI model. - - `model`: Required. Specifies the AI model to use. This could be some of the OpenAI, Mistral or Anthropic models supported by EdgeDB AI. + - `model`: Required. Specifies the AI model to use. This could be some of the OpenAI, Mistral or Anthropic models supported by Gel AI. - `prompt`: Optional. Defines the input messages for the AI model. The prompt can have an `ID` or a `name` referencing a stored prompt. The referenced prompt will supply predefined messages. Optionally, include a custom list of messages using the `custom` field. These custom messages will be concatenated with messages from the stored prompt referenced by `id` or `name`. If no `id` or `name` is specified, only the `custom` messages will be used. If no `id`, `name`, or `custom` messages are provided, the built-in system prompt will be used by default. -### `EdgeDBAI` +### `GelAI` #### Public Methods -- `withConfig(options: Partial): EdgeDBAI` +- `withConfig(options: Partial): GelAI` - Returns a new `EdgeDBAI` instance with updated configuration options. + Returns a new `GelAI` instance with updated configuration options. -- `withContext(context: Partial): EdgeDBAI` +- `withContext(context: Partial): GelAI` - Returns a new `EdgeDBAI` instance with an updated query context. + Returns a new `GelAI` instance with an updated query context. - `async queryRag(message: string, context?: QueryContext): Promise` @@ -54,14 +54,14 @@ Creates an instance of `EdgeDBAI` with the specified client and options. ## Tool Calls -Tool calls are supported by the AI extension. They should be executed on the client side and tool call results should be provided back to the EdgeDB AI. +Tool calls are supported by the AI extension. They should be executed on the client side and tool call results should be provided back to the Gel AI. ## Example -The following example demonstrates how to use the `@edgedb/ai` package to query an AI model about astronomy and chemistry. +The following example demonstrates how to use the `@gel/ai` package to query an AI model about astronomy and chemistry. ```typescript -import { createClient } from "edgedb"; +import { createClient } from "gel"; import { createAI } from "./src/index.js"; const client = createClient({ diff --git a/packages/ai/package.json b/packages/ai/package.json index 6c32db540..798833026 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -1,12 +1,12 @@ { - "name": "@edgedb/ai", - "description": "Helper library for the EdgeDB AI extension", + "name": "@gel/ai", + "description": "Helper library for the Gel AI extension", "version": "0.1.0-alpha.2", - "author": "EdgeDB ", + "author": "Gel ", "type": "module", "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git", + "url": "https://github.com/geldata/gel-js.git", "directory": "packages/ai" }, "main": "./dist/index.js", @@ -39,11 +39,11 @@ "jest": "29.7.0", "ts-jest": "29.1.4", "typescript": "^5.5.2", - "edgedb": "*", + "gel": "*", "@repo/tsconfig": "*" }, "peerDependencies": { - "edgedb": "^1.5.0" + "gel": "^1.5.0" }, "dependencies": { "eventsource-parser": "^1.1.2" diff --git a/packages/ai/src/core.ts b/packages/ai/src/core.ts index 4663d909f..9816623d7 100644 --- a/packages/ai/src/core.ts +++ b/packages/ai/src/core.ts @@ -1,11 +1,11 @@ -import type { Client } from "edgedb"; +import type { Client } from "gel"; import { EventSourceParserStream } from "eventsource-parser/stream"; -import type { ResolvedConnectConfig } from "edgedb/dist/conUtils.js"; +import type { ResolvedConnectConfig } from "gel/dist/conUtils.js"; import { getAuthenticatedFetch, type AuthenticatedFetch, -} from "edgedb/dist/utils.js"; +} from "gel/dist/utils.js"; import { type AIOptions, type QueryContext, @@ -14,17 +14,17 @@ import { type EmbeddingRequest, isPromptRequest, } from "./types.js"; -import { getHTTPSCRAMAuth } from "edgedb/dist/httpScram.js"; -import { cryptoUtils } from "edgedb/dist/browserCrypto.js"; +import { getHTTPSCRAMAuth } from "gel/dist/httpScram.js"; +import { cryptoUtils } from "gel/dist/browserCrypto.js"; import { extractMessageFromParsedEvent, handleResponseError } from "./utils.js"; export function createAI(client: Client, options: AIOptions) { - return new EdgeDBAI(client, options); + return new GelAI(client, options); } const httpSCRAMAuth = getHTTPSCRAMAuth(cryptoUtils); -export class EdgeDBAI { +export class GelAI { /** @internal */ private readonly authenticatedFetch: Promise; private readonly options: AIOptions; @@ -36,7 +36,7 @@ export class EdgeDBAI { options: AIOptions, context: Partial = {}, ) { - this.authenticatedFetch = EdgeDBAI.getAuthenticatedFetch(client); + this.authenticatedFetch = GelAI.getAuthenticatedFetch(client); this.options = options; this.context = { query: context.query ?? "", @@ -54,7 +54,7 @@ export class EdgeDBAI { } withConfig(options: Partial) { - return new EdgeDBAI( + return new GelAI( this.client, { ...this.options, ...options }, this.context, @@ -62,7 +62,7 @@ export class EdgeDBAI { } withContext(context: Partial) { - return new EdgeDBAI(this.client, this.options, { + return new GelAI(this.client, this.options, { ...this.context, ...context, }); diff --git a/packages/ai/src/types.ts b/packages/ai/src/types.ts index 419bc9ef6..ce08a34e5 100644 --- a/packages/ai/src/types.ts +++ b/packages/ai/src/types.ts @@ -1,16 +1,16 @@ export type ChatParticipantRole = "system" | "user" | "assistant" | "tool"; -export interface EdgeDBSystemMessage { +export interface GelSystemMessage { role: "system"; content: string; } -export interface EdgeDBUserMessage { +export interface GelUserMessage { role: "user"; content: { type: "text"; text: string }[]; } -export interface EdgeDBAssistantMessage { +export interface GelAssistantMessage { role: "assistant"; content: string; tool_calls?: { @@ -20,22 +20,22 @@ export interface EdgeDBAssistantMessage { }[]; } -export interface EdgeDBToolMessage { +export interface GelToolMessage { role: "tool"; content: string; tool_call_id: string; } -export type EdgeDBMessage = - | EdgeDBSystemMessage - | EdgeDBUserMessage - | EdgeDBAssistantMessage - | EdgeDBToolMessage; +export type GelMessage = + | GelSystemMessage + | GelUserMessage + | GelAssistantMessage + | GelToolMessage; export type Prompt = - | { name: string; custom?: EdgeDBMessage[] } - | { id: string; custom?: EdgeDBMessage[] } - | { custom: EdgeDBMessage[] }; + | { name: string; custom?: GelMessage[] } + | { id: string; custom?: GelMessage[] } + | { custom: GelMessage[] }; export interface AIOptions { model: string; @@ -55,7 +55,7 @@ export interface RagRequestPrompt { } export interface RagRequestMessages { - messages: EdgeDBMessage[]; + messages: GelMessage[]; [key: string]: unknown; } diff --git a/packages/auth-core/genConsts.js b/packages/auth-core/genConsts.js index e25bc7508..bc89f1687 100644 --- a/packages/auth-core/genConsts.js +++ b/packages/auth-core/genConsts.js @@ -1,5 +1,5 @@ const fs = require("node:fs/promises"); -const { createClient } = require("edgedb"); +const { createClient } = require("gel"); const client = createClient("_localdev"); @@ -38,9 +38,9 @@ export type BuiltinOAuthProviderNames = export const emailPasswordProviderName = ${providerNames.emailpassword.replace( /^'|'$/g, - '"' + '"', )}; -` +`, ); console.log('Generated into "src/consts.ts"'); diff --git a/packages/auth-core/package.json b/packages/auth-core/package.json index 2590317a7..e6a7f32c5 100644 --- a/packages/auth-core/package.json +++ b/packages/auth-core/package.json @@ -1,11 +1,11 @@ { - "name": "@edgedb/auth-core", - "description": "Core helper library for the EdgeDB Auth extension", + "name": "@gel/auth-core", + "description": "Core helper library for the Gel Auth extension", "version": "0.2.1", - "author": "EdgeDB ", + "author": "Gel ", "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git", + "url": "https://github.com/geldata/gel-js.git", "directory": "packages/auth-core" }, "main": "./dist/index.js", @@ -39,11 +39,11 @@ "jest": "29.7.0", "ts-jest": "29.1.4", "typescript": "^5.5.2", - "edgedb": "*", + "gel": "*", "@repo/tsconfig": "*" }, "peerDependencies": { - "edgedb": "^1.3.6" + "gel": "^1.3.6" }, "dependencies": { "jwt-decode": "^4.0.0" diff --git a/packages/auth-core/readme.md b/packages/auth-core/readme.md index 33bf96348..030b4f690 100644 --- a/packages/auth-core/readme.md +++ b/packages/auth-core/readme.md @@ -1,10 +1,10 @@ -# @edgedb/auth-core: Core helper library for the EdgeDB Auth extension +# @gel/auth-core: Core helper library for the Gel Auth extension > Warning: This library is still in an alpha state, and so, bugs are likely and the api's should be considered unstable and may change in future releases. -This library contains some low-level utilities to help working with the EdgeDB auth extension; namely resolving the api endpoint urls from an edgedb `Client` object, providing wrappers around those api's to help handle the various auth flows (including handling PKCE), and adding typesafety. +This library contains some low-level utilities to help working with the Gel auth extension; namely resolving the api endpoint urls from an gel `Client` object, providing wrappers around those api's to help handle the various auth flows (including handling PKCE), and adding typesafety. It is recommended to instead use the separate helper libraries created to make integration with popular frameworks as easy as possible. Currently supported frameworks: -- Next.js (@edgedb/auth-nextjs) +- Next.js (@gel/auth-nextjs) - _...more coming soon_ diff --git a/packages/auth-core/src/core.ts b/packages/auth-core/src/core.ts index be164b5fc..2f9c4ab38 100644 --- a/packages/auth-core/src/core.ts +++ b/packages/auth-core/src/core.ts @@ -1,6 +1,6 @@ import { jwtDecode } from "jwt-decode"; -import * as edgedb from "edgedb"; -import { type ResolvedConnectConfig } from "edgedb/dist/conUtils"; +import * as gel from "gel"; +import { type ResolvedConnectConfig } from "gel/dist/conUtils"; import * as pkce from "./pkce"; import { @@ -24,13 +24,13 @@ export class Auth { public readonly baseUrl: string; protected constructor( - public readonly client: edgedb.Client, + public readonly client: gel.Client, baseUrl: string, ) { this.baseUrl = baseUrl; } - static async create(client: edgedb.Client) { + static async create(client: gel.Client) { const connectConfig: ResolvedConnectConfig = ( await (client as any).pool._getNormalizedConnectConfig() ).connectionParams; @@ -363,7 +363,7 @@ export class Auth { emailPassword := exists providers[is EmailPasswordProviderConfig] }`); } catch (err) { - if (err instanceof edgedb.InvalidReferenceError) { + if (err instanceof gel.InvalidReferenceError) { throw new errors.ConfigurationError("auth extension is not enabled"); } throw err; diff --git a/packages/auth-core/src/errors.ts b/packages/auth-core/src/errors.ts index b1379beac..8f466fd0b 100644 --- a/packages/auth-core/src/errors.ts +++ b/packages/auth-core/src/errors.ts @@ -1,14 +1,14 @@ /** Base class for all exceptions raised by the auth extension. */ -export class EdgeDBAuthError extends Error { +export class GelAuthError extends Error { get type() { - return "_EdgeDBAuth"; + return "_GelAuth"; } } /** Error returned by auth extension could not be decoded into a * known error class. */ -export class UnknownError extends EdgeDBAuthError { +export class UnknownError extends GelAuthError { get type() { return "_Unknown"; } @@ -17,7 +17,7 @@ export class UnknownError extends EdgeDBAuthError { /** Base class for all backend auth extension errors. It is not recommended to * return these errors to the user. */ -export class BackendError extends EdgeDBAuthError { +export class BackendError extends GelAuthError { get type() { return "_Backend"; } @@ -26,14 +26,14 @@ export class BackendError extends EdgeDBAuthError { /** Base class for all errors arising during normal use of the auth extension. * These errors are considered safe to return to the user. */ -export class UserError extends EdgeDBAuthError { +export class UserError extends GelAuthError { get type() { return "_User"; } } /** Required resource could not be found. */ -export class NotFoundError extends EdgeDBAuthError { +export class NotFoundError extends GelAuthError { get type() { return "NotFound"; } diff --git a/packages/auth-core/src/utils.ts b/packages/auth-core/src/utils.ts index aec9a20d0..1a3e63428 100644 --- a/packages/auth-core/src/utils.ts +++ b/packages/auth-core/src/utils.ts @@ -87,11 +87,11 @@ export const errorMapping = new Map( ) .filter((entry) => entry != null) as unknown as [ string, - errors.EdgeDBAuthError, + errors.GelAuthError, ][], ); -export function decodeError(errorBody: string): errors.EdgeDBAuthError { +export function decodeError(errorBody: string): errors.GelAuthError { try { const errorJson = JSON.parse(errorBody); if ( diff --git a/packages/auth-core/test/core.test.ts b/packages/auth-core/test/core.test.ts index 4265ee86b..73fb35c27 100644 --- a/packages/auth-core/test/core.test.ts +++ b/packages/auth-core/test/core.test.ts @@ -20,7 +20,7 @@ beforeAll(async () => { ext::auth::AuthConfig::token_time_to_live := '24 hours'; configure current database set - ext::auth::SMTPConfig::sender := 'noreply@example.edgedb.com'; + ext::auth::SMTPConfig::sender := 'noreply@example.geldata.com'; configure current database insert ext::auth::EmailPasswordProviderConfig {}; @@ -39,7 +39,7 @@ test("test password signup/signin flow", async () => { const auth = await Auth.create(client); const signupResponse = await auth.signupWithEmailPassword( - "test@example.edgedb.com", + "test@example.geldata.com", "supersecretpassword", `${auth.baseUrl}/auth/emailpassword/verify`, ); @@ -49,7 +49,7 @@ test("test password signup/signin flow", async () => { await expect( auth.signinWithEmailPassword( - "test@example.edgedb.com", + "test@example.geldata.com", "supersecretpassword", ), ).rejects.toThrow("Email verification is required"); diff --git a/packages/auth-core/test/globalSetup.ts b/packages/auth-core/test/globalSetup.ts index bf3e0f9c5..1793f189c 100644 --- a/packages/auth-core/test/globalSetup.ts +++ b/packages/auth-core/test/globalSetup.ts @@ -9,7 +9,7 @@ import { export default async () => { // tslint:disable-next-line - console.log("\nStarting EdgeDB test cluster..."); + console.log("\nStarting Gel test cluster..."); const statusFile = generateStatusFileName("node"); console.log("Node status file:", statusFile); @@ -22,18 +22,17 @@ export default async () => { const { proc, config } = await startServer(args, statusFile); // @ts-ignore - global.edgedbProc = proc; + global.gelProc = proc; - process.env._JEST_EDGEDB_CONNECT_CONFIG = JSON.stringify(config); - process.env._JEST_EDGEDB_AVAILABLE_FEATURES = - JSON.stringify(availableFeatures); + process.env._JEST_GEL_CONNECT_CONFIG = JSON.stringify(config); + process.env._JEST_GEL_AVAILABLE_FEATURES = JSON.stringify(availableFeatures); const { client, version } = await connectToServer(config); // @ts-ignore - global.edgedbConn = client; - process.env._JEST_EDGEDB_VERSION = JSON.stringify(version); + global.gelConn = client; + process.env._JEST_GEL_VERSION = JSON.stringify(version); // tslint:disable-next-line - console.log(`EdgeDB test cluster is up [port: ${config.port}]...`); + console.log(`Gel test cluster is up [port: ${config.port}]...`); }; diff --git a/packages/auth-core/test/globalTeardown.ts b/packages/auth-core/test/globalTeardown.ts index ef11aad67..0948e98b6 100644 --- a/packages/auth-core/test/globalTeardown.ts +++ b/packages/auth-core/test/globalTeardown.ts @@ -2,13 +2,13 @@ import { shutdown } from "../../driver/test/testUtil"; export default async () => { // tslint:disable-next-line - console.log("Shutting down EdgeDB test cluster..."); + console.log("Shutting down Gel test cluster..."); try { // @ts-ignore - await shutdown(global.edgedbProc, global.edgedbConn); + await shutdown(global.gelProc, global.gelConn); } finally { // tslint:disable-next-line - console.log("EdgeDB test cluster is down..."); + console.log("Gel test cluster is down..."); } }; diff --git a/packages/auth-core/test/testbase.ts b/packages/auth-core/test/testbase.ts index 7b95da653..9b890bd1e 100644 --- a/packages/auth-core/test/testbase.ts +++ b/packages/auth-core/test/testbase.ts @@ -1,4 +1,4 @@ -import { Client, ConnectOptions } from "edgedb"; +import { Client, ConnectOptions } from "gel"; import * as testbase from "../../driver/test/testbase"; export const getClient = testbase.getClient as unknown as ( diff --git a/packages/auth-express/package.json b/packages/auth-express/package.json index 2515c0c36..9b71ee85f 100644 --- a/packages/auth-express/package.json +++ b/packages/auth-express/package.json @@ -1,12 +1,12 @@ { - "name": "@edgedb/auth-express", - "description": "Helper library to integrate the EdgeDB Auth extension with Express", + "name": "@gel/auth-express", + "description": "Helper library to integrate the Gel Auth extension with Express", "version": "0.2.2", "type": "module", - "author": "EdgeDB ", + "author": "Gel ", "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git", + "url": "https://github.com/geldata/gel-js.git", "directory": "packages/auth-express" }, "license": "Apache-2.0", @@ -36,16 +36,16 @@ "@repo/tsconfig": "*", "@types/express": "^4.17.21", "@types/node": "^20.12.13", - "edgedb": "*", + "gel": "*", "express": "^4.19.2", "typescript": "^5.5.2" }, "peerDependencies": { "cookie-parser": "^1.4.6", - "edgedb": "^1.3.6", + "gel": "^1.3.6", "express": "^4.18.2" }, "dependencies": { - "@edgedb/auth-core": "^0.2.1" + "@gel/auth-core": "^0.2.1" } } diff --git a/packages/auth-express/readme.md b/packages/auth-express/readme.md index 537288382..1ab78f262 100644 --- a/packages/auth-express/readme.md +++ b/packages/auth-express/readme.md @@ -1,4 +1,4 @@ -# `@edgedb/auth-express` +# `@gel/auth-express` This library provides a set of utilities to help you integrate authentication into your [Express](https://expressjs.com/) application. It supports various authentication methods including OAuth, email/password, and session-based authentication. @@ -7,7 +7,7 @@ This library provides a set of utilities to help you integrate authentication in This package is published on npm and can be installed with your package manager of choice. ```bash -npm install @edgedb/auth-express +npm install @gel/auth-express ``` **Note:** We have tested this library against the latest version of Express v4 with the types provided at DefinitelyTyped and have set up `peerDependencies` based on typical usage with npm. @@ -15,9 +15,10 @@ npm install @edgedb/auth-express ## Setup **Prerequisites**: + - Node v18+ - **Note**: Due to using the `crypto` global, you will need to start Node with `--experimental-global-webcrypto`. You can add this option to your `NODE_OPTIONS` environment variable, like `NODE_OPTIONS='--experimental-global-webcrypto'` in the appropriate `.env` file. -- Before adding EdgeDB auth to your Express app, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers (you can do this in CLI or EdgeDB UI). Refer to the auth extension docs for details on how to do this. +- Before adding Gel auth to your Express app, you will first need to enable the `auth` extension in your Gel schema, and have configured the extension with some providers (you can do this in CLI or Gel UI). Refer to the auth extension docs for details on how to do this. - We depend on the following middleware being installed in your Express app: - `body-parser`: both JSON and urlencoded - `cookie-parser` @@ -33,22 +34,22 @@ app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); ``` -This library provides a few affordances for adding EdgeDB Auth to your existing Express app: +This library provides a few affordances for adding Gel Auth to your existing Express app: -- Routers and route handlers to handle the authentication flow required by EdgeDB. +- Routers and route handlers to handle the authentication flow required by Gel. - Middleware to attach sessions to requests. - Some additional utility functions for handling various auth related concerns. ## Configuring the `ExpressAuth` class -After [configuring the EdgeDB Auth extension](https://www.edgedb.com/docs/guides/auth/index), you can set up the various auth routes with our route builders. +After [configuring the Gel Auth extension](https://www.geldata.com/docs/guides/auth/index), you can set up the various auth routes with our route builders. -Start by instantiating an `ExpressAuth` object by passing it a configured EdgeDB client and some options: +Start by instantiating an `ExpressAuth` object by passing it a configured Gel client and some options: ```ts -import { createClient } from "edgedb"; -import createExpressAuth from "@edgedb/auth-express"; -import * as expressAuth from "@edgedb/auth-express"; +import { createClient } from "gel"; +import createExpressAuth from "@gel/auth-express"; +import * as expressAuth from "@gel/auth-express"; const client = createClient(); const auth = createExpressAuth(client, { @@ -73,10 +74,10 @@ app.get("/dashboard", (req: expressAuth.SessionRequest, res) => { } // Render a template using Pug or EJS - res.render( - "dashboard", - { title: "Dashboard", message: "Welcome to your dashboard!" } - ); + res.render("dashboard", { + title: "Dashboard", + message: "Welcome to your dashboard!", + }); }); ``` @@ -88,7 +89,7 @@ You can centralize the logic to redirect unauthenticated routes into a custom mi function requireAuth( req: expressAuth.SessionRequest, res: Response, - next: NextFunction + next: NextFunction, ) { if (!(await req.session?.isSignedIn())) { return res.redirect("/auth/builtin/signin"); @@ -103,10 +104,10 @@ Then you can use this to protect your route like this: ```ts app.get("/dashboard", requireAuth, (req: expressAuth.SessionRequest, res) => { // Render a template using Pug or EJS - res.render( - "dashboard", - { title: "Dashboard", message: "Welcome to your dashboard!" } - ); + res.render("dashboard", { + title: "Dashboard", + message: "Welcome to your dashboard!", + }); }); ``` @@ -162,7 +163,6 @@ app.use("/auth", builtinRouter); - `resetPassword: (express.RouteHandler | express.ErrorHandler)[]`, Attached middleware executes after the user successfully resets their password. Typically you will redirect the user to your application here. - `resendVerificationEmail: (express.RouteHandler | express.ErrorHandler)[]`, Attached middleware executes after the user resends their email verification email. Typically you will redirect the user to some success page, or if you do not _require_ verification to use your app, you can redirect to your app here. - ```ts const emailPasswordRouter = auth.createEmailPasswordRouter( "/auth/email-password", // Path to mount router at @@ -198,7 +198,7 @@ const emailPasswordRouter = auth.createEmailPasswordRouter( res.redirect("/"); }, ], - } + }, ); app.use(emailPasswordRouter); @@ -257,9 +257,9 @@ const magicLinkRouter = auth.createMagicLinkRouter( signUp: [ (req, res) => { res.redirect("/check-email.html"); - } - ] - } + }, + ], + }, ); app.use(magicLinkRouter); @@ -271,12 +271,12 @@ app.use(magicLinkRouter); ### Custom UI: WebAuthn -Unlike the other authentication methods, WebAuthn requires a client-side script that runs in the browser. This script requests JSON from the EdgeDB Auth server that gets options to pass to the Web Authentication API built into the browser, and then after successfully creating new credentials or retrieving existing credentials, it calls back to the endpoints you're configuring below. +Unlike the other authentication methods, WebAuthn requires a client-side script that runs in the browser. This script requests JSON from the Gel Auth server that gets options to pass to the Web Authentication API built into the browser, and then after successfully creating new credentials or retrieving existing credentials, it calls back to the endpoints you're configuring below. In order to facilitate the sign in and sign up ceremonies, we export a helper class called `WebAuthnClient` that you must configure with some relevant paths based on how you set up your routing below. ```ts -import { WebAuthnClient } from "@edgedb/auth-express"; +import { WebAuthnClient } from "@gel/auth-express"; const webAuthnClient = new WebAuthnClient({ signupOptionsUrl: "http://localhost:3000/auth/webauthn/signup/options", @@ -291,32 +291,29 @@ const webAuthnClient = new WebAuthnClient({ - `signIn: (express.RouteHandler | express.ErrorHandler)[]`, required, Attached middleware executes when sign-in attempt succeeds. Typically you will redirect the user to your application here. - `signUp: (express.RouteHandler | express.ErrorHandler)[]`, required, Attached middleware executes when sign-up attempt succeeds. Typically you will redirect the user to your application here. - `verify: (express.RouteHandler | express.ErrorHandler)[]`, Attached middleware executes after the user verifies their email successfully. Typically you will redirect the user to your application here. -- `signInOptions: (express.RouteHandler | express.ErrorHandler)[]`, This redirects the user to the appropriate URL of the EdgeDB server to retrieve the WebAuthn sign in options. -- `signUpOptions: (express.RouteHandler | express.ErrorHandler)[]`, This redirects the user to the appropriate URL of the EdgeDB server to retrieve the WebAuthn sign up options. +- `signInOptions: (express.RouteHandler | express.ErrorHandler)[]`, This redirects the user to the appropriate URL of the Gel server to retrieve the WebAuthn sign in options. +- `signUpOptions: (express.RouteHandler | express.ErrorHandler)[]`, This redirects the user to the appropriate URL of the Gel server to retrieve the WebAuthn sign up options. ```ts -const webAuthnRouter = auth.createWebAuthnRouter( - "/auth/webauthn", - { - signInOptions: [], - signIn: [ - (req: expressAuth.AuthRequest, res) => { - res.redirect("/"); - }, - ], - signUpOptions: [], - signUp: [ - (req: expressAuth.AuthRequest, res) => { - res.redirect("/onboarding"); - }, - ], - verify: [ - (req: expressAuth.AuthRequest, res) => { - res.redirect("/"); - }, - ], - } -); +const webAuthnRouter = auth.createWebAuthnRouter("/auth/webauthn", { + signInOptions: [], + signIn: [ + (req: expressAuth.AuthRequest, res) => { + res.redirect("/"); + }, + ], + signUpOptions: [], + signUp: [ + (req: expressAuth.AuthRequest, res) => { + res.redirect("/onboarding"); + }, + ], + verify: [ + (req: expressAuth.AuthRequest, res) => { + res.redirect("/"); + }, + ], +}); app.use(webAuthnRouter); // This creates the following routes: @@ -346,7 +343,7 @@ const builtinRouter = Router() } res.redirect("/"); - } + }, ); app.use("/auth", builtinRouter); @@ -361,48 +358,48 @@ const emailPasswordRouter = Router() auth.emailPassword.signIn, (req: expressAuth.AuthRequest, res) => { res.redirect("/"); - } + }, ) .post( "/signup", auth.emailPassword.signUp( // URL of the verify endpoint configured below - "http://localhost:3000/auth/email-password/verify" + "http://localhost:3000/auth/email-password/verify", ), (req: expressAuth.AuthRequest, res) => { res.redirect("/onboarding"); - } + }, ) .get( "/verify", auth.emailPassword.verify, (req: expressAuth.AuthRequest, res) => { res.redirect("/"); - } + }, ) .post( "/send-password-reset-email", auth.emailPassword.sendPasswordResetEmail( // URL of the reset password endpoint configured below - "http://localhost:3000/auth/email-password/reset-password" + "http://localhost:3000/auth/email-password/reset-password", ), (req: expressAuth.AuthRequest, res) => { res.redirect("/email-success"); - } + }, ) .post( "/reset-password", auth.emailPassword.resetPassword, (req: expressAuth.AuthRequest, res) => { res.redirect("/email-success"); - } + }, ) .post( "/resend-verification-email", auth.emailPassword.resendVerificationEmail, (req: expressAuth.AuthRequest, res) => { res.redirect("/"); - } + }, ); app.use("/auth/email-password", emailPasswordRouter); @@ -416,15 +413,15 @@ const oAuthRouter = Router() "/", auth.oAuth.redirect( // URL of the callback endpoint configured below - "http://localhost:3000/auth/oauth/callback" - ) + "http://localhost:3000/auth/oauth/callback", + ), ) .get( "/callback", auth.oAuth.callback, (req: expressAuth.AuthRequest, res) => { res.redirect("/"); - } + }, ); app.use("/auth/oauth", oAuthRouter); @@ -461,7 +458,6 @@ const magicLinkRoute = Router() }, ); - app.use("/auth/magic-link", router); ``` @@ -469,35 +465,25 @@ app.use("/auth/magic-link", router); ```ts const webAuthnRouter = Router() - .get( - "/signin/options", - auth.webauthn.signInOptions - ) + .get("/signin/options", auth.webauthn.signInOptions) .post( "/signin", auth.webauthn.signIn, (req: expressAuth.AuthRequest, res) => { res.redirect("/"); - } - ) - .get( - "/signup/options", - auth.webauthn.signUpOptions + }, ) + .get("/signup/options", auth.webauthn.signUpOptions) .post( "/signup", auth.webauthn.signUp, (req: expressAuth.AuthRequest, res) => { res.redirect("/onboarding"); - } + }, ) - .get( - "/verify", - auth.webauthn.verify, - (req: expressAuth.AuthRequest, res) => { - res.redirect("/"); - } - ); + .get("/verify", auth.webauthn.verify, (req: expressAuth.AuthRequest, res) => { + res.redirect("/"); + }); app.use("/auth/webauthn", webAuthnRouter); ``` @@ -528,8 +514,8 @@ const builtinRouter = auth.createBuiltinRouter({ ### `createExpressAuth` (default package export) - `baseUrl: string`, required, The url of your application; needed for various auth flows (eg. OAuth) to redirect back to. -- `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to 'edgedb-session'. -- `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to 'edgedb-pkce-verifier' +- `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to 'gel-session'. +- `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to 'gel-pkce-verifier' - `passwordResetUrl?: string`: The url of the the password reset page; needed if you want to enable password reset emails in your app. Returns: `ExpressAuth` @@ -572,4 +558,3 @@ This is an extension of the Express `Request` interface containing some optional - `session?: ExpressAuthSession` - `tokenData?: TokenData` - diff --git a/packages/auth-express/src/index.ts b/packages/auth-express/src/index.ts index e30b699c9..ddeddc340 100644 --- a/packages/auth-express/src/index.ts +++ b/packages/auth-express/src/index.ts @@ -7,9 +7,9 @@ import { InvalidDataError, OAuthProviderFailureError, PKCEError, - EdgeDBAuthError, -} from "@edgedb/auth-core"; -import type { Client } from "edgedb"; + GelAuthError, +} from "@gel/auth-core"; +import type { Client } from "gel"; import { type Request as ExpressRequest, type Response as ExpressResponse, @@ -21,7 +21,7 @@ import { type RouterStack = (RequestHandler | ErrorRequestHandler)[]; -export * from "@edgedb/auth-core/errors"; +export * from "@gel/auth-core/errors"; export type BuiltinProviderNames = | BuiltinOAuthProviderNames @@ -84,9 +84,9 @@ export class ExpressAuth { ) { this.options = { baseUrl: options.baseUrl.replace(/\/$/, ""), - authCookieName: options.authCookieName ?? "edgedb-session", + authCookieName: options.authCookieName ?? "gel-session", pkceVerifierCookieName: - options.pkceVerifierCookieName ?? "edgedb-pkce-verifier", + options.pkceVerifierCookieName ?? "gel-pkce-verifier", }; this.core = Auth.create(client); this.isSecure = this.options.baseUrl.startsWith("https"); @@ -118,8 +118,32 @@ export class ExpressAuth { }); }; + private getVerifier(cookies: Record) { + return ( + cookies[this.options.pkceVerifierCookieName] || + cookies["edgedb-pkce-verifier"] + ); + } + + private clearVerifierCookie(res: ExpressResponse) { + res.clearCookie(this.options.pkceVerifierCookieName); + res.clearCookie("edgedb-pkce-verifier"); + } + + private clearAuthCookie(res: ExpressResponse) { + res.clearCookie(this.options.authCookieName, { + httpOnly: true, + sameSite: "strict", + }); + res.clearCookie("edgedb-session", { + httpOnly: true, + sameSite: "strict", + }); + } + getSession = (req: ExpressRequest) => { - const authCookie = req.cookies[this.options.authCookieName]; + const authCookie = + req.cookies[this.options.authCookieName] || req.cookies["edgedb-session"]; return new ExpressAuthSession(this.client, authCookie); }; @@ -268,10 +292,7 @@ export class ExpressAuth { next: NextFunction, ) => { try { - res.clearCookie(this.options.authCookieName, { - httpOnly: true, - sameSite: "strict", - }); + this.clearAuthCookie(res); req.session = new ExpressAuthSession(this.client, undefined); req.tokenData = undefined; next(); @@ -334,14 +355,14 @@ export class ExpressAuth { } throw new PKCEError("no pkce code in response"); } - const verifier = req.cookies[this.options.pkceVerifierCookieName]; + const verifier = this.getVerifier(req.cookies); if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); } const isSignUp = searchParams.get("isSignUp") === "true"; const tokenData = await (await this.core).getToken(code, verifier); this.createAuthCookie(res, tokenData.auth_token); - res.clearCookie(this.options.pkceVerifierCookieName); + this.clearVerifierCookie(res); req.session = new ExpressAuthSession(this.client, tokenData.auth_token); req.tokenData = tokenData; @@ -397,7 +418,7 @@ export class ExpressAuth { const error = searchParams.get("error"); if (error) { const desc = searchParams.get("error_description"); - throw new EdgeDBAuthError(error + (desc ? `: ${desc}` : "")); + throw new GelAuthError(error + (desc ? `: ${desc}` : "")); } const code = searchParams.get("code"); const verificationEmailSentAt = searchParams.get( @@ -411,7 +432,7 @@ export class ExpressAuth { } throw new PKCEError("no pkce code in response"); } - const verifier = req.cookies[this.options.pkceVerifierCookieName]; + const verifier = this.getVerifier(req.cookies); if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); } @@ -493,7 +514,7 @@ export class ExpressAuth { try { const searchParams = new URLSearchParams(req.url.split("?")[1]); const verificationToken = searchParams.get("verification_token"); - const verifier = req.cookies[this.options.pkceVerifierCookieName]; + const verifier = this.getVerifier(req.cookies); if (!verificationToken) { throw new PKCEError("no verification_token in response"); } @@ -504,7 +525,7 @@ export class ExpressAuth { await this.core ).verifyEmailPasswordSignup(verificationToken, verifier); this.createAuthCookie(res, tokenData.auth_token); - res.clearCookie(this.options.pkceVerifierCookieName); + this.clearVerifierCookie(res); req.session = new ExpressAuthSession(this.client, tokenData.auth_token); req.tokenData = tokenData; @@ -538,7 +559,7 @@ export class ExpressAuth { next: NextFunction, ) => { try { - const verifier = req.cookies[this.options.pkceVerifierCookieName]; + const verifier = this.getVerifier(req.cookies); if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); } @@ -552,7 +573,7 @@ export class ExpressAuth { await this.core ).resetPasswordWithResetToken(resetToken, verifier, password); this.createAuthCookie(res, tokenData.auth_token); - res.clearCookie(this.options.pkceVerifierCookieName); + this.clearVerifierCookie(res); req.session = new ExpressAuthSession(this.client, tokenData.auth_token); req.tokenData = tokenData; next(); @@ -610,7 +631,7 @@ export class ExpressAuth { const error = searchParams.get("error"); if (error) { const desc = searchParams.get("error_description"); - throw new EdgeDBAuthError(error + (desc ? `: ${desc}` : "")); + throw new GelAuthError(error + (desc ? `: ${desc}` : "")); } const code = searchParams.get("code"); if (!code) { @@ -618,14 +639,13 @@ export class ExpressAuth { } const isSignUp = searchParams.get("isSignUp") === "true"; - const verifier = req.cookies[this.options.pkceVerifierCookieName]; + const verifier = this.getVerifier(req.cookies); if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); } const tokenData = await (await this.core).getToken(code, verifier); this.createAuthCookie(res, tokenData.auth_token); - res.clearCookie(this.options.pkceVerifierCookieName); - + this.clearVerifierCookie(res); req.session = new ExpressAuthSession(this.client, tokenData.auth_token); req.tokenData = tokenData; req.isSignUp = isSignUp; @@ -695,7 +715,7 @@ export class ExpressAuth { try { const searchParams = new URLSearchParams(req.url.split("?")[1]); const verificationToken = searchParams.get("verification_token"); - const verifier = req.cookies[this.options.pkceVerifierCookieName]; + const verifier = this.getVerifier(req.cookies); if (!verificationToken) { throw new PKCEError("no verification_token in response"); } @@ -706,7 +726,7 @@ export class ExpressAuth { await this.core ).verifyWebAuthnSignup(verificationToken, verifier); this.createAuthCookie(res, tokenData.auth_token); - res.clearCookie(this.options.pkceVerifierCookieName); + this.clearVerifierCookie(res); req.session = new ExpressAuthSession(this.client, tokenData.auth_token); req.tokenData = tokenData; diff --git a/packages/auth-express/src/webauthn.ts b/packages/auth-express/src/webauthn.ts index e41382e60..4ff9ac347 100644 --- a/packages/auth-express/src/webauthn.ts +++ b/packages/auth-express/src/webauthn.ts @@ -1 +1 @@ -export { WebAuthnClient } from "@edgedb/auth-core/webauthn"; +export { WebAuthnClient } from "@gel/auth-core/webauthn"; diff --git a/packages/auth-nextjs/package.json b/packages/auth-nextjs/package.json index d1af2e586..2bf74604f 100644 --- a/packages/auth-nextjs/package.json +++ b/packages/auth-nextjs/package.json @@ -1,11 +1,11 @@ { - "name": "@edgedb/auth-nextjs", - "description": "Helper library to integrate the EdgeDB Auth extension with Next.js", + "name": "@gel/auth-nextjs", + "description": "Helper library to integrate the Gel Auth extension with Next.js", "version": "0.3.2", - "author": "EdgeDB ", + "author": "Gel ", "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git", + "url": "https://github.com/geldata/gel-js.git", "directory": "packages/auth-nextjs" }, "license": "Apache-2.0", @@ -28,18 +28,18 @@ "@repo/tsconfig": "*", "@types/node": "^20.12.13", "@types/react": "npm:types-react@rc", - "edgedb": "*", + "gel": "*", "next": "15.0.3", "react": "19.0.0-rc-b01722d5-20241114", "typescript": "^5.5.2" }, "peerDependencies": { - "edgedb": "^1.3.6", + "gel": "^1.3.6", "next": ">=13.5.6 <16.0.0", "react": "^18.2.0 || ^19.0" }, "dependencies": { - "@edgedb/auth-core": "0.2.1" + "@gel/auth-core": "0.2.1" }, "overrides": { "@types/react": "npm:types-react@rc" diff --git a/packages/auth-nextjs/readme.md b/packages/auth-nextjs/readme.md index 87a9a01c5..110ce168d 100644 --- a/packages/auth-nextjs/readme.md +++ b/packages/auth-nextjs/readme.md @@ -1,21 +1,22 @@ -# @edgedb/auth-nextjs: Helper library to integrate the EdgeDB Auth extension with Next.js +# @gel/auth-nextjs: Helper library to integrate the Gel Auth extension with Next.js > Warning: This library is still in an alpha state, and so, bugs are likely and the api's should be considered unstable and may change in future releases. ### Setup **Prerequisites**: + - Node v18+ - **Note**: Due to using the `crypto` global, you will need to start Node with `--experimental-global-webcrypto`. You can add this option to your `NODE_OPTIONS` environment variable, like `NODE_OPTIONS='--experimental-global-webcrypto'` in the appropriate `.env` file. -- Before adding EdgeDB auth to your Next.js app, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers. Refer to the auth extension docs for details on how to do this. +- Before adding Gel auth to your Next.js app, you will first need to enable the `auth` extension in your Gel schema, and have configured the extension with some providers. Refer to the auth extension docs for details on how to do this. -1. Initialize the auth helper by passing an EdgeDB `Client` object to `createAuth()`, along with some configuration options. This will return a `NextAppAuth` object which you can use across your app. Similarly to the `Client` it's recommended to export this auth object from some root configuration file in your app. +1. Initialize the auth helper by passing an Gel `Client` object to `createAuth()`, along with some configuration options. This will return a `NextAppAuth` object which you can use across your app. Similarly to the `Client` it's recommended to export this auth object from some root configuration file in your app. ```ts - // edgedb.ts + // gel.ts - import { createClient } from "edgedb"; - import createAuth from "@edgedb/auth-nextjs/app"; + import { createClient } from "gel"; + import createAuth from "@gel/auth-nextjs/app"; export const client = createClient(); @@ -28,8 +29,8 @@ - `baseUrl: string`, _required_, The url of your application; needed for various auth flows (eg. OAuth) to redirect back to. - `authRoutesPath?: string`, The path to the auth route handlers, defaults to `'auth'`, see below for more details. - - `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to `'edgedb-session'`. - - `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to `'edgedb-pkce-verifier'` + - `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to `'gel-session'`. + - `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to `'gel-pkce-verifier'` - `passwordResetPath?: string`: The path relative to the `baseUrl` of the the password reset page; needed if you want to enable password reset emails in your app. - `magicLinkFailurePath?: string`: The path relative to the `baseUrl` of the page we should redirect users to if there is an error when trying to sign in with a magic link. The page will get an `error` search parameter attached with an error message. This property is required if you use the Magic Link authentication feature. @@ -39,7 +40,7 @@ // app/auth/[...auth]/route.ts import { redirect } from "next/navigation"; - import { auth } from "@/edgedb"; + import { auth } from "@/gel"; const { GET, POST } = auth.createAuthRouteHandlers({ onOAuthCallback({ error, tokenData, isSignUp }) { @@ -68,7 +69,7 @@ By default the handlers expect to exist under the `/auth` path in your app, however if you want to place them elsewhere, you will also need to configure the `authRoutesPath` option of `createAuth` to match. -3. Now we just need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the EdgeDB Auth's builtin UI. Or alternatively you can implement your own custom UI. +3. Now we just need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the Gel Auth's builtin UI. Or alternatively you can implement your own custom UI. **Builtin UI** @@ -97,7 +98,7 @@ Now you have auth all configured and user's can signin/signup/etc. you can use the `auth.getSession()` method in your app pages to retrieve an `AuthSession` object. This session object allows you to check if the user is currently logged in with the `isSignedIn` method, and also provides a `Client` object automatically configured with the `ext::auth::client_token` global, so you can run queries using the `ext::auth::ClientTokenIdentity` of the currently signed in user. ```ts -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; export default async function Home() { const session = await auth.getSession(); diff --git a/packages/auth-nextjs/src/app/client.ts b/packages/auth-nextjs/src/app/client.ts index 97c42e64a..12e350ea1 100644 --- a/packages/auth-nextjs/src/app/client.ts +++ b/packages/auth-nextjs/src/app/client.ts @@ -4,7 +4,7 @@ import { type NextAuthOptions, } from "../shared.client"; -export * from "@edgedb/auth-core/errors"; +export * from "@gel/auth-core/errors"; export { type NextAuthOptions, type BuiltinProviderNames }; export default function createNextAppClientAuth(options: NextAuthOptions) { diff --git a/packages/auth-nextjs/src/app/index.ts b/packages/auth-nextjs/src/app/index.ts index 45dad82ef..97d8e6f79 100644 --- a/packages/auth-nextjs/src/app/index.ts +++ b/packages/auth-nextjs/src/app/index.ts @@ -3,8 +3,8 @@ import { ConfigurationError, PKCEError, InvalidDataError, -} from "@edgedb/auth-core"; -import type { Client } from "edgedb"; +} from "@gel/auth-core"; +import type { Client } from "gel"; import { cookies } from "next/headers"; import { cache } from "react"; @@ -17,7 +17,7 @@ import { _extractParams, } from "../shared"; -export * from "@edgedb/auth-core/errors"; +export * from "@gel/auth-core/errors"; export { NextAuthSession, type NextAuthOptions, @@ -31,15 +31,16 @@ export class NextAppAuth extends NextAuth { const cookieStore = await cookies(); return new NextAuthSession( this.client, - cookieStore.get(this.options.authCookieName)?.value.split(";")[0] ?? null, + cookieStore.get(this.options.authCookieName)?.value.split(";")[0] || + cookieStore.get("edgedb-session")?.value.split(";")[0] || + null, ); }); createServerActions() { return { signout: async () => { - const cookieStore = await cookies(); - cookieStore.delete(this.options.authCookieName); + this.deleteAuthCookie(); }, emailPasswordSignIn: async ( data: FormData | { email: string; password: string }, @@ -101,9 +102,9 @@ export class NextAppAuth extends NextAuth { data: FormData | { reset_token: string; password: string }, ) => { const cookieStore = await cookies(); - const verifier = cookieStore.get( - this.options.pkceVerifierCookieName, - )?.value; + const verifier = + cookieStore.get(this.options.pkceVerifierCookieName)?.value || + cookieStore.get("edgedb-pkce-verifier")?.value; if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); } @@ -116,7 +117,7 @@ export class NextAppAuth extends NextAuth { await this.core ).resetPasswordWithResetToken(resetToken, verifier, password); await this.setAuthCookie(tokenData.auth_token); - cookieStore.delete(this.options.pkceVerifierCookieName); + this.deleteVerifierCookie(); return tokenData; }, emailPasswordResendVerificationEmail: async ( diff --git a/packages/auth-nextjs/src/pages/client.ts b/packages/auth-nextjs/src/pages/client.ts index 2cd8a6557..3e334a42c 100644 --- a/packages/auth-nextjs/src/pages/client.ts +++ b/packages/auth-nextjs/src/pages/client.ts @@ -4,9 +4,9 @@ import { NextAuthHelpers, type NextAuthOptions, } from "../shared.client"; -import { errorMapping } from "@edgedb/auth-core/utils"; +import { errorMapping } from "@gel/auth-core/utils"; -export * from "@edgedb/auth-core/errors"; +export * from "@gel/auth-core/errors"; export { type NextAuthOptions, type BuiltinProviderNames }; export default function createNextPagesClientAuth(options: NextAuthOptions) { diff --git a/packages/auth-nextjs/src/pages/server.ts b/packages/auth-nextjs/src/pages/server.ts index f044850e8..6f47f5436 100644 --- a/packages/auth-nextjs/src/pages/server.ts +++ b/packages/auth-nextjs/src/pages/server.ts @@ -1,5 +1,5 @@ -import { type Client } from "edgedb"; -import { type TokenData } from "@edgedb/auth-core"; +import { type Client } from "gel"; +import { type TokenData } from "@gel/auth-core"; import { type BuiltinProviderNames, type CreateAuthRouteHandlers, @@ -8,7 +8,7 @@ import { NextAuthSession, } from "../shared"; -export * from "@edgedb/auth-core/errors"; +export * from "@gel/auth-core/errors"; export { NextAuthSession, type NextAuthOptions, @@ -32,7 +32,9 @@ export class NextPagesAuth extends NextAuth { sessionCache.get(req) ?? new NextAuthSession( this.client, - req.cookies[this.options.authCookieName]?.split(";")[0] ?? null, + req.cookies[this.options.authCookieName]?.split(";")[0] || + req.cookies["edgedb-session"]?.split(";")[0] || + null, ); sessionCache.set(req, session); return session; diff --git a/packages/auth-nextjs/src/shared.client.ts b/packages/auth-nextjs/src/shared.client.ts index 9a3f8d881..09112b6e5 100644 --- a/packages/auth-nextjs/src/shared.client.ts +++ b/packages/auth-nextjs/src/shared.client.ts @@ -1,10 +1,10 @@ import { type BuiltinOAuthProviderNames, type emailPasswordProviderName, -} from "@edgedb/auth-core"; -import { WebAuthnClient } from "@edgedb/auth-core/webauthn"; +} from "@gel/auth-core"; +import { WebAuthnClient } from "@gel/auth-core/webauthn"; -export * as webauthn from "@edgedb/auth-core/webauthn"; +export * as webauthn from "@gel/auth-core/webauthn"; export type BuiltinProviderNames = | BuiltinOAuthProviderNames @@ -33,9 +33,9 @@ export abstract class NextAuthHelpers { this.options = { baseUrl: options.baseUrl.replace(/\/$/, ""), authRoutesPath: options.authRoutesPath?.replace(/^\/|\/$/g, "") ?? "auth", - authCookieName: options.authCookieName ?? "edgedb-session", + authCookieName: options.authCookieName ?? "gel-session", pkceVerifierCookieName: - options.pkceVerifierCookieName ?? "edgedb-pkce-verifier", + options.pkceVerifierCookieName ?? "gel-pkce-verifier", passwordResetPath: options.passwordResetPath, magicLinkFailurePath: options.magicLinkFailurePath, }; diff --git a/packages/auth-nextjs/src/shared.ts b/packages/auth-nextjs/src/shared.ts index e085bcf07..61e05e7e8 100644 --- a/packages/auth-nextjs/src/shared.ts +++ b/packages/auth-nextjs/src/shared.ts @@ -1,4 +1,4 @@ -import { type Client } from "edgedb"; +import { type Client } from "gel"; import { Auth, type BuiltinOAuthProviderNames, @@ -6,10 +6,10 @@ import { ConfigurationError, InvalidDataError, PKCEError, - EdgeDBAuthError, + GelAuthError, OAuthProviderFailureError, type SignupResponse, -} from "@edgedb/auth-core"; +} from "@gel/auth-core"; import { type BuiltinProviderNames, @@ -125,11 +125,6 @@ export abstract class NextAuth extends NextAuthHelpers { }); } - async deleteVerifierCookie() { - const cookieStore = await cookies(); - cookieStore.delete(this.options.pkceVerifierCookieName); - } - async setAuthCookie(token: string) { const cookieStore = await cookies(); const expirationDate = Auth.getTokenExpiration(token); @@ -144,6 +139,18 @@ export abstract class NextAuth extends NextAuthHelpers { }); } + async deleteVerifierCookie() { + const cookieStore = await cookies(); + cookieStore.delete(this.options.pkceVerifierCookieName); + cookieStore.delete("edgedb-pkce-verifier"); + } + + async deleteAuthCookie() { + const cookieStore = await cookies(); + cookieStore.delete(this.options.authCookieName); + cookieStore.delete("edgedb-session"); + } + public oAuth = { /** * Start the OAuth flow by getting the OAuth configuration from the request @@ -261,6 +268,10 @@ export abstract class NextAuth extends NextAuthHelpers { req: NextRequest, ctx: { params: Promise<{ auth: string[] }> }, ) => { + const verifier = + req.cookies.get(this.options.pkceVerifierCookieName)?.value || + req.cookies.get("edgedb-pkce-verifier")?.value; + const params = await ctx.params; switch (params.auth.join("/")) { case "oauth": { @@ -292,9 +303,6 @@ export abstract class NextAuth extends NextAuthHelpers { const code = req.nextUrl.searchParams.get("code"); const isSignUp = req.nextUrl.searchParams.get("isSignUp") === "true"; - const verifier = req.cookies.get( - this.options.pkceVerifierCookieName, - )?.value; if (!code) { return onOAuthCallback( { @@ -345,9 +353,6 @@ export abstract class NextAuth extends NextAuthHelpers { } const verificationToken = req.nextUrl.searchParams.get("verification_token"); - const verifier = req.cookies.get( - this.options.pkceVerifierCookieName, - )?.value; if (!verificationToken) { return onEmailVerify( { @@ -414,9 +419,6 @@ export abstract class NextAuth extends NextAuthHelpers { } const verificationToken = req.nextUrl.searchParams.get("verification_token"); - const verifier = req.cookies.get( - this.options.pkceVerifierCookieName, - )?.value; if (!verificationToken) { return onEmailVerify( { @@ -474,9 +476,6 @@ export abstract class NextAuth extends NextAuthHelpers { const code = req.nextUrl.searchParams.get("code"); const isSignUp = req.nextUrl.searchParams.get("isSignUp") === "true"; - const verifier = req.cookies.get( - this.options.pkceVerifierCookieName, - )?.value; if (!code) { return onMagicLinkCallback( { @@ -527,7 +526,7 @@ export abstract class NextAuth extends NextAuthHelpers { const desc = req.nextUrl.searchParams.get("error_description"); return onBuiltinUICallback( { - error: new EdgeDBAuthError(error + (desc ? `: ${desc}` : "")), + error: new GelAuthError(error + (desc ? `: ${desc}` : "")), }, req, ); @@ -556,9 +555,6 @@ export abstract class NextAuth extends NextAuthHelpers { req, ); } - const verifier = req.cookies.get( - this.options.pkceVerifierCookieName, - )?.value; if (!verifier) { return onBuiltinUICallback( { @@ -614,8 +610,7 @@ export abstract class NextAuth extends NextAuthHelpers { `'onSignout' auth route handler not configured`, ); } - const cookieStore = await cookies(); - cookieStore.delete(this.options.authCookieName); + this.deleteAuthCookie(); return onSignout(req); } default: @@ -747,9 +742,9 @@ export abstract class NextAuth extends NextAuthHelpers { } let tokenData: TokenData; try { - const verifier = req.cookies.get( - this.options.pkceVerifierCookieName, - )?.value; + const verifier = + req.cookies.get(this.options.pkceVerifierCookieName)?.value || + req.cookies.get("edgedb-pkce-verifier")?.value; if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); } @@ -1034,7 +1029,7 @@ function _wrapResponse(res: Promise | undefined, isAction: boolean) { function _wrapError(err: Error) { return { _error: { - type: err instanceof EdgeDBAuthError ? err.type : null, + type: err instanceof GelAuthError ? err.type : null, message: err instanceof Error ? err.message : String(err), }, }; diff --git a/packages/auth-remix/package.json b/packages/auth-remix/package.json index 1db864d26..2ff724918 100644 --- a/packages/auth-remix/package.json +++ b/packages/auth-remix/package.json @@ -1,12 +1,12 @@ { - "name": "@edgedb/auth-remix", - "description": "Helper library to integrate the EdgeDB Auth extension with Remix", + "name": "@gel/auth-remix", + "description": "Helper library to integrate the Gel Auth extension with Remix", "version": "0.2.2", - "author": "EdgeDB ", + "author": "Gel ", "type": "module", "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git", + "url": "https://github.com/geldata/gel-js.git", "directory": "packages/auth-remix" }, "license": "Apache-2.0", @@ -23,14 +23,14 @@ "devDependencies": { "@repo/tsconfig": "*", "@types/node": "^20.12.13", - "edgedb": "*", + "gel": "*", "typescript": "^5.5.2" }, "peerDependencies": { - "edgedb": "^1.3.6" + "gel": "^1.3.6" }, "dependencies": { - "@edgedb/auth-core": "^0.2.1", + "@gel/auth-core": "^0.2.1", "@remix-run/server-runtime": "^2.9.2", "cookie": "^0.6.0" }, diff --git a/packages/auth-remix/readme.md b/packages/auth-remix/readme.md index 05d5b5783..71fd29b3d 100644 --- a/packages/auth-remix/readme.md +++ b/packages/auth-remix/readme.md @@ -1,4 +1,4 @@ -# @edgedb/auth-remix +# @gel/auth-remix This library provides a set of utilities to help you integrate authentication into your [Remix](https://remix.run/) application. It supports authentication with various OAuth providers, as well as email/password authentication. @@ -8,15 +8,16 @@ It supports authentication with various OAuth providers, as well as email/passwo This package is published on npm and can be installed with your package manager of choice. ```bash -npm install @edgedb/auth-remix +npm install @gel/auth-remix ``` ## Setup **Prerequisites**: + - Node v18+ - **Note**: Due to using the `crypto` global, you will need to start Node with `--experimental-global-webcrypto`. You can add this option to your `NODE_OPTIONS` environment variable, like `NODE_OPTIONS='--experimental-global-webcrypto'` in the appropriate `.env` file. -- Before adding EdgeDB auth to your Remix app, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers (you can do this in CLI or EdgeDB UI). Refer to the auth extension docs for details on how to do this. +- Before adding Gel auth to your Remix app, you will first need to enable the `auth` extension in your Gel schema, and have configured the extension with some providers (you can do this in CLI or Gel UI). Refer to the auth extension docs for details on how to do this. 1. Initialize the client auth helper by passing configuration options to `createClientAuth()`. This will return a `RemixClientAuth` object which you can use in your components. You can skip this part if you find it unnecessary and provide all your data through the loader (the next step), but we suggest having the client auth too and use it directly in your components to get OAuth, BuiltinUI and signout URLs. @@ -25,7 +26,7 @@ npm install @edgedb/auth-remix import createClientAuth, { type RemixAuthOptions, -} from "@edgedb/auth-remix/client"; +} from "@gel/auth-remix/client"; export const options: RemixAuthOptions = { baseUrl: "http://localhost:3000", @@ -37,13 +38,13 @@ const auth = createClientAuth(options); export default auth; ``` -2. Initialize the server auth helper by passing an EdgeDB `Client` object to `createServerAuth()`, along with configuration options. This will return a `RemixServerAuth` object which you can use across your app on the server side. +2. Initialize the server auth helper by passing an Gel `Client` object to `createServerAuth()`, along with configuration options. This will return a `RemixServerAuth` object which you can use across your app on the server side. ```ts // app/services/auth.server.ts - import createServerAuth from "@edgedb/auth-remix/server"; - import { createClient } from "edgedb"; + import createServerAuth from "@gel/auth-remix/server"; + import { createClient } from "gel"; import { options } from "./auth"; export const client = createClient({ @@ -58,8 +59,8 @@ export default auth; - `baseUrl: string`, _required_, The url of your application; needed for various auth flows (eg. OAuth) to redirect back to. - `authRoutesPath?: string`, The path to the auth route handlers, defaults to `'auth'`, see below for more details. - - `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to `'edgedb-session'`. - - `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to `'edgedb-pkce-verifier'` + - `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to `'gel-session'`. + - `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to `'gel-pkce-verifier'` - `passwordResetUrl?: string`: The url of the the password reset page; needed if you want to enable password reset emails in your app. 3. Setup the auth route handlers, with `auth.createAuthRouteHandlers()`. Callback functions can be provided to handle various auth events, where you can define what to do in the case of successful signin's or errors. You only need to configure callback functions for the types of auth you wish to use in your app. @@ -89,7 +90,7 @@ export default auth; By default the handlers expect to exist under the `/routes/auth` path in your app, however if you want to place them elsewhere, you will also need to configure the `authRoutesPath` option of `createServerAuth` to match. -4. Now we just need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the EdgeDB Auth's builtin UI. Or alternatively you can implement your own custom UI. +4. Now we just need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the Gel Auth's builtin UI. Or alternatively you can implement your own custom UI. **Builtin UI** @@ -108,7 +109,7 @@ export default auth; - `emailPasswordResetPassword` - `signout` - `isPasswordResetTokenValid(resetToken: string)`: Checks if a password reset token is still valid. - - `getOAuthUrl(providerName: string)`: This method takes the name of an OAuth provider (make sure you configure providers you need in the auth ext config first using CLI or EdgeDB UI) and returns a link that will initiate the OAuth sign in flow for that provider. You will also need to configure the `onOAuthCallback` auth route handler. + - `getOAuthUrl(providerName: string)`: This method takes the name of an OAuth provider (make sure you configure providers you need in the auth ext config first using CLI or Gel UI) and returns a link that will initiate the OAuth sign in flow for that provider. You will also need to configure the `onOAuthCallback` auth route handler. ## Usage diff --git a/packages/auth-remix/src/client.ts b/packages/auth-remix/src/client.ts index fd81c9ea9..5440d88f3 100644 --- a/packages/auth-remix/src/client.ts +++ b/packages/auth-remix/src/client.ts @@ -1,5 +1,5 @@ -import type { BuiltinOAuthProviderNames } from "@edgedb/auth-core"; -import { WebAuthnClient } from "@edgedb/auth-core/webauthn"; +import type { BuiltinOAuthProviderNames } from "@gel/auth-core"; +import { WebAuthnClient } from "@gel/auth-core/webauthn"; export interface RemixAuthOptions { baseUrl: string; @@ -27,8 +27,8 @@ export class RemixClientAuth { /** @internal */ constructor(options: RemixAuthOptions) { this.options = { - authCookieName: "edgedb-session", - pkceVerifierCookieName: "edgedb-pkce-verifier", + authCookieName: "gel-session", + pkceVerifierCookieName: "gel-pkce-verifier", ...options, baseUrl: options.baseUrl.replace(/\/$/, ""), authRoutesPath: options.authRoutesPath?.replace(/^\/|\/$/g, "") ?? "auth", diff --git a/packages/auth-remix/src/server.ts b/packages/auth-remix/src/server.ts index d55941ccb..c72957c5d 100644 --- a/packages/auth-remix/src/server.ts +++ b/packages/auth-remix/src/server.ts @@ -1,6 +1,6 @@ import { redirect, json, type TypedResponse } from "@remix-run/server-runtime"; import * as cookie from "cookie"; -import type { Client } from "edgedb"; +import type { Client } from "gel"; import { Auth, builtinOAuthProviderNames, @@ -12,14 +12,14 @@ import { PKCEError, BackendError, OAuthProviderFailureError, - EdgeDBAuthError, + GelAuthError, MagicLinkFailureError, type AuthenticationResponseJSON, type RegistrationResponseJSON, -} from "@edgedb/auth-core"; +} from "@gel/auth-core"; import { type RemixAuthOptions, RemixClientAuth } from "./client.js"; -export * from "@edgedb/auth-core/errors"; +export * from "@gel/auth-core/errors"; export type { TokenData, RemixAuthOptions }; export type BuiltinProviderNames = @@ -118,7 +118,7 @@ export class RemixServerAuth extends RemixClientAuth { getSession(req: Request) { return new RemixAuthSession( this.client, - parseCookies(req)[this.options.authCookieName], + parseCookies(req, this.options).authCookie, ); } @@ -218,8 +218,7 @@ export class RemixServerAuth extends RemixClientAuth { } const code = searchParams.get("code"); const isSignUp = searchParams.get("isSignUp") === "true"; - const verifier = - parseCookies(req)[this.options.pkceVerifierCookieName]; + const verifier = parseCookies(req, this.options).pkceVerifierCookie; if (!code) { return cbCall(onOAuthCallback, { error: new PKCEError("no pkce code in response"), @@ -238,18 +237,10 @@ export class RemixServerAuth extends RemixClientAuth { error: err instanceof Error ? err : new Error(String(err)), }); } - const headers = new Headers(); - headers.append( - "Set-Cookie", - this.createAuthCookie(tokenData.auth_token), - ); - headers.append( - "Set-Cookie", - cookie.serialize(this.options.pkceVerifierCookieName, "", { - maxAge: 0, - path: "/", - }), - ); + const headers = new Headers({ + "Set-Cookie": this.createAuthCookie(tokenData.auth_token), + }); + deleteVerifierCookie(headers, this.options.pkceVerifierCookieName); return cbCall( onOAuthCallback, { @@ -281,8 +272,7 @@ export class RemixServerAuth extends RemixClientAuth { } const code = searchParams.get("code"); const isSignUp = searchParams.get("isSignUp") === "true"; - const verifier = - parseCookies(req)[this.options.pkceVerifierCookieName]; + const verifier = parseCookies(req, this.options).pkceVerifierCookie; if (!code) { return cbCall(onMagicLinkCallback, { error: new PKCEError("no pkce code in response"), @@ -301,18 +291,10 @@ export class RemixServerAuth extends RemixClientAuth { error: err instanceof Error ? err : new Error(String(err)), }); } - const headers = new Headers(); - headers.append( - "Set-Cookie", - this.createAuthCookie(tokenData.auth_token), - ); - headers.append( - "Set-Cookie", - cookie.serialize(this.options.pkceVerifierCookieName, "", { - maxAge: 0, - path: "/", - }), - ); + const headers = new Headers({ + "Set-Cookie": this.createAuthCookie(tokenData.auth_token), + }); + deleteVerifierCookie(headers, this.options.pkceVerifierCookieName); return cbCall( onMagicLinkCallback, { @@ -334,7 +316,7 @@ export class RemixServerAuth extends RemixClientAuth { if (error) { const desc = searchParams.get("error_description"); return cbCall(onBuiltinUICallback, { - error: new EdgeDBAuthError(error + (desc ? `: ${desc}` : "")), + error: new GelAuthError(error + (desc ? `: ${desc}` : "")), }); } const code = searchParams.get("code"); @@ -354,8 +336,7 @@ export class RemixServerAuth extends RemixClientAuth { error: new PKCEError("no pkce code in response"), }); } - const verifier = - parseCookies(req)[this.options.pkceVerifierCookieName]; + const verifier = parseCookies(req, this.options).pkceVerifierCookie; if (!verifier) { return cbCall(onBuiltinUICallback, { @@ -414,8 +395,7 @@ export class RemixServerAuth extends RemixClientAuth { ); } const verificationToken = searchParams.get("verification_token"); - const verifier = - parseCookies(req)[this.options.pkceVerifierCookieName]; + const verifier = parseCookies(req, this.options).pkceVerifierCookie; if (!verificationToken) { return cbCall(onEmailVerify, { error: new PKCEError("no verification_token in response"), @@ -441,6 +421,7 @@ export class RemixServerAuth extends RemixClientAuth { const headers = new Headers({ "Set-Cookie": this.createAuthCookie(tokenData.auth_token), }); + deleteVerifierCookie(headers, this.options.pkceVerifierCookieName); return cbCall( onEmailVerify, { @@ -478,8 +459,7 @@ export class RemixServerAuth extends RemixClientAuth { ); } const verificationToken = searchParams.get("verification_token"); - const verifier = - parseCookies(req)[this.options.pkceVerifierCookieName]; + const verifier = parseCookies(req, this.options).pkceVerifierCookie; if (!verificationToken) { return cbCall(onEmailVerify, { error: new PKCEError("no verification_token in response"), @@ -505,6 +485,7 @@ export class RemixServerAuth extends RemixClientAuth { const headers = new Headers({ "Set-Cookie": this.createAuthCookie(tokenData.auth_token), }); + deleteVerifierCookie(headers, this.options.pkceVerifierCookieName); return cbCall( onEmailVerify, { @@ -521,14 +502,9 @@ export class RemixServerAuth extends RemixClientAuth { `'onSignout' auth route handler not configured`, ); } - const headers = new Headers({ - "Set-Cookie": cookie.serialize(this.options.authCookieName, "", { - httpOnly: true, - sameSite: "strict", - path: "/", - maxAge: 0, - }), - }); + + const headers = deleteAuthCookie(this.options.authCookieName); + return cbCall(onSignout, undefined, headers); } @@ -957,7 +933,7 @@ export class RemixServerAuth extends RemixClientAuth { > { return handleAction( async (data, headers, req) => { - const verifier = parseCookies(req)[this.options.pkceVerifierCookieName]; + const verifier = parseCookies(req, this.options).pkceVerifierCookie; if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); @@ -978,13 +954,7 @@ export class RemixServerAuth extends RemixClientAuth { this.createAuthCookie(tokenData.auth_token), ); - headers.append( - "Set-Cookie", - cookie.serialize(this.options.pkceVerifierCookieName, "", { - maxAge: 0, - path: "/", - }), - ); + deleteVerifierCookie(headers, this.options.pkceVerifierCookieName); return { tokenData }; }, @@ -1116,14 +1086,7 @@ export class RemixServerAuth extends RemixClientAuth { } | (Res extends Response ? Res : TypedResponse) > { - const headers = new Headers({ - "Set-Cookie": cookie.serialize(this.options.authCookieName, "", { - httpOnly: true, - sameSite: "strict", - maxAge: 0, - path: "/", - }), - }); + const headers = deleteAuthCookie(this.options.authCookieName); if (cb) return actionCbCall(cb, headers); @@ -1131,9 +1094,35 @@ export class RemixServerAuth extends RemixClientAuth { } } -function parseCookies(req: Request) { - const cookies = req.headers.get("Cookie"); - return cookie.parse(cookies || ""); +function deleteVerifierCookie(headers: Headers, verifierCookieName: string) { + const cookies = [verifierCookieName, "edgedb-pkce-verifier"]; + cookies.forEach((c) => + headers.append( + "Set-Cookie", + cookie.serialize(c, "", { + maxAge: 0, + path: "/", + }), + ), + ); +} + +function deleteAuthCookie(authCookieName: string) { + const headers = new Headers(); + const cookies = [authCookieName, "edgedb-session"]; + cookies.forEach((c) => + headers.append( + "Set-Cookie", + cookie.serialize(c, "", { + httpOnly: true, + sameSite: "strict" as const, + maxAge: 0, + path: "/", + }), + ), + ); + + return headers; } function _extractParams( @@ -1169,6 +1158,23 @@ function _extractParams( return params; } +function parseCookies( + req: Request, + options: { + authCookieName: string; + pkceVerifierCookieName: string; + }, +) { + const cookies = req.headers.get("Cookie") || ""; + const parsed = cookie.parse(cookies); + + return { + authCookie: parsed[options.authCookieName] || parsed["edgedb-session"], + pkceVerifierCookie: + parsed[options.pkceVerifierCookieName] || parsed["edgedb-pkce-verifier"], + }; +} + async function handleAction | FormData>( action: (data: DataT, headers: Headers, req: Request) => Promise, req: Request, diff --git a/packages/auth-sveltekit/package.json b/packages/auth-sveltekit/package.json index 841ec79aa..144aa735d 100644 --- a/packages/auth-sveltekit/package.json +++ b/packages/auth-sveltekit/package.json @@ -1,12 +1,12 @@ { - "name": "@edgedb/auth-sveltekit", - "description": "Helper library to integrate the EdgeDB Auth extension with Sveltekit.", + "name": "@gel/auth-sveltekit", + "description": "Helper library to integrate the Gel Auth extension with Sveltekit.", "version": "0.2.3", - "author": "EdgeDB ", + "author": "Gel ", "type": "module", "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git", + "url": "https://github.com/geldata/gel-js.git", "directory": "packages/auth-sveltekit" }, "license": "Apache-2.0", @@ -24,16 +24,16 @@ "@repo/tsconfig": "*", "@sveltejs/kit": "^2.5.10", "@types/node": "^20.12.13", - "edgedb": "*", + "gel": "*", "svelte": "^4.2.17", "typescript": "^5.5.2", "vite": "^5.2.12" }, "peerDependencies": { - "edgedb": "^1.3.6" + "gel": "^1.3.6" }, "dependencies": { - "@edgedb/auth-core": "^0.2.1" + "@gel/auth-core": "^0.2.1" }, "exports": { "./*": "./dist/*.js" diff --git a/packages/auth-sveltekit/readme.md b/packages/auth-sveltekit/readme.md index 4654b5f03..f70544dd6 100644 --- a/packages/auth-sveltekit/readme.md +++ b/packages/auth-sveltekit/readme.md @@ -1,4 +1,4 @@ -# @edgedb/auth-sveltekit +# @gel/auth-sveltekit This library provides a set of utilities to help you integrate authentication into your [SvelteKit](https://kit.svelte.dev/) application. It supports authentication with various OAuth providers, as well as email/password authentication. @@ -8,15 +8,16 @@ It supports authentication with various OAuth providers, as well as email/passwo This package is published on npm and can be installed with your package manager of choice. ```bash -npm install @edgedb/auth-sveltekit +npm install @gel/auth-sveltekit ``` ## Setup **Prerequisites**: + - Node v18+ - **Note**: Due to using the `crypto` global, you will need to start Node with `--experimental-global-webcrypto`. You can add this option to your `NODE_OPTIONS` environment variable, like `NODE_OPTIONS='--experimental-global-webcrypto'` in the appropriate `.env` file. -- Before adding EdgeDB auth to your SvelteKit app, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers (you can do this in CLI or EdgeDB UI). Refer to the auth extension docs for details on how to do this. +- Before adding Gel auth to your SvelteKit app, you will first need to enable the `auth` extension in your Gel schema, and have configured the extension with some providers (you can do this in CLI or Gel UI). Refer to the auth extension docs for details on how to do this. ### Client auth helper @@ -25,9 +26,7 @@ Initialize the client auth helper by passing configuration options to `createCli ```ts // src/lib/auth.ts -import createClientAuth, { - type AuthOptions, -} from "@edgedb/auth-sveltekit/client"; +import createClientAuth, { type AuthOptions } from "@gel/auth-sveltekit/client"; export const options: AuthOptions = { baseUrl: "http://localhost:5173", @@ -43,18 +42,18 @@ The available auth config options are as follows: - `baseUrl: string`, _required_, The url of your application; needed for various auth flows (eg. OAuth) to redirect back to. - `authRoutesPath?: string`, The path to the auth route handlers, defaults to `'auth'`, see below for more details. -- `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to `'edgedb-session'`. -- `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to `'edgedb-pkce-verifier'` +- `authCookieName?: string`, The name of the cookie where the auth token will be stored, defaults to `'gel-session'`. +- `pkceVerifierCookieName?: string`: The name of the cookie where the verifier for the PKCE flow will be stored, defaults to `'gel-pkce-verifier'` - `passwordResetUrl?: string`: The url of the the password reset page; needed if you want to enable password reset emails in your app.   -### EdgeDB client +### Gel client -Lets create an EdgeDB client that you will need for creating server auth client. +Lets create an Gel client that you will need for creating server auth client. ```ts // src/lib/server/auth.ts -import { createClient } from "edgedb"; +import { createClient } from "gel"; export const client = createClient({ //Note: when developing locally you will need to set tls security to insecure, because the dev server uses self-signed certificates which will cause api calls with the fetch api to fail. @@ -64,13 +63,11 @@ export const client = createClient({ ### Server auth client -Create the server auth client in a handle hook. Firstly call `serverAuth` passing to it EdgeDB client you created in the previous step, along with configuration options from step 1. This will give you back the `createServerRequestAuth` and `createAuthRouteHook`. You should call `createServerRequestAuth` inside a handle to attach the server client to `event.locals`. Calling `createAuthRouteHook` will give you back a hook so you should just invoke it inside `sequence` and pass your auth route handlers to it. +Create the server auth client in a handle hook. Firstly call `serverAuth` passing to it Gel client you created in the previous step, along with configuration options from step 1. This will give you back the `createServerRequestAuth` and `createAuthRouteHook`. You should call `createServerRequestAuth` inside a handle to attach the server client to `event.locals`. Calling `createAuthRouteHook` will give you back a hook so you should just invoke it inside `sequence` and pass your auth route handlers to it. You can now access the server auth in all actions and load functions through `event.locals`. ```ts -import serverAuth, { - type AuthRouteHandlers, -} from "@edgedb/auth-sveltekit/server"; +import serverAuth, { type AuthRouteHandlers } from "@gel/auth-sveltekit/server"; import { redirect, type Handle } from "@sveltejs/kit"; import { sequence } from "@sveltejs/kit/hooks"; import { client } from "$lib/server/auth"; @@ -79,7 +76,7 @@ import { options } from "$lib/auth"; const { createServerRequestAuth, createAuthRouteHook } = serverAuth( client, - options + options, ); const createServerAuthClient: Handle = ({ event, resolve }) => { @@ -100,14 +97,14 @@ const authRouteHandlers: AuthRouteHandlers = { export const handle = sequence( createServerAuthClient, - createAuthRouteHook(authRouteHandlers) + createAuthRouteHook(authRouteHandlers), ); ``` \* If you use typescript you need to update `Locals` type with `auth` so that auth is correctly recognized throughout the project: ```ts -import type { ServerRequestAuth } from "@edgedb/auth-sveltekit/server"; +import type { ServerRequestAuth } from "@gel/auth-sveltekit/server"; declare global { namespace App { @@ -135,7 +132,7 @@ In any of them you can define what to do in case of success or error. Every hand ### UI -Now we just need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the EdgeDB Auth's builtin UI. Or alternatively you can implement your own custom UI. +Now we just need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the Gel Auth's builtin UI. Or alternatively you can implement your own custom UI. **Builtin UI** @@ -154,7 +151,7 @@ To help with implementing your own custom auth UI, the `auth` object has a numbe - `emailPasswordResetPassword(data: { reset_token: string; password: string } | FormData)` - `signout()` - `isPasswordResetTokenValid(resetToken: string)`: Checks if a password reset token is still valid. -- `getOAuthUrl(providerName: string)`: This method takes the name of an OAuth provider (make sure you configure providers you need in the auth ext config first using CLI or EdgeDB UI) and returns a link that will initiate the OAuth sign in flow for that provider. You will also need to configure the `onOAuthCallback` auth route handler. +- `getOAuthUrl(providerName: string)`: This method takes the name of an OAuth provider (make sure you configure providers you need in the auth ext config first using CLI or Gel UI) and returns a link that will initiate the OAuth sign in flow for that provider. You will also need to configure the `onOAuthCallback` auth route handler. ## Usage diff --git a/packages/auth-sveltekit/src/client.ts b/packages/auth-sveltekit/src/client.ts index 7d77a3ac4..d0575f3f7 100644 --- a/packages/auth-sveltekit/src/client.ts +++ b/packages/auth-sveltekit/src/client.ts @@ -1,5 +1,5 @@ -import type { BuiltinOAuthProviderNames } from "@edgedb/auth-core"; -import { WebAuthnClient } from "@edgedb/auth-core/webauthn"; +import type { BuiltinOAuthProviderNames } from "@gel/auth-core"; +import { WebAuthnClient } from "@gel/auth-core/webauthn"; export interface AuthOptions { baseUrl: string; @@ -23,9 +23,9 @@ export function getConfig(options: AuthOptions) { return { baseUrl, authRoutesPath, - authCookieName: options.authCookieName ?? "edgedb-session", + authCookieName: options.authCookieName ?? "gel-session", pkceVerifierCookieName: - options.pkceVerifierCookieName ?? "edgedb-pkce-verifier", + options.pkceVerifierCookieName ?? "gel-pkce-verifier", passwordResetPath: options.passwordResetPath, magicLinkFailurePath: options.magicLinkFailurePath, authRoute: `${baseUrl}/${authRoutesPath}`, diff --git a/packages/auth-sveltekit/src/server.ts b/packages/auth-sveltekit/src/server.ts index 253e98c1d..5b0500157 100644 --- a/packages/auth-sveltekit/src/server.ts +++ b/packages/auth-sveltekit/src/server.ts @@ -4,7 +4,7 @@ import { type RequestEvent, type Handle, } from "@sveltejs/kit"; -import type { Client } from "edgedb"; +import type { Client } from "gel"; import { Auth, builtinOAuthProviderNames, @@ -16,11 +16,11 @@ import { PKCEError, InvalidDataError, OAuthProviderFailureError, - EdgeDBAuthError, + GelAuthError, MagicLinkFailureError, type AuthenticationResponseJSON, type RegistrationResponseJSON, -} from "@edgedb/auth-core"; +} from "@gel/auth-core"; import { ClientAuth, getConfig, @@ -28,7 +28,7 @@ import { type AuthOptions, } from "./client.js"; -export * from "@edgedb/auth-core/errors"; +export * from "@gel/auth-core/errors"; export type { TokenData, AuthOptions, Client }; export type BuiltinProviderNames = @@ -163,17 +163,20 @@ export class ServerRequestAuth extends ClientAuth { private deleteVerifierCookie() { deleteCookie(this.cookies, this.config.pkceVerifierCookieName); + deleteCookie(this.cookies, "edgedb-pkce-verifier"); } private deleteAuthCookie() { deleteCookie(this.cookies, this.config.authCookieName); + deleteCookie(this.cookies, "edgedb-session"); } get session() { if (!this._session) { this._session = new AuthSession( this.client, - this.cookies.get(this.config.authCookieName), + this.cookies.get(this.config.authCookieName) || + this.cookies.get("edgedb-session"), ); } @@ -308,7 +311,9 @@ export class ServerRequestAuth extends ClientAuth { async emailPasswordResetPassword( data: { reset_token: string; password: string } | FormData, ): Promise<{ tokenData: TokenData }> { - const verifier = this.cookies.get(this.config.pkceVerifierCookieName); + const verifier = + this.cookies.get(this.config.pkceVerifierCookieName) || + this.cookies.get("edgedb-pkce-verifier"); if (!verifier) { throw new PKCEError("no pkce verifier cookie found"); @@ -487,6 +492,18 @@ async function handleAuthRoutes( const searchParams = url.searchParams; const path = url.pathname.split("/").slice(2).join("/"); + function deleteVerifierCookie() { + deleteCookie(cookies, config.pkceVerifierCookieName); + deleteCookie(cookies, "edgedb-pkce-verifier"); + } + + function getVerifierCookie() { + return ( + cookies.get(config.pkceVerifierCookieName) || + cookies.get("edgedb-pkce-verifier") + ); + } + switch (path) { case "oauth": { if (!onOAuthCallback) { @@ -532,7 +549,7 @@ async function handleAuthRoutes( } const code = searchParams.get("code"); const isSignUp = searchParams.get("isSignUp") === "true"; - const verifier = cookies.get(config.pkceVerifierCookieName); + const verifier = getVerifierCookie(); if (!code) { return onOAuthCallback({ error: new PKCEError("no pkce code in response"), @@ -554,7 +571,7 @@ async function handleAuthRoutes( setAuthCookie(cookies, config, tokenData.auth_token); - deleteCookie(cookies, config.pkceVerifierCookieName); + deleteVerifierCookie(); return onOAuthCallback({ error: null, @@ -574,7 +591,7 @@ async function handleAuthRoutes( if (error) { const desc = searchParams.get("error_description"); return onBuiltinUICallback({ - error: new EdgeDBAuthError(error + (desc ? `: ${desc}` : "")), + error: new GelAuthError(error + (desc ? `: ${desc}` : "")), }); } const code = searchParams.get("code"); @@ -594,7 +611,7 @@ async function handleAuthRoutes( error: new PKCEError("no pkce code in response"), }); } - const verifier = cookies.get(config.pkceVerifierCookieName); + const verifier = getVerifierCookie(); if (!verifier) { return onBuiltinUICallback({ @@ -646,7 +663,7 @@ async function handleAuthRoutes( ); } const verificationToken = searchParams.get("verification_token"); - const verifier = cookies.get(config.pkceVerifierCookieName); + const verifier = getVerifierCookie(); if (!verificationToken) { return onEmailVerify({ error: new PKCEError("no verification_token in response"), @@ -672,6 +689,8 @@ async function handleAuthRoutes( setAuthCookie(cookies, config, tokenData.auth_token); + deleteVerifierCookie(); + return onEmailVerify({ error: null, tokenData, @@ -695,7 +714,7 @@ async function handleAuthRoutes( const code = searchParams.get("code"); const isSignUp = searchParams.get("isSignUp") === "true"; - const verifier = cookies.get(config.pkceVerifierCookieName); + const verifier = getVerifierCookie(); if (!code) { return onMagicLinkCallback({ error: new PKCEError("no pkce code in response"), @@ -719,7 +738,7 @@ async function handleAuthRoutes( setAuthCookie(cookies, config, tokenData.auth_token); - deleteCookie(cookies, config.pkceVerifierCookieName); + deleteVerifierCookie(); return onMagicLinkCallback({ error: null, @@ -753,7 +772,7 @@ async function handleAuthRoutes( ); } const verificationToken = searchParams.get("verification_token"); - const verifier = cookies.get(config.pkceVerifierCookieName); + const verifier = getVerifierCookie(); if (!verificationToken) { return onEmailVerify({ error: new PKCEError("no verification_token in response"), @@ -779,6 +798,8 @@ async function handleAuthRoutes( setAuthCookie(cookies, config, tokenData.auth_token); + deleteVerifierCookie(); + return onEmailVerify({ error: null, tokenData, @@ -793,6 +814,8 @@ async function handleAuthRoutes( } deleteCookie(cookies, config.authCookieName); + deleteCookie(cookies, "edgedb-session"); + return onSignout(); } diff --git a/packages/create/README.md b/packages/create/README.md index 077df4940..357970777 100644 --- a/packages/create/README.md +++ b/packages/create/README.md @@ -1,26 +1,26 @@ -# `@edgedb/create`: Project scaffolding for EdgeDB-backed applications +# `@gel/create`: Project scaffolding for Gel-backed applications -The `@edgedb/create` package provides a starting point for various frameworks with everything you need to start building an EdgeDB-backed application. We aim to follow the same conventions as the original "create-app" templates, but with EdgeDB as the database. There are a few different templates to choose from, including: Next.js, Remix, Express, Node HTTP Server. +The `@gel/create` package provides a starting point for various frameworks with everything you need to start building an Gel-backed application. We aim to follow the same conventions as the original "create-app" templates, but with Gel as the database. There are a few different templates to choose from, including: Next.js, Remix, Express, Node HTTP Server. Important points to note: - **Upstream changes:** We try to actively monitor and incorporate significant changes from the original "create-app" templates to to ensure developers have access to the latest features and best practices. - **Support for major options:** While we strive to support the major options offered by the upstream "create-apps", we might not cover every possible configuration or permutation due to the vast scope of possibilities. -- **EdgeDB CLI installation:** For users who do not have the EdgeDB CLI installed, we automatically install it using our typical installation procedure. +- **Gel CLI installation:** For users who do not have the Gel CLI installed, we automatically install it using our typical installation procedure. ## Usage ```bash -$ npm create @edgedb +$ npm create @gel # or -yarn create @edgedb +yarn create @gel # or -pnpm create @edgedb +pnpm create @gel # or -bun create @edgedb +bun create @gel ``` -After running the command, you will be prompted to provide a project name and choose a template. You can also specify whether to use EdgeDB Auth, initialize a git repository, and install dependencies. +After running the command, you will be prompted to provide a project name and choose a template. You can also specify whether to use Gel Auth, initialize a git repository, and install dependencies. The tool will then create a new directory with the specified name and set up the project. @@ -42,7 +42,7 @@ Navigate into `packages/create`: $ cd packages/create ``` -Build `@edgedb/generate` +Build `@gel/generate` ```bash $ yarn build diff --git a/packages/create/package.json b/packages/create/package.json index 487e60c7a..ee24ded5b 100644 --- a/packages/create/package.json +++ b/packages/create/package.json @@ -1,16 +1,17 @@ { - "name": "@edgedb/create", + "name": "@gel/create", "version": "0.2.2", "type": "module", - "description": "Create a new EdgeDB-based project", - "homepage": "https://edgedb.com/docs", - "author": "EdgeDB ", + "description": "Create a new Gel-based project", + "homepage": "https://geldata.com/docs", + "author": "Gel ", "engines": { "node": ">= 18.0.0" }, "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git" + "url": "https://github.com/geldata/gel-js.git", + "directory": "packages/create" }, "license": "Apache-2.0", "sideEffects": false, diff --git a/packages/create/src/cli.ts b/packages/create/src/cli.ts index 29183db6c..b1ed4d5e7 100755 --- a/packages/create/src/cli.ts +++ b/packages/create/src/cli.ts @@ -6,7 +6,7 @@ import pc from "picocolors"; import { baseRecipe, recipes as _recipes } from "./recipes/index.js"; async function main() { - p.intro("Welcome to the EdgeDB Create CLI 🚀"); + p.intro("Welcome to the Gel Create CLI 🚀"); const baseOptions = await baseRecipe.getOptions(); const recipeOptions: any[] = []; @@ -25,14 +25,14 @@ async function main() { } p.outro(`\ -Your EdgeDB project has been initialized! 🚀 +Your Gel project has been initialized! 🚀 Enter your project directory using: ${pc.green( `cd ${baseOptions.projectName}`, )} Follow the instructions in the ${pc.green("README.md")} file to get started. -Need help? Join our community at ${pc.green("https://edgedb.com/community")}`); +Need help? Join our community at ${pc.green("https://geldata.com/community")}`); } await main(); diff --git a/packages/create/src/recipes/_base/index.ts b/packages/create/src/recipes/_base/index.ts index 028ebf3ea..42866a762 100644 --- a/packages/create/src/recipes/_base/index.ts +++ b/packages/create/src/recipes/_base/index.ts @@ -9,7 +9,7 @@ import { updatePackage } from "write-package"; import { getPackageManager, copyTemplateFiles } from "../../utils.js"; import type { Framework, BaseRecipe, BaseOptions } from "../types.js"; -const logger = debug("@edgedb/create:recipe:base"); +const logger = debug("@gel/create:recipe:base"); const recipe: BaseRecipe = { async getOptions() { @@ -34,9 +34,9 @@ const recipe: BaseRecipe = { { value: "none", label: "None" }, ], }), - useEdgeDBAuth: () => + useGelAuth: () => p.confirm({ - message: "Use the EdgeDB Auth extension?", + message: "Use the Gel Auth extension?", initialValue: true, }), }, diff --git a/packages/create/src/recipes/_base/template/package.json b/packages/create/src/recipes/_base/template/package.json index d9ecd52ce..7875b12e0 100644 --- a/packages/create/src/recipes/_base/template/package.json +++ b/packages/create/src/recipes/_base/template/package.json @@ -3,10 +3,10 @@ "version": "0.1.0", "private": true, "dependencies": { - "edgedb": "1.x" + "gel": "1.x" }, "devDependencies": { - "@edgedb/generate": "0.x", + "@gel/generate": "0.x", "@typescript-eslint/eslint-plugin": "6.x", "@typescript-eslint/parser": "6.x", "@eslint/eslintrc": "2.x", diff --git a/packages/create/src/recipes/_edgedb/index.ts b/packages/create/src/recipes/_edgedb/index.ts deleted file mode 100644 index 3c896e649..000000000 --- a/packages/create/src/recipes/_edgedb/index.ts +++ /dev/null @@ -1,141 +0,0 @@ -import * as p from "@clack/prompts"; -import fs from "node:fs/promises"; -import path from "node:path"; -import debug from "debug"; - -import type { BaseOptions, Recipe } from "../types.js"; -import { copyTemplateFiles, execInLoginShell } from "../../utils.js"; - -const logger = debug("@edgedb/create:recipe:edgedb"); - -interface EdgeDBOptions { - initializeProject: boolean; -} - -const recipe: Recipe = { - getOptions() { - return p.group({ - initializeProject: () => - p.confirm({ - message: "Initialize a new EdgeDB project with edgedb project init?", - initialValue: true, - }), - }); - }, - - async apply( - { projectDir, useEdgeDBAuth }: BaseOptions, - { initializeProject }: EdgeDBOptions, - ) { - logger("Running edgedb recipe"); - logger("Checking for existing EdgeDB CLI"); - - const spinner = p.spinner(); - - if (initializeProject) { - let edgedbCliVersion: string | null = null; - let shouldInstallCli: boolean | symbol = true; - try { - const { stdout } = await execInLoginShell("edgedb --version"); - edgedbCliVersion = stdout.trim(); - logger(edgedbCliVersion); - } catch (_error) { - logger("No EdgeDB CLI detected"); - shouldInstallCli = await p.confirm({ - message: - "The EdgeDB CLI is required to initialize a project. Install now?", - initialValue: true, - }); - } - - if (edgedbCliVersion === null) { - if (shouldInstallCli === false) { - logger("User declined to install EdgeDB CLI"); - throw new Error("EdgeDB CLI is required"); - } - - logger("Installing EdgeDB CLI"); - - spinner.start("Installing EdgeDB CLI"); - const { stdout, stderr } = await execInLoginShell( - "curl --proto '=https' --tlsv1.2 -sSf https://sh.edgedb.com | sh -s -- -y", - ); - logger({ stdout, stderr }); - spinner.stop("EdgeDB CLI installed"); - } - - try { - const { stdout } = await execInLoginShell("edgedb --version"); - edgedbCliVersion = stdout.trim(); - logger(edgedbCliVersion); - } catch (error) { - logger("EdgeDB CLI could not be installed."); - logger(error); - throw new Error("EdgeDB CLI could not be installed."); - } - - spinner.start("Initializing EdgeDB project"); - try { - await execInLoginShell("edgedb project init --non-interactive", { - cwd: projectDir, - }); - const { stdout, stderr } = await execInLoginShell( - "edgedb query 'select sys::get_version_as_str()'", - { cwd: projectDir }, - ); - const serverVersion = JSON.parse(stdout.trim()); - logger(`EdgeDB server version: ${serverVersion}`); - if (serverVersion === "") { - const err = new Error( - "There was a problem initializing the EdgeDB project", - ); - spinner.stop(err.message); - logger({ stdout, stderr }); - - throw err; - } - spinner.stop(`EdgeDB v${serverVersion} project initialized`); - } catch (error) { - logger(error); - throw error; - } finally { - spinner.stop(); - } - } else { - logger("Skipping edgedb project init"); - logger("Copying basic EdgeDB project files"); - - const dirname = path.dirname(new URL(import.meta.url).pathname); - await copyTemplateFiles(path.resolve(dirname, "./template"), projectDir); - } - - if (useEdgeDBAuth) { - logger("Adding auth extension to project"); - - spinner.start("Enabling auth extension in EdgeDB schema"); - const filePath = path.resolve(projectDir, "./dbschema/default.esdl"); - const data = await fs.readFile(filePath, "utf8"); - await fs.writeFile(filePath, `using extension auth;\n\n${data}`); - spinner.stop("Auth extension enabled in EdgeDB schema"); - - if (initializeProject) { - logger("Creating and applying initial migration"); - spinner.start("Creating and applying initial migration"); - try { - await execInLoginShell("edgedb migration create", { - cwd: projectDir, - }); - await execInLoginShell("edgedb migrate", { cwd: projectDir }); - spinner.stop("Initial migration created and applied"); - } catch (error) { - logger(error); - throw error; - } finally { - spinner.stop(); - } - } - } - }, -}; - -export default recipe; diff --git a/packages/create/src/recipes/_gel/index.ts b/packages/create/src/recipes/_gel/index.ts new file mode 100644 index 000000000..d9cfc3a46 --- /dev/null +++ b/packages/create/src/recipes/_gel/index.ts @@ -0,0 +1,108 @@ +import * as p from "@clack/prompts"; +import fs from "node:fs/promises"; +import path from "node:path"; +import debug from "debug"; + +import type { BaseOptions, Recipe } from "../types.js"; +import { copyTemplateFiles, ProjectManager } from "../../utils.js"; + +const logger = debug("@gel/create:recipe:gel"); + +interface GelOptions { + initializeProject: boolean; +} + +const recipe: Recipe = { + getOptions() { + return p.group({ + initializeProject: () => + p.confirm({ + message: "Initialize a new Gel project with gel project init?", + initialValue: true, + }), + }); + }, + + async apply( + { projectDir, useGelAuth }: BaseOptions, + { initializeProject }: GelOptions, + ) { + logger("Running gel recipe"); + + const spinner = p.spinner(); + const manager = new ProjectManager(); + + if (initializeProject) { + spinner.start("Initializing Gel project"); + try { + await manager.runPackageBin( + "gel", + ["project", "init", "--non-interactive"], + { + cwd: projectDir, + }, + ); + + const { stdout, stderr } = await manager.runPackageBin( + "gel", + ["query", "select sys::get_version_as_str()"], + { cwd: projectDir }, + ); + + const serverVersion = JSON.parse(stdout.trim()); + logger(`Gel server version: ${serverVersion}`); + + if (serverVersion === "") { + const err = new Error( + "There was a problem initializing the Gel project", + ); + spinner.stop(err.message); + logger({ stdout, stderr }); + throw err; + } + + spinner.stop(`Gel v${serverVersion} project initialized`); + } catch (error) { + logger(error); + spinner.stop("Failed to initialize Gel project"); + throw error; + } + } else { + logger("Skipping gel project init"); + logger("Copying basic Gel project files"); + + const dirname = path.dirname(new URL(import.meta.url).pathname); + await copyTemplateFiles(path.resolve(dirname, "./template"), projectDir); + } + + if (useGelAuth) { + logger("Adding auth extension to project"); + + spinner.start("Enabling auth extension in Gel schema"); + const filePath = path.resolve(projectDir, "./dbschema/default.esdl"); + const data = await fs.readFile(filePath, "utf8"); + await fs.writeFile(filePath, `using extension auth;\n\n${data}`); + spinner.stop("Auth extension enabled in Gel schema"); + + if (initializeProject) { + logger("Creating and applying initial migration"); + spinner.start("Creating and applying initial migration"); + try { + await manager.runPackageBin("gel", ["migration", "create"], { + cwd: projectDir, + }); + await manager.runPackageBin("gel", ["migrate"], { + cwd: projectDir, + }); + spinner.stop("Initial migration created and applied"); + } catch (error) { + logger(error); + spinner.stop("Failed to create and apply migration"); + throw error; + } + } + } + }, +}; + +export default recipe; diff --git a/packages/create/src/recipes/_edgedb/template/dbschema/default.esdl b/packages/create/src/recipes/_gel/template/dbschema/default.esdl similarity index 100% rename from packages/create/src/recipes/_edgedb/template/dbschema/default.esdl rename to packages/create/src/recipes/_gel/template/dbschema/default.esdl diff --git a/packages/create/src/recipes/_install/index.ts b/packages/create/src/recipes/_install/index.ts index a794b0094..7019a1f67 100644 --- a/packages/create/src/recipes/_install/index.ts +++ b/packages/create/src/recipes/_install/index.ts @@ -4,7 +4,7 @@ import * as p from "@clack/prompts"; import type { BaseOptions, Recipe } from "../types.js"; import { execInLoginShell } from "../../utils.js"; -const logger = debug("@edgedb/create:recipe:install"); +const logger = debug("@gel/create:recipe:install"); interface InstallOptions { shouldGitInit: boolean; diff --git a/packages/create/src/recipes/express/README.md b/packages/create/src/recipes/express/README.md index ec04b63af..797777172 100644 --- a/packages/create/src/recipes/express/README.md +++ b/packages/create/src/recipes/express/README.md @@ -1,22 +1,22 @@ -# Express Integration Recipe for EdgeDB +# Express Integration Recipe for Gel -This recipe provides a starting point for building an [Express](https://expressjs.com/) application with EdgeDB as the database. +This recipe provides a starting point for building an [Express](https://expressjs.com/) application with Gel as the database. -✨ Check out the [`@edgedb/create` package](https://github.com/edgedb/edgedb-js/blob/master/packages/create/README.md) for more information. +✨ Check out the [`@gel/create` package](https://github.com/gel/gel-js/blob/master/packages/create/README.md) for more information. ## Usage ```bash -$ npm create @edgedb +$ npm create @gel # or -yarn create @edgedb +yarn create @gel # or -pnpm create @edgedb +pnpm create @gel # or -bun create @edgedb +bun create @gel ``` -After running the command, you will be prompted to provide a project name and choose the **"Express"** template. You can also specify whether to use EdgeDB Auth, initialize a git repository, and install dependencies. +After running the command, you will be prompted to provide a project name and choose the **"Express"** template. You can also specify whether to use Gel Auth, initialize a git repository, and install dependencies. The tool will then create a new directory with the specified name and set up the project. @@ -34,7 +34,7 @@ Navigate into `packages/create`: $ cd packages/create ``` -Build @edgedb/create +Build @gel/create ```bash $ yarn build diff --git a/packages/create/src/recipes/express/index.ts b/packages/create/src/recipes/express/index.ts index 1fcd875c6..16d93c70e 100644 --- a/packages/create/src/recipes/express/index.ts +++ b/packages/create/src/recipes/express/index.ts @@ -5,7 +5,7 @@ import { updatePackage } from "write-package"; import type { BaseOptions, Recipe } from "../types.js"; import { copyTemplateFiles } from "../../utils.js"; -const logger = debug("@edgedb/create:recipe:express"); +const logger = debug("@gel/create:recipe:express"); const recipe: Recipe = { skip(opts: BaseOptions) { @@ -24,15 +24,13 @@ const recipe: Recipe = { sideEffects: false, type: "module", scripts: { - dev: "DEBUG=* EDGEDB_CLIENT_SECURITY=insecure_dev_mode tsx watch --clear-screen=false src/index.ts", + dev: "DEBUG=* GEL_CLIENT_SECURITY=insecure_dev_mode tsx watch --clear-screen=false src/index.ts", build: "tsc", lint: "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .", typecheck: "tsc --noEmit", }, dependencies: { - ...(baseOptions.useEdgeDBAuth - ? { "@edgedb/auth-express": "^0.1.0" } - : {}), + ...(baseOptions.useGelAuth ? { "@gel/auth-express": "^0.1.0" } : {}), "cookie-parser": "^1.4.6", express: "^4.18.2", }, diff --git a/packages/create/src/recipes/express/template/src/auth.ts b/packages/create/src/recipes/express/template/src/auth.ts index 5bfce74c6..6e26f21a9 100644 --- a/packages/create/src/recipes/express/template/src/auth.ts +++ b/packages/create/src/recipes/express/template/src/auth.ts @@ -2,7 +2,7 @@ import { type NextFunction, type Response, Router } from "express"; import createExpressAuth, { type AuthRequest, type CallbackRequest, -} from "@edgedb/auth-express"; +} from "@gel/auth-express"; import { client } from "./db.js"; import { PORT } from "./env.js"; diff --git a/packages/create/src/recipes/express/template/src/db.ts b/packages/create/src/recipes/express/template/src/db.ts index 70ee406e4..061ef6542 100644 --- a/packages/create/src/recipes/express/template/src/db.ts +++ b/packages/create/src/recipes/express/template/src/db.ts @@ -1,3 +1,3 @@ -import { createClient } from "edgedb"; +import { createClient } from "gel"; export const client = createClient(); diff --git a/packages/create/src/recipes/express/template/src/index.ts b/packages/create/src/recipes/express/template/src/index.ts index 3b7231030..055378d2c 100644 --- a/packages/create/src/recipes/express/template/src/index.ts +++ b/packages/create/src/recipes/express/template/src/index.ts @@ -1,6 +1,6 @@ import express from "express"; import cookieParser from "cookie-parser"; -import { type AuthRequest } from "@edgedb/auth-express"; +import { type AuthRequest } from "@gel/auth-express"; import { styles } from "./styles.js"; import { auth, requireAuth, signoutRoute, builtinUIRouter } from "./auth.js"; @@ -14,7 +14,7 @@ app.use(cookieParser()); app.use(auth.createSessionMiddleware()); app.get("/api/deep-thought", requireAuth, async (req: AuthRequest, res) => { - // See more examples of making queries here: https://github.com/edgedb/edgedb-examples/blob/main/express-auth/todos.ts + // See more examples of making queries here: https://github.com/gel/gel-examples/blob/main/express-auth/todos.ts const answer = await req.session!.client.query("select 42;"); res.json(answer); }); diff --git a/packages/create/src/recipes/index.ts b/packages/create/src/recipes/index.ts index 73255230f..8113d37cb 100644 --- a/packages/create/src/recipes/index.ts +++ b/packages/create/src/recipes/index.ts @@ -1,5 +1,5 @@ import baseRecipe from "./_base/index.js"; -import _edgedbInit from "./_edgedb/index.js"; +import _gelInit from "./_gel/index.js"; import _install from "./_install/index.js"; import express from "./express/index.js"; @@ -18,6 +18,6 @@ export const recipes: Recipe[] = [ remix, sveltekit, // init - _edgedbInit, + _gelInit, _install, ]; diff --git a/packages/create/src/recipes/nextjs/README.md b/packages/create/src/recipes/nextjs/README.md index a133a54e3..dd5720af0 100644 --- a/packages/create/src/recipes/nextjs/README.md +++ b/packages/create/src/recipes/nextjs/README.md @@ -1,24 +1,24 @@ -# Next.js Integration Recipe for EdgeDB +# Next.js Integration Recipe for Gel -This recipe provides a starting point for building a [Next.js](https://nextjs.org/) application with EdgeDB as the database. It is based on the official Next.js starter template. +This recipe provides a starting point for building a [Next.js](https://nextjs.org/) application with Gel as the database. It is based on the official Next.js starter template. We try to actively monitor and incorporate significant changes from the original "create-app" templates to ensure developers have access to the latest features and best practices. However, we might not cover every possible configuration or permutation due to the vast scope of possibilities. -✨ Check out the [`@edgedb/create` package](https://github.com/edgedb/edgedb-js/blob/master/packages/create/README.md) for more information. +✨ Check out the [`@gel/create` package](https://github.com/gel/gel-js/blob/master/packages/create/README.md) for more information. ## Usage ```bash -$ npm create @edgedb +$ npm create @gel # or -yarn create @edgedb +yarn create @gel # or -pnpm create @edgedb +pnpm create @gel # or -bun create @edgedb +bun create @gel ``` -After running the command, you will be prompted to provide a project name and choose the **"Next.js"** template. You can also specify whether to use EdgeDB Auth, initialize a git repository, and install dependencies. +After running the command, you will be prompted to provide a project name and choose the **"Next.js"** template. You can also specify whether to use Gel Auth, initialize a git repository, and install dependencies. The tool will then create a new directory with the specified name and set up the project. @@ -36,7 +36,7 @@ Navigate into `packages/create`: $ cd packages/create ``` -Build @edgedb/create +Build @gel/create ```bash $ yarn build diff --git a/packages/create/src/recipes/nextjs/index.ts b/packages/create/src/recipes/nextjs/index.ts index a0022961c..9c1a1d909 100644 --- a/packages/create/src/recipes/nextjs/index.ts +++ b/packages/create/src/recipes/nextjs/index.ts @@ -6,7 +6,7 @@ import { updatePackage } from "write-package"; import type { BaseOptions, Recipe } from "../types.js"; import { copyTemplateFiles } from "../../utils.js"; -const logger = debug("@edgedb/create:recipe:nextjs"); +const logger = debug("@gel/create:recipe:nextjs"); interface NextjsOptions { useTS: boolean; @@ -49,7 +49,7 @@ const recipe: Recipe = { }); }, async apply( - { projectDir, useEdgeDBAuth }: BaseOptions, + { projectDir, useGelAuth }: BaseOptions, { useTS, router, useTailwind, useSrcDir }: NextjsOptions, ) { logger("Running nextjs recipe"); @@ -58,7 +58,7 @@ const recipe: Recipe = { const tags = new Set([router, useTailwind ? "tw" : "no-tw"]); - if (useEdgeDBAuth) { + if (useGelAuth) { tags.add("auth"); } @@ -97,8 +97,8 @@ const recipe: Recipe = { lint: "next lint", }, dependencies: { - ...(useEdgeDBAuth ? { "@edgedb/auth-nextjs": "^0.1.0" } : {}), - edgedb: "^1.4.1", + ...(useGelAuth ? { "@gel/auth-nextjs": "^0.1.0" } : {}), + gel: "^1.4.1", react: "^18", "react-dom": "^18", next: "14.0.4", diff --git a/packages/create/src/recipes/nextjs/template/js/src/app/auth/[...auth]/route.__auth.js b/packages/create/src/recipes/nextjs/template/js/src/app/auth/[...auth]/route.__auth.js index ff9edf974..992f09492 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/app/auth/[...auth]/route.__auth.js +++ b/packages/create/src/recipes/nextjs/template/js/src/app/auth/[...auth]/route.__auth.js @@ -1,5 +1,5 @@ import { redirect } from "next/navigation"; -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; export const { GET, POST } = auth.createAuthRouteHandlers({ async onBuiltinUICallback({ error, tokenData, provider, isSignUp }) { diff --git a/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__auth.jsx b/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__auth.jsx index 524632ccc..7394912bf 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__auth.jsx +++ b/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__auth.jsx @@ -1,7 +1,7 @@ import Image from "next/image"; import styles from "./page.module.css"; -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; export default async function Home() { const session = auth.getSession(); diff --git a/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__tw.__auth.jsx b/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__tw.__auth.jsx index 5cd16ba03..33673abfc 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__tw.__auth.jsx +++ b/packages/create/src/recipes/nextjs/template/js/src/app/page.__app.__tw.__auth.jsx @@ -1,6 +1,6 @@ import Image from "next/image"; -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; export default async function Home() { const session = auth.getSession(); diff --git a/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__app.js b/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__app.js index c696369e2..1c853890f 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__app.js +++ b/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__app.js @@ -1,5 +1,5 @@ -import { createClient } from "edgedb"; -import createAuth from "@edgedb/auth-nextjs/app"; +import { createClient } from "gel"; +import createAuth from "@gel/auth-nextjs/app"; export const client = createClient({ // Note: when developing locally you will need to set tls security to diff --git a/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__pages.js b/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__pages.js index a6947fdb1..44c753eb7 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__pages.js +++ b/packages/create/src/recipes/nextjs/template/js/src/edgedb.__auth.__pages.js @@ -1,6 +1,6 @@ -import { createClient } from "edgedb"; -import createAuth from "@edgedb/auth-nextjs/pages/server"; -import { options } from "./edgedb.client"; +import { createClient } from "gel"; +import createAuth from "@gel/auth-nextjs/pages/server"; +import { options } from "./gel.client"; export const client = createClient({ // Note: when developing locally you will need to set tls security to diff --git a/packages/create/src/recipes/nextjs/template/js/src/edgedb.client.__auth.__pages.js b/packages/create/src/recipes/nextjs/template/js/src/edgedb.client.__auth.__pages.js index 5884379b2..bcb649f86 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/edgedb.client.__auth.__pages.js +++ b/packages/create/src/recipes/nextjs/template/js/src/edgedb.client.__auth.__pages.js @@ -1,4 +1,4 @@ -import createAuth from "@edgedb/auth-nextjs/pages/client"; +import createAuth from "@gel/auth-nextjs/pages/client"; export const options = { baseUrl: "http://localhost:3000", diff --git a/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/api/hello.__auth.js b/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/api/hello.__auth.js index c9d11d288..758523813 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/api/hello.__auth.js +++ b/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/api/hello.__auth.js @@ -1,10 +1,10 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; export default async function handler(req, res) { const session = auth.getSession(req); const identity = await session.client.querySingle( - `select global ext::auth::ClientTokenIdentity {*}` + `select global ext::auth::ClientTokenIdentity {*}`, ); res.status(200).json({ name: "John Doe", identity }); diff --git a/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/index.__auth.jsx b/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/index.__auth.jsx index 9b5884945..2554a053b 100644 --- a/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/index.__auth.jsx +++ b/packages/create/src/recipes/nextjs/template/js/src/pages.__pages/index.__auth.jsx @@ -3,8 +3,8 @@ import Image from "next/image"; import { Inter } from "next/font/google"; import styles from "@/styles/Home.module.css"; -import { auth } from "@/edgedb"; -import { auth as clientAuth } from "@/edgedb.client"; +import { auth } from "@/gel"; +import { auth as clientAuth } from "@/gel.client"; const inter = Inter({ subsets: ["latin"] }); diff --git a/packages/create/src/recipes/nextjs/template/ts/src/app/auth/[...auth]/route.__auth.ts b/packages/create/src/recipes/nextjs/template/ts/src/app/auth/[...auth]/route.__auth.ts index ccf5e3137..59db01a01 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/app/auth/[...auth]/route.__auth.ts +++ b/packages/create/src/recipes/nextjs/template/ts/src/app/auth/[...auth]/route.__auth.ts @@ -1,6 +1,6 @@ import { redirect } from "next/navigation"; -import { auth } from "@/edgedb"; -import type { TokenData } from "@edgedb/auth-core"; +import { auth } from "@/gel"; +import type { TokenData } from "@gel/auth-core"; export const { GET, POST } = auth.createAuthRouteHandlers({ async onBuiltinUICallback({ diff --git a/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__auth.tsx b/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__auth.tsx index 837bf5025..71be16d7b 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__auth.tsx +++ b/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__auth.tsx @@ -1,7 +1,7 @@ import Image from "next/image"; import styles from "./page.module.css"; -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; export default async function Home() { const session = auth.getSession(); diff --git a/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__tw.__auth.tsx b/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__tw.__auth.tsx index e45042d5d..9d7e3c63b 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__tw.__auth.tsx +++ b/packages/create/src/recipes/nextjs/template/ts/src/app/page.__app.__tw.__auth.tsx @@ -1,6 +1,6 @@ import Image from "next/image"; -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; export default async function Home() { const session = auth.getSession(); diff --git a/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__app.ts b/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__app.ts index c696369e2..1c853890f 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__app.ts +++ b/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__app.ts @@ -1,5 +1,5 @@ -import { createClient } from "edgedb"; -import createAuth from "@edgedb/auth-nextjs/app"; +import { createClient } from "gel"; +import createAuth from "@gel/auth-nextjs/app"; export const client = createClient({ // Note: when developing locally you will need to set tls security to diff --git a/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__pages.ts b/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__pages.ts index a6947fdb1..44c753eb7 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__pages.ts +++ b/packages/create/src/recipes/nextjs/template/ts/src/edgedb.__auth.__pages.ts @@ -1,6 +1,6 @@ -import { createClient } from "edgedb"; -import createAuth from "@edgedb/auth-nextjs/pages/server"; -import { options } from "./edgedb.client"; +import { createClient } from "gel"; +import createAuth from "@gel/auth-nextjs/pages/server"; +import { options } from "./gel.client"; export const client = createClient({ // Note: when developing locally you will need to set tls security to diff --git a/packages/create/src/recipes/nextjs/template/ts/src/edgedb.client.__auth.__pages.ts b/packages/create/src/recipes/nextjs/template/ts/src/edgedb.client.__auth.__pages.ts index beefdca59..4d85709ae 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/edgedb.client.__auth.__pages.ts +++ b/packages/create/src/recipes/nextjs/template/ts/src/edgedb.client.__auth.__pages.ts @@ -1,6 +1,6 @@ import createAuth, { type NextAuthOptions, -} from "@edgedb/auth-nextjs/pages/client"; +} from "@gel/auth-nextjs/pages/client"; export const options: NextAuthOptions = { baseUrl: "http://localhost:3000", diff --git a/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/api/hello.__auth.ts b/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/api/hello.__auth.ts index d66fa7685..915b687d3 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/api/hello.__auth.ts +++ b/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/api/hello.__auth.ts @@ -1,7 +1,7 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type { NextApiRequest, NextApiResponse } from "next"; -import { auth } from "@/edgedb"; +import { auth } from "@/gel"; interface Data { name: string; diff --git a/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/index.__auth.tsx b/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/index.__auth.tsx index 83c95e637..491eeffd7 100644 --- a/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/index.__auth.tsx +++ b/packages/create/src/recipes/nextjs/template/ts/src/pages.__pages/index.__auth.tsx @@ -4,8 +4,8 @@ import Image from "next/image"; import { Inter } from "next/font/google"; import styles from "@/styles/Home.module.css"; -import { auth } from "@/edgedb"; -import { auth as clientAuth } from "@/edgedb.client"; +import { auth } from "@/gel"; +import { auth as clientAuth } from "@/gel.client"; const inter = Inter({ subsets: ["latin"] }); diff --git a/packages/create/src/recipes/remix/README.md b/packages/create/src/recipes/remix/README.md index 4a5d642c9..3f912158d 100644 --- a/packages/create/src/recipes/remix/README.md +++ b/packages/create/src/recipes/remix/README.md @@ -1,24 +1,24 @@ -# Remix Integration Recipe for EdgeDB +# Remix Integration Recipe for Gel -This recipe provides a starting point for building a [Remix](https://remix.run/) application with EdgeDB as the database. It is based on the official Remix starter template. +This recipe provides a starting point for building a [Remix](https://remix.run/) application with Gel as the database. It is based on the official Remix starter template. We try to actively monitor and incorporate significant changes from the original "create-app" templates to ensure developers have access to the latest features and best practices. However, we might not cover every possible configuration or permutation due to the vast scope of possibilities. -✨ Check out the [`@edgedb/create` package](https://github.com/edgedb/edgedb-js/blob/master/packages/create/README.md) for more information. +✨ Check out the [`@gel/create` package](https://github.com/gel/gel-js/blob/master/packages/create/README.md) for more information. ## Usage ```bash -$ npm create @edgedb +$ npm create @gel # or -yarn create @edgedb +yarn create @gel # or -pnpm create @edgedb +pnpm create @gel # or -bun create @edgedb +bun create @gel ``` -After running the command, you will be prompted to provide a project name and choose the **"Remix"** template. You can also specify whether to use EdgeDB Auth, initialize a git repository, and install dependencies. +After running the command, you will be prompted to provide a project name and choose the **"Remix"** template. You can also specify whether to use Gel Auth, initialize a git repository, and install dependencies. The tool will then create a new directory with the specified name and set up the project. @@ -36,7 +36,7 @@ Navigate into `packages/create`: $ cd packages/create ``` -Build @edgedb/create +Build @gel/create ```bash $ yarn build diff --git a/packages/create/src/recipes/remix/index.ts b/packages/create/src/recipes/remix/index.ts index 11f951dd3..5e22b650d 100644 --- a/packages/create/src/recipes/remix/index.ts +++ b/packages/create/src/recipes/remix/index.ts @@ -5,20 +5,20 @@ import { updatePackage } from "write-package"; import type { BaseOptions, Recipe } from "../types.js"; import { copyTemplateFiles } from "../../utils.js"; -const logger = debug("@edgedb/create:recipe:remix"); +const logger = debug("@gel/create:recipe:remix"); const recipe: Recipe = { skip(opts: BaseOptions) { return opts.framework !== "remix"; }, - async apply({ projectDir, useEdgeDBAuth }: BaseOptions) { + async apply({ projectDir, useGelAuth }: BaseOptions) { logger("Running remix recipe"); const dirname = path.dirname(new URL(import.meta.url).pathname); let tags; - if (useEdgeDBAuth) { + if (useGelAuth) { tags = new Set(["auth"]); } @@ -37,7 +37,7 @@ const recipe: Recipe = { typecheck: "tsc", }, dependencies: { - ...(useEdgeDBAuth ? { "@edgedb/auth-remix": "^0.1.0" } : {}), + ...(useGelAuth ? { "@gel/auth-remix": "^0.1.0" } : {}), react: "^18", "react-dom": "^18", "@remix-run/css-bundle": "*", diff --git a/packages/create/src/recipes/remix/template/app/services.__auth/auth.server.ts b/packages/create/src/recipes/remix/template/app/services.__auth/auth.server.ts index bb899a231..14418f104 100644 --- a/packages/create/src/recipes/remix/template/app/services.__auth/auth.server.ts +++ b/packages/create/src/recipes/remix/template/app/services.__auth/auth.server.ts @@ -1,5 +1,5 @@ -import createServerAuth from "@edgedb/auth-remix/server"; -import { createClient } from "edgedb"; +import createServerAuth from "@gel/auth-remix/server"; +import { createClient } from "gel"; import { options } from "./auth"; export const client = createClient({ diff --git a/packages/create/src/recipes/remix/template/app/services.__auth/auth.ts b/packages/create/src/recipes/remix/template/app/services.__auth/auth.ts index 9b24b1fb2..4940f0075 100644 --- a/packages/create/src/recipes/remix/template/app/services.__auth/auth.ts +++ b/packages/create/src/recipes/remix/template/app/services.__auth/auth.ts @@ -1,6 +1,6 @@ import createClientAuth, { type RemixAuthOptions, -} from "@edgedb/auth-remix/client"; +} from "@gel/auth-remix/client"; export const options: RemixAuthOptions = { baseUrl: "http://localhost:3000", diff --git a/packages/create/src/recipes/sveltekit/README.md b/packages/create/src/recipes/sveltekit/README.md index 589ba5be0..539af336a 100644 --- a/packages/create/src/recipes/sveltekit/README.md +++ b/packages/create/src/recipes/sveltekit/README.md @@ -1,24 +1,24 @@ -# Sveltekit Integration Recipe for EdgeDB +# Sveltekit Integration Recipe for Gel -This recipe provides a starting point for building a [Sveltekit](https://kit.svelte.dev/) application with EdgeDB as the database. +This recipe provides a starting point for building a [Sveltekit](https://kit.svelte.dev/) application with Gel as the database. We try to actively monitor and incorporate significant changes from the original "create-app" templates to ensure developers have access to the latest features and best practices. However, we might not cover every possible configuration or permutation due to the vast scope of possibilities. -✨ Check out the [`@edgedb/create` package](https://github.com/edgedb/edgedb-js/blob/master/packages/create/README.md) for more information. +✨ Check out the [`@gel/create` package](https://github.com/gel/gel-js/blob/master/packages/create/README.md) for more information. ## Usage ```bash -$ npm create @edgedb +$ npm create @gel # or -yarn create @edgedb +yarn create @gel # or -pnpm create @edgedb +pnpm create @gel # or -bun create @edgedb +bun create @gel ``` -After running the command, you will be prompted to provide a project name and choose the **"Sveltekit"** template. You can also specify whether to use EdgeDB Auth, initialize a git repository, and install dependencies. +After running the command, you will be prompted to provide a project name and choose the **"Sveltekit"** template. You can also specify whether to use Gel Auth, initialize a git repository, and install dependencies. The tool will then create a new directory with the specified name and set up the project. @@ -36,7 +36,7 @@ Navigate into `packages/create`: $ cd packages/create ``` -Build @edgedb/create +Build @gel/create ```bash $ yarn build diff --git a/packages/create/src/recipes/sveltekit/index.ts b/packages/create/src/recipes/sveltekit/index.ts index 631b545db..10a00af8a 100644 --- a/packages/create/src/recipes/sveltekit/index.ts +++ b/packages/create/src/recipes/sveltekit/index.ts @@ -5,7 +5,7 @@ import { updatePackage } from "write-package"; import { copyTemplateFiles } from "../../utils.js"; import type { BaseOptions, Recipe } from "../types.js"; -const logger = debug("@edgedb/create:recipe:sveltekit"); +const logger = debug("@gel/create:recipe:sveltekit"); interface SveltekitOptions { lang: "ts" | "jsdoc" | "js"; @@ -41,7 +41,7 @@ const recipe: Recipe = { }); }, async apply( - { projectDir, useEdgeDBAuth }: BaseOptions, + { projectDir, useGelAuth }: BaseOptions, { lang }: SveltekitOptions, ) { logger("Running Sveltekit recipe"); @@ -49,7 +49,7 @@ const recipe: Recipe = { const dirname = path.dirname(new URL(import.meta.url).pathname); let tags; - if (useEdgeDBAuth) { + if (useGelAuth) { tags = new Set(["auth"]); } @@ -78,8 +78,8 @@ const recipe: Recipe = { }), }, dependencies: { - ...(useEdgeDBAuth && { - "@edgedb/auth-sveltekit": "^0.1.1", + ...(useGelAuth && { + "@gel/auth-sveltekit": "^0.1.1", }), }, devDependencies: { diff --git a/packages/create/src/recipes/sveltekit/template/js/src/hooks.server.__auth.js b/packages/create/src/recipes/sveltekit/template/js/src/hooks.server.__auth.js index e812ef117..936307658 100644 --- a/packages/create/src/recipes/sveltekit/template/js/src/hooks.server.__auth.js +++ b/packages/create/src/recipes/sveltekit/template/js/src/hooks.server.__auth.js @@ -1,7 +1,7 @@ import { redirect } from "@sveltejs/kit"; import { sequence } from "@sveltejs/kit/hooks"; -import serverAuth from "@edgedb/auth-sveltekit/server"; -import { client } from "$lib/server/edgedb"; +import serverAuth from "@gel/auth-sveltekit/server"; +import { client } from "$lib/server/gel"; import { options } from "$lib/auth"; const authRouteHandlers = { @@ -28,7 +28,7 @@ const authRouteHandlers = { const { createServerRequestAuth, createAuthRouteHook } = serverAuth( client, - options + options, ); export const handle = sequence(({ event, resolve }) => { diff --git a/packages/create/src/recipes/sveltekit/template/js/src/lib/auth.__auth.js b/packages/create/src/recipes/sveltekit/template/js/src/lib/auth.__auth.js index 433c8deab..346b04fac 100644 --- a/packages/create/src/recipes/sveltekit/template/js/src/lib/auth.__auth.js +++ b/packages/create/src/recipes/sveltekit/template/js/src/lib/auth.__auth.js @@ -1,4 +1,4 @@ -import createClientAuth from "@edgedb/auth-sveltekit/client"; +import createClientAuth from "@gel/auth-sveltekit/client"; export const options = { baseUrl: "http://localhost:5173", diff --git a/packages/create/src/recipes/sveltekit/template/js/src/lib/server/edgedb.js b/packages/create/src/recipes/sveltekit/template/js/src/lib/server/edgedb.js index bdadbf1cb..71acf1a03 100644 --- a/packages/create/src/recipes/sveltekit/template/js/src/lib/server/edgedb.js +++ b/packages/create/src/recipes/sveltekit/template/js/src/lib/server/edgedb.js @@ -1,4 +1,4 @@ -import { createClient } from "edgedb"; +import { createClient } from "gel"; export const client = createClient({ // Note: when developing locally you will need to set tls security to insecure, because the dev server uses self-signed certificates which will cause api calls with the fetch api to fail. diff --git a/packages/create/src/recipes/sveltekit/template/jsdoc/src/app.__auth.d.ts b/packages/create/src/recipes/sveltekit/template/jsdoc/src/app.__auth.d.ts index 89491a40e..6033db0e6 100644 --- a/packages/create/src/recipes/sveltekit/template/jsdoc/src/app.__auth.d.ts +++ b/packages/create/src/recipes/sveltekit/template/jsdoc/src/app.__auth.d.ts @@ -1,7 +1,7 @@ // See https://kit.svelte.dev/docs/types#app // for information about these interfaces -import type { ServerRequestAuth } from "@edgedb/auth-sveltekit/server"; +import type { ServerRequestAuth } from "@gel/auth-sveltekit/server"; declare global { namespace App { diff --git a/packages/create/src/recipes/sveltekit/template/jsdoc/src/hooks.server.__auth.js b/packages/create/src/recipes/sveltekit/template/jsdoc/src/hooks.server.__auth.js index af5852fa5..ac68ca9eb 100644 --- a/packages/create/src/recipes/sveltekit/template/jsdoc/src/hooks.server.__auth.js +++ b/packages/create/src/recipes/sveltekit/template/jsdoc/src/hooks.server.__auth.js @@ -1,10 +1,10 @@ import { redirect } from "@sveltejs/kit"; import { sequence } from "@sveltejs/kit/hooks"; -import serverAuth from "@edgedb/auth-sveltekit/server"; -import { client } from "$lib/server/edgedb"; +import serverAuth from "@gel/auth-sveltekit/server"; +import { client } from "$lib/server/gel"; import { options } from "$lib/auth"; -/** @type {import('@edgedb/auth-sveltekit/server').AuthRouteHandlers} */ +/** @type {import('@gel/auth-sveltekit/server').AuthRouteHandlers} */ const authRouteHandlers = { async onBuiltinUICallback({ error, tokenData, isSignUp }) { if (error) { @@ -29,7 +29,7 @@ const authRouteHandlers = { const { createServerRequestAuth, createAuthRouteHook } = serverAuth( client, - options + options, ); export const handle = sequence(({ event, resolve }) => { diff --git a/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/auth.__auth.js b/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/auth.__auth.js index 8b3a29fdb..c9061d90f 100644 --- a/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/auth.__auth.js +++ b/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/auth.__auth.js @@ -1,6 +1,6 @@ -import createClientAuth from "@edgedb/auth-sveltekit/client"; +import createClientAuth from "@gel/auth-sveltekit/client"; -/** @type {import('@edgedb/auth-sveltekit/client').AuthOptions} */ +/** @type {import('@gel/auth-sveltekit/client').AuthOptions} */ export const options = { baseUrl: "http://localhost:5173", }; diff --git a/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/server/edgedb.js b/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/server/edgedb.js index bdadbf1cb..71acf1a03 100644 --- a/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/server/edgedb.js +++ b/packages/create/src/recipes/sveltekit/template/jsdoc/src/lib/server/edgedb.js @@ -1,4 +1,4 @@ -import { createClient } from "edgedb"; +import { createClient } from "gel"; export const client = createClient({ // Note: when developing locally you will need to set tls security to insecure, because the dev server uses self-signed certificates which will cause api calls with the fetch api to fail. diff --git a/packages/create/src/recipes/sveltekit/template/ts/src/app.__auth.d.ts b/packages/create/src/recipes/sveltekit/template/ts/src/app.__auth.d.ts index 89491a40e..6033db0e6 100644 --- a/packages/create/src/recipes/sveltekit/template/ts/src/app.__auth.d.ts +++ b/packages/create/src/recipes/sveltekit/template/ts/src/app.__auth.d.ts @@ -1,7 +1,7 @@ // See https://kit.svelte.dev/docs/types#app // for information about these interfaces -import type { ServerRequestAuth } from "@edgedb/auth-sveltekit/server"; +import type { ServerRequestAuth } from "@gel/auth-sveltekit/server"; declare global { namespace App { diff --git a/packages/create/src/recipes/sveltekit/template/ts/src/hooks.server.__auth.ts b/packages/create/src/recipes/sveltekit/template/ts/src/hooks.server.__auth.ts index 943a319e1..b23713d47 100644 --- a/packages/create/src/recipes/sveltekit/template/ts/src/hooks.server.__auth.ts +++ b/packages/create/src/recipes/sveltekit/template/ts/src/hooks.server.__auth.ts @@ -1,9 +1,7 @@ import { redirect } from "@sveltejs/kit"; import { sequence } from "@sveltejs/kit/hooks"; -import serverAuth, { - type AuthRouteHandlers, -} from "@edgedb/auth-sveltekit/server"; -import { client } from "$lib/server/edgedb"; +import serverAuth, { type AuthRouteHandlers } from "@gel/auth-sveltekit/server"; +import { client } from "$lib/server/gel"; import { options } from "$lib/auth"; const authRouteHandlers: AuthRouteHandlers = { diff --git a/packages/create/src/recipes/sveltekit/template/ts/src/lib/auth.__auth.ts b/packages/create/src/recipes/sveltekit/template/ts/src/lib/auth.__auth.ts index faf8562c3..6ccb607cf 100644 --- a/packages/create/src/recipes/sveltekit/template/ts/src/lib/auth.__auth.ts +++ b/packages/create/src/recipes/sveltekit/template/ts/src/lib/auth.__auth.ts @@ -1,6 +1,4 @@ -import createClientAuth, { - type AuthOptions, -} from "@edgedb/auth-sveltekit/client"; +import createClientAuth, { type AuthOptions } from "@gel/auth-sveltekit/client"; export const options: AuthOptions = { baseUrl: "http://localhost:5173", diff --git a/packages/create/src/recipes/sveltekit/template/ts/src/lib/server/edgedb.ts b/packages/create/src/recipes/sveltekit/template/ts/src/lib/server/edgedb.ts index bdadbf1cb..71acf1a03 100644 --- a/packages/create/src/recipes/sveltekit/template/ts/src/lib/server/edgedb.ts +++ b/packages/create/src/recipes/sveltekit/template/ts/src/lib/server/edgedb.ts @@ -1,4 +1,4 @@ -import { createClient } from "edgedb"; +import { createClient } from "gel"; export const client = createClient({ // Note: when developing locally you will need to set tls security to insecure, because the dev server uses self-signed certificates which will cause api calls with the fetch api to fail. diff --git a/packages/create/src/recipes/types.ts b/packages/create/src/recipes/types.ts index c49f53483..3676b2174 100644 --- a/packages/create/src/recipes/types.ts +++ b/packages/create/src/recipes/types.ts @@ -13,7 +13,7 @@ export interface BaseOptions { projectName: string; framework: Framework; projectDir: string; - useEdgeDBAuth: boolean; + useGelAuth: boolean; } export interface Recipe { diff --git a/packages/create/src/utils.ts b/packages/create/src/utils.ts index 4d59a417a..7cee92945 100644 --- a/packages/create/src/utils.ts +++ b/packages/create/src/utils.ts @@ -153,3 +153,35 @@ stdout: ${stdout}`, }); }); } + +export class ProjectManager { + public packageManager: PackageManager; + + constructor() { + this.packageManager = getPackageManager(); + } + + private getPackageRunner(): string { + switch (this.packageManager) { + case "yarn": + // yarn-berry and modern yarn 1.x support dlx + return "yarn dlx"; + case "pnpm": + return "pnpm dlx"; + case "bun": + return "bunx"; + default: + return "npx"; + } + } + + async runPackageBin( + binName: string, + args: string[] = [], + options?: SpawnOptionsWithoutStdio, + ): Promise<{ stdout: string; stderr: string }> { + const runner = this.getPackageRunner(); + const command = `${runner} ${binName} ${args.join(" ")}`; + return execInLoginShell(command, options); + } +} diff --git a/packages/driver/genErrors.mjs b/packages/driver/genErrors.mjs index 0d15b0e56..4e964fbfc 100644 --- a/packages/driver/genErrors.mjs +++ b/packages/driver/genErrors.mjs @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,9 +59,9 @@ const __filename = new URL("", import.meta.url).pathname; errorsBuf.nl(); errorsBuf.code("/* tslint:disable */"); errorsBuf.nl(); - errorsBuf.code("import {EdgeDBError} from './base'"); + errorsBuf.code("import {GelError} from './base'"); errorsBuf.code("import * as tags from './tags'"); - errorsBuf.code("export {EdgeDBError} from './base'"); + errorsBuf.code("export {GelError} from './base'"); errorsBuf.code("export * from './tags'"); errorsBuf.nl(); @@ -89,7 +89,7 @@ const __filename = new URL("", import.meta.url).pathname; c4.toString(16).padStart(2, "0"); if (!base) { - base = "EdgeDBError"; + base = "GelError"; } let tag_items = tags.map((t) => "[tags." + t + "]: true"); @@ -98,7 +98,7 @@ const __filename = new URL("", import.meta.url).pathname; if (tag_items.length > 0) { line += ` override protected static tags = {${tag_items.join(", ")}}\n`; } - if (base !== "EdgeDBError") { + if (base !== "GelError") { line += ` override get code(): number {\n return ${code};\n }\n`; } else { line += ` get code(): number {\n return ${code};\n }\n`; @@ -116,6 +116,12 @@ const __filename = new URL("", import.meta.url).pathname; const errors_ts = prettier.format(errorsBuf.render(), prettierOptions); const mapping_ts = prettier.format(mappingBuf.render(), prettierOptions); - fs.writeFileSync(path.join(__dirname, "./src/errors/index.ts"), await errors_ts); - fs.writeFileSync(path.join(__dirname, "./src/errors/map.ts"), await mapping_ts); + fs.writeFileSync( + path.join(__dirname, "./src/errors/index.ts"), + await errors_ts, + ); + fs.writeFileSync( + path.join(__dirname, "./src/errors/map.ts"), + await mapping_ts, + ); })(); diff --git a/packages/driver/package.json b/packages/driver/package.json index c8f282df4..4e51a4b9a 100644 --- a/packages/driver/package.json +++ b/packages/driver/package.json @@ -1,15 +1,15 @@ { - "name": "edgedb", + "name": "gel", "version": "1.5.12", - "description": "The official Node.js client library for EdgeDB", - "homepage": "https://edgedb.com/docs", - "author": "EdgeDB ", + "description": "The official Node.js client library for Gel", + "homepage": "https://geldata.com/docs", + "author": "Gel ", "engines": { "node": ">= 18.0.0" }, "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git" + "url": "https://github.com/geldata/gel-js.git" }, "main": "./dist/index.node.js", "types": "./dist/index.node.d.ts", @@ -22,7 +22,7 @@ "./dist/index.node.js": "./dist/index.browser.js" }, "bin": { - "edgedb": "./dist/cli.mjs" + "gel": "./dist/cli.mjs" }, "devDependencies": { "@js-temporal/polyfill": "0.4.3", @@ -43,13 +43,12 @@ }, "scripts": { "typecheck": "tsc --project tsconfig.json --noEmit", - "build": "echo 'Building edgedb driver...' && rm -rf dist && yarn build:cjs && yarn build:cli", + "build": "echo 'Building gel driver...' && rm -rf dist && yarn build:cjs && yarn build:cli", "build:cli": "tsc -p tsconfig.cli.json", "build:cjs": "tsc -p tsconfig.json", "lint": "eslint --quiet", "lint:fix": "eslint --fix", "test": "NODE_OPTIONS='--experimental-global-webcrypto' npx jest --detectOpenHandles", - "format": "prettier --write 'src/**/*.ts' 'test/**/*.ts'", "gen-errors": "edb gen-errors-json --client | node genErrors.mjs", "watch": "nodemon -e js,ts,tsx --ignore dist -x ", "dev": "yarn tsc --project tsconfig.json --incremental" diff --git a/packages/driver/src/baseClient.ts b/packages/driver/src/baseClient.ts index 9d7c1326b..f61d51496 100644 --- a/packages/driver/src/baseClient.ts +++ b/packages/driver/src/baseClient.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -151,14 +151,14 @@ export class ClientConnectionHolder { await transaction._rollback(); } } catch (rollback_err) { - if (!(rollback_err instanceof errors.EdgeDBError)) { - // We ignore EdgeDBError errors on rollback, retrying + if (!(rollback_err instanceof errors.GelError)) { + // We ignore GelError errors on rollback, retrying // if possible. All other errors are propagated. throw rollback_err; } } if ( - err instanceof errors.EdgeDBError && + err instanceof errors.GelError && err.hasTag(errors.SHOULD_RETRY) && !(commitFailed && err instanceof errors.ClientConnectionError) ) { @@ -200,7 +200,7 @@ export class ClientConnectionHolder { return result; } catch (err) { if ( - err instanceof errors.EdgeDBError && + err instanceof errors.GelError && err.hasTag(errors.SHOULD_RETRY) && // query is readonly or it's a transaction serialization error (conn.getQueryCapabilities( @@ -630,7 +630,7 @@ export class Client implements Executor { action: (transaction: Transaction) => Promise, ): Promise { if (this.pool.isStateless) { - throw new errors.EdgeDBError( + throw new errors.GelError( `cannot use 'transaction()' API on HTTP client`, ); } diff --git a/packages/driver/src/baseConn.ts b/packages/driver/src/baseConn.ts index 8161ffdab..a60b9a2f4 100644 --- a/packages/driver/src/baseConn.ts +++ b/packages/driver/src/baseConn.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,7 +102,7 @@ export type ParseResult = [ capabilities: number, inCodecBuffer: Uint8Array | null, outCodecBuffer: Uint8Array | null, - warnings: errors.EdgeDBError[], + warnings: errors.GelError[], ]; export type connConstructor = new ( @@ -201,6 +201,7 @@ export class BaseRawConnection { const value = this.buffer.readString(); headers[key] = value; } + return headers; } @@ -233,10 +234,10 @@ export class BaseRawConnection { number, Uint8Array, Uint8Array, - errors.EdgeDBError[], + errors.GelError[], ] { let capabilities = -1; - let warnings: errors.EdgeDBError[] = []; + let warnings: errors.GelError[] = []; const headers = this._readHeaders(); if (headers["warnings"] != null) { @@ -582,7 +583,7 @@ export class BaseRawConnection { let outCodec: ICodec | null = null; let inCodecBuf: Uint8Array | null = null; let outCodecBuf: Uint8Array | null = null; - let warnings: errors.EdgeDBError[] = []; + let warnings: errors.GelError[] = []; while (parsing) { if (!this.buffer.takeMessage()) { @@ -684,7 +685,7 @@ export class BaseRawConnection { result: any[] | WriteBuffer, capabilitiesFlags: number = RESTRICTED_CAPABILITIES, options?: QueryOptions, - ): Promise { + ): Promise { let ctx = state.makeCodecContext(); const wb = new WriteMessageBuffer(); @@ -717,7 +718,7 @@ export class BaseRawConnection { let error: Error | null = null; let parsing = true; - let warnings: errors.EdgeDBError[] = []; + let warnings: errors.GelError[] = []; while (parsing) { if (!this.buffer.takeMessage()) { @@ -908,7 +909,7 @@ export class BaseRawConnection { state: Options, privilegedMode = false, language: Language = Language.EDGEQL, - ): Promise<{ result: any; warnings: errors.EdgeDBError[] }> { + ): Promise<{ result: any; warnings: errors.GelError[] }> { if ( language !== Language.EDGEQL && versionGreaterThan([3, 0], this.protocolVersion) @@ -934,7 +935,7 @@ export class BaseRawConnection { const ret: any[] = []; // @ts-ignore let _; - let warnings: errors.EdgeDBError[] = []; + let warnings: errors.GelError[] = []; let [card, inCodec, outCodec] = this.queryCodecCache.get(key) ?? []; diff --git a/packages/driver/src/browserClient.ts b/packages/driver/src/browserClient.ts index 901fd7014..6f5ad0431 100644 --- a/packages/driver/src/browserClient.ts +++ b/packages/driver/src/browserClient.ts @@ -1,7 +1,7 @@ import { BaseClientPool, Client, type ConnectOptions } from "./baseClient"; import { getConnectArgumentsParser } from "./conUtils"; import { cryptoUtils } from "./browserCrypto"; -import { EdgeDBError } from "./errors"; +import { GelError } from "./errors"; import { FetchConnection } from "./fetchConn"; import { getHTTPSCRAMAuth } from "./httpScram"; import { Options } from "./options"; @@ -15,7 +15,7 @@ class FetchClientPool extends BaseClientPool { } export function createClient(): Client { - throw new EdgeDBError( + throw new GelError( `'createClient()' cannot be used in browser (or edge runtime) environment, ` + `use 'createHttpClient()' API instead`, ); diff --git a/packages/driver/src/cli.mts b/packages/driver/src/cli.mts index 4165f1400..13e9af51b 100644 --- a/packages/driver/src/cli.mts +++ b/packages/driver/src/cli.mts @@ -55,13 +55,13 @@ async function main(args: string[]) { const maybeCachedCliLocation = await getCliLocationFromCache(); const cliLocation = maybeCachedCliLocation ?? - (await whichEdgeDbCli()) ?? + (await whichGelCli()) ?? (await getCliLocationFromTempCli()) ?? (await selfInstallFromTempCli()) ?? null; if (cliLocation === null) { - throw Error("Failed to find or install EdgeDB CLI."); + throw Error("Failed to find or install Gel CLI."); } try { @@ -92,9 +92,13 @@ async function main(args: string[]) { process.exit(0); } -async function whichEdgeDbCli() { +async function whichGelCli() { debug("Checking if CLI is in PATH..."); - const locations = (await which("edgedb", { nothrow: true, all: true })) || []; + const locations = + (await which("gel", { nothrow: true, all: true })) || + (await which("edgedb", { nothrow: true, all: true })) || + []; + for (const location of locations) { const actualLocation = await fs.realpath(location); debug( @@ -211,7 +215,7 @@ async function writeCliLocationToCache(cliLocation: string) { } async function selfInstallFromTempCli(): Promise { - debug("Self-installing EdgeDB CLI..."); + debug("Self-installing Gel CLI..."); // n.b. need -y because in the Vercel build container, $HOME and euid-obtained // home are different, and the CLI installation requires this as confirmation const cmd = ["_self_install", "-y"]; @@ -225,7 +229,7 @@ async function selfInstallFromTempCli(): Promise { async function downloadCliPackage() { if (IS_TTY) { - console.log("No EdgeDB CLI found, downloading CLI package..."); + console.log("No Gel CLI found, downloading CLI package..."); } debug("Downloading CLI package..."); const cliPkg = await findPackage(); @@ -249,7 +253,7 @@ function runEdgeDbCli( execOptions: ExecSyncOptions = { stdio: "inherit" }, ) { const command = quote([pathToCli, ...args]); - debug(`Running EdgeDB CLI: ${command}`); + debug(`Running Gel CLI: ${command}`); return execSync(command, execOptions); } @@ -270,7 +274,7 @@ async function findPackage(): Promise { ); if (!pkg) { throw Error( - `No compatible EdgeDB CLI package found for the current platform ${dist}`, + `No compatible Gel CLI package found for the current platform ${dist}`, ); } debug(" - Package found:", pkg); @@ -328,7 +332,7 @@ async function getMatchingPkg( return matchingPkg; } else { throw Error( - "no published EdgeDB CLI version matches requested version " + + "no published Gel CLI version matches requested version " + `'${cliVersionRange}'`, ); } diff --git a/packages/driver/src/codecs/array.ts b/packages/driver/src/codecs/array.ts index 5482e14fa..f9c540dd9 100644 --- a/packages/driver/src/codecs/array.ts +++ b/packages/driver/src/codecs/array.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/boolean.ts b/packages/driver/src/codecs/boolean.ts index 5323d6d5f..3b869b3e3 100644 --- a/packages/driver/src/codecs/boolean.ts +++ b/packages/driver/src/codecs/boolean.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/bytes.ts b/packages/driver/src/codecs/bytes.ts index ad9565981..f88f7cbe3 100644 --- a/packages/driver/src/codecs/bytes.ts +++ b/packages/driver/src/codecs/bytes.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/codecs.ts b/packages/driver/src/codecs/codecs.ts index 7e40fa99a..f3bf38919 100644 --- a/packages/driver/src/codecs/codecs.ts +++ b/packages/driver/src/codecs/codecs.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/consts.ts b/packages/driver/src/codecs/consts.ts index bdd6da121..938d7e8be 100644 --- a/packages/driver/src/codecs/consts.ts +++ b/packages/driver/src/codecs/consts.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/datetime.ts b/packages/driver/src/codecs/datetime.ts index 9cf8f2482..bce9b92ea 100644 --- a/packages/driver/src/codecs/datetime.ts +++ b/packages/driver/src/codecs/datetime.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,7 +90,7 @@ export class DateTimeCodec extends ScalarCodec implements ICodec { export class LocalDateTimeCodec extends ScalarCodec implements ICodec { override tsType = "LocalDateTime"; - override tsModule = "edgedb"; + override tsModule = "gel"; encode(buf: WriteBuffer, object: unknown, ctx: CodecContext): void { if (ctx.hasOverload(this)) { @@ -169,7 +169,7 @@ export class LocalDateTimeCodec extends ScalarCodec implements ICodec { export class LocalDateCodec extends ScalarCodec implements ICodec { override tsType = "LocalDate"; - override tsModule = "edgedb"; + override tsModule = "gel"; encode(buf: WriteBuffer, object: unknown, ctx: CodecContext): void { if (ctx.hasOverload(this)) { const ret = ctx.preEncode(this, object); @@ -203,7 +203,7 @@ export class LocalDateCodec extends ScalarCodec implements ICodec { export class LocalTimeCodec extends ScalarCodec implements ICodec { override tsType = "LocalTime"; - override tsModule = "edgedb"; + override tsModule = "gel"; encode(buf: WriteBuffer, object: unknown, ctx: CodecContext): void { if (ctx.hasOverload(this)) { const us = ctx.preEncode(this, object); @@ -268,7 +268,7 @@ const unencodableDurationFields: (keyof Duration)[] = [ "days", ]; -export function checkValidEdgeDBDuration(duration: Duration): null | string { +export function checkValidGelDuration(duration: Duration): null | string { for (const field of unencodableDurationFields) { if (duration[field] !== 0) { return field; @@ -279,7 +279,7 @@ export function checkValidEdgeDBDuration(duration: Duration): null | string { export class DurationCodec extends ScalarCodec implements ICodec { override tsType = "Duration"; - override tsModule = "edgedb"; + override tsModule = "gel"; encode(buf: WriteBuffer, object: unknown, ctx: CodecContext): void { if (ctx.hasOverload(this)) { const us = ctx.preEncode(this, object); @@ -301,7 +301,7 @@ export class DurationCodec extends ScalarCodec implements ICodec { `a Duration instance was expected, got "${object}"`, ); } - const invalidField = checkValidEdgeDBDuration(object); + const invalidField = checkValidGelDuration(object); if (invalidField) { throw new InvalidArgumentError( `Cannot encode a 'Duration' with a non-zero number of ${invalidField}`, @@ -382,7 +382,7 @@ export class DurationCodec extends ScalarCodec implements ICodec { export class RelativeDurationCodec extends ScalarCodec implements ICodec { override tsType = "RelativeDuration"; - override tsModule = "edgedb"; + override tsModule = "gel"; encode(buf: WriteBuffer, object: unknown, ctx: CodecContext): void { if (ctx.hasOverload(this)) { const ret = ctx.preEncode(this, object); @@ -466,7 +466,7 @@ export class RelativeDurationCodec extends ScalarCodec implements ICodec { export class DateDurationCodec extends ScalarCodec implements ICodec { override tsType = "DateDuration"; - override tsModule = "edgedb"; + override tsModule = "gel"; encode(buf: WriteBuffer, object: unknown, ctx: CodecContext): void { if (ctx.hasOverload(this)) { const ret = ctx.preEncode(this, object); diff --git a/packages/driver/src/codecs/enum.ts b/packages/driver/src/codecs/enum.ts index 153abfefb..6d2464edd 100644 --- a/packages/driver/src/codecs/enum.ts +++ b/packages/driver/src/codecs/enum.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/ifaces.ts b/packages/driver/src/codecs/ifaces.ts index 9db774176..07d321833 100644 --- a/packages/driver/src/codecs/ifaces.ts +++ b/packages/driver/src/codecs/ifaces.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/json.ts b/packages/driver/src/codecs/json.ts index c63f539dd..f08306520 100644 --- a/packages/driver/src/codecs/json.ts +++ b/packages/driver/src/codecs/json.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/memory.ts b/packages/driver/src/codecs/memory.ts index 52079aea2..8b0f4d436 100644 --- a/packages/driver/src/codecs/memory.ts +++ b/packages/driver/src/codecs/memory.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import type { CodecContext } from "./context"; export class ConfigMemoryCodec extends ScalarCodec implements ICodec { override tsType = "ConfigMemory"; - override tsModule = "edgedb"; + override tsModule = "gel"; encode(buf: WriteBuffer, object: any, ctx: CodecContext): void { if (ctx.hasOverload(this)) { diff --git a/packages/driver/src/codecs/namedtuple.ts b/packages/driver/src/codecs/namedtuple.ts index f287f933e..714bb3792 100644 --- a/packages/driver/src/codecs/namedtuple.ts +++ b/packages/driver/src/codecs/namedtuple.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/numbers.ts b/packages/driver/src/codecs/numbers.ts index 23e4fc764..d76c6c3ff 100644 --- a/packages/driver/src/codecs/numbers.ts +++ b/packages/driver/src/codecs/numbers.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/numerics.ts b/packages/driver/src/codecs/numerics.ts index aa0ae4886..fa0e7a0d8 100644 --- a/packages/driver/src/codecs/numerics.ts +++ b/packages/driver/src/codecs/numerics.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/object.ts b/packages/driver/src/codecs/object.ts index e1bfb230b..0125290c6 100644 --- a/packages/driver/src/codecs/object.ts +++ b/packages/driver/src/codecs/object.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/pgvector.ts b/packages/driver/src/codecs/pgvector.ts index 471e5c3af..cb4005495 100644 --- a/packages/driver/src/codecs/pgvector.ts +++ b/packages/driver/src/codecs/pgvector.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ export class PgVectorCodec extends ScalarCodec implements ICodec { export class PgVectorHalfVecCodec extends ScalarCodec implements ICodec { override readonly tsType = "Float16Array"; - override readonly tsModule = "edgedb"; + override readonly tsModule = "gel"; encode(buf: WriteBuffer, object: any, ctx: CodecContext): void { object = ctx.preEncode(this, object); @@ -156,7 +156,7 @@ export class PgVectorHalfVecCodec extends ScalarCodec implements ICodec { export class PgVectorSparseVecCodec extends ScalarCodec implements ICodec { override readonly tsType = "SparseVector"; - override readonly tsModule = "edgedb"; + override readonly tsModule = "gel"; encode(buf: WriteBuffer, object: any, ctx: CodecContext): void { let dims: number; diff --git a/packages/driver/src/codecs/range.ts b/packages/driver/src/codecs/range.ts index 362e6d84f..47b4c9cb6 100644 --- a/packages/driver/src/codecs/range.ts +++ b/packages/driver/src/codecs/range.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,7 +104,7 @@ function decodeRange( export class RangeCodec extends Codec implements ICodec { readonly tsType = "Range"; - readonly tsModule = "edgedb"; + readonly tsModule = "gel"; private subCodec: ICodec; readonly typeName: string; @@ -134,7 +134,7 @@ export class RangeCodec extends Codec implements ICodec { export class MultiRangeCodec extends Codec implements ICodec { readonly tsType = "MultiRange"; - readonly tsModule = "edgedb"; + readonly tsModule = "gel"; private subCodec: ICodec; public typeName: string; diff --git a/packages/driver/src/codecs/record.ts b/packages/driver/src/codecs/record.ts index e862d0f0b..b5541aa92 100644 --- a/packages/driver/src/codecs/record.ts +++ b/packages/driver/src/codecs/record.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/registry.ts b/packages/driver/src/codecs/registry.ts index ddf484da0..a35ab8287 100644 --- a/packages/driver/src/codecs/registry.ts +++ b/packages/driver/src/codecs/registry.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,7 @@ export class CodecsRegistry { if (!versionGreaterThanOrEqual(protocolVersion, [2, 0])) { throw new UnsupportedProtocolVersionError( "unsupported old protocol version v1; downgrade to the previous " + - "version of edgedb-js", + "version of gel-js", ); } diff --git a/packages/driver/src/codecs/set.ts b/packages/driver/src/codecs/set.ts index 5c3195c22..7565f3a55 100644 --- a/packages/driver/src/codecs/set.ts +++ b/packages/driver/src/codecs/set.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/sparseObject.ts b/packages/driver/src/codecs/sparseObject.ts index bce346734..cb281dc41 100644 --- a/packages/driver/src/codecs/sparseObject.ts +++ b/packages/driver/src/codecs/sparseObject.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/text.ts b/packages/driver/src/codecs/text.ts index ac7ec843f..3a9bfd20a 100644 --- a/packages/driver/src/codecs/text.ts +++ b/packages/driver/src/codecs/text.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/tuple.ts b/packages/driver/src/codecs/tuple.ts index ea6ca1a57..aeb313436 100644 --- a/packages/driver/src/codecs/tuple.ts +++ b/packages/driver/src/codecs/tuple.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/codecs/uuid.ts b/packages/driver/src/codecs/uuid.ts index 04baa0f95..789513ea4 100644 --- a/packages/driver/src/codecs/uuid.ts +++ b/packages/driver/src/codecs/uuid.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/conUtils.ts b/packages/driver/src/conUtils.ts index cdf0cfdfa..fe4688b71 100644 --- a/packages/driver/src/conUtils.ts +++ b/packages/driver/src/conUtils.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import { validateCredentials, } from "./credentials"; import { Duration, parseHumanDurationString } from "./datatypes/datetime"; -import { checkValidEdgeDBDuration } from "./codecs/datetime"; +import { checkValidGelDuration } from "./codecs/datetime"; import { InterfaceError } from "./errors"; import { decodeB64, utf8Decoder, utf8Encoder } from "./primitives/buffer"; import { crcHqx } from "./primitives/crcHqx"; @@ -137,7 +137,19 @@ export type ResolvedConnectConfigReadonly = Readonly< >; function getEnv(envName: string, _required = false): string | undefined { - return process.env[envName]; + const gelEnv = envName; + const edgedbEnv = envName.replace(/^GEL_/, "EDGEDB_"); + + const gelValue = process.env[gelEnv]; + const edgedbValue = process.env[edgedbEnv]; + + if (gelValue !== undefined && edgedbValue !== undefined) { + console.warn( + `Both GEL_w+ and EDGEDB_w+ are set; EDGEDB_w+ will be ignored`, + ); + } + + return gelValue ?? edgedbValue; } export class ResolvedConnectConfig { @@ -308,13 +320,13 @@ export class ResolvedConnectConfig { .join(", ")}`, ); } - const clientSecurity = getEnv("EDGEDB_CLIENT_SECURITY"); + const clientSecurity = getEnv("GEL_CLIENT_SECURITY"); if (clientSecurity !== undefined) { if ( !["default", "insecure_dev_mode", "strict"].includes(clientSecurity) ) { throw new InterfaceError( - `invalid EDGEDB_CLIENT_SECURITY value: '${clientSecurity}', ` + + `invalid GEL_CLIENT_SECURITY value: '${clientSecurity}', ` + `must be one of 'default', 'insecure_dev_mode' or 'strict'`, ); } @@ -329,9 +341,9 @@ export class ResolvedConnectConfig { ) { throw new InterfaceError( `'tlsSecurity' value (${_tlsSecurity}) conflicts with ` + - `EDGEDB_CLIENT_SECURITY value (${clientSecurity}), ` + + `GEL_CLIENT_SECURITY value (${clientSecurity}), ` + `'tlsSecurity' value cannot be lower than security level ` + - `set by EDGEDB_CLIENT_SECURITY`, + `set by GEL_CLIENT_SECURITY`, ); } _tlsSecurity = "strict"; @@ -512,7 +524,7 @@ export function parseDuration(duration: string | number | Duration): number { } } if (duration instanceof Duration) { - const invalidField = checkValidEdgeDBDuration(duration); + const invalidField = checkValidGelDuration(duration); if (invalidField) { throw new InterfaceError( `invalid waitUntilAvailable duration, cannot have a '${invalidField}' value`, @@ -563,7 +575,7 @@ async function parseConnectDsnAndArgs( user: config.user, password: config.password, secretKey: config.secretKey, - cloudProfile: getEnv("EDGEDB_CLOUD_PROFILE"), + cloudProfile: getEnv("GEL_CLOUD_PROFILE"), tlsCA: config.tlsCA, tlsCAFile: config.tlsCAFile, tlsServerName: config.tlsServerName, @@ -586,7 +598,7 @@ async function parseConnectDsnAndArgs( user: `'user' option`, password: `'password' option`, secretKey: `'secretKey' option`, - cloudProfile: `'EDGEDB_CLOUD_PROFILE' environment variable`, + cloudProfile: `'GEL_CLOUD_PROFILE' environment variable`, tlsCA: `'tlsCA' option`, tlsCAFile: `'tlsCAFile' option`, tlsSecurity: `'tlsSecurity' option`, @@ -602,12 +614,10 @@ async function parseConnectDsnAndArgs( if (!hasCompoundOptions) { // resolve config from env vars - let port: string | undefined = getEnv("EDGEDB_PORT"); + let port: string | undefined = getEnv("GEL_PORT"); if (resolvedConfig._port === null && port?.startsWith("tcp://")) { - // EDGEDB_PORT is set by 'docker --link' so ignore and warn - console.warn( - `EDGEDB_PORT in 'tcp://host:port' format, so will be ignored`, - ); + // GEL_PORT is set by 'docker --link' so ignore and warn + console.warn(`GEL_PORT in 'tcp://host:port' format, so will be ignored`); port = undefined; } @@ -615,44 +625,44 @@ async function parseConnectDsnAndArgs( await resolveConfigOptions( resolvedConfig, { - dsn: getEnv("EDGEDB_DSN"), - instanceName: getEnv("EDGEDB_INSTANCE"), - credentials: getEnv("EDGEDB_CREDENTIALS"), - credentialsFile: getEnv("EDGEDB_CREDENTIALS_FILE"), - host: getEnv("EDGEDB_HOST"), + dsn: getEnv("GEL_DSN"), + instanceName: getEnv("GEL_INSTANCE"), + credentials: getEnv("GEL_CREDENTIALS"), + credentialsFile: getEnv("GEL_CREDENTIALS_FILE"), + host: getEnv("GEL_HOST"), port, - database: getEnv("EDGEDB_DATABASE"), - branch: getEnv("EDGEDB_BRANCH"), - user: getEnv("EDGEDB_USER"), - password: getEnv("EDGEDB_PASSWORD"), - secretKey: getEnv("EDGEDB_SECRET_KEY"), - tlsCA: getEnv("EDGEDB_TLS_CA"), - tlsCAFile: getEnv("EDGEDB_TLS_CA_FILE"), - tlsServerName: getEnv("EDGEDB_TLS_SERVER_NAME"), - tlsSecurity: getEnv("EDGEDB_CLIENT_TLS_SECURITY"), - waitUntilAvailable: getEnv("EDGEDB_WAIT_UNTIL_AVAILABLE"), + database: getEnv("GEL_DATABASE"), + branch: getEnv("GEL_BRANCH"), + user: getEnv("GEL_USER"), + password: getEnv("GEL_PASSWORD"), + secretKey: getEnv("GEL_SECRET_KEY"), + tlsCA: getEnv("GEL_TLS_CA"), + tlsCAFile: getEnv("GEL_TLS_CA_FILE"), + tlsServerName: getEnv("GEL_TLS_SERVER_NAME"), + tlsSecurity: getEnv("GEL_CLIENT_TLS_SECURITY"), + waitUntilAvailable: getEnv("GEL_WAIT_UNTIL_AVAILABLE"), }, { - dsn: `'EDGEDB_DSN' environment variable`, - instanceName: `'EDGEDB_INSTANCE' environment variable`, - credentials: `'EDGEDB_CREDENTIALS' environment variable`, - credentialsFile: `'EDGEDB_CREDENTIALS_FILE' environment variable`, - host: `'EDGEDB_HOST' environment variable`, - port: `'EDGEDB_PORT' environment variable`, - database: `'EDGEDB_DATABASE' environment variable`, - branch: `'EDGEDB_BRANCH' environment variable`, - user: `'EDGEDB_USER' environment variable`, - password: `'EDGEDB_PASSWORD' environment variable`, - secretKey: `'EDGEDB_SECRET_KEY' environment variable`, - tlsCA: `'EDGEDB_TLS_CA' environment variable`, - tlsCAFile: `'EDGEDB_TLS_CA_FILE' environment variable`, - tlsServerName: `'EDGEDB_TLS_SERVER_NAME' environment variable`, - tlsSecurity: `'EDGEDB_CLIENT_TLS_SECURITY' environment variable`, - waitUntilAvailable: `'EDGEDB_WAIT_UNTIL_AVAILABLE' environment variable`, + dsn: `'GEL_DSN' environment variable`, + instanceName: `'GEL_INSTANCE' environment variable`, + credentials: `'GEL_CREDENTIALS' environment variable`, + credentialsFile: `'GEL_CREDENTIALS_FILE' environment variable`, + host: `'GEL_HOST' environment variable`, + port: `'GEL_PORT' environment variable`, + database: `'GEL_DATABASE' environment variable`, + branch: `'GEL_BRANCH' environment variable`, + user: `'GEL_USER' environment variable`, + password: `'GEL_PASSWORD' environment variable`, + secretKey: `'GEL_SECRET_KEY' environment variable`, + tlsCA: `'GEL_TLS_CA' environment variable`, + tlsCAFile: `'GEL_TLS_CA_FILE' environment variable`, + tlsServerName: `'GEL_TLS_SERVER_NAME' environment variable`, + tlsSecurity: `'GEL_CLIENT_TLS_SECURITY' environment variable`, + waitUntilAvailable: `'GEL_WAIT_UNTIL_AVAILABLE' environment variable`, }, `Cannot have more than one of the following connection environment variables: ` + - `'EDGEDB_DSN', 'EDGEDB_INSTANCE', 'EDGEDB_CREDENTIALS', ` + - `'EDGEDB_CREDENTIALS_FILE' or 'EDGEDB_HOST'`, + `'GEL_DSN', 'GEL_INSTANCE', 'GEL_CREDENTIALS', ` + + `'GEL_CREDENTIALS_FILE' or 'GEL_HOST'`, serverUtils, )); } @@ -671,8 +681,8 @@ async function parseConnectDsnAndArgs( throw new errors.ClientConnectionError( "no project config file found and no connection options " + "specified either via arguments to `createClient()` API or via " + - "environment variables EDGEDB_HOST, EDGEDB_INSTANCE, EDGEDB_DSN, " + - "EDGEDB_CREDENTIALS or EDGEDB_CREDENTIALS_FILE", + "environment variables GEL_HOST, GEL_INSTANCE, GEL_DSN, " + + "GEL_CREDENTIALS or GEL_CREDENTIALS_FILE", ); } const stashDir = await serverUtils.findStashPath(projectDir); @@ -725,7 +735,7 @@ async function parseConnectDsnAndArgs( } else { throw new errors.ClientConnectionError( "Found project config file but the project is not initialized. " + - "Run 'edgedb project init'.", + "Run 'gel project init'.", ); } } @@ -1232,7 +1242,7 @@ async function parseCloudInstanceNameIntoConfig( const host = `${domainName}.c-${dnsBucket}.i.${dnsZone}`; config.setHost(host, `resolved from 'secretKey' and ${source}`); } catch (e) { - if (e instanceof errors.EdgeDBError) { + if (e instanceof errors.GelError) { throw e; } else { throw new InterfaceError(`Invalid secret key: ${e}`); diff --git a/packages/driver/src/datatypes/datetime.ts b/packages/driver/src/datatypes/datetime.ts index 79f58bf3c..f45249c8f 100644 --- a/packages/driver/src/datatypes/datetime.ts +++ b/packages/driver/src/datatypes/datetime.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import { isLeapYear, } from "./dateutil"; -export const DATE_PRIVATE = Symbol.for("edgedb.datetime"); +export const DATE_PRIVATE = Symbol.for("gel.datetime"); // Converts value to number, or if value is NaN returns 0 // as defined in temporal spec: diff --git a/packages/driver/src/datatypes/dateutil.ts b/packages/driver/src/datatypes/dateutil.ts index 59e6a053c..f72d9d295 100644 --- a/packages/driver/src/datatypes/dateutil.ts +++ b/packages/driver/src/datatypes/dateutil.ts @@ -1,5 +1,5 @@ /*! - * Portions Copyright (c) 2019 MagicStack Inc. and the EdgeDB authors. + * Portions Copyright (c) 2019 MagicStack Inc. and the Gel authors. * Portions Copyright (c) 2001-2019 Python Software Foundation. * All rights reserved. * Licence: PSFL https://docs.python.org/3/license.html diff --git a/packages/driver/src/datatypes/memory.ts b/packages/driver/src/datatypes/memory.ts index 30f3797ca..1409ed4f8 100644 --- a/packages/driver/src/datatypes/memory.ts +++ b/packages/driver/src/datatypes/memory.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/datatypes/range.ts b/packages/driver/src/datatypes/range.ts index 78bd029d3..afb9ce61e 100644 --- a/packages/driver/src/datatypes/range.ts +++ b/packages/driver/src/datatypes/range.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/errors/base.ts b/packages/driver/src/errors/base.ts index f5c3ff190..b24f63ef4 100644 --- a/packages/driver/src/errors/base.ts +++ b/packages/driver/src/errors/base.ts @@ -1,7 +1,7 @@ import { utf8Decoder } from "../primitives/buffer"; import type { tags } from "./tags"; -export class EdgeDBError extends Error { +export class GelError extends Error { protected static tags: { [tag in tags]?: boolean } = {}; private _message: string; private _query?: string; @@ -36,12 +36,12 @@ export class EdgeDBError extends Error { } hasTag(tag: tags): boolean { - const error_type = this.constructor as typeof EdgeDBError; + const error_type = this.constructor as typeof GelError; return error_type.tags[tag] ?? false; } } -export type ErrorType = new (msg: string) => EdgeDBError; +export type ErrorType = new (msg: string) => GelError; export enum ErrorAttr { hint = 1, diff --git a/packages/driver/src/errors/index.ts b/packages/driver/src/errors/index.ts index 6f73f848c..5b8b9364b 100644 --- a/packages/driver/src/errors/index.ts +++ b/packages/driver/src/errors/index.ts @@ -1,9 +1,9 @@ /* AUTOGENERATED */ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,24 +20,24 @@ /* tslint:disable */ -import { EdgeDBError } from "./base"; +import { GelError } from "./base"; import * as tags from "./tags"; -export { EdgeDBError } from "./base"; +export { GelError } from "./base"; export * from "./tags"; -export class InternalServerError extends EdgeDBError { +export class InternalServerError extends GelError { get code(): number { return 0x01_00_00_00; } } -export class UnsupportedFeatureError extends EdgeDBError { +export class UnsupportedFeatureError extends GelError { get code(): number { return 0x02_00_00_00; } } -export class ProtocolError extends EdgeDBError { +export class ProtocolError extends GelError { get code(): number { return 0x03_00_00_00; } @@ -110,7 +110,7 @@ export class DisabledCapabilityError extends CapabilityError { } } -export class QueryError extends EdgeDBError { +export class QueryError extends GelError { get code(): number { return 0x04_00_00_00; } @@ -393,7 +393,7 @@ export class IdleTransactionTimeoutError extends TransactionTimeoutError { } } -export class ExecutionError extends EdgeDBError { +export class ExecutionError extends GelError { get code(): number { return 0x05_00_00_00; } @@ -486,13 +486,13 @@ export class WatchError extends ExecutionError { } } -export class ConfigurationError extends EdgeDBError { +export class ConfigurationError extends GelError { get code(): number { return 0x06_00_00_00; } } -export class AccessError extends EdgeDBError { +export class AccessError extends GelError { get code(): number { return 0x07_00_00_00; } @@ -504,7 +504,7 @@ export class AuthenticationError extends AccessError { } } -export class AvailabilityError extends EdgeDBError { +export class AvailabilityError extends GelError { get code(): number { return 0x08_00_00_00; } @@ -543,7 +543,7 @@ export class ServerBlockedError extends AvailabilityError { } } -export class BackendError extends EdgeDBError { +export class BackendError extends GelError { get code(): number { return 0x09_00_00_00; } @@ -555,7 +555,7 @@ export class UnsupportedBackendFeatureError extends BackendError { } } -export class LogMessage extends EdgeDBError { +export class LogMessage extends GelError { get code(): number { return 0xf0_00_00_00; } @@ -567,7 +567,7 @@ export class WarningMessage extends LogMessage { } } -export class ClientError extends EdgeDBError { +export class ClientError extends GelError { get code(): number { return 0xff_00_00_00; } diff --git a/packages/driver/src/errors/map.ts b/packages/driver/src/errors/map.ts index 7f9cf1fef..634a6ef83 100644 --- a/packages/driver/src/errors/map.ts +++ b/packages/driver/src/errors/map.ts @@ -1,9 +1,9 @@ /* AUTOGENERATED */ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/errors/resolve.ts b/packages/driver/src/errors/resolve.ts index 39a784db5..7ec3eb1aa 100644 --- a/packages/driver/src/errors/resolve.ts +++ b/packages/driver/src/errors/resolve.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ export function resolveErrorCode(code: number): ErrorType { return result; } - return errors.EdgeDBError; + return errors.GelError; } const _JSON_FIELDS = { diff --git a/packages/driver/src/fetchConn.ts b/packages/driver/src/fetchConn.ts index 9d91fe033..16cc421d6 100644 --- a/packages/driver/src/fetchConn.ts +++ b/packages/driver/src/fetchConn.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2022-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2022-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -205,7 +205,7 @@ export class AdminUIFetchConnection extends BaseFetchConnection { return conn as InstanceType; } - // These methods are exposed for use by EdgeDB Studio + // These methods are exposed for use by Gel Studio public async rawParse( language: Language, query: string, diff --git a/packages/driver/src/httpScram.ts b/packages/driver/src/httpScram.ts index ef87f4f29..acb47261b 100644 --- a/packages/driver/src/httpScram.ts +++ b/packages/driver/src/httpScram.ts @@ -46,7 +46,7 @@ export function getHTTPSCRAMAuth(cryptoUtils: CryptoUtils): HttpSCRAMAuth { // The first request must have status 401 Unauthorized and provide a // WWW-Authenticate header with a SCRAM-SHA-256 challenge. - // See: https://github.com/edgedb/edgedb/blob/09782afd3b759440abbb1b26ee19b6589be04275/edb/server/protocol/auth/scram.py#L153-L157 + // See: https://github.com/geldata/gel/blob/09782afd3b759440abbb1b26ee19b6589be04275/edb/server/protocol/auth/scram.py#L153-L157 const authenticateHeader = serverFirstRes.headers.get("WWW-Authenticate"); if (serverFirstRes.status !== 401 || !authenticateHeader) { const body = await serverFirstRes.text(); @@ -64,10 +64,11 @@ export function getHTTPSCRAMAuth(cryptoUtils: CryptoUtils): HttpSCRAMAuth { // The server may respond with a 401 Unauthorized and `WWW-Authenticate: SCRAM-SHA-256` with // no parameters if authentication fails, e.g., due to an incorrect username. - // See: https://github.com/edgedb/edgedb/blob/09782afd3b759440abbb1b26ee19b6589be04275/edb/server/protocol/auth/scram.py#L112-L120 + // See: https://github.com/geldata/gel/blob/09782afd3b759440abbb1b26ee19b6589be04275/edb/server/protocol/auth/scram.py#L112-L120 const authParams = authenticateHeader.split(/ (.+)?/, 2)[1] ?? ""; if (authParams.length === 0) { const body = await serverFirstRes.text(); + throw new ProtocolError(`authentication failed: ${body}`); } @@ -98,8 +99,9 @@ export function getHTTPSCRAMAuth(cryptoUtils: CryptoUtils): HttpSCRAMAuth { // The second request is successful if the server responds with a 200 and an // Authentication-Info header (see https://datatracker.ietf.org/doc/html/rfc7615#section-3). - // See: https://github.com/edgedb/edgedb/blob/09782afd3b759440abbb1b26ee19b6589be04275/edb/server/protocol/auth/scram.py#L252-L254 + // See: https://github.com/geldata/gel/blob/09782afd3b759440abbb1b26ee19b6589be04275/edb/server/protocol/auth/scram.py#L252-L254 const authInfoHeader = serverFinalRes.headers.get("Authentication-Info"); + if (!serverFinalRes.ok || !authInfoHeader) { const body = await serverFinalRes.text(); throw new ProtocolError(`authentication failed: ${body}`); diff --git a/packages/driver/src/ifaces.ts b/packages/driver/src/ifaces.ts index cb1bcb68c..345d797a7 100644 --- a/packages/driver/src/ifaces.ts +++ b/packages/driver/src/ifaces.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/index.browser.ts b/packages/driver/src/index.browser.ts index 16417a65d..8651e9638 100644 --- a/packages/driver/src/index.browser.ts +++ b/packages/driver/src/index.browser.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/index.node.ts b/packages/driver/src/index.node.ts index e6c16674f..2291d5090 100644 --- a/packages/driver/src/index.node.ts +++ b/packages/driver/src/index.node.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/index.shared.ts b/packages/driver/src/index.shared.ts index df17e2200..de33a56fa 100644 --- a/packages/driver/src/index.shared.ts +++ b/packages/driver/src/index.shared.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/options.ts b/packages/driver/src/options.ts index eb9340dda..4255dedbc 100644 --- a/packages/driver/src/options.ts +++ b/packages/driver/src/options.ts @@ -40,19 +40,19 @@ export interface SimpleRetryOptions { backoff?: BackoffFunction; } -export type WarningHandler = (warnings: errors.EdgeDBError[]) => void; +export type WarningHandler = (warnings: errors.GelError[]) => void; -export function throwWarnings(warnings: errors.EdgeDBError[]) { +export function throwWarnings(warnings: errors.GelError[]) { throw new Error( `warnings occurred while running query: ${warnings.map((warn) => warn.message)}`, { cause: warnings }, ); } -export function logWarnings(warnings: errors.EdgeDBError[]) { +export function logWarnings(warnings: errors.GelError[]) { for (const warning of warnings) { console.warn( - new Error(`EdgeDB warning: ${warning.message}`, { cause: warning }), + new Error(`Gel warning: ${warning.message}`, { cause: warning }), ); } } @@ -85,7 +85,7 @@ export class RetryOptions { return result; } - getRuleForException(err: errors.EdgeDBError): RetryRule { + getRuleForException(err: errors.GelError): RetryRule { let result; if (err instanceof errors.TransactionConflictError) { result = this.overrides.get(RetryCondition.TransactionConflict); diff --git a/packages/driver/src/primitives/buffer.ts b/packages/driver/src/primitives/buffer.ts index 592c90514..987c577ed 100644 --- a/packages/driver/src/primitives/buffer.ts +++ b/packages/driver/src/primitives/buffer.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/primitives/chars.ts b/packages/driver/src/primitives/chars.ts index 0da851ef9..a5337a198 100644 --- a/packages/driver/src/primitives/chars.ts +++ b/packages/driver/src/primitives/chars.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/primitives/event.ts b/packages/driver/src/primitives/event.ts index 30ad09d4f..279d84416 100644 --- a/packages/driver/src/primitives/event.ts +++ b/packages/driver/src/primitives/event.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2021-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2021-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/primitives/lru.ts b/packages/driver/src/primitives/lru.ts index db81ce515..ca2aae575 100644 --- a/packages/driver/src/primitives/lru.ts +++ b/packages/driver/src/primitives/lru.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/primitives/queues.ts b/packages/driver/src/primitives/queues.ts index 99413fabd..d94f3ecf0 100644 --- a/packages/driver/src/primitives/queues.ts +++ b/packages/driver/src/primitives/queues.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/rawConn.ts b/packages/driver/src/rawConn.ts index d38050943..c1354834e 100644 --- a/packages/driver/src/rawConn.ts +++ b/packages/driver/src/rawConn.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ function getTlsOptions(config: ResolvedConnectConfig): tls.ConnectionOptions { const isIPAddress = net.isIP(config.address[0]) !== 0; if (!isIPAddress) { // XXX Deno doesn't support this and that means it won't - // work with EdgeDB Cloud. + // work with Gel Cloud. tlsOptions.servername = config.tlsServerName || config.address[0]; } @@ -294,7 +294,7 @@ export class RawConnection extends BaseRawConnection { `connection timed out (${config.connectTimeout}ms)`, ); } - if (e instanceof errors.EdgeDBError) { + if (e instanceof errors.GelError) { throw e; } else { let err: errors.ClientConnectionError; diff --git a/packages/driver/src/reflection/analyzeQuery.ts b/packages/driver/src/reflection/analyzeQuery.ts index fe5c9922e..ebd469e6d 100644 --- a/packages/driver/src/reflection/analyzeQuery.ts +++ b/packages/driver/src/reflection/analyzeQuery.ts @@ -41,7 +41,7 @@ export async function analyzeQuery( cardinality, query, importMap: imports, - imports: imports.get("edgedb") ?? new Set(), + imports: imports.get("gel") ?? new Set(), }; } diff --git a/packages/driver/src/reflection/index.ts b/packages/driver/src/reflection/index.ts index b500a0706..7125a60f4 100644 --- a/packages/driver/src/reflection/index.ts +++ b/packages/driver/src/reflection/index.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/reflection/strictMap.ts b/packages/driver/src/reflection/strictMap.ts index 647b2c0df..5bc8ded39 100644 --- a/packages/driver/src/reflection/strictMap.ts +++ b/packages/driver/src/reflection/strictMap.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/retry.ts b/packages/driver/src/retry.ts index 487857fdd..5813ffc7a 100644 --- a/packages/driver/src/retry.ts +++ b/packages/driver/src/retry.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,8 +67,8 @@ export async function retryingConnect( logMsg.push( `\n\n\n` + `Hint: it looks like the program is running from a ` + - `directory initialized with "edgedb project init". ` + - `Consider calling "edgedb.connect()" without arguments.` + + `directory initialized with "gel project init". ` + + `Consider calling "gel.connect()" without arguments.` + `\n`, ); } diff --git a/packages/driver/src/scram.ts b/packages/driver/src/scram.ts index 61eb61985..5b3a3cee6 100644 --- a/packages/driver/src/scram.ts +++ b/packages/driver/src/scram.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/src/transaction.ts b/packages/driver/src/transaction.ts index 2eec3c566..cfdd07526 100644 --- a/packages/driver/src/transaction.ts +++ b/packages/driver/src/transaction.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ export class Transaction implements Executor { const abortError = this._rawConn.getConnAbortError(); if ( - abortError instanceof errors.EdgeDBError && + abortError instanceof errors.GelError && abortError.cause instanceof errors.TransactionTimeoutError ) { throw abortError.cause; diff --git a/packages/driver/src/utils.ts b/packages/driver/src/utils.ts index 723a961d4..505b22eea 100644 --- a/packages/driver/src/utils.ts +++ b/packages/driver/src/utils.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ export function getUniqueId(prefix = ""): string { idCounter[prefix] = 0; } const id = ++idCounter[prefix]; - return `_edgedb_${prefix}_${id.toString(16)}_`; + return `_gel_${prefix}_${id.toString(16)}_`; } export function sleep(durationMillis: number): Promise { @@ -119,6 +119,7 @@ export async function getAuthenticatedFetch( const headers = new Headers(init?.headers); if (config.user !== undefined) { + // TODO: headers.append("X-Gel-User", config.user); headers.append("X-EdgeDB-User", config.user); } diff --git a/packages/driver/test/browser.test.ts b/packages/driver/test/browser.test.ts index ad39edcb3..00b4abdbc 100644 --- a/packages/driver/test/browser.test.ts +++ b/packages/driver/test/browser.test.ts @@ -5,7 +5,7 @@ const { TextEncoder, TextDecoder } = require("util"); global.TextEncoder = TextEncoder; global.TextDecoder = TextDecoder; -import { getEdgeDBVersion } from "./testbase"; +import { getGelVersion } from "./testbase"; const nodeVersion = parseInt(process.version.slice(1).split(".")[0], 10); @@ -14,7 +14,7 @@ if (nodeVersion >= 15) { crypto.subtle = require("crypto").webcrypto.subtle; } -const version = getEdgeDBVersion(); +const version = getGelVersion(); beforeAll(async () => { for (const nodeModule of [ @@ -64,20 +64,16 @@ beforeAll(async () => { } }); -import { - createClient, - createHttpClient, - EdgeDBError, -} from "../src/index.browser"; +import { createClient, createHttpClient, GelError } from "../src/index.browser"; const brokenConnectOpts = JSON.parse( - process.env._JEST_EDGEDB_CONNECT_CONFIG || "", + process.env._JEST_GEL_CONNECT_CONFIG || "", ); -const edgedbVersion = JSON.parse(process.env._JEST_EDGEDB_VERSION!); +const gelVersion = JSON.parse(process.env._JEST_GEL_VERSION!); const connectOpts = { ...brokenConnectOpts, - user: edgedbVersion.major >= 6 ? "admin" : "edgedb", + user: gelVersion.major >= 6 ? "admin" : "edgedb", tlsCAFile: undefined, tlsSecurity: "insecure", }; @@ -86,7 +82,7 @@ const connectOpts = { if (nodeVersion >= 15) { test("createClient fails", () => { if (version.major < 2) return; - expect(() => createClient()).toThrowError(EdgeDBError); + expect(() => createClient()).toThrowError(GelError); }); test("createHttpClient no options", async () => { diff --git a/packages/driver/test/buffers.test.ts b/packages/driver/test/buffers.test.ts index 502f7d079..6717e6f43 100644 --- a/packages/driver/test/buffers.test.ts +++ b/packages/driver/test/buffers.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import { } from "../src/primitives/buffer"; import * as chars from "../src/primitives/chars"; -test("matches edgedb-python packing", () => { +test("matches gel-python packing", () => { const w: WriteMessageBuffer = new WriteMessageBuffer(); w.beginMessage(chars.$E) diff --git a/packages/driver/test/client.test.ts b/packages/driver/test/client.test.ts index ec28ce690..d91a52b22 100644 --- a/packages/driver/test/client.test.ts +++ b/packages/driver/test/client.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import type { Executor, _ICodec, Codecs } from "../src/index.node"; import { DivisionByZeroError, Duration, - EdgeDBError, + GelError, LocalDate, LocalDateTime, Range, @@ -61,7 +61,7 @@ import { getAvailableFeatures, getClient, getConnectOptions, - getEdgeDBVersion, + getGelVersion, } from "./testbase"; import { PG_VECTOR_MAX_DIM } from "../src/codecs/pgvector"; import { getHTTPSCRAMAuth } from "../src/httpScram"; @@ -761,7 +761,7 @@ test("fetch: named args", async () => { } }); -if (getEdgeDBVersion().major >= 3) { +if (getGelVersion().major >= 3) { test("fetch: tuples in args", async () => { const client = getClient(); try { @@ -1388,7 +1388,7 @@ function expandRangeJS(lower: any, upper: any) { ]; } -if (getEdgeDBVersion().major >= 2) { +if (getGelVersion().major >= 2) { test("fetch: ranges", async () => { const client = getClient(); @@ -1501,7 +1501,7 @@ if (getEdgeDBVersion().major >= 2) { }); } -if (getEdgeDBVersion().major >= 4) { +if (getGelVersion().major >= 4) { test("fetch: multirange", async () => { const client = getClient(); try { @@ -1971,7 +1971,7 @@ test("execute", async () => { expect(e.toString()).toMatch("division by zero"); expect(e instanceof DivisionByZeroError).toBeTruthy(); expect(e instanceof MissingRequiredError).toBeFalsy(); - expect(e instanceof EdgeDBError).toBeTruthy(); + expect(e instanceof GelError).toBeTruthy(); expect((e).code).toBe(0x05_01_00_01); }); } finally { @@ -1987,7 +1987,7 @@ test("scripts and args", async () => { };`); try { - if (getEdgeDBVersion().major >= 2) { + if (getGelVersion().major >= 2) { await expect( client.execute( ` @@ -2069,7 +2069,7 @@ test("scripts and args", async () => { { name: "test" }, ), ).rejects.toThrowError( - /arguments in execute\(\) is not supported in this version of EdgeDB/, + /arguments in execute\(\) is not supported in this version of Gel/, ); await expect( @@ -2080,7 +2080,7 @@ test("scripts and args", async () => { { name: "test" }, ), ).rejects.toThrowError( - /arguments in execute\(\) is not supported in this version of EdgeDB/, + /arguments in execute\(\) is not supported in this version of Gel/, ); await expect( @@ -2188,19 +2188,19 @@ test("pretty error message", async () => { }); test("warnings handler", async () => { - if (getEdgeDBVersion().major < 6) return; + if (getGelVersion().major < 6) return; let client = getClient(); try { - let warnings: EdgeDBError[] | null = null; + let warnings: GelError[] | null = null; client = client.withWarningHandler((_warnings) => (warnings = _warnings)); await expect(client.query("select _warn_on_call();")).resolves.toEqual([0]); expect(Array.isArray(warnings)).toBe(true); expect(warnings!.length).toBe(1); - expect(warnings![0]).toBeInstanceOf(EdgeDBError); + expect(warnings![0]).toBeInstanceOf(GelError); expect(warnings![0].message.trim()).toBe("Test warning please ignore"); warnings = null; @@ -2211,7 +2211,7 @@ test("warnings handler", async () => { expect(Array.isArray(warnings)).toBe(true); expect(warnings!.length).toBe(1); - expect(warnings![0]).toBeInstanceOf(EdgeDBError); + expect(warnings![0]).toBeInstanceOf(GelError); expect(warnings![0].message.trim()).toBe("Test warning please ignore"); client = client.withWarningHandler(throwWarnings); @@ -2252,14 +2252,14 @@ if (getAvailableFeatures().has("binary-over-http")) { tlsSecurity: "insecure", }); - const edgedbVer = getEdgeDBVersion(); + const gelVer = getGelVersion(); const fetchConn = AdminUIFetchConnection.create( await getAuthenticatedFetch( config.connectionParams, getHTTPSCRAMAuth(cryptoUtils), ), codecsRegistry, - [edgedbVer.major, edgedbVer.minor], + [gelVer.major, gelVer.minor], ); const query = `SELECT Function { name }`; @@ -2309,7 +2309,7 @@ if (getAvailableFeatures().has("binary-over-http")) { }); } -if (getEdgeDBVersion().major >= 5) { +if (getGelVersion().major >= 5) { test("fetch: int64 as bigint", async () => { const con = getClient().withCodecs({ "std::int64": { @@ -2430,7 +2430,7 @@ if (getEdgeDBVersion().major >= 5) { | "ext::pgvector::halfvec" // just need to write a test | "ext::pgvector::sparsevec" - // these are only available in EdgeDB 6, and also re-use the + // these are only available in Gel 6, and also re-use the // existing codecs, so I'm not too worried on testing them. | "std::pg::json" | "std::pg::timestamptz" @@ -2575,7 +2575,7 @@ if (getEdgeDBVersion().major >= 5) { }); } -if (getEdgeDBVersion().major >= 6) { +if (getGelVersion().major >= 6) { test("querySQL", async () => { let client = getClient(); diff --git a/packages/driver/test/connection-config.test.ts b/packages/driver/test/connection-config.test.ts index 8be070b6e..14c2d0c8e 100644 --- a/packages/driver/test/connection-config.test.ts +++ b/packages/driver/test/connection-config.test.ts @@ -174,7 +174,7 @@ const errorMapping: { [key: string]: string | RegExp } = { env_not_found: /environment variable '.*' doesn't exist/, file_not_found: /no such file or directory/, invalid_tls_security: - /^invalid 'tlsSecurity' value|'tlsSecurity' value cannot be lower than security level set by EDGEDB_CLIENT_SECURITY/, + /^invalid 'tlsSecurity' value|'tlsSecurity' value cannot be lower than security level set by GEL_CLIENT_SECURITY/, exclusive_options: /^Cannot specify both .* and .*|are mutually exclusive/, secret_key_not_found: /^Cannot connect to cloud instances without a secret key/, @@ -182,7 +182,8 @@ const errorMapping: { [key: string]: string | RegExp } = { }; const warningMapping: { [key: string]: string } = { - docker_tcp_port: `EDGEDB_PORT in 'tcp://host:port' format, so will be ignored`, + docker_tcp_port: `GEL_PORT in 'tcp://host:port' format, so will be ignored`, + gel_and_edgedb: `Both GEL_\w+ and EDGEDB_\w+ are set; EDGEDB_\w+ will be ignored`, }; interface ConnectionResult { @@ -471,6 +472,7 @@ test("logging, inProject, fromProject, fromEnv", async () => { fromProject: false, fromEnv: false, }, + // fromEnv: true - should take into account env vars { opts: { user: "user" }, env: { @@ -491,6 +493,27 @@ test("logging, inProject, fromProject, fromEnv", async () => { fromProject: false, fromEnv: true, }, + { + opts: { user: "user" }, + env: { + GEL_DATABASE: "testdb", + GEL_PASSWORD: "passw", + GEL_HOST: "host", + GEL_PORT: "123", + }, + result: { + ...defaults, + address: ["host", 123], + user: "user", + database: "testdb", + password: "passw", + }, + logging: true, + inProject: false, + fromProject: false, + fromEnv: true, + }, + // fromEnv: false - should not take into account env vars { opts: { dsn: "edgedb://", user: "user" }, env: { @@ -508,6 +531,26 @@ test("logging, inProject, fromProject, fromEnv", async () => { fromProject: false, fromEnv: false, }, + { + opts: { dsn: "gel://", user: "user" }, + env: { + GEL_DATABASE: "testdb", + GEL_PASSWORD: "passw", + GEL_HOST: "host", + GEL_PORT: "123", + }, + result: { + ...defaults, + user: "user", + }, + logging: true, + inProject: false, + fromProject: false, + fromEnv: false, + }, + // Considers credentials file, environment variables, and inline options in + // order of precedence: credentials file < environment variables < inline + // options, where each level overrides the one before it. { opts: { user: "user" }, env: { @@ -539,6 +582,39 @@ test("logging, inProject, fromProject, fromEnv", async () => { fromProject: true, fromEnv: true, }, + { + opts: { user: "user" }, + env: { + GEL_DATABASE: "testdb", + GEL_PASSWORD: "passw", + }, + fs: { + cwd: "/home/edgedb/test", + homedir: "/home/edgedb", + files: { + "/home/edgedb/test/gel.toml": "", + "/home/edgedb/.config/edgedb/projects/test-cf3c86df8fc33fbb73a47671ac5762eda8219158": + "", + "/home/edgedb/.config/edgedb/projects/test-cf3c86df8fc33fbb73a47671ac5762eda8219158/instance-name": + "test_project", + "/home/edgedb/.config/edgedb/credentials/test_project.json": + '{"port": 10702, "user": "test3n", "password": "lZTBy1RVCfOpBAOwSCwIyBIR", "database": "test3n"}', + }, + }, + result: { + ...defaults, + address: ["localhost", 10702], + user: "user", + database: "testdb", + password: "passw", + }, + logging: true, + inProject: true, + fromProject: true, + fromEnv: true, + }, + // Considers credentials file and inline options. Inline options + // have higher precedence and ovverride config from the file. { opts: { user: "user", database: "db", password: "secret" }, env: { @@ -570,6 +646,38 @@ test("logging, inProject, fromProject, fromEnv", async () => { fromProject: true, fromEnv: false, }, + { + opts: { user: "user", database: "db", password: "secret" }, + env: { + GEL_DATABASE: "testdb", + GEL_PASSWORD: "passw", + }, + fs: { + cwd: "/home/edgedb/test", + homedir: "/home/edgedb", + files: { + "/home/edgedb/test/gel.toml": "", + "/home/edgedb/.config/edgedb/projects/test-cf3c86df8fc33fbb73a47671ac5762eda8219158": + "", + "/home/edgedb/.config/edgedb/projects/test-cf3c86df8fc33fbb73a47671ac5762eda8219158/instance-name": + "test_project", + "/home/edgedb/.config/edgedb/credentials/test_project.json": + '{"port": 10702, "user": "test3n", "password": "lZTBy1RVCfOpBAOwSCwIyBIR", "database": "test3n"}', + }, + }, + result: { + ...defaults, + address: ["localhost", 10702], + user: "user", + database: "db", + password: "secret", + }, + logging: true, + inProject: true, + fromProject: true, + fromEnv: false, + }, + // Considers inline options only. Config from the file and env vars is ignored. { opts: { host: "test.local" }, env: { @@ -592,6 +700,28 @@ test("logging, inProject, fromProject, fromEnv", async () => { fromProject: false, fromEnv: false, }, + { + opts: { host: "test.local" }, + env: { + GEL_DATABASE: "testdb", + GEL_PASSWORD: "passw", + }, + fs: { + cwd: "/home/edgedb/test", + homedir: "/home/edgedb", + files: { + "/home/edgedb/test/gel.toml": "", + }, + }, + result: { + ...defaults, + address: ["test.local", 5656], + }, + logging: true, + inProject: true, + fromProject: false, + fromEnv: false, + }, ]) { if ( testcase.fs && @@ -624,7 +754,9 @@ test("logging, inProject, fromProject, fromEnv", async () => { } }); -test("EDGEDB_CLIENT_SECURITY env var", async () => { +// Checks if _tlsSecurity is correctly set up based on env vars and inline +// options for CLIENT_SECURITY and CLIENT_TLS_SECURITY. +test("GEL_CLIENT_SECURITY env var", async () => { const truthTable: [string, string, string | null][] = [ // CLIENT_SECURITY, CLIENT_TLS_SECURITY, result ["default", "default", "default"], @@ -645,7 +777,7 @@ test("EDGEDB_CLIENT_SECURITY env var", async () => { await envWrap( { env: { - EDGEDB_CLIENT_SECURITY: clientSecurity, + GEL_CLIENT_SECURITY: clientSecurity, }, }, async () => { diff --git a/packages/driver/test/connection.test.ts b/packages/driver/test/connection.test.ts index 01779d30b..ef3997f26 100644 --- a/packages/driver/test/connection.test.ts +++ b/packages/driver/test/connection.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/test/createClient.test.ts b/packages/driver/test/createClient.test.ts index 0447e9cbc..c3c77dffb 100644 --- a/packages/driver/test/createClient.test.ts +++ b/packages/driver/test/createClient.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/test/datetime.test.ts b/packages/driver/test/datetime.test.ts index 627f9e2ac..f309dd7d4 100644 --- a/packages/driver/test/datetime.test.ts +++ b/packages/driver/test/datetime.test.ts @@ -9,12 +9,12 @@ import { import { Duration, LocalDateTime, LocalTime } from "../src/index.shared"; import { ReadBuffer, WriteBuffer } from "../src/primitives/buffer"; -// EdgeDB date/time types have microsecond precision. +// Gel date/time types have microsecond precision. // JS Date has millisecond precision, Temporal types have nanosecond. // When converting from micro -> milli, or nano -> micro, round to nearest even // should be used. -// Tests adapted from https://github.com/edgedb/edgedb-rust/blob/master/edgedb-protocol/tests/datetime_chrono.rs +// Tests adapted from https://github.com/geldata/gel-rust/blob/master/gel-protocol/tests/datetime_chrono.rs test("datetime", () => { const codec = new DateTimeCodec( diff --git a/packages/driver/test/errors.test.ts b/packages/driver/test/errors.test.ts index 6ad13c017..3274ab0bd 100644 --- a/packages/driver/test/errors.test.ts +++ b/packages/driver/test/errors.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,19 @@ * limitations under the License. */ -import * as edgedb from "../src/index.node"; +import * as gel from "../src/index.node"; import { resolveErrorCode } from "../src/errors/resolve"; test("resolve error", () => { - expect(resolveErrorCode(0x04_02_01_01)).toBe(edgedb.InvalidLinkTargetError); - expect(resolveErrorCode(0x04_02_01_ff)).toBe(edgedb.InvalidTargetError); - expect(resolveErrorCode(0x04_02_ff_ff)).toBe(edgedb.InvalidTypeError); - expect(resolveErrorCode(0x04_ff_ff_ff)).toBe(edgedb.QueryError); - expect(resolveErrorCode(0xfe_ff_ff_ff)).toBe(edgedb.EdgeDBError); + expect(resolveErrorCode(0x04_02_01_01)).toBe(gel.InvalidLinkTargetError); + expect(resolveErrorCode(0x04_02_01_ff)).toBe(gel.InvalidTargetError); + expect(resolveErrorCode(0x04_02_ff_ff)).toBe(gel.InvalidTypeError); + expect(resolveErrorCode(0x04_ff_ff_ff)).toBe(gel.QueryError); + expect(resolveErrorCode(0xfe_ff_ff_ff)).toBe(gel.GelError); }); test("message is set with attrs and query", () => { - const error = new edgedb.AccessError("test"); + const error = new gel.AccessError("test"); const attrs = new Map(); const columnStart = 2; @@ -53,7 +53,7 @@ test("message is set with attrs and query", () => { }); test("message is set with attrs and query without position", () => { - const error = new edgedb.AccessError("test"); + const error = new gel.AccessError("test"); const attrs = new Map(); // hint diff --git a/packages/driver/test/globalSetup.ts b/packages/driver/test/globalSetup.ts index 98d97fc7e..766cd1304 100644 --- a/packages/driver/test/globalSetup.ts +++ b/packages/driver/test/globalSetup.ts @@ -10,7 +10,7 @@ import { export default async () => { // tslint:disable-next-line - console.log("\nStarting EdgeDB test cluster..."); + console.log("\nStarting Gel test cluster..."); const statusFile = generateStatusFileName("node"); console.log("Node status file:", statusFile); @@ -27,15 +27,14 @@ export default async () => { }; // @ts-ignore - global.edgedbProc = proc; + global.gelProc = proc; - process.env._JEST_EDGEDB_CONNECT_CONFIG = JSON.stringify(jestConfig); - process.env._JEST_EDGEDB_AVAILABLE_FEATURES = - JSON.stringify(availableFeatures); + process.env._JEST_GEL_CONNECT_CONFIG = JSON.stringify(jestConfig); + process.env._JEST_GEL_AVAILABLE_FEATURES = JSON.stringify(availableFeatures); // @ts-ignore - global.edgedbConn = client; - process.env._JEST_EDGEDB_VERSION = JSON.stringify(version); + global.gelConn = client; + process.env._JEST_GEL_VERSION = JSON.stringify(version); const availableExtensions = ( await client.query<{ @@ -43,9 +42,9 @@ export default async () => { version: { major: number; minor: number }; }>(`select sys::ExtensionPackage {name, version}`) ).map(({ name, version }) => [name, version]); - process.env._JEST_EDGEDB_AVAILABLE_EXTENSIONS = + process.env._JEST_GEL_AVAILABLE_EXTENSIONS = JSON.stringify(availableExtensions); // tslint:disable-next-line - console.log(`EdgeDB test cluster is up [port: ${jestConfig.port}]...`); + console.log(`Gel test cluster is up [port: ${jestConfig.port}]...`); }; diff --git a/packages/driver/test/globalTeardown.ts b/packages/driver/test/globalTeardown.ts index 4496902b4..6174f74d7 100644 --- a/packages/driver/test/globalTeardown.ts +++ b/packages/driver/test/globalTeardown.ts @@ -2,13 +2,13 @@ import { shutdown } from "./testUtil"; export default async () => { // tslint:disable-next-line - console.log("Shutting down EdgeDB test cluster..."); + console.log("Shutting down Gel test cluster..."); try { // @ts-ignore - await shutdown(global.edgedbProc, global.edgedbConn); + await shutdown(global.gelProc, global.gelConn); } finally { // tslint:disable-next-line - console.log("EdgeDB test cluster is down..."); + console.log("Gel test cluster is down..."); } }; diff --git a/packages/driver/test/lru.test.ts b/packages/driver/test/lru.test.ts index 1a8d7830c..db0d68904 100644 --- a/packages/driver/test/lru.test.ts +++ b/packages/driver/test/lru.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/test/misc.test.ts b/packages/driver/test/misc.test.ts index 310456b3d..7a1354447 100644 --- a/packages/driver/test/misc.test.ts +++ b/packages/driver/test/misc.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/test/pool.test.ts b/packages/driver/test/pool.test.ts index eb3d0a3b0..f672a7fa8 100644 --- a/packages/driver/test/pool.test.ts +++ b/packages/driver/test/pool.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/test/queues.test.ts b/packages/driver/test/queues.test.ts index 0fee2aa7c..2ce413fe6 100644 --- a/packages/driver/test/queues.test.ts +++ b/packages/driver/test/queues.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/test/retry.test.ts b/packages/driver/test/retry.test.ts index fdf37e242..ad71610db 100644 --- a/packages/driver/test/retry.test.ts +++ b/packages/driver/test/retry.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -124,7 +124,7 @@ async function checkRetries(client: Client, client2: Client, name: string) { // This magic query makes the test more reliable for some // reason. I guess this is because starting a transaction - // in EdgeDB (and/or Postgres) is accomplished somewhat + // in Gel (and/or Postgres) is accomplished somewhat // lazily, i.e. only start transaction on the first query // rather than on the `START TRANSACTION`. await tx.query(`SELECT 1`); diff --git a/packages/driver/test/retryConnError.test.ts b/packages/driver/test/retryConnError.test.ts index e28d81ad1..f24526406 100644 --- a/packages/driver/test/retryConnError.test.ts +++ b/packages/driver/test/retryConnError.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,10 +85,10 @@ test("transaction retry on connection error after start", async () => { currentSocket!.destroy(); } - return await tx.querySingle(`select 'Hello EdgeDB!'`); + return await tx.querySingle(`select 'Hello Gel!'`); }); - expect(result).toBe("Hello EdgeDB!"); + expect(result).toBe("Hello Gel!"); expect(retryCount).toBe(2); await client.close(); @@ -101,7 +101,7 @@ test("transaction retry on connection error before commit", async () => { const result = await client.transaction(async (tx) => { retryCount++; - const result = await tx.querySingle(`select 'Hello EdgeDB!'`); + const result = await tx.querySingle(`select 'Hello Gel!'`); if (retryCount === 1) { currentSocket!.destroy(); @@ -111,7 +111,7 @@ test("transaction retry on connection error before commit", async () => { return result; }); - expect(result).toBe("Hello EdgeDB!"); + expect(result).toBe("Hello Gel!"); expect(retryCount).toBe(2); await client.close(); @@ -125,7 +125,7 @@ test("transaction retry on connection error after commit", async () => { client.transaction(async (tx) => { retryCount++; - const result = await tx.querySingle(`select 'Hello EdgeDB!'`); + const result = await tx.querySingle(`select 'Hello Gel!'`); if (retryCount === 1) { // abort connection on CommandComplete message from 'COMMIT' @@ -153,13 +153,13 @@ test("retry readonly queries: complete fetch", async () => { // complete fetch - retrying currentSocket!.abortOnNextMessageType(chars.$D); - await expect(client.querySingle(`select 'Hello EdgeDB!'`)).resolves.toBe( - "Hello EdgeDB!", + await expect(client.querySingle(`select 'Hello Gel!'`)).resolves.toBe( + "Hello Gel!", ); currentSocket!.abortOnNextMessageType(chars.$D); await expect( - nonRetryingClient.query(`select 'Hello edgedb-js!'`), + nonRetryingClient.query(`select 'Hello gel-js!'`), ).rejects.toThrow(); }); @@ -171,13 +171,13 @@ test("retry readonly queries: optimistic fetch", async () => { await client.ensureConnected(); currentSocket!.abortOnNextMessageType(chars.$D); - await expect(client.querySingle(`select 'Hello EdgeDB!'`)).resolves.toBe( - "Hello EdgeDB!", + await expect(client.querySingle(`select 'Hello Gel!'`)).resolves.toBe( + "Hello Gel!", ); currentSocket!.abortOnNextMessageType(chars.$D); await expect( - nonRetryingClient.querySingle(`select 'Hello EdgeDB!'`), + nonRetryingClient.querySingle(`select 'Hello Gel!'`), ).rejects.toThrow(); await client.close(); diff --git a/packages/driver/test/scram.test.ts b/packages/driver/test/scram.test.ts index fdde3a5a9..183badbc4 100644 --- a/packages/driver/test/scram.test.ts +++ b/packages/driver/test/scram.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/driver/test/session.test.ts b/packages/driver/test/session.test.ts index 5e4e0ccf7..7d5e14e0d 100644 --- a/packages/driver/test/session.test.ts +++ b/packages/driver/test/session.test.ts @@ -3,9 +3,9 @@ import { DisabledCapabilityError, InvalidReferenceError, } from "../src/index.node"; -import { getClient, getEdgeDBVersion } from "./testbase"; +import { getClient, getGelVersion } from "./testbase"; -if (getEdgeDBVersion().major >= 2) { +if (getGelVersion().major >= 2) { test("with module", async () => { const client = getClient({ concurrency: 1 }); @@ -205,13 +205,13 @@ if (getEdgeDBVersion().major >= 2) { .withGlobals({ userId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }) .query("select 1"), ).rejects.toThrowError( - /setting session state is not supported in this version of EdgeDB/, + /setting session state is not supported in this version of Gel/, ); await expect( client.withModuleAliases({ module: "sys" }).query("select 1"), ).rejects.toThrowError( - /setting session state is not supported in this version of EdgeDB/, + /setting session state is not supported in this version of Gel/, ); await expect( @@ -221,7 +221,7 @@ if (getEdgeDBVersion().major >= 2) { }) .query("select 1"), ).rejects.toThrowError( - /setting session state is not supported in this version of EdgeDB/, + /setting session state is not supported in this version of Gel/, ); }); } diff --git a/packages/driver/test/shared-client-testcases b/packages/driver/test/shared-client-testcases index 071f60430..d720f509b 160000 --- a/packages/driver/test/shared-client-testcases +++ b/packages/driver/test/shared-client-testcases @@ -1 +1 @@ -Subproject commit 071f60430207e331b847e1dcc10cba19c5b5f2f4 +Subproject commit d720f509b352f2fe587b5ea6d0c624553b95e04b diff --git a/packages/driver/test/testUtil.ts b/packages/driver/test/testUtil.ts index a386b2402..0a1df71a3 100644 --- a/packages/driver/test/testUtil.ts +++ b/packages/driver/test/testUtil.ts @@ -8,9 +8,9 @@ import * as readline from "node:readline"; import type { ConnectConfig } from "../src/conUtils"; import { Client, createClient } from "../src/index.node"; -import type { EdgeDBVersion } from "./testbase"; +import type { GelVersion } from "./testbase"; -export type { EdgeDBVersion, ConnectConfig }; +export type { GelVersion, ConnectConfig }; interface ServerInfo { port: number; @@ -76,7 +76,7 @@ const generateTempID = (): number => { export const generateStatusFileName = (tag: string): string => { return path.join( os.tmpdir(), - `edgedb-js-status-file-${tag}-${generateTempID()}`, + `gel-js-status-file-${tag}-${generateTempID()}`, ); }; @@ -85,14 +85,14 @@ export const getServerCommand = ( strictSecurity = true, ): { args: string[]; availableFeatures: string[] } => { const availableFeatures: string[] = []; - let srvcmd = `edgedb-server`; - if (process.env.EDGEDB_SERVER_BIN) { - srvcmd = process.env.EDGEDB_SERVER_BIN; - } + + // we can check version here and use gel-server for newer versions + // but edgedb-server works for all versions + const srvcmd = process.env.GEL_SERVER_BIN || "edgedb-server"; let args = [srvcmd]; if (process.platform === "win32") { - args = ["wsl", "-u", "edgedb", ...args]; + args = ["wsl", "-u", "gel", ...args]; } const helpCmd = [...args, "--help"]; @@ -130,7 +130,6 @@ export const getServerCommand = ( `--security=${strictSecurity ? "strict" : "insecure_dev_mode"}`, "--bootstrap-command=ALTER ROLE edgedb { SET password := 'edgedbtest' }", ]; - return { args, availableFeatures }; }; @@ -144,12 +143,12 @@ export const startServer = async ( statusFile: string, env: { [key: string]: string } = {}, ): Promise => { - if (process.env.EDGEDB_DEBUG_SERVER) { + if (process.env.GEL_DEBUG_SERVER) { console.log(`running command: ${cmd.join(" ")}`); } const maybeEnvWithDevMode = - process.env.EDGEDB_SERVER_BIN || process.env.CI + process.env.GEL_SERVER_BIN || process.env.CI ? {} : { __EDGEDB_DEVMODE: "1", @@ -160,7 +159,7 @@ export const startServer = async ( }); try { - if (process.env.EDGEDB_DEBUG_SERVER) { + if (process.env.GEL_DEBUG_SERVER) { proc.stdout.on("data", (data) => { process.stdout.write(data.toString()); }); @@ -168,7 +167,7 @@ export const startServer = async ( let stderrData: string = ""; proc.stderr.on("data", (data) => { - if (process.env.EDGEDB_DEBUG_SERVER) { + if (process.env.GEL_DEBUG_SERVER) { process.stderr.write(data.toString()); } else { stderrData += data; @@ -180,13 +179,12 @@ export const startServer = async ( new Promise((_, reject) => { proc.addListener("exit", (code, signal) => { if (stderrData) { - console.log("--- EdgeDB output start ---"); + console.log("--- Gel output start ---"); console.log(stderrData); - console.log("--- EdgeDB output end ---"); + console.log("--- Gel output end ---"); } reject( - `EdgeDB exited prematurely with ` + - `code ${code} or signal ${signal}`, + `Gel exited prematurely with ` + `code ${code} or signal ${signal}`, ); }); }), @@ -226,10 +224,10 @@ export const startServer = async ( export const connectToServer = async ( config: ConnectConfig, -): Promise<{ client: Client; version: EdgeDBVersion }> => { +): Promise<{ client: Client; version: GelVersion }> => { const client = createClient(config); - let version: EdgeDBVersion; + let version: GelVersion; try { await client.execute(` CREATE DATABASE jest; @@ -267,14 +265,14 @@ export const shutdown = async ( await new Promise((resolve, reject) => { const to = setTimeout(() => { // tslint:disable-next-line - console.error("!!! EdgeDB exit timeout... !!!"); + console.error("!!! Gel exit timeout... !!!"); proc.kill("SIGTERM"); }, 30_000); proc.on("exit", (_code: number, signal: string) => { clearTimeout(to); if (signal === "SIGTERM") { - reject(new Error("edgedb did not shutdown gracefully")); + reject(new Error("gel did not shutdown gracefully")); } else { resolve(); } @@ -370,13 +368,13 @@ export function configToEnv(config: ConnectConfig): { [key: string]: string | undefined; } { return { - EDGEDB_HOST: config.host, - EDGEDB_PORT: config.port?.toString(), - EDGEDB_DATABASE: config.database, - EDGEDB_USER: config.user, - EDGEDB_PASSWORD: config.password, - // EDGEDB_TLS_CA_FILE: config.tlsCAFile, - // EDGEDB_CLIENT_TLS_SECURITY: config.tlsSecurity, - EDGEDB_CLIENT_SECURITY: "insecure_dev_mode", + GEL_HOST: config.host, + GEL_PORT: config.port?.toString(), + GEL_DATABASE: config.database, + GEL_USER: config.user, + GEL_PASSWORD: config.password, + // GEL_TLS_CA_FILE: config.tlsCAFile, + // GEL_CLIENT_TLS_SECURITY: config.tlsSecurity, + GEL_CLIENT_SECURITY: "insecure_dev_mode", }; } diff --git a/packages/driver/test/testbase.ts b/packages/driver/test/testbase.ts index 9bc8957be..f37d365e6 100644 --- a/packages/driver/test/testbase.ts +++ b/packages/driver/test/testbase.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import createClient, { Client, ConnectOptions } from "../src/index.node"; import * as process from "node:process"; -export interface EdgeDBVersion { +export interface GelVersion { major: number; minor: number; stage: string; @@ -29,9 +29,9 @@ export interface EdgeDBVersion { function _getOpts(opts: ConnectOptions): ConnectOptions { let config; try { - config = JSON.parse(process.env._JEST_EDGEDB_CONNECT_CONFIG || ""); + config = JSON.parse(process.env._JEST_GEL_CONNECT_CONFIG || ""); } catch { - throw new Error("EdgeDB Jest test environment is not initialized"); + throw new Error("Gel Jest test environment is not initialized"); } if (!opts.user) { opts.user = "jest"; @@ -52,16 +52,16 @@ export function getClient(opts: ConnectOptions = {}): Client { } export function getAvailableFeatures(): Set { - return new Set(JSON.parse(process.env._JEST_EDGEDB_AVAILABLE_FEATURES!)); + return new Set(JSON.parse(process.env._JEST_GEL_AVAILABLE_FEATURES!)); } -export function getEdgeDBVersion(): EdgeDBVersion { - return JSON.parse(process.env._JEST_EDGEDB_VERSION!); +export function getGelVersion(): GelVersion { + return JSON.parse(process.env._JEST_GEL_VERSION!); } export function getAvailableExtensions(): Map< string, { major: number; minor: number } > { - return new Map(JSON.parse(process.env._JEST_EDGEDB_AVAILABLE_EXTENSIONS!)); + return new Map(JSON.parse(process.env._JEST_GEL_AVAILABLE_EXTENSIONS!)); } diff --git a/packages/driver/test/transaction.test.ts b/packages/driver/test/transaction.test.ts index d1e826cc8..7507f278a 100644 --- a/packages/driver/test/transaction.test.ts +++ b/packages/driver/test/transaction.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2020-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2020-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -144,7 +144,7 @@ test("no transaction statements", async () => { // This test is broken, first rollback query throws CapabilityError, but // then second rollback query doesn't throw any error - // https://github.com/edgedb/edgedb/issues/3120 + // https://github.com/geldata/gel/issues/3120 // await client.transaction(async (tx) => { // await expect(tx.execute("rollback")).rejects.toThrow( diff --git a/packages/driver/test/types.test.ts b/packages/driver/test/types.test.ts index 4cc8a673c..8222170bd 100644 --- a/packages/driver/test/types.test.ts +++ b/packages/driver/test/types.test.ts @@ -1,7 +1,7 @@ /*! - * This source file is part of the EdgeDB open source project. + * This source file is part of the Gel open source project. * - * Copyright 2019-present MagicStack Inc. and the EdgeDB authors. + * Copyright 2019-present MagicStack Inc. and the Gel authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/packages/edgeql-js/index.js b/packages/edgeql-js/index.js deleted file mode 100755 index 5f9fb1741..000000000 --- a/packages/edgeql-js/index.js +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env node - -console.log( - `Failure: The \`npx edgeql-js\` command is no longer supported. - -To generate the EdgeDB query builder, install \`@edgedb/generate\` -package as a dev dependency in your local project. This package implements -a set of code generators for EdgeDB (including the query builder). - - $ npm install -D @edgedb/generate (npm) - $ yarn add -D @edgedb/generate (yarn) - -Then run the following command to generate the query builder. - - $ npx @edgedb/generate edgeql-js -` -); diff --git a/packages/edgeql-js/package.json b/packages/edgeql-js/package.json deleted file mode 100644 index 5d632c634..000000000 --- a/packages/edgeql-js/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "edgeql-js", - "version": "1.0.0", - "description": "Issues warning when `npx edgeql-js` is executed without locally installed package.", - "homepage": "https://edgedb.com/docs", - "author": "EdgeDB ", - "engines": { - "node": ">= 10.0.0" - }, - "repository": { - "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git" - }, - "main": "index.js", - "license": "Apache-2.0", - "scripts": { - "typecheck": "echo 'Skipping typecheck...'", - "test": "echo 'No tests. Done.'", - "build": "echo 'Building edgeql-js...'", - "edgeql-js": "./index.js", - "lint": "eslint --quiet", - "lint:fix": "eslint --fix" - }, - "bin": "./index.js", - "keywords": [] -} diff --git a/packages/edgeql-js/yarn.lock b/packages/edgeql-js/yarn.lock deleted file mode 100644 index 4c29cbb27..000000000 --- a/packages/edgeql-js/yarn.lock +++ /dev/null @@ -1,13 +0,0 @@ -# This file is generated by running "yarn install" inside your project. -# Manual changes might be lost - proceed with caution! - -__metadata: - version: 4 - -"edgedb-generate@workspace:.": - version: 0.0.0-use.local - resolution: "edgedb-generate@workspace:." - bin: - edgedb-generate: ./index.js - languageName: unknown - linkType: soft diff --git a/packages/generate/README.md b/packages/generate/README.md index acf5ba433..ca8dd6c7b 100644 --- a/packages/generate/README.md +++ b/packages/generate/README.md @@ -1,25 +1,25 @@ -# `@edgedb/generate`: Code generation tools for EdgeDB +# `@gel/generate`: Code generation tools for Gel -The `@edgedb/generate` package implements a set of code generation tools that are useful when developing an EdgeDB-backed applications with TypeScript/JavaScript. +The `@gel/generate` package implements a set of code generation tools that are useful when developing an Gel-backed applications with TypeScript/JavaScript. -✨ [View Documentation >>](https://www.edgedb.com/docs/clients/js/generation) +✨ [View Documentation >>](https://www.geldata.com/docs/clients/js/generation) ## Installation > If you're using Deno, you can skip this step. -Install the `edgedb` package. +Install the `gel` package. ```bash -$ npm install edgedb # npm users -$ yarn add edgedb # yarn users +$ npm install gel # npm users +$ yarn add gel # yarn users ``` -Then install `@edgedb/generate` as a dev dependency. +Then install `@gel/generate` as a dev dependency. ```bash -$ npm install @edgedb/generate --save-dev # npm users -$ yarn add @edgedb/generate --dev # yarn users +$ npm install @gel/generate --save-dev # npm users +$ yarn add @gel/generate --dev # yarn users ``` ## Run a generator @@ -29,13 +29,13 @@ Run a generator with the following command. **Node.js** ```bash -$ npx @edgedb/generate [options] +$ npx @gel/generate [options] ``` **Deno** ```bash -$ deno run --allow-all npm:@edgedb/generate [options] +$ deno run --allow-all npm:@gel/generate [options] ``` The value of `` should be one of the following. @@ -46,12 +46,12 @@ The value of `` should be one of the following. ## Third-party generators -✨ If you build a code generator for EdgeDB, ping us or open a PR and we'll list it here! ✨ +✨ If you build a code generator for Gel, ping us or open a PR and we'll list it here! ✨ -The `edgedb` package exports a set of utilities to introspect the schema and analyze queries. We use this same set of tools to implement the first-party generators. +The `gel` package exports a set of utilities to introspect the schema and analyze queries. We use this same set of tools to implement the first-party generators. ```ts -import { createClient, $ } from "edgedb"; +import { createClient, $ } from "gel"; const client = createClient(); @@ -73,7 +73,7 @@ yarn workspaces run build # build all packages Navigate into `packages/generate`: -Build `@edgedb/generate` +Build `@gel/generate` ``` yarn build @@ -88,8 +88,8 @@ yarn build:fast Run a generator: ``` -npx @edgedb/generate edgeql-js # query builder -npx @edgedb/generate queries # query files +npx @gel/generate edgeql-js # query builder +npx @gel/generate queries # query files ``` Execute `playground.ts` (uses `tsx`). Useful for testing things quickly in development: @@ -98,7 +98,7 @@ Execute `playground.ts` (uses `tsx`). Useful for testing things quickly in devel yarn play ``` -> ⚠️ All imports from `"edgedb"` resolve to the local build version of the driver in `packages/driver/dist`. This imports the _built_ library, not the so you need to re-run `yarn workspace edgedb build` for changes to be reflected in your playground code. Run `yarn dev` watcher inside `packages/driver` to rebuild the project anytime you make a change. +> ⚠️ All imports from `"gel"` resolve to the local build version of the driver in `packages/driver/dist`. This imports the _built_ library, not the so you need to re-run `yarn workspace gel build` for changes to be reflected in your playground code. Run `yarn dev` watcher inside `packages/driver` to rebuild the project anytime you make a change. Run commands in watch mode. Useful when in development. The following command rebuilds the package and executes the playground whenever a file change is detected. diff --git a/packages/generate/embedVersion.ts b/packages/generate/embedVersion.ts index 5305f0f7e..8b1566418 100644 --- a/packages/generate/embedVersion.ts +++ b/packages/generate/embedVersion.ts @@ -1,16 +1,16 @@ import path from "path"; -import {readFileSync, writeFileSync} from "fs"; +import { readFileSync, writeFileSync } from "fs"; const packageVersion = JSON.parse( - readFileSync(path.join(__dirname, "package.json"), "utf8") + readFileSync(path.join(__dirname, "package.json"), "utf8"), ).version; for (const filepath of process.argv.slice(2)) { writeFileSync( filepath, readFileSync(filepath, "utf8").replace( - "__@edgedb/generate__VERSION_PLACEHOLDER__", - packageVersion - ) + "__@gel/generate__VERSION_PLACEHOLDER__", + packageVersion, + ), ); } diff --git a/packages/generate/edgedb.toml b/packages/generate/gel.toml similarity index 100% rename from packages/generate/edgedb.toml rename to packages/generate/gel.toml diff --git a/packages/generate/makeSyntax.ts b/packages/generate/makeSyntax.ts index a0579ef33..5f601df8e 100644 --- a/packages/generate/makeSyntax.ts +++ b/packages/generate/makeSyntax.ts @@ -14,7 +14,7 @@ const srcSyntax = path.join(__dirname, "src", "syntax"); const distSyntax = path.join(__dirname, "dist", "syntax"); const esmSyntax = path.join(__dirname, "dist", "__esm", "syntax"); -const reDriver = /"edgedb\/dist([a-zA-Z0-9\_\/]*)"/g; +const reDriver = /"gel\/dist([a-zA-Z0-9\_\/]*)"/g; const reRelativeImports = /"(\.?\.\/.+)"/g; const reTsExpectErrorComment = /\/\/ @ts-expect-error GENERATED/g; @@ -63,7 +63,7 @@ async function run() { ...(await readGlob({ pattern: "*.js", cwd: distSyntax, - contentTx: (content) => content.replace(reDriver, `"edgedb/dist$1.js"`), + contentTx: (content) => content.replace(reDriver, `"gel/dist$1.js"`), })), ...dtsFiles, ]; @@ -77,7 +77,7 @@ async function run() { pathTx: (p) => p.replace(/\.js/g, ".mjs"), contentTx: (content) => content - .replace(reDriver, `"edgedb/dist$1.js"`) + .replace(reDriver, `"gel/dist$1.js"`) .replace(reRelativeImports, `"$1.mjs"`), })), ...dtsFiles, @@ -91,7 +91,7 @@ async function run() { pathTx: (p) => p.replace(/\.ts/g, ".mts"), contentTx: (content) => content - .replace(reDriver, `"edgedb/dist$1.js"`) + .replace(reDriver, `"gel/dist$1.js"`) .replace(reRelativeImports, `"$1.mjs"`) .replace(reTsExpectErrorComment, ""), }); @@ -102,8 +102,8 @@ async function run() { cwd: srcSyntax, contentTx: (content) => { return content - .replace(/"edgedb"/g, `"npm:edgedb"`) - .replace(reDriver, `"npm:edgedb/dist$1.js"`) + .replace(/"gel"/g, `"npm:gel"`) + .replace(reDriver, `"npm:gel/dist$1.js"`) .replace(reRelativeImports, `"$1.ts"`) .replace(reTsExpectErrorComment, ""); }, diff --git a/packages/generate/package.json b/packages/generate/package.json index b11f61a4e..2a55a9b74 100644 --- a/packages/generate/package.json +++ b/packages/generate/package.json @@ -1,15 +1,15 @@ { - "name": "@edgedb/generate", + "name": "@gel/generate", "version": "0.5.6", - "description": "EdgeDB code generators for TS/JavaScript", - "homepage": "https://edgedb.com/docs", - "author": "EdgeDB ", + "description": "Gel code generators for TS/JavaScript", + "homepage": "https://geldata.com/docs", + "author": "Gel ", "engines": { "node": ">= 18.0.0" }, "repository": { "type": "git", - "url": "https://github.com/edgedb/edgedb-js.git" + "url": "https://github.com/geldata/gel-js.git" }, "license": "Apache-2.0", "sideEffects": false, @@ -18,14 +18,14 @@ ], "bin": "dist/cli.js", "peerDependencies": { - "edgedb": "^1.5.10" + "gel": "^1.5.10" }, "devDependencies": { "@repo/tsconfig": "*", "@types/jest": "^29.5.12", "@types/node": "^20.12.13", "conditional-type-checks": "^1.0.6", - "edgedb": "*", + "gel": "*", "esbuild": "^0.21.4", "globby": "^14.0.1", "jest": "^29.7.0", diff --git a/packages/generate/playground.ts b/packages/generate/playground.ts index 0a571a189..480ac8b53 100644 --- a/packages/generate/playground.ts +++ b/packages/generate/playground.ts @@ -1,26 +1,26 @@ // tslint:disable:no-console -import {setupTests} from "./test/setupTeardown"; +import { setupTests } from "./test/setupTeardown"; import e from "./dbschema/edgeql-js"; -import {createClient} from "edgedb"; +import { createClient } from "gel"; const client = createClient(); async function run() { - const {client} = await setupTests(); + const { client } = await setupTests(); - const query = e.params({title: e.optional(e.str)}, params => { - return e.update(e.Movie, m => ({ - filter_single: {title: "not a real title"}, + const query = e.params({ title: e.optional(e.str) }, (params) => { + return e.update(e.Movie, (m) => ({ + filter_single: { title: "not a real title" }, set: { // Error here - title: params.title - } + title: params.title, + }, })); }); console.log(query.toEdgeQL()); - const result = await query.run(client, {title: "asdf"}); + const result = await query.run(client, { title: "asdf" }); console.log(result); } diff --git a/packages/generate/src/builders.ts b/packages/generate/src/builders.ts index a65fbc5c8..f722db8f7 100644 --- a/packages/generate/src/builders.ts +++ b/packages/generate/src/builders.ts @@ -1,7 +1,7 @@ import { promises as fs } from "node:fs"; import path from "node:path"; -import { systemUtils } from "edgedb"; -import { StrictMap } from "edgedb/dist/reflection/strictMap"; +import { systemUtils } from "gel"; +import { StrictMap } from "gel/dist/reflection/strictMap"; import * as genutil from "./genutil"; import { importExportHelpers } from "./importExportHelpers"; diff --git a/packages/generate/src/cli.ts b/packages/generate/src/cli.ts index 978ed4fb8..971733b11 100644 --- a/packages/generate/src/cli.ts +++ b/packages/generate/src/cli.ts @@ -2,20 +2,15 @@ import path from "node:path"; import process from "node:process"; -import { - systemUtils, - type Client, - createClient, - createHttpClient, -} from "edgedb"; +import { systemUtils, type Client, createClient, createHttpClient } from "gel"; import * as TOML from "@iarna/toml"; import { type ConnectConfig, validTlsSecurityValues, isValidTlsSecurityValue, -} from "edgedb/dist/conUtils"; -import { parseConnectArguments } from "edgedb/dist/conUtils.server"; +} from "gel/dist/conUtils"; +import { parseConnectArguments } from "gel/dist/conUtils.server"; import { type CommandOptions, promptForPassword, @@ -53,7 +48,7 @@ const run = async () => { } if (!generator || generator[0] === "-") { console.error( - `Error: No generator specified.\n \`npx @edgedb/generate \`${availableGeneratorsHelp}`, + `Error: No generator specified.\n \`npx @gel/generate \`${availableGeneratorsHelp}`, ); process.exit(); } @@ -303,7 +298,7 @@ const run = async () => { if (!projectRoot) { throw new Error( `Failed to detect project root. -Run this command inside an EdgeDB project directory or specify the desired target language with \`--target\``, +Run this command inside an Gel project directory or specify the desired target language with \`--target\``, ); } @@ -320,7 +315,7 @@ Run this command inside an EdgeDB project directory or specify the desired targe // doesn't work with `extends` // switch to more robust solution after splitting - // @edgedb/generate into separate package + // @gel/generate into separate package // @ts-ignore const isDenoRuntime = typeof Deno !== "undefined"; @@ -362,7 +357,7 @@ Run this command inside an EdgeDB project directory or specify the desired targe } } const overrideTargetMessage = ` To override this, use the --target flag. - Run \`npx @edgedb/generate --help\` for full options.`; + Run \`npx @gel/generate --help\` for full options.`; console.log(overrideTargetMessage); } @@ -428,12 +423,12 @@ Run this command inside an EdgeDB project directory or specify the desired targe }; function printHelp() { - console.log(`@edgedb/generate + console.log(`@gel/generate -Official EdgeDB code generators for TypeScript/JavaScript +Official Gel code generators for TypeScript/JavaScript USAGE - npx @edgedb/generate [COMMAND] [OPTIONS] + npx @gel/generate [COMMAND] [OPTIONS] COMMANDS: queries Generate typed functions from .edgeql files diff --git a/packages/generate/src/commandutil.ts b/packages/generate/src/commandutil.ts index 4658f8825..938697fde 100644 --- a/packages/generate/src/commandutil.ts +++ b/packages/generate/src/commandutil.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node import process from "node:process"; -import { systemUtils } from "edgedb"; +import { systemUtils } from "gel"; import { type Target, exitWithError } from "./genutil"; import type { defaultFutureFlags } from "./edgeql-js"; diff --git a/packages/generate/src/edgeql-js.ts b/packages/generate/src/edgeql-js.ts index 72ab298ea..cd4687085 100644 --- a/packages/generate/src/edgeql-js.ts +++ b/packages/generate/src/edgeql-js.ts @@ -1,6 +1,6 @@ import { promises as fs } from "node:fs"; import path from "node:path"; -import { $, systemUtils, type Client } from "edgedb"; +import { $, systemUtils, type Client } from "gel"; import { type CommandOptions, isTTY, promptBoolean } from "./commandutil"; import { headerComment } from "./genutil"; import { DirBuilder } from "./builders"; @@ -18,7 +18,7 @@ import { generateSetImpl } from "./edgeql-js/generateSetImpl"; const { readFileUtf8, exists, walk } = systemUtils; -export const configFileHeader = `// EdgeDB query builder`; +export const configFileHeader = `// Gel query builder`; export type GeneratorParams = { dir: DirBuilder; @@ -29,7 +29,7 @@ export type GeneratorParams = { functions: $.introspect.FunctionTypes; globals: $.introspect.Globals; operators: $.introspect.OperatorTypes; - edgedbVersion: Version; + gelVersion: Version; }; export type Target = "ts" | "esm" | "cjs" | "mts" | "deno"; @@ -60,8 +60,8 @@ export async function generateQueryBuilder(params: { outputDir = path.join(root, schemaDir, "edgeql-js"); } else { throw new Error( - "No project config file found. Initialize an EdgeDB project with\n" + - "'edgedb project init' or specify an output directory with '--output-dir'", + "No project config file found. Initialize an Gel project with\n" + + "'gel project init' or specify an output directory with '--output-dir'", ); } @@ -124,7 +124,7 @@ export async function generateQueryBuilder(params: { functions, globals, operators, - edgedbVersion: version, + gelVersion: version, }; console.log("Generating runtime spec..."); generateRuntimeSpec(generatorParams); @@ -155,7 +155,7 @@ export async function generateQueryBuilder(params: { const importsFile = dir.getPath("imports"); - importsFile.addExportStar("edgedb", { as: "edgedb" }); + importsFile.addExportStar("gel", { as: "gel" }); importsFile.addExportFrom({ spec: true }, "./__spec__", { allowFileExt: true, }); diff --git a/packages/generate/src/edgeql-js/generateCastMaps.ts b/packages/generate/src/edgeql-js/generateCastMaps.ts index d7a506f47..f3825d4fa 100644 --- a/packages/generate/src/edgeql-js/generateCastMaps.ts +++ b/packages/generate/src/edgeql-js/generateCastMaps.ts @@ -13,13 +13,13 @@ import { getStringRepresentation } from "./generateObjectTypes"; const getRuntimeRef = (name: string) => getRef(name, { prefix: "" }); export const generateCastMaps = (params: GeneratorParams) => { - const { dir, types, casts, typesByName, edgedbVersion } = params; + const { dir, types, casts, typesByName, gelVersion } = params; const { implicitCastMap } = casts; - const literalToScalarMapping = getLiteralToScalarMapping(edgedbVersion); + const literalToScalarMapping = getLiteralToScalarMapping(gelVersion); const f = dir.getPath("castMaps"); - f.addImportStar("edgedb", "edgedb"); + f.addImportStar("gel", "gel"); f.addImportStar("$", "./reflection", { modes: ["ts", "dts"], allowFileExt: true, @@ -269,7 +269,7 @@ export const generateCastMaps = (params: GeneratorParams) => { dts`declare `, t`type scalarLiterals =\n | ${Object.keys(literalToScalarMapping).join( "\n | ", - )}\n | edgedb.Range | edgedb.MultiRange;\n\n`, + )}\n | gel.Range | gel.MultiRange;\n\n`, ]); f.writeln([ @@ -297,9 +297,9 @@ export const generateCastMaps = (params: GeneratorParams) => { f.writeln([t` ? never`]); f.writeln([t` : T["__tstype__"]`]); f.writeln([t` : T extends $.RangeType`]); - f.writeln([t` ? edgedb.Range`]); + f.writeln([t` ? gel.Range`]); f.writeln([t` : T extends $.MultiRangeType`]); - f.writeln([t` ? edgedb.MultiRange`]); + f.writeln([t` ? gel.MultiRange`]); f.writeln([t` : never;`]); f.writeln([ t`export `, @@ -346,10 +346,10 @@ export const generateCastMaps = (params: GeneratorParams) => { ]); } f.writeln([ - t` T extends edgedb.Range ? $.RangeType> :`, + t` T extends gel.Range ? $.RangeType> :`, ]); f.writeln([ - t` T extends edgedb.MultiRange ? $.MultiRangeType> :`, + t` T extends gel.MultiRange ? $.MultiRangeType> :`, ]); // todo probably should be ScalarType or never f.writeln([t` $.BaseType;\n\n`]); diff --git a/packages/generate/src/edgeql-js/generateIndex.ts b/packages/generate/src/edgeql-js/generateIndex.ts index 43ebd9ab8..67f8e9193 100644 --- a/packages/generate/src/edgeql-js/generateIndex.ts +++ b/packages/generate/src/edgeql-js/generateIndex.ts @@ -18,7 +18,7 @@ export function generateIndex(params: GeneratorParams) { // }); index.addImportStar("$", "./reflection"); - index.addExportFrom({ createClient: true }, "edgedb"); + index.addExportFrom({ createClient: true }, "gel"); index.addImportStar("$syntax", "./syntax", { allowFileExt: true }); index.addImportStar("$op", "./operators", { allowFileExt: true }); diff --git a/packages/generate/src/edgeql-js/generateInterfaces.ts b/packages/generate/src/edgeql-js/generateInterfaces.ts index 2820449d1..1ae2b4a07 100644 --- a/packages/generate/src/edgeql-js/generateInterfaces.ts +++ b/packages/generate/src/edgeql-js/generateInterfaces.ts @@ -19,7 +19,7 @@ export const generateInterfaces = (params: GenerateInterfacesParams) => { const { dir, types } = params; const plainTypesCode = dir.getPath("interfaces"); - plainTypesCode.addImportStar("edgedb", "edgedb", { + plainTypesCode.addImportStar("gel", "gel", { typeOnly: true, }); const plainTypeModules = new Map(); @@ -130,7 +130,7 @@ export const generateInterfaces = (params: GenerateInterfacesParams) => { } else { return toTSScalarType(targetType as $.introspect.PrimitiveType, types, { getEnumRef: (enumType) => getTypeName(enumType.name), - edgedbDatatypePrefix: "", + gelDatatypePrefix: "", }).join(""); } }; diff --git a/packages/generate/src/edgeql-js/generateOperatorTypes.ts b/packages/generate/src/edgeql-js/generateOperatorTypes.ts index a414bab5c..c23a782f4 100644 --- a/packages/generate/src/edgeql-js/generateOperatorTypes.ts +++ b/packages/generate/src/edgeql-js/generateOperatorTypes.ts @@ -240,7 +240,7 @@ function operatorFromOpDef( opName === "std::if_else" ? "if_else" : splitName(opDef.originalName).name.toLowerCase(); - const log = debug(`edgedb:codegen:operatorFromOpDef:${opName}`); + const log = debug(`gel:codegen:operatorFromOpDef:${opName}`); log({ opName, operatorSymbol, @@ -600,7 +600,7 @@ export function generateOperators({ for (const [opName, _opDefs] of operators.entries()) { if (skipOperators.has(opName)) continue; - const log = debug(`edgedb:codegen:generateOperators:${opName}`); + const log = debug(`gel:codegen:generateOperators:${opName}`); log( _opDefs.map((opDef) => ({ return_type: opDef.return_type, diff --git a/packages/generate/src/edgeql-js/generateRuntimeSpec.ts b/packages/generate/src/edgeql-js/generateRuntimeSpec.ts index c71d7eb23..25306c0d1 100644 --- a/packages/generate/src/edgeql-js/generateRuntimeSpec.ts +++ b/packages/generate/src/edgeql-js/generateRuntimeSpec.ts @@ -2,7 +2,7 @@ import { dts, t, r, ts } from "../builders"; import type { GeneratorParams } from "../genutil"; export const generateRuntimeSpec = (params: GeneratorParams) => { - const { dir, types, edgedbVersion } = params; + const { dir, types, gelVersion } = params; const spec = dir.getPath("__spec__"); @@ -30,7 +30,7 @@ export const generateRuntimeSpec = (params: GeneratorParams) => { `const complexParamKinds`, t`: Set<$.TypeKind>`, r` = new Set([${ - edgedbVersion.major <= 2 ? `$.TypeKind.tuple, $.TypeKind.namedtuple` : "" + gelVersion.major <= 2 ? `$.TypeKind.tuple, $.TypeKind.namedtuple` : "" }])`, `;`, ]); diff --git a/packages/generate/src/funcoputil.ts b/packages/generate/src/funcoputil.ts index 1a1e3e135..34ef16c7a 100644 --- a/packages/generate/src/funcoputil.ts +++ b/packages/generate/src/funcoputil.ts @@ -1,4 +1,4 @@ -import { $ } from "edgedb"; +import { $ } from "gel"; import type { CodeFragment } from "./builders"; import type { FuncopDef } from "./edgeql-js/generateFunctionTypes"; import { getStringRepresentation } from "./edgeql-js/generateObjectTypes"; diff --git a/packages/generate/src/genutil.ts b/packages/generate/src/genutil.ts index b07621e04..744f85805 100644 --- a/packages/generate/src/genutil.ts +++ b/packages/generate/src/genutil.ts @@ -1,7 +1,7 @@ import process from "node:process"; -import type { $ } from "edgedb"; -import type * as introspect from "edgedb/dist/reflection/queries/types"; -import { util } from "edgedb/dist/reflection/index"; +import type { $ } from "gel"; +import type * as introspect from "gel/dist/reflection/queries/types"; +import { util } from "gel/dist/reflection/index"; import type { CodeBuilder, CodeFragment, @@ -9,13 +9,13 @@ import type { IdentRef, } from "./builders"; -export { OperatorKind, StrictMapSet } from "edgedb/dist/reflection/index"; +export { OperatorKind, StrictMapSet } from "gel/dist/reflection/index"; -export { $ } from "edgedb"; +export { $ } from "gel"; export const splitName = util.splitName; -export const headerComment = `// GENERATED by @edgedb/generate v__@edgedb/generate__VERSION_PLACEHOLDER__\n\n`; +export const headerComment = `// GENERATED by @gel/generate v__@gel/generate__VERSION_PLACEHOLDER__\n\n`; export function toIdent(name: string): string { if (name.includes("::")) { @@ -70,12 +70,12 @@ export const scalarToLiteralMapping: { extraTypes: ["string"], }, "std::duration": { - type: "edgedb.Duration", + type: "gel.Duration", literalKind: "instanceof", extraTypes: ["string"], }, "cfg::memory": { - type: "edgedb.ConfigMemory", + type: "gel.ConfigMemory", literalKind: "instanceof", extraTypes: ["string"], }, @@ -89,53 +89,53 @@ export const scalarToLiteralMapping: { // keep this order of mapping, adding firstly mapping as it is in v6 and greater // then also add mappings as they are in < v6 "std::cal::local_datetime": { - type: "edgedb.LocalDateTime", + type: "gel.LocalDateTime", literalKind: "instanceof", extraTypes: ["string"], }, "std::cal::local_date": { - type: "edgedb.LocalDate", + type: "gel.LocalDate", literalKind: "instanceof", extraTypes: ["string"], }, "std::cal::local_time": { - type: "edgedb.LocalTime", + type: "gel.LocalTime", literalKind: "instanceof", extraTypes: ["string"], }, "std::cal::relative_duration": { - type: "edgedb.RelativeDuration", + type: "gel.RelativeDuration", literalKind: "instanceof", extraTypes: ["string"], }, "std::cal::date_duration": { - type: "edgedb.DateDuration", + type: "gel.DateDuration", literalKind: "instanceof", extraTypes: ["string"], }, // server version < 6 "cal::local_datetime": { - type: "edgedb.LocalDateTime", + type: "gel.LocalDateTime", literalKind: "instanceof", extraTypes: ["string"], }, "cal::local_date": { - type: "edgedb.LocalDate", + type: "gel.LocalDate", literalKind: "instanceof", extraTypes: ["string"], }, "cal::local_time": { - type: "edgedb.LocalTime", + type: "gel.LocalTime", literalKind: "instanceof", extraTypes: ["string"], }, "cal::relative_duration": { - type: "edgedb.RelativeDuration", + type: "gel.RelativeDuration", literalKind: "instanceof", extraTypes: ["string"], }, "cal::date_duration": { - type: "edgedb.DateDuration", + type: "gel.DateDuration", literalKind: "instanceof", extraTypes: ["string"], }, @@ -151,7 +151,7 @@ export function getLiteralToScalarMapping(version: Version) { )) { if (literalKind) { if (literalToScalarMapping[type] && version.major > 5) { - // there's for example edgedb.LocalTime that maps to the std::cal::local_time + // there's for example gel.LocalTime that maps to the std::cal::local_time // if the server version > 5 continue, otherwise overwrite this mapping with cal::local_time continue; } @@ -166,9 +166,9 @@ export function toTSScalarType( types: introspect.Types, opts: { getEnumRef?: (type: introspect.Type) => string; - edgedbDatatypePrefix: string; + gelDatatypePrefix: string; } = { - edgedbDatatypePrefix: "_.", + gelDatatypePrefix: "_.", }, ): CodeFragment[] { switch (type.kind) { @@ -190,7 +190,7 @@ export function toTSScalarType( const literalType = scalarToLiteralMapping[type.name]?.type ?? "unknown"; return [ - (literalType.startsWith("edgedb.") ? opts.edgedbDatatypePrefix : "") + + (literalType.startsWith("gel.") ? opts.gelDatatypePrefix : "") + literalType, ]; } @@ -245,7 +245,7 @@ export function toTSScalarType( types, opts, ); - return frag`${opts.edgedbDatatypePrefix}edgedb.Range<${tn}>`; + return frag`${opts.gelDatatypePrefix}gel.Range<${tn}>`; } case "multirange": { @@ -254,7 +254,7 @@ export function toTSScalarType( types, opts, ); - return frag`${opts.edgedbDatatypePrefix}edgedb.MultiRange<${tn}>`; + return frag`${opts.gelDatatypePrefix}gel.MultiRange<${tn}>`; } default: @@ -500,7 +500,7 @@ export type GeneratorParams = { functions: $.introspect.FunctionTypes; globals: $.introspect.Globals; operators: $.introspect.OperatorTypes; - edgedbVersion: Version; + gelVersion: Version; }; export function exitWithError(message: string): never { diff --git a/packages/generate/src/interfaces.ts b/packages/generate/src/interfaces.ts index 5c7c6f90a..65c7c396d 100644 --- a/packages/generate/src/interfaces.ts +++ b/packages/generate/src/interfaces.ts @@ -3,7 +3,7 @@ import path from "node:path"; import type { CommandOptions } from "./commandutil"; import { headerComment } from "./genutil"; -import { $, type Client } from "edgedb"; +import { $, type Client } from "gel"; import { DirBuilder } from "./builders"; import { generateInterfaces } from "./edgeql-js/generateInterfaces"; @@ -24,8 +24,8 @@ export async function runInterfacesGenerator(params: { outFile = path.join(root, schemaDir, "interfaces.ts"); } else { throw new Error( - "No project config file found. Initialize an EdgeDB project with\n" + - "'edgedb project init' or specify an output file with '--file'", + "No project config file found. Initialize an Gel project with\n" + + "'gel project init' or specify an output file with '--file'", ); } diff --git a/packages/generate/src/queries.ts b/packages/generate/src/queries.ts index 41ec9b0e4..2e48f7512 100644 --- a/packages/generate/src/queries.ts +++ b/packages/generate/src/queries.ts @@ -1,6 +1,6 @@ import path from "node:path"; import { promises as fs } from "node:fs"; -import { $, systemUtils, type Client, type Executor } from "edgedb"; +import { $, systemUtils, type Client, type Executor } from "gel"; import { type CommandOptions } from "./commandutil"; import { headerComment } from "./genutil"; import type { Target } from "./genutil"; @@ -224,10 +224,8 @@ ${params.types.query.trim().replace(/\\/g, "\\\\").replace(/`/g, "\\`")}\`${ const tsImports = params.types.importMap ?? - new ImportMap( - params.types.imports ? [["edgedb", params.types.imports]] : [], - ); - tsImports.add("edgedb", "Executor"); + new ImportMap(params.types.imports ? [["gel", params.types.imports]] : []); + tsImports.add("gel", "Executor"); const tsImpl = `${queryDefs} diff --git a/packages/generate/src/syntax/cardinality.ts b/packages/generate/src/syntax/cardinality.ts index d4856090c..04a6df458 100644 --- a/packages/generate/src/syntax/cardinality.ts +++ b/packages/generate/src/syntax/cardinality.ts @@ -1,4 +1,4 @@ -import { Cardinality } from "edgedb/dist/reflection/index"; +import { Cardinality } from "gel/dist/reflection/index"; import type { TypeSet } from "./typesystem"; // Computing cardinality of path diff --git a/packages/generate/src/syntax/cast.ts b/packages/generate/src/syntax/cast.ts index 3e711d454..0e41f781b 100644 --- a/packages/generate/src/syntax/cast.ts +++ b/packages/generate/src/syntax/cast.ts @@ -1,4 +1,4 @@ -import { ExpressionKind, Cardinality } from "edgedb/dist/reflection/index"; +import { ExpressionKind, Cardinality } from "gel/dist/reflection/index"; import type { Expression, BaseType, diff --git a/packages/generate/src/syntax/casting.ts b/packages/generate/src/syntax/casting.ts index 3fdb46948..349f9ca4e 100644 --- a/packages/generate/src/syntax/casting.ts +++ b/packages/generate/src/syntax/casting.ts @@ -1,4 +1,4 @@ -import type { Cardinality } from "edgedb/dist/reflection/index"; +import type { Cardinality } from "gel/dist/reflection/index"; import type { ArrayType, BaseType, @@ -99,7 +99,7 @@ export type setToAssignmentExpression< >, cardutil.assignable< // Allow expressions with AtMostOne or Many cardinality in - // insert/update shape even when link is required since EdgeDB will + // insert/update shape even when link is required since Gel will // assert cardinality at runtime cardutil.overrideLowerBound > diff --git a/packages/generate/src/syntax/collections.ts b/packages/generate/src/syntax/collections.ts index 25f8676b6..9401f7265 100644 --- a/packages/generate/src/syntax/collections.ts +++ b/packages/generate/src/syntax/collections.ts @@ -3,7 +3,7 @@ import { ExpressionKind, TypeKind, type typeutil, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import { cardutil } from "./cardinality"; import type { $expr_Array, diff --git a/packages/generate/src/syntax/detached.ts b/packages/generate/src/syntax/detached.ts index 5580af5f1..954701733 100644 --- a/packages/generate/src/syntax/detached.ts +++ b/packages/generate/src/syntax/detached.ts @@ -1,4 +1,4 @@ -import { ExpressionKind } from "edgedb/dist/reflection/index"; +import { ExpressionKind } from "gel/dist/reflection/index"; import type { Expression, TypeSet } from "./typesystem"; import { $expressionify } from "./path"; diff --git a/packages/generate/src/syntax/for.ts b/packages/generate/src/syntax/for.ts index 1c4a042df..bd4b7d959 100644 --- a/packages/generate/src/syntax/for.ts +++ b/packages/generate/src/syntax/for.ts @@ -1,4 +1,4 @@ -import { Cardinality, ExpressionKind } from "edgedb/dist/reflection/index"; +import { Cardinality, ExpressionKind } from "gel/dist/reflection/index"; import { cardutil } from "./cardinality"; import type { Expression, BaseType, BaseTypeSet } from "./typesystem"; import { $expressionify } from "./path"; diff --git a/packages/generate/src/syntax/funcops.ts b/packages/generate/src/syntax/funcops.ts index 221b74ad4..9fe25cfd4 100644 --- a/packages/generate/src/syntax/funcops.ts +++ b/packages/generate/src/syntax/funcops.ts @@ -2,7 +2,7 @@ import { Cardinality, type introspect, TypeKind, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import { cardutil } from "./cardinality"; import { makeType } from "./hydrate"; import type { @@ -19,10 +19,7 @@ import { cast } from "./cast"; import { isImplicitlyCastableTo, literalToTypeSet } from "./castMaps"; import { literal } from "./literal"; -import type { - ExpressionKind, - OperatorKind, -} from "edgedb/dist/reflection/index"; +import type { ExpressionKind, OperatorKind } from "gel/dist/reflection/index"; export type $expr_Function< // Name extends string = string, diff --git a/packages/generate/src/syntax/globals.ts b/packages/generate/src/syntax/globals.ts index 9520c0de7..26b6150a0 100644 --- a/packages/generate/src/syntax/globals.ts +++ b/packages/generate/src/syntax/globals.ts @@ -1,4 +1,4 @@ -import { type Cardinality, ExpressionKind } from "edgedb/dist/reflection/index"; +import { type Cardinality, ExpressionKind } from "gel/dist/reflection/index"; import type { Expression, BaseType } from "./typesystem"; import { $expressionify } from "./path"; diff --git a/packages/generate/src/syntax/group.ts b/packages/generate/src/syntax/group.ts index b1269de3f..fe059dcc2 100644 --- a/packages/generate/src/syntax/group.ts +++ b/packages/generate/src/syntax/group.ts @@ -12,7 +12,7 @@ import { Cardinality, ExpressionKind, TypeKind, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import { makeType } from "./hydrate"; import { $expressionify, $getScopedExpr } from "./path"; diff --git a/packages/generate/src/syntax/hydrate.ts b/packages/generate/src/syntax/hydrate.ts index 1fdf66c39..abda2c398 100644 --- a/packages/generate/src/syntax/hydrate.ts +++ b/packages/generate/src/syntax/hydrate.ts @@ -1,4 +1,4 @@ -import type { $ } from "edgedb"; +import type { $ } from "gel"; import type { BaseType, @@ -9,8 +9,8 @@ import type { TupleType, } from "./typesystem"; -import { util, TypeKind } from "edgedb/dist/reflection/index"; -import type { typeutil } from "edgedb/dist/reflection/index"; +import { util, TypeKind } from "gel/dist/reflection/index"; +import type { typeutil } from "gel/dist/reflection/index"; const typeCache = new Map(); @@ -51,7 +51,7 @@ function applySpec( _linkProps ] = {}); for (const linkProp of ptr.pointers ?? []) { - // We only support "link properties" in EdgeDB, currently. + // We only support "link properties" in Gel, currently. if (linkProp.kind !== "property") { return; } diff --git a/packages/generate/src/syntax/insert.ts b/packages/generate/src/syntax/insert.ts index 0df6f270c..4d1a67b6d 100644 --- a/packages/generate/src/syntax/insert.ts +++ b/packages/generate/src/syntax/insert.ts @@ -3,7 +3,7 @@ import { ExpressionKind, type typeutil, TypeKind, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import type { Expression, LinkDesc, diff --git a/packages/generate/src/syntax/json.ts b/packages/generate/src/syntax/json.ts index 79345e99d..bc209a21f 100644 --- a/packages/generate/src/syntax/json.ts +++ b/packages/generate/src/syntax/json.ts @@ -1,6 +1,6 @@ -import { ExpressionKind, TypeKind } from "edgedb/dist/reflection/index"; +import { ExpressionKind, TypeKind } from "gel/dist/reflection/index"; import type { ParamType } from "./typesystem"; -import { encodeB64 } from "edgedb/dist/primitives/buffer"; +import { encodeB64 } from "gel/dist/primitives/buffer"; import type { $expr_WithParams } from "./params"; function jsonStringify(type: ParamType, val: any): string { diff --git a/packages/generate/src/syntax/literal.ts b/packages/generate/src/syntax/literal.ts index 02f185f94..4279349bd 100644 --- a/packages/generate/src/syntax/literal.ts +++ b/packages/generate/src/syntax/literal.ts @@ -7,7 +7,7 @@ import type { import { $expressionify } from "./path"; import { spec } from "./__spec__"; -import { Cardinality, ExpressionKind } from "edgedb/dist/reflection/index"; +import { Cardinality, ExpressionKind } from "gel/dist/reflection/index"; import { makeType } from "./hydrate"; export type $expr_Literal = Expression<{ diff --git a/packages/generate/src/syntax/modules/cal.ts b/packages/generate/src/syntax/modules/cal.ts index d964c85da..6d9dc74c2 100644 --- a/packages/generate/src/syntax/modules/cal.ts +++ b/packages/generate/src/syntax/modules/cal.ts @@ -1,4 +1,4 @@ -import type { LocalDate, LocalDateTime } from "edgedb"; +import type { LocalDate, LocalDateTime } from "gel"; import type { ScalarType } from "../typesystem"; export type $local_date = ScalarType<"cal::local_date", LocalDate>; diff --git a/packages/generate/src/syntax/modules/std.ts b/packages/generate/src/syntax/modules/std.ts index 04aeb58bd..ff4650769 100644 --- a/packages/generate/src/syntax/modules/std.ts +++ b/packages/generate/src/syntax/modules/std.ts @@ -1,4 +1,4 @@ -import type { Duration } from "edgedb"; +import type { Duration } from "gel"; import type { BaseType, TypeSet, @@ -8,7 +8,7 @@ import type { } from "../typesystem"; import type { $expr_PathNode } from "../path"; -import type { Cardinality } from "edgedb/dist/reflection/index"; +import type { Cardinality } from "gel/dist/reflection/index"; declare function assert_single(input: TypeSet): any; declare const number: scalarTypeWithConstructor< diff --git a/packages/generate/src/syntax/params.ts b/packages/generate/src/syntax/params.ts index 3cd904a59..1d16a3365 100644 --- a/packages/generate/src/syntax/params.ts +++ b/packages/generate/src/syntax/params.ts @@ -1,9 +1,9 @@ -import type { Executor } from "edgedb"; +import type { Executor } from "gel"; import { ExpressionKind, Cardinality, TypeKind, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import type { Expression, ParamType, diff --git a/packages/generate/src/syntax/path.ts b/packages/generate/src/syntax/path.ts index 1cdd8f79a..8425b40b4 100644 --- a/packages/generate/src/syntax/path.ts +++ b/packages/generate/src/syntax/path.ts @@ -10,7 +10,7 @@ import { Cardinality, // BaseType, type typeutil, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import { cardutil } from "./cardinality"; diff --git a/packages/generate/src/syntax/query.ts b/packages/generate/src/syntax/query.ts index 27991e62a..6f6269df2 100644 --- a/packages/generate/src/syntax/query.ts +++ b/packages/generate/src/syntax/query.ts @@ -1,5 +1,5 @@ -import type * as edgedb from "edgedb"; -import { Cardinality, ExpressionKind } from "edgedb/dist/reflection/index"; +import type * as gel from "gel"; +import { Cardinality, ExpressionKind } from "gel/dist/reflection/index"; import { jsonifyComplexParams } from "./json"; import { select } from "./select"; @@ -17,7 +17,7 @@ export const runnableExpressionKinds = new Set([ const wrappedExprCache = new WeakMap(); -export async function $queryFunc(this: any, cxn: edgedb.Executor, args: any) { +export async function $queryFunc(this: any, cxn: gel.Executor, args: any) { const expr = runnableExpressionKinds.has(this.__kind__) ? this : wrappedExprCache.get(this) ?? @@ -38,11 +38,7 @@ export async function $queryFunc(this: any, cxn: edgedb.Executor, args: any) { } } -export async function $queryFuncJSON( - this: any, - cxn: edgedb.Executor, - args: any, -) { +export async function $queryFuncJSON(this: any, cxn: gel.Executor, args: any) { const expr = runnableExpressionKinds.has(this.__kind__) ? this : wrappedExprCache.get(this) ?? diff --git a/packages/generate/src/syntax/range.ts b/packages/generate/src/syntax/range.ts index aaf4f903e..f00143731 100644 --- a/packages/generate/src/syntax/range.ts +++ b/packages/generate/src/syntax/range.ts @@ -1,6 +1,6 @@ -import type { LocalDate, LocalDateTime, Duration } from "edgedb"; -import { Range } from "edgedb"; -import { TypeKind, ExpressionKind } from "edgedb/dist/reflection/index"; +import type { LocalDate, LocalDateTime, Duration } from "gel"; +import { Range } from "gel"; +import { TypeKind, ExpressionKind } from "gel/dist/reflection/index"; import type { cardutil } from "./cardinality"; import type { diff --git a/packages/generate/src/syntax/reflection.ts b/packages/generate/src/syntax/reflection.ts index 3f0b3173e..ad6cf3245 100644 --- a/packages/generate/src/syntax/reflection.ts +++ b/packages/generate/src/syntax/reflection.ts @@ -1,4 +1,4 @@ -export * from "edgedb/dist/reflection/index"; +export * from "gel/dist/reflection/index"; export * from "./typesystem"; export { cardutil } from "./cardinality"; export type { $expr_Literal } from "./literal"; diff --git a/packages/generate/src/syntax/select.ts b/packages/generate/src/syntax/select.ts index 0788daf61..d2fc10e11 100644 --- a/packages/generate/src/syntax/select.ts +++ b/packages/generate/src/syntax/select.ts @@ -6,7 +6,7 @@ import { RelativeDuration, ConfigMemory, DateDuration, -} from "edgedb"; +} from "gel"; import type { $bool, $number } from "./modules/std"; import { @@ -14,7 +14,7 @@ import { ExpressionKind, TypeKind, OperatorKind, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import { makeType } from "./hydrate"; import { cardutil } from "./cardinality"; diff --git a/packages/generate/src/syntax/set.ts b/packages/generate/src/syntax/set.ts index 163f5bf42..c4908c992 100644 --- a/packages/generate/src/syntax/set.ts +++ b/packages/generate/src/syntax/set.ts @@ -1,5 +1,5 @@ -import type { ExpressionKind, Cardinality } from "edgedb/dist/reflection/index"; -import { TypeKind } from "edgedb/dist/reflection/index"; +import type { ExpressionKind, Cardinality } from "gel/dist/reflection/index"; +import { TypeKind } from "gel/dist/reflection/index"; import type { ArrayType, BaseTypeTuple, diff --git a/packages/generate/src/syntax/toEdgeQL.ts b/packages/generate/src/syntax/toEdgeQL.ts index c2861df2c..880429ef0 100644 --- a/packages/generate/src/syntax/toEdgeQL.ts +++ b/packages/generate/src/syntax/toEdgeQL.ts @@ -7,14 +7,14 @@ import { DateDuration, Range, InputDataError, -} from "edgedb"; +} from "gel"; import { Cardinality, ExpressionKind, OperatorKind, TypeKind, util, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import { type $expr_Array, type $expr_NamedTuple, @@ -37,7 +37,7 @@ import type { $expr_PathNode, $expr_TypeIntersection, } from "./path"; -import { reservedKeywords } from "edgedb/dist/reflection/index"; +import { reservedKeywords } from "gel/dist/reflection/index"; import type { $expr_Cast } from "./cast"; import type { $expr_Detached } from "./detached"; import type { $expr_For, $expr_ForVar } from "./for"; @@ -1616,7 +1616,7 @@ function indent(str: string, depth: number) { } // backtick quote identifiers if needed -// https://github.com/edgedb/edgedb/blob/master/edb/edgeql/quote.py +// https://github.com/geldata/gel/blob/master/edb/edgeql/quote.py function q(ident: string, allowBacklinks = true): string { if ( !ident || diff --git a/packages/generate/src/syntax/typesystem.ts b/packages/generate/src/syntax/typesystem.ts index 5e8db8d07..fce60835e 100644 --- a/packages/generate/src/syntax/typesystem.ts +++ b/packages/generate/src/syntax/typesystem.ts @@ -1,4 +1,4 @@ -import type { Executor } from "edgedb/dist/ifaces"; +import type { Executor } from "gel/dist/ifaces"; import type { $expr_PathNode, $expr_TypeIntersection, $pathify } from "./path"; import type { $expr_Literal } from "./literal"; import type { $expr_Operator } from "./funcops"; @@ -6,10 +6,10 @@ import type { typeutil, Cardinality, ExpressionKind, -} from "edgedb/dist/reflection/index"; -import { TypeKind } from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; +import { TypeKind } from "gel/dist/reflection/index"; import type { cardutil } from "./cardinality"; -import type { Range, MultiRange } from "edgedb"; +import type { Range, MultiRange } from "gel"; import type { $Shape, normaliseShape } from "./select"; import type { future } from "./future"; diff --git a/packages/generate/src/syntax/update.ts b/packages/generate/src/syntax/update.ts index bbf2e0c77..67d43b851 100644 --- a/packages/generate/src/syntax/update.ts +++ b/packages/generate/src/syntax/update.ts @@ -2,7 +2,7 @@ import { ExpressionKind, type typeutil, type Cardinality, -} from "edgedb/dist/reflection/index"; +} from "gel/dist/reflection/index"; import type { Expression, ObjectTypePointers, diff --git a/packages/generate/src/syntax/with.ts b/packages/generate/src/syntax/with.ts index ddb82047c..fa87870b2 100644 --- a/packages/generate/src/syntax/with.ts +++ b/packages/generate/src/syntax/with.ts @@ -1,4 +1,4 @@ -import { type Cardinality, ExpressionKind } from "edgedb/dist/reflection/index"; +import { type Cardinality, ExpressionKind } from "gel/dist/reflection/index"; import type { BaseType, Expression, TypeSet } from "./typesystem"; import type { $expr_Select } from "./select"; import type { $expr_For } from "./for"; diff --git a/packages/generate/test/cli.test.ts b/packages/generate/test/cli.test.ts index 283147fb2..7298f0050 100644 --- a/packages/generate/test/cli.test.ts +++ b/packages/generate/test/cli.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import path from "path"; -import { systemUtils } from "edgedb"; +import { systemUtils } from "gel"; import { execSync } from "child_process"; const QBDIR = path.resolve(__dirname, ".."); diff --git a/packages/generate/test/globalSetup.ts b/packages/generate/test/globalSetup.ts index 4692a7fbb..bd0f5d693 100644 --- a/packages/generate/test/globalSetup.ts +++ b/packages/generate/test/globalSetup.ts @@ -1,9 +1,9 @@ -import createClient from "edgedb"; +import createClient from "gel"; export default async () => { const client = createClient(); - process.env._JEST_EDGEDB_VERSION = await client.queryRequiredSingleJSON( + process.env._JEST_GEL_VERSION = await client.queryRequiredSingleJSON( `select sys::get_version()`, ); }; diff --git a/packages/generate/test/setupTeardown.ts b/packages/generate/test/setupTeardown.ts index 907e82b2d..cec7016cd 100644 --- a/packages/generate/test/setupTeardown.ts +++ b/packages/generate/test/setupTeardown.ts @@ -1,5 +1,5 @@ import * as tc from "conditional-type-checks"; -import { Client, createClient } from "edgedb"; +import { Client, createClient } from "gel"; export { tc }; @@ -131,7 +131,7 @@ export async function teardownTests(client: Client) { } export const versionGTE = (majorVer: number) => { - const version = JSON.parse(process.env._JEST_EDGEDB_VERSION!); + const version = JSON.parse(process.env._JEST_GEL_VERSION!); return version.major >= majorVer; }; diff --git a/packages/generate/test/testRunner.ts b/packages/generate/test/testRunner.ts index 0ce782f75..fd9c0692c 100644 --- a/packages/generate/test/testRunner.ts +++ b/packages/generate/test/testRunner.ts @@ -12,7 +12,7 @@ import { } from "../../driver/test/testUtil"; (async function main() { - console.log("\nStarting EdgeDB test cluster..."); + console.log("\nStarting Gel test cluster..."); const statusFile = generateStatusFileName("node"); console.log("Node status file:", statusFile); @@ -21,7 +21,7 @@ import { const { proc, config } = await startServer(args, statusFile); - console.log(`EdgeDB test cluster is up [port: ${config.port}]...`); + console.log(`Gel test cluster is up [port: ${config.port}]...`); const managementConn = await createClient(config).ensureConnected(); @@ -33,8 +33,8 @@ import { console.error(err); process.exit(1); } finally { - console.log("Shutting down EdgeDB test cluster..."); + console.log("Shutting down Gel test cluster..."); await shutdown(proc, managementConn); - console.log("EdgeDB test cluster is down..."); + console.log("Gel test cluster is down..."); } })(); diff --git a/packages/vercel-ai-provider/README.md b/packages/vercel-ai-provider/README.md index 4e7e4fe27..b5ed4067d 100644 --- a/packages/vercel-ai-provider/README.md +++ b/packages/vercel-ai-provider/README.md @@ -1,37 +1,40 @@ # Provider for the Vercel AI SDK -The provider for the [Vercel AI SDK](https://sdk.vercel.ai/docs) contains language model support for -the OpenAi, Mistral and Anthropic chat and completion APIs that implements EdgeDB RAG, and embedding model support for the OpenAI and Mistral embeddings API. +The provider for the [Vercel AI SDK](https://sdk.vercel.ai/docs) contains +language model support for the OpenAi, Mistral and Anthropic chat and completion +APIs that implements Gel RAG, and embedding model support for the OpenAI and +Mistral embeddings API. ## Setup -Provider is available in the `@edgedb/vercel-ai-provider` module. You can install it with: +Provider is available in the `@gel/vercel-ai-provider` module. You can install +it with: ```bash -npm i @edgedb/vercel-ai-provider +npm i @gel/vercel-ai-provider ``` ## Provider Instance -You can import the default provider instance `edgedb` from `@edgedb/vercel-ai-provider`: +You can import the default provider instance `gel` from `@gel/vercel-ai-provider`: ```ts -import { edgedb } from "@edgedb/vercel-ai-provider"; +import { gel } from "@gel/vercel-ai-provider"; ``` ## Example ```ts import { generateText } from "ai"; -import { createClient } from "edgedb"; -import { edgedb } from "@edgedb/vercel-ai-provider"; +import { createClient } from "gel"; +import { gel } from "@gel/vercel-ai-provider"; -const textModel = (await edgedb).languageModel("gpt-4-turbo-preview"); +const textModel = (await gel).languageModel("gpt-4-turbo-preview", { + context: { query: "your context" }, +}); const { text } = await generateText({ - model: textModel.withSettings({ - context: { query: "your context" }, - }), + model: textModel, prompt: "your prompt", }); @@ -40,4 +43,4 @@ console.log(text); ## Documentation -Please check out the **[EdgeDB provider documentation](https://docs.edgedb.com/ai/vercel-ai-provider)** for more information. +Please check out the **[Gel provider documentation](https://docs.geldata.com/ai/vercel_ai_sdk_provider)** for more information. diff --git a/packages/vercel-ai-provider/package.json b/packages/vercel-ai-provider/package.json index fc8e07af5..fabedfb17 100644 --- a/packages/vercel-ai-provider/package.json +++ b/packages/vercel-ai-provider/package.json @@ -1,8 +1,13 @@ { - "name": "@edgedb/vercel-ai-provider", + "name": "@gel/vercel-ai-provider", "description": "Provider for the Vercel AI SDK", "version": "0.0.1", "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "https://github.com/geldata/gel-js.git", + "directory": "packages/vercel-ai-provider" + }, "sideEffects": false, "main": "./dist/index.js", "module": "./dist/index.mjs", @@ -36,11 +41,11 @@ "tsup": "^8", "typescript": "5.5.4", "zod": "3.23.8", - "edgedb": "*" + "gel": "*" }, "peerDependencies": { "zod": "^3.0.0", - "edgedb": "^1.5.0" + "gel": "^1.5.0" }, "engines": { "node": ">=18" diff --git a/packages/vercel-ai-provider/src/convert-to-edgedb-messages.ts b/packages/vercel-ai-provider/src/convert-to-gel-messages.ts similarity index 93% rename from packages/vercel-ai-provider/src/convert-to-edgedb-messages.ts rename to packages/vercel-ai-provider/src/convert-to-gel-messages.ts index 3d7b9a897..5b0ee136c 100644 --- a/packages/vercel-ai-provider/src/convert-to-edgedb-messages.ts +++ b/packages/vercel-ai-provider/src/convert-to-gel-messages.ts @@ -1,10 +1,10 @@ import { type LanguageModelV1Prompt } from "@ai-sdk/provider"; -import type { EdgeDBMessage } from "./edgedb-chat-settings"; +import type { GelMessage } from "./gel-chat-settings"; -export function convertToEdgeDBMessages( +export function convertToGelMessages( prompt: LanguageModelV1Prompt, -): EdgeDBMessage[] { - const messages: EdgeDBMessage[] = []; +): GelMessage[] { + const messages: GelMessage[] = []; for (const { role, content } of prompt) { switch (role) { diff --git a/packages/vercel-ai-provider/src/edgedb-provider.ts b/packages/vercel-ai-provider/src/edgedb-provider.ts deleted file mode 100644 index d27f4f290..000000000 --- a/packages/vercel-ai-provider/src/edgedb-provider.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { type Client, createClient } from "edgedb"; -import { getHTTPSCRAMAuth } from "edgedb/dist/httpScram.js"; -import { cryptoUtils } from "edgedb/dist/browserCrypto.js"; -import { getAuthenticatedFetch } from "edgedb/dist/utils.js"; -import type { - EmbeddingModelV1, - LanguageModelV1, - ProviderV1, -} from "@ai-sdk/provider"; -import { EdgeDBChatLanguageModel } from "./edgedb-chat-language-model"; -import type { - EdgeDBChatModelId, - EdgeDBChatSettings, -} from "./edgedb-chat-settings"; -import { EdgeDBEmbeddingModel } from "./edgedb-embedding-model"; -import type { - EdgeDBEmbeddingModelId, - EdgeDBEmbeddingSettings, -} from "./edgedb-embedding-settings"; - -const httpSCRAMAuth = getHTTPSCRAMAuth(cryptoUtils); - -export interface EdgeDBProvider extends ProviderV1 { - ( - modelId: EdgeDBChatModelId | EdgeDBEmbeddingModelId, - settings?: EdgeDBChatSettings, - ): LanguageModelV1; - - languageModel( - modelId: EdgeDBChatModelId, - settings?: EdgeDBChatSettings, - ): EdgeDBChatLanguageModel; - - textEmbeddingModel: ( - modelId: EdgeDBEmbeddingModelId, - settings?: EdgeDBEmbeddingSettings, - ) => EmbeddingModelV1; -} - -export interface EdgeDBProviderSettings { - /** -Use a different URL prefix for API calls, e.g. to use proxy servers. - */ - // baseURL?: string; - - /** -Custom headers to include in the requests. - */ - headers?: Record; -} - -export async function createEdgeDB( - client: Client, - options: EdgeDBProviderSettings = {}, -): Promise { - const connectConfig = await client.resolveConnectionParams(); - // const baseURL = withoutTrailingSlash(options.baseURL) ?? null; - - // In case we want to add more things to this in the future - const getHeaders = () => ({ - ...options.headers, - }); - - const fetch = await getAuthenticatedFetch( - connectConfig, - httpSCRAMAuth, - "ext/ai/", - ); - - const createChatModel = ( - modelId: EdgeDBChatModelId, - settings: EdgeDBChatSettings = {}, - ) => - new EdgeDBChatLanguageModel(modelId, settings, { - provider: "edgedb.chat", - fetch, - headers: getHeaders, - }); - - const createEmbeddingModel = ( - modelId: EdgeDBEmbeddingModelId, - settings: EdgeDBEmbeddingSettings = {}, - ) => { - return new EdgeDBEmbeddingModel(modelId, settings, { - provider: "edgedb.embedding", - fetch, - headers: getHeaders, - }); - }; - - const provider = function ( - modelId: EdgeDBChatModelId, - settings?: EdgeDBChatSettings, - ) { - if (new.target) { - throw new Error( - "The EdgeDB model function cannot be called with the new keyword.", - ); - } - - return createChatModel(modelId, settings); - }; - - provider.languageModel = createChatModel; - provider.textEmbeddingModel = createEmbeddingModel; - - return provider; -} - -/** -Default provider instance. - */ -export const edgedb = createEdgeDB(createClient()); diff --git a/packages/vercel-ai-provider/src/edgedb-chat-language-model.ts b/packages/vercel-ai-provider/src/gel-chat-language-model.ts similarity index 91% rename from packages/vercel-ai-provider/src/edgedb-chat-language-model.ts rename to packages/vercel-ai-provider/src/gel-chat-language-model.ts index a5dab469c..c5c551371 100644 --- a/packages/vercel-ai-provider/src/edgedb-chat-language-model.ts +++ b/packages/vercel-ai-provider/src/gel-chat-language-model.ts @@ -17,41 +17,41 @@ import { combineHeaders, } from "@ai-sdk/provider-utils"; import { - type EdgeDBChatModelId, - type EdgeDBChatSettings, - type EdgeDBMessage, + type GelChatModelId, + type GelChatSettings, + type GelMessage, isAnthropicModel, -} from "./edgedb-chat-settings"; -import { edgedbFailedResponseHandler } from "./edgedb-error"; +} from "./gel-chat-settings"; +import { gelFailedResponseHandler } from "./gel-error"; import { - mapEdgedbStopReason, + mapGelStopReason, getResponseMetadata, mapOpenAICompletionLogProbs, } from "./utils"; -import { convertToEdgeDBMessages } from "./convert-to-edgedb-messages"; -import { prepareTools } from "./edgedb-prepare-tools"; +import { convertToGelMessages } from "./convert-to-gel-messages"; +import { prepareTools } from "./gel-prepare-tools"; -export interface EdgeDBChatConfig { +export interface GelChatConfig { provider: string; fetch: FetchFunction; // baseURL: string | null; headers: () => Record; } -export class EdgeDBChatLanguageModel implements LanguageModelV1 { +export class GelChatLanguageModel implements LanguageModelV1 { readonly specificationVersion = "v1"; readonly defaultObjectGenerationMode = "json"; readonly supportsImageUrls = false; - readonly modelId: EdgeDBChatModelId; - readonly settings: EdgeDBChatSettings; + readonly modelId: GelChatModelId; + readonly settings: GelChatSettings; - private readonly config: EdgeDBChatConfig; + private readonly config: GelChatConfig; constructor( - modelId: EdgeDBChatModelId, - settings: EdgeDBChatSettings, - config: EdgeDBChatConfig, + modelId: GelChatModelId, + settings: GelChatSettings, + config: GelChatConfig, ) { this.modelId = modelId; this.settings = settings; @@ -132,7 +132,7 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { const baseArgs = { model: this.modelId, - messages: convertToEdgeDBMessages(prompt), + messages: convertToGelMessages(prompt), temperature, max_tokens: maxTokens, top_p: topP, @@ -188,7 +188,7 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { } } - private buildPrompt(messages: EdgeDBMessage[]) { + private buildPrompt(messages: GelMessage[]) { const providedPromptId = this.settings.prompt && ("name" in this.settings.prompt || "id" in this.settings.prompt); @@ -207,7 +207,7 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { }; } - private buildQuery(messages: EdgeDBMessage[]) { + private buildQuery(messages: GelMessage[]) { return [...messages].reverse().find((msg) => msg.role === "user")! .content[0].text; } @@ -229,10 +229,9 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { query: this.buildQuery(messages), stream: false, }, - failedResponseHandler: edgedbFailedResponseHandler, - successfulResponseHandler: createJsonResponseHandler( - edgedbRagResponseSchema, - ), + failedResponseHandler: gelFailedResponseHandler, + successfulResponseHandler: + createJsonResponseHandler(gelRagResponseSchema), abortSignal: options.abortSignal, fetch: this.config.fetch, }); @@ -249,7 +248,7 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { toolName: toolCall.name, args: JSON.stringify(toolCall.args), })), - finishReason: mapEdgedbStopReason(finish_reason), + finishReason: mapGelStopReason(finish_reason), logprobs: mapOpenAICompletionLogProbs(logprobs), usage: { promptTokens: usage.prompt_tokens, @@ -279,9 +278,9 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { query: this.buildQuery(messages), stream: true, }, - failedResponseHandler: edgedbFailedResponseHandler, + failedResponseHandler: gelFailedResponseHandler, successfulResponseHandler: - createEventSourceResponseHandler(edgedbRagChunkSchema), + createEventSourceResponseHandler(gelRagChunkSchema), abortSignal: options.abortSignal, fetch: this.config.fetch, }); @@ -310,7 +309,7 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { return { stream: response.pipeThrough( new TransformStream< - ParseResult>, + ParseResult>, LanguageModelV1StreamPart >({ transform(chunk, controller) { @@ -428,7 +427,7 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { } case "message_delta": { - finishReason = mapEdgedbStopReason(value.delta.stop_reason); + finishReason = mapGelStopReason(value.delta.stop_reason); if (value.usage) { usage.completionTokens = value.usage.completion_tokens; } @@ -467,7 +466,7 @@ export class EdgeDBChatLanguageModel implements LanguageModelV1 { } } -const edgedbRagResponseSchema = z.object({ +const gelRagResponseSchema = z.object({ id: z.string().nullish(), model: z.string().nullish(), created: z.number().nullish(), @@ -496,7 +495,7 @@ const edgedbRagResponseSchema = z.object({ .nullish(), }); -const edgedbRagChunkSchema = z.discriminatedUnion("type", [ +const gelRagChunkSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("message_start"), message: z.object({ diff --git a/packages/vercel-ai-provider/src/edgedb-chat-settings.ts b/packages/vercel-ai-provider/src/gel-chat-settings.ts similarity index 85% rename from packages/vercel-ai-provider/src/edgedb-chat-settings.ts rename to packages/vercel-ai-provider/src/gel-chat-settings.ts index 227fd6b0e..a52501f1e 100644 --- a/packages/vercel-ai-provider/src/edgedb-chat-settings.ts +++ b/packages/vercel-ai-provider/src/gel-chat-settings.ts @@ -26,13 +26,13 @@ export type AnthropicModelId = | "claude-3-sonnet-20240229" | "claude-3-haiku-20240307"; -export type EdgeDBChatModelId = +export type GelChatModelId = | OpenAIModelId | MistralModelId | AnthropicModelId | (string & {}); -export function isAnthropicModel(model: EdgeDBChatModelId): boolean { +export function isAnthropicModel(model: GelChatModelId): boolean { return ( model === "claude-3-5-sonnet-latest" || model === "claude-3-5-haiku-latest" || @@ -42,7 +42,7 @@ export function isAnthropicModel(model: EdgeDBChatModelId): boolean { ); } -export function isOpenAIModel(model: EdgeDBChatModelId): boolean { +export function isOpenAIModel(model: GelChatModelId): boolean { return ( model === "gpt-4o" || model === "gpt-4o-mini" || @@ -54,9 +54,9 @@ export function isOpenAIModel(model: EdgeDBChatModelId): boolean { } export type Prompt = - | { name: string; custom?: EdgeDBMessage[] } - | { id: string; custom?: EdgeDBMessage[] } - | { custom: EdgeDBMessage[] }; + | { name: string; custom?: GelMessage[] } + | { id: string; custom?: GelMessage[] } + | { custom: GelMessage[] }; export interface QueryContext { query: string; @@ -65,7 +65,7 @@ export interface QueryContext { max_object_count?: number; } -export interface EdgeDBChatSettings { +export interface GelChatSettings { context?: QueryContext; prompt?: Prompt; @@ -126,23 +126,23 @@ monitor and detect abuse. Learn more. // cacheControl?: boolean; } -export type EdgeDBMessage = - | EdgeDBSystemMessage - | EdgeDBUserMessage - | EdgeDBAssistantMessage - | EdgeDBToolMessage; +export type GelMessage = + | GelSystemMessage + | GelUserMessage + | GelAssistantMessage + | GelToolMessage; -export interface EdgeDBSystemMessage { +export interface GelSystemMessage { role: "system"; content: string; } -export interface EdgeDBUserMessage { +export interface GelUserMessage { role: "user"; content: { type: "text"; text: string }[]; } -export interface EdgeDBAssistantMessage { +export interface GelAssistantMessage { role: "assistant"; content: string; tool_calls?: { @@ -152,7 +152,7 @@ export interface EdgeDBAssistantMessage { }[]; } -export interface EdgeDBToolMessage { +export interface GelToolMessage { role: "tool"; content: string; tool_call_id: string; diff --git a/packages/vercel-ai-provider/src/edgedb-embedding-model.ts b/packages/vercel-ai-provider/src/gel-embedding-model.ts similarity index 78% rename from packages/vercel-ai-provider/src/edgedb-embedding-model.ts rename to packages/vercel-ai-provider/src/gel-embedding-model.ts index 7f5fa004c..9bf8b5994 100644 --- a/packages/vercel-ai-provider/src/edgedb-embedding-model.ts +++ b/packages/vercel-ai-provider/src/gel-embedding-model.ts @@ -11,29 +11,29 @@ import { import { z } from "zod"; import { isMistralEmbeddingModel, - type EdgeDBEmbeddingModelId, - type EdgeDBEmbeddingSettings, -} from "./edgedb-embedding-settings"; -import { edgedbFailedResponseHandler } from "./edgedb-error"; + type GelEmbeddingModelId, + type GelEmbeddingSettings, +} from "./gel-embedding-settings"; +import { gelFailedResponseHandler } from "./gel-error"; -interface EdgeDBEmbeddingConfig { +interface GelEmbeddingConfig { provider: string; fetch?: FetchFunction; // baseURL: string | null; headers: () => Record; } -export class EdgeDBEmbeddingModel implements EmbeddingModelV1 { +export class GelEmbeddingModel implements EmbeddingModelV1 { readonly specificationVersion = "v1"; - readonly modelId: EdgeDBEmbeddingModelId; + readonly modelId: GelEmbeddingModelId; - private readonly config: EdgeDBEmbeddingConfig; - private readonly settings: EdgeDBEmbeddingSettings; + private readonly config: GelEmbeddingConfig; + private readonly settings: GelEmbeddingSettings; constructor( - modelId: EdgeDBEmbeddingModelId, - settings: EdgeDBEmbeddingSettings, - config: EdgeDBEmbeddingConfig, + modelId: GelEmbeddingModelId, + settings: GelEmbeddingSettings, + config: GelEmbeddingConfig, ) { this.modelId = modelId; this.settings = settings; @@ -87,9 +87,9 @@ export class EdgeDBEmbeddingModel implements EmbeddingModelV1 { dimensions: this.settings.dimensions, user: this.settings.user, }, - failedResponseHandler: edgedbFailedResponseHandler, + failedResponseHandler: gelFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( - EdgeDBTextEmbeddingResponseSchema, + GelTextEmbeddingResponseSchema, ), abortSignal, fetch: this.config.fetch, @@ -105,7 +105,7 @@ export class EdgeDBEmbeddingModel implements EmbeddingModelV1 { } } -const EdgeDBTextEmbeddingResponseSchema = z.object({ +const GelTextEmbeddingResponseSchema = z.object({ data: z.array(z.object({ embedding: z.array(z.number()) })), usage: z.object({ prompt_tokens: z.number() }).nullish(), }); diff --git a/packages/vercel-ai-provider/src/edgedb-embedding-settings.ts b/packages/vercel-ai-provider/src/gel-embedding-settings.ts similarity index 79% rename from packages/vercel-ai-provider/src/edgedb-embedding-settings.ts rename to packages/vercel-ai-provider/src/gel-embedding-settings.ts index 794bba9bc..ab7ed437c 100644 --- a/packages/vercel-ai-provider/src/edgedb-embedding-settings.ts +++ b/packages/vercel-ai-provider/src/gel-embedding-settings.ts @@ -1,17 +1,15 @@ -export type EdgeDBEmbeddingModelId = +export type GelEmbeddingModelId = | "text-embedding-ada-002" | "text-embedding-3-small" | "text-embedding-3-large" | "mistral-embed" | (string & {}); -export function isMistralEmbeddingModel( - model: EdgeDBEmbeddingModelId, -): boolean { +export function isMistralEmbeddingModel(model: GelEmbeddingModelId): boolean { return model === "mistral-embed"; } -export interface EdgeDBEmbeddingSettings { +export interface GelEmbeddingSettings { /** Override the maximum number of embeddings per call. */ diff --git a/packages/vercel-ai-provider/src/edgedb-error.ts b/packages/vercel-ai-provider/src/gel-error.ts similarity index 64% rename from packages/vercel-ai-provider/src/edgedb-error.ts rename to packages/vercel-ai-provider/src/gel-error.ts index b8a253cc1..0f2dc2f0c 100644 --- a/packages/vercel-ai-provider/src/edgedb-error.ts +++ b/packages/vercel-ai-provider/src/gel-error.ts @@ -1,7 +1,7 @@ import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils"; import { z } from "zod"; -const edgedbErrorDataSchema = z.object({ +const gelErrorDataSchema = z.object({ object: z.literal("error"), message: z.string(), type: z.string(), @@ -9,11 +9,11 @@ const edgedbErrorDataSchema = z.object({ code: z.string().nullable(), }); -export type EdgedDBErrorData = z.infer; +export type EdgedDBErrorData = z.infer; -export const edgedbFailedResponseHandler: ReturnType< +export const gelFailedResponseHandler: ReturnType< typeof createJsonErrorResponseHandler > = createJsonErrorResponseHandler({ - errorSchema: edgedbErrorDataSchema, + errorSchema: gelErrorDataSchema, errorToMessage: (data) => data.message, }); diff --git a/packages/vercel-ai-provider/src/edgedb-prepare-tools.ts b/packages/vercel-ai-provider/src/gel-prepare-tools.ts similarity index 83% rename from packages/vercel-ai-provider/src/edgedb-prepare-tools.ts rename to packages/vercel-ai-provider/src/gel-prepare-tools.ts index b823eede5..72b3a7dc3 100644 --- a/packages/vercel-ai-provider/src/edgedb-prepare-tools.ts +++ b/packages/vercel-ai-provider/src/gel-prepare-tools.ts @@ -5,10 +5,10 @@ import { UnsupportedFunctionalityError, } from "@ai-sdk/provider"; import { - type EdgeDBChatModelId, + type GelChatModelId, isAnthropicModel, isOpenAIModel, -} from "./edgedb-chat-settings"; +} from "./gel-chat-settings"; interface OpenAILikeTool { type: "function"; @@ -29,7 +29,7 @@ export function prepareTools( mode: Parameters[0]["mode"] & { type: "regular"; }, - model: EdgeDBChatModelId, + model: GelChatModelId, ) { const isOpenAI = isOpenAIModel(model); const isAnthropic = isAnthropicModel(model); @@ -42,20 +42,20 @@ export function prepareTools( return { toolWarnings }; } - const edgedbOpenAILikeTools: OpenAILikeTool[] = []; - const edgedbAnthropicTools: AnthropicTool[] = []; + const gelOpenAILikeTools: OpenAILikeTool[] = []; + const gelAnthropicTools: AnthropicTool[] = []; for (const tool of tools) { switch (tool.type) { case "function": if (isAnthropic) { - edgedbAnthropicTools.push({ + gelAnthropicTools.push({ name: tool.name, description: tool.description, input_schema: tool.parameters, }); } else { - edgedbOpenAILikeTools.push({ + gelOpenAILikeTools.push({ type: "function", function: { name: tool.name, @@ -78,13 +78,11 @@ export function prepareTools( } const toolChoice = mode.toolChoice; - const edgedbTools = isAnthropic - ? edgedbAnthropicTools - : edgedbOpenAILikeTools; + const gelTools = isAnthropic ? gelAnthropicTools : gelOpenAILikeTools; if (toolChoice == null) { return { - tools: edgedbTools, + tools: gelTools, toolWarnings, }; } @@ -94,7 +92,7 @@ export function prepareTools( switch (type) { case "auto": return { - tools: edgedbTools, + tools: gelTools, tool_choice: isAnthropic ? { type: "auto" } : "auto", toolWarnings, // add betas to Anthropic in all cases @@ -102,10 +100,10 @@ export function prepareTools( case "none": return isAnthropic ? { toolWarnings } - : { tools: edgedbTools, tool_choice: type, toolWarnings }; + : { tools: gelTools, tool_choice: type, toolWarnings }; case "required": return { - tools: edgedbTools, + tools: gelTools, tool_choice: isAnthropic ? { type: "any" } : isOpenAI @@ -119,7 +117,7 @@ export function prepareTools( case "tool": return isAnthropic ? { - tools: edgedbTools, + tools: gelTools, tool_choice: { type: "tool", name: toolChoice.toolName, @@ -128,7 +126,7 @@ export function prepareTools( } : isOpenAI ? { - tools: edgedbTools, + tools: gelTools, tool_choice: { type: "function", function: { @@ -138,7 +136,7 @@ export function prepareTools( toolWarnings, } : { - tools: (edgedbTools as OpenAILikeTool[]).filter( + tools: (gelTools as OpenAILikeTool[]).filter( (tool) => tool.function!.name === toolChoice.toolName, ), tool_choice: "any", diff --git a/packages/vercel-ai-provider/src/gel-provider.ts b/packages/vercel-ai-provider/src/gel-provider.ts new file mode 100644 index 000000000..5d6dfd1d9 --- /dev/null +++ b/packages/vercel-ai-provider/src/gel-provider.ts @@ -0,0 +1,110 @@ +import { type Client, createClient } from "gel"; +import { getHTTPSCRAMAuth } from "gel/dist/httpScram.js"; +import { cryptoUtils } from "gel/dist/browserCrypto.js"; +import { getAuthenticatedFetch } from "gel/dist/utils.js"; +import type { + EmbeddingModelV1, + LanguageModelV1, + ProviderV1, +} from "@ai-sdk/provider"; +import { GelChatLanguageModel } from "./gel-chat-language-model"; +import type { GelChatModelId, GelChatSettings } from "./gel-chat-settings"; +import { GelEmbeddingModel } from "./gel-embedding-model"; +import type { + GelEmbeddingModelId, + GelEmbeddingSettings, +} from "./gel-embedding-settings"; + +const httpSCRAMAuth = getHTTPSCRAMAuth(cryptoUtils); + +export interface GelProvider extends ProviderV1 { + ( + modelId: GelChatModelId | GelEmbeddingModelId, + settings?: GelChatSettings, + ): LanguageModelV1; + + languageModel( + modelId: GelChatModelId, + settings?: GelChatSettings, + ): GelChatLanguageModel; + + textEmbeddingModel: ( + modelId: GelEmbeddingModelId, + settings?: GelEmbeddingSettings, + ) => EmbeddingModelV1; +} + +export interface GelProviderSettings { + /** +Use a different URL prefix for API calls, e.g. to use proxy servers. + */ + // baseURL?: string; + + /** +Custom headers to include in the requests. + */ + headers?: Record; +} + +export async function createGel( + client: Client, + options: GelProviderSettings = {}, +): Promise { + const connectConfig = await client.resolveConnectionParams(); + // const baseURL = withoutTrailingSlash(options.baseURL) ?? null; + + // In case we want to add more things to this in the future + const getHeaders = () => ({ + ...options.headers, + }); + + const fetch = await getAuthenticatedFetch( + connectConfig, + httpSCRAMAuth, + "ext/ai/", + ); + + const createChatModel = ( + modelId: GelChatModelId, + settings: GelChatSettings = {}, + ) => + new GelChatLanguageModel(modelId, settings, { + provider: "gel.chat", + fetch, + headers: getHeaders, + }); + + const createEmbeddingModel = ( + modelId: GelEmbeddingModelId, + settings: GelEmbeddingSettings = {}, + ) => { + return new GelEmbeddingModel(modelId, settings, { + provider: "gel.embedding", + fetch, + headers: getHeaders, + }); + }; + + const provider = function ( + modelId: GelChatModelId, + settings?: GelChatSettings, + ) { + if (new.target) { + throw new Error( + "The Gel model function cannot be called with the new keyword.", + ); + } + + return createChatModel(modelId, settings); + }; + + provider.languageModel = createChatModel; + provider.textEmbeddingModel = createEmbeddingModel; + + return provider; +} + +/** +Default provider instance. + */ +export const gel = createGel(createClient()); diff --git a/packages/vercel-ai-provider/src/index.ts b/packages/vercel-ai-provider/src/index.ts index ee8cdb6e5..25a54c29b 100644 --- a/packages/vercel-ai-provider/src/index.ts +++ b/packages/vercel-ai-provider/src/index.ts @@ -1,2 +1,2 @@ -export { createEdgeDB, edgedb } from "./edgedb-provider"; -export type { EdgeDBProvider } from "./edgedb-provider"; +export { createGel, gel } from "./gel-provider"; +export type { GelProvider } from "./gel-provider"; diff --git a/packages/vercel-ai-provider/src/utils.ts b/packages/vercel-ai-provider/src/utils.ts index ae9b2f8b3..5142bf2ea 100644 --- a/packages/vercel-ai-provider/src/utils.ts +++ b/packages/vercel-ai-provider/src/utils.ts @@ -1,7 +1,7 @@ import type { LanguageModelV1FinishReason } from "@ai-sdk/provider"; import type { LanguageModelV1LogProbs } from "@ai-sdk/provider"; -export function mapEdgedbStopReason( +export function mapGelStopReason( finishReason: string | null | undefined, ): LanguageModelV1FinishReason { switch (finishReason) { diff --git a/turbo.json b/turbo.json index a44e03e81..e85c1f4bd 100644 --- a/turbo.json +++ b/turbo.json @@ -12,31 +12,25 @@ }, "test": { "dependsOn": ["build"], - "env": ["EDGEDB_SERVER_BIN"] + "env": ["GEL_SERVER_BIN"] }, "ci:typecheck": { "dependsOn": [ - "@edgedb/auth-nextjs#typecheck", - "@edgedb/auth-express#typecheck", - "@edgedb/auth-remix#typecheck", - "@edgedb/auth-sveltekit#typecheck", - "@edgedb/ai#typecheck", - "@edgedb/vercel-ai-provider#typecheck" + "@gel/auth-nextjs#typecheck", + "@gel/auth-express#typecheck", + "@gel/auth-remix#typecheck", + "@gel/auth-sveltekit#typecheck", + "@gel/ai#typecheck", + "@gel/vercel-ai-provider#typecheck" ] }, "ci:test": { - "dependsOn": [ - "build", - "edgedb#test", - "@edgedb/auth-core#test", - "@edgedb/create#test", - "@edgedb/ai#test" - ], - "env": ["CI", "EDGEDB_SERVER_BIN"] + "dependsOn": ["build", "gel#test", "@gel/auth-core#test"], + "env": ["CI", "GEL_SERVER_BIN"] }, "ci:integration-test": { "dependsOn": ["build"], - "env": ["CI", "EDGEDB_SERVER_BIN"] + "env": ["CI", "GEL_SERVER_BIN"] } } }