From 2a38fea274a2dc94633065003384496fa19a5d62 Mon Sep 17 00:00:00 2001 From: GNRSN <9020004+GNRSN@users.noreply.github.com> Date: Tue, 25 Jun 2024 20:59:10 +0200 Subject: [PATCH] Initial commit --- .env.example | 21 + .github/DISCUSSION_TEMPLATE/ideas.yml | 21 + .github/FUNDING.yml | 3 + .github/ISSUE_TEMPLATE/bug_report.yml | 37 + .github/ISSUE_TEMPLATE/config.yml | 7 + .github/renovate.json | 16 + .github/workflows/ci.yml | 57 + .gitignore | 52 + .npmrc | 1 + .nvmrc | 1 + .vscode/extensions.json | 9 + .vscode/launch.json | 13 + .vscode/settings.json | 25 + LICENSE | 21 + README.md | 267 + apps/auth-proxy/.env.example | 7 + apps/auth-proxy/README.md | 26 + apps/auth-proxy/eslint.config.js | 9 + apps/auth-proxy/package.json | 28 + apps/auth-proxy/routes/r/[...auth].ts | 18 + apps/auth-proxy/tsconfig.json | 4 + apps/expo/.expo-shared/assets.json | 4 + apps/expo/app.config.ts | 42 + apps/expo/assets/icon.png | Bin 0 -> 10788 bytes apps/expo/babel.config.js | 11 + apps/expo/eas.json | 31 + apps/expo/eslint.config.mjs | 11 + apps/expo/metro.config.js | 55 + apps/expo/package.json | 62 + apps/expo/src/app/_layout.tsx | 34 + apps/expo/src/app/index.tsx | 159 + apps/expo/src/app/post/[id].tsx | 24 + apps/expo/src/styles.css | 50 + apps/expo/src/types/nativewind-env.d.ts | 1 + apps/expo/src/utils/api.tsx | 57 + apps/expo/src/utils/auth.tsx | 53 + apps/expo/src/utils/base-url.tsx | 26 + apps/expo/src/utils/session-store.ts | 6 + apps/expo/tailwind.config.ts | 10 + apps/expo/tsconfig.json | 15 + apps/nextjs/README.md | 28 + apps/nextjs/eslint.config.js | 14 + apps/nextjs/next.config.js | 25 + apps/nextjs/package.json | 50 + apps/nextjs/postcss.config.cjs | 5 + apps/nextjs/public/favicon.ico | Bin 0 -> 103027 bytes apps/nextjs/public/t3-icon.svg | 13 + .../src/app/_components/auth-showcase.tsx | 42 + apps/nextjs/src/app/_components/posts.tsx | 176 + .../src/app/api/auth/[...nextauth]/route.ts | 81 + apps/nextjs/src/app/api/trpc/[trpc]/route.ts | 46 + apps/nextjs/src/app/globals.css | 50 + apps/nextjs/src/app/layout.tsx | 63 + apps/nextjs/src/app/page.tsx | 42 + apps/nextjs/src/env.ts | 40 + apps/nextjs/src/middleware.ts | 11 + apps/nextjs/src/trpc/react.tsx | 75 + apps/nextjs/src/trpc/server.ts | 21 + apps/nextjs/tailwind.config.ts | 19 + apps/nextjs/tsconfig.json | 16 + package.json | 33 + packages/api/eslint.config.js | 9 + packages/api/package.json | 38 + packages/api/src/index.ts | 33 + packages/api/src/root.ts | 11 + packages/api/src/router/auth.ts | 21 + packages/api/src/router/post.ts | 40 + packages/api/src/trpc.ts | 120 + packages/api/tsconfig.json | 9 + packages/auth/env.ts | 19 + packages/auth/eslint.config.js | 10 + packages/auth/package.json | 40 + packages/auth/src/config.ts | 75 + packages/auth/src/index.rsc.ts | 22 + packages/auth/src/index.ts | 15 + packages/auth/tsconfig.json | 8 + packages/db/drizzle.config.ts | 13 + packages/db/eslint.config.js | 10 + packages/db/package.json | 50 + packages/db/src/client.ts | 6 + packages/db/src/index.ts | 2 + packages/db/src/schema.ts | 92 + packages/db/tsconfig.json | 9 + packages/ui/components.json | 17 + packages/ui/eslint.config.js | 11 + packages/ui/package.json | 52 + packages/ui/src/button.tsx | 58 + packages/ui/src/dropdown-menu.tsx | 200 + packages/ui/src/form.tsx | 201 + packages/ui/src/index.ts | 6 + packages/ui/src/input.tsx | 24 + packages/ui/src/label.tsx | 25 + packages/ui/src/theme.tsx | 42 + packages/ui/src/toast.tsx | 31 + packages/ui/tailwind.config.ts | 12 + packages/ui/tsconfig.json | 10 + packages/validators/eslint.config.js | 9 + packages/validators/package.json | 33 + packages/validators/src/index.ts | 8 + packages/validators/tsconfig.json | 9 + pnpm-lock.yaml | 16454 ++++++++++++++++ pnpm-workspace.yaml | 4 + tooling/eslint/base.js | 80 + tooling/eslint/nextjs.js | 17 + tooling/eslint/package.json | 33 + tooling/eslint/react.js | 22 + tooling/eslint/tsconfig.json | 8 + tooling/eslint/types.d.ts | 67 + tooling/github/package.json | 3 + tooling/github/setup/action.yml | 17 + tooling/prettier/index.js | 50 + tooling/prettier/package.json | 24 + tooling/prettier/tsconfig.json | 8 + tooling/tailwind/base.ts | 48 + tooling/tailwind/eslint.config.js | 6 + tooling/tailwind/native.ts | 9 + tooling/tailwind/package.json | 31 + tooling/tailwind/tsconfig.json | 8 + tooling/tailwind/web.ts | 40 + tooling/typescript/base.json | 29 + tooling/typescript/internal-package.json | 11 + tooling/typescript/package.json | 8 + turbo.json | 70 + turbo/generators/config.ts | 95 + .../generators/templates/eslint.config.js.hbs | 9 + turbo/generators/templates/package.json.hbs | 25 + turbo/generators/templates/tsconfig.json.hbs | 8 + 127 files changed, 20728 insertions(+) create mode 100644 .env.example create mode 100644 .github/DISCUSSION_TEMPLATE/ideas.yml create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/renovate.json create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .npmrc create mode 100644 .nvmrc create mode 100644 .vscode/extensions.json create mode 100644 .vscode/launch.json create mode 100644 .vscode/settings.json create mode 100644 LICENSE create mode 100644 README.md create mode 100644 apps/auth-proxy/.env.example create mode 100644 apps/auth-proxy/README.md create mode 100644 apps/auth-proxy/eslint.config.js create mode 100644 apps/auth-proxy/package.json create mode 100644 apps/auth-proxy/routes/r/[...auth].ts create mode 100644 apps/auth-proxy/tsconfig.json create mode 100644 apps/expo/.expo-shared/assets.json create mode 100644 apps/expo/app.config.ts create mode 100644 apps/expo/assets/icon.png create mode 100644 apps/expo/babel.config.js create mode 100644 apps/expo/eas.json create mode 100644 apps/expo/eslint.config.mjs create mode 100644 apps/expo/metro.config.js create mode 100644 apps/expo/package.json create mode 100644 apps/expo/src/app/_layout.tsx create mode 100644 apps/expo/src/app/index.tsx create mode 100644 apps/expo/src/app/post/[id].tsx create mode 100644 apps/expo/src/styles.css create mode 100644 apps/expo/src/types/nativewind-env.d.ts create mode 100644 apps/expo/src/utils/api.tsx create mode 100644 apps/expo/src/utils/auth.tsx create mode 100644 apps/expo/src/utils/base-url.tsx create mode 100644 apps/expo/src/utils/session-store.ts create mode 100644 apps/expo/tailwind.config.ts create mode 100644 apps/expo/tsconfig.json create mode 100644 apps/nextjs/README.md create mode 100644 apps/nextjs/eslint.config.js create mode 100644 apps/nextjs/next.config.js create mode 100644 apps/nextjs/package.json create mode 100644 apps/nextjs/postcss.config.cjs create mode 100644 apps/nextjs/public/favicon.ico create mode 100644 apps/nextjs/public/t3-icon.svg create mode 100644 apps/nextjs/src/app/_components/auth-showcase.tsx create mode 100644 apps/nextjs/src/app/_components/posts.tsx create mode 100644 apps/nextjs/src/app/api/auth/[...nextauth]/route.ts create mode 100644 apps/nextjs/src/app/api/trpc/[trpc]/route.ts create mode 100644 apps/nextjs/src/app/globals.css create mode 100644 apps/nextjs/src/app/layout.tsx create mode 100644 apps/nextjs/src/app/page.tsx create mode 100644 apps/nextjs/src/env.ts create mode 100644 apps/nextjs/src/middleware.ts create mode 100644 apps/nextjs/src/trpc/react.tsx create mode 100644 apps/nextjs/src/trpc/server.ts create mode 100644 apps/nextjs/tailwind.config.ts create mode 100644 apps/nextjs/tsconfig.json create mode 100644 package.json create mode 100644 packages/api/eslint.config.js create mode 100644 packages/api/package.json create mode 100644 packages/api/src/index.ts create mode 100644 packages/api/src/root.ts create mode 100644 packages/api/src/router/auth.ts create mode 100644 packages/api/src/router/post.ts create mode 100644 packages/api/src/trpc.ts create mode 100644 packages/api/tsconfig.json create mode 100644 packages/auth/env.ts create mode 100644 packages/auth/eslint.config.js create mode 100644 packages/auth/package.json create mode 100644 packages/auth/src/config.ts create mode 100644 packages/auth/src/index.rsc.ts create mode 100644 packages/auth/src/index.ts create mode 100644 packages/auth/tsconfig.json create mode 100644 packages/db/drizzle.config.ts create mode 100644 packages/db/eslint.config.js create mode 100644 packages/db/package.json create mode 100644 packages/db/src/client.ts create mode 100644 packages/db/src/index.ts create mode 100644 packages/db/src/schema.ts create mode 100644 packages/db/tsconfig.json create mode 100644 packages/ui/components.json create mode 100644 packages/ui/eslint.config.js create mode 100644 packages/ui/package.json create mode 100644 packages/ui/src/button.tsx create mode 100644 packages/ui/src/dropdown-menu.tsx create mode 100644 packages/ui/src/form.tsx create mode 100644 packages/ui/src/index.ts create mode 100644 packages/ui/src/input.tsx create mode 100644 packages/ui/src/label.tsx create mode 100644 packages/ui/src/theme.tsx create mode 100644 packages/ui/src/toast.tsx create mode 100644 packages/ui/tailwind.config.ts create mode 100644 packages/ui/tsconfig.json create mode 100644 packages/validators/eslint.config.js create mode 100644 packages/validators/package.json create mode 100644 packages/validators/src/index.ts create mode 100644 packages/validators/tsconfig.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 tooling/eslint/base.js create mode 100644 tooling/eslint/nextjs.js create mode 100644 tooling/eslint/package.json create mode 100644 tooling/eslint/react.js create mode 100644 tooling/eslint/tsconfig.json create mode 100644 tooling/eslint/types.d.ts create mode 100644 tooling/github/package.json create mode 100644 tooling/github/setup/action.yml create mode 100644 tooling/prettier/index.js create mode 100644 tooling/prettier/package.json create mode 100644 tooling/prettier/tsconfig.json create mode 100644 tooling/tailwind/base.ts create mode 100644 tooling/tailwind/eslint.config.js create mode 100644 tooling/tailwind/native.ts create mode 100644 tooling/tailwind/package.json create mode 100644 tooling/tailwind/tsconfig.json create mode 100644 tooling/tailwind/web.ts create mode 100644 tooling/typescript/base.json create mode 100644 tooling/typescript/internal-package.json create mode 100644 tooling/typescript/package.json create mode 100644 turbo.json create mode 100644 turbo/generators/config.ts create mode 100644 turbo/generators/templates/eslint.config.js.hbs create mode 100644 turbo/generators/templates/package.json.hbs create mode 100644 turbo/generators/templates/tsconfig.json.hbs diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..ccb32a3 --- /dev/null +++ b/.env.example @@ -0,0 +1,21 @@ +# Since .env is gitignored, you can use .env.example to build a new `.env` file when you clone the repo. +# Keep this file up-to-date when you add new variables to \`.env\`. + +# This file will be committed to version control, so make sure not to have any secrets in it. +# If you are cloning this repo, create a copy of this file named `.env` and populate it with your secrets. + +# The database URL is used to connect to your Supabase database. +POSTGRES_URL="postgres://postgres.[USERNAME]:[PASSWORD]@aws-0-eu-central-1.pooler.supabase.com:6543/postgres?workaround=supabase-pooler.vercel" + + +# You can generate the secret via 'openssl rand -base64 32' on Unix +# @see https://next-auth.js.org/configuration/options#secret +AUTH_SECRET='supersecret' + +# Preconfigured Discord OAuth provider, works out-of-the-box +# @see https://next-auth.js.org/providers/discord +AUTH_DISCORD_ID='' +AUTH_DISCORD_SECRET='' + +# In case you're using the Auth Proxy (apps/auth-proxy) +# AUTH_REDIRECT_PROXY_URL='https://auth.your-server.com/r' \ No newline at end of file diff --git a/.github/DISCUSSION_TEMPLATE/ideas.yml b/.github/DISCUSSION_TEMPLATE/ideas.yml new file mode 100644 index 0000000..c15eba2 --- /dev/null +++ b/.github/DISCUSSION_TEMPLATE/ideas.yml @@ -0,0 +1,21 @@ +body: + - type: markdown + attributes: + value: | + Thank you for taking the time to file a feature request. Please fill out this form as completely as possible. + - type: textarea + attributes: + label: Describe the feature you'd like to request + description: Please describe the feature as clear and concise as possible. Remember to add context as to why you believe this feature is needed. + validations: + required: true + - type: textarea + attributes: + label: Describe the solution you'd like to see + description: Please describe the solution you would like to see. Adding example usage is a good way to provide context. + validations: + required: true + - type: textarea + attributes: + label: Additional information + description: Add any other information related to the feature here. If your feature request is related to any issues or discussions, link them here. diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..043f0f9 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: juliusmarminge diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..54199a8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,37 @@ +name: 🐞 Bug Report +description: Create a bug report to help us improve +title: "bug: " +labels: ["🐞❔ unconfirmed bug"] +body: + - type: textarea + attributes: + label: Provide environment information + description: | + Run this command in your project root and paste the results in a code block: + ```bash + npx envinfo --system --binaries + ``` + validations: + required: true + - type: textarea + attributes: + label: Describe the bug + description: A clear and concise description of the bug, as well as what you expected to happen when encountering it. + validations: + required: true + - type: input + attributes: + label: Link to reproduction + description: Please provide a link to a reproduction of the bug. Issues without a reproduction repo may be ignored. + validations: + required: true + - type: textarea + attributes: + label: To reproduce + description: Describe how to reproduce your bug. Steps, code snippets, reproduction repos etc. + validations: + required: true + - type: textarea + attributes: + label: Additional information + description: Add any other information related to the bug here, screenshots if applicable. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..1b73188 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,7 @@ +contact_links: + - name: Ask a question + url: https://github.com/t3-oss/create-t3-turbo/discussions + about: Ask questions and discuss with other community members + - name: Feature request + url: https://github.com/t3-oss/create-t3-turbo/discussions/new?category=ideas + about: Feature requests should be opened as discussions diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 0000000..4144940 --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:base"], + "packageRules": [ + { + "matchPackagePatterns": ["^@acme/"], + "enabled": false + } + ], + "updateInternalDeps": true, + "rangeStrategy": "bump", + "automerge": true, + "npm": { + "fileMatch": ["(^|/)package\\.json$", "(^|/)package\\.json\\.hbs$"] + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8500662 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,57 @@ +name: CI + +on: + pull_request: + branches: ["*"] + push: + branches: ["main"] + merge_group: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# You can leverage Vercel Remote Caching with Turbo to speed up your builds +# @link https://turborepo.org/docs/core-concepts/remote-caching#remote-caching-on-vercel-builds +env: + FORCE_COLOR: 3 + TURBO_TEAM: ${{ vars.TURBO_TEAM }} + TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup + uses: ./tooling/github/setup + + - name: Copy env + shell: bash + run: cp .env.example .env + + - name: Lint + run: pnpm lint && pnpm lint:ws + + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup + uses: ./tooling/github/setup + + - name: Format + run: pnpm format + + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup + uses: ./tooling/github/setup + + - name: Typecheck + run: pnpm typecheck diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ec0c6c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +node_modules +.pnp +.pnp.js + +# testing +coverage + +# next.js +.next/ +out/ +next-env.d.ts + +# nitro +.nitro/ +.output/ + +# expo +.expo/ +expo-env.d.ts +apps/expo/.gitignore +apps/expo/ios +apps/expo/android + +# production +build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +dist/ + +# turbo +.turbo diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..d67f374 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +node-linker=hoisted diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..d5908b9 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +20.12 \ No newline at end of file diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..3606d87 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "dbaeumer.vscode-eslint", + "expo.vscode-expo-tools", + "esbenp.prettier-vscode", + "yoavbls.pretty-ts-errors", + "bradlc.vscode-tailwindcss" + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..5fcd845 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,13 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Next.js", + "type": "node-terminal", + "request": "launch", + "command": "pnpm dev", + "cwd": "${workspaceFolder}/apps/nextjs/", + "skipFiles": ["/**"] + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..ea77a68 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,25 @@ +{ + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + }, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "eslint.rules.customizations": [{ "rule": "*", "severity": "warn" }], + "eslint.experimental.useFlatConfig": true, + "eslint.workingDirectories": [ + { "pattern": "apps/*/" }, + { "pattern": "packages/*/" }, + { "pattern": "tooling/*/" } + ], + "tailwindCSS.experimental.classRegex": [ + ["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"], + ["cx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"] + ], + "tailwindCSS.experimental.configFile": "./tooling/tailwind/web.ts", + "typescript.enablePromptUseWorkspaceTsdk": true, + "typescript.preferences.autoImportFileExcludePatterns": [ + "next/router.d.ts", + "next/dist/client/router.d.ts" + ], + "typescript.tsdk": "node_modules/typescript/lib" +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..435503e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Julius Marminge + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4514094 --- /dev/null +++ b/README.md @@ -0,0 +1,267 @@ +# create-t3-turbo + +> [!NOTE] +> +> NextAuth setup now works for Expo app! + +> [!NOTE] +> +> OAuth deployments are now working for preview deployments. Read [deployment guide](https://github.com/t3-oss/create-t3-turbo#auth-proxy) and [check out the source](./apps/auth-proxy) to learn more! + +> [!NOTE] +> +> Due to high demand, this repo now uses the `app` directory with some new experimental features. If you want to use the more traditional `pages` router, [check out the repo before the update](https://github.com/t3-oss/create-t3-turbo/tree/414aff131ca124573e721f3779df3edb64989fd4). + +## Installation + +There are two ways of initializing an app using the `create-t3-turbo` starter. You can either use this repository as a template: + +![use-as-template](https://github.com/t3-oss/create-t3-turbo/assets/51714798/bb6c2e5d-d8b6-416e-aeb3-b3e50e2ca994) + +or use Turbo's CLI to init your project (use PNPM as package manager): + +```bash +npx create-turbo@latest -e https://github.com/t3-oss/create-t3-turbo +``` + +## About + +Ever wondered how to migrate your T3 application into a monorepo? Stop right here! This is the perfect starter repo to get you running with the perfect stack! + +It uses [Turborepo](https://turborepo.org) and contains: + +```text +.github + └─ workflows + └─ CI with pnpm cache setup +.vscode + └─ Recommended extensions and settings for VSCode users +apps + ├─ auth-proxy + | ├─ Nitro server to proxy OAuth requests in preview deployments + | └─ Uses Auth.js Core + ├─ expo + | ├─ Expo SDK 51 + | ├─ React Native using React 18 + | ├─ Navigation using Expo Router + | ├─ Tailwind using NativeWind + | └─ Typesafe API calls using tRPC + └─ next.js + ├─ Next.js 14 + ├─ React 18 + ├─ Tailwind CSS + └─ E2E Typesafe API Server & Client +packages + ├─ api + | └─ tRPC v11 router definition + ├─ auth + | └─ Authentication using next-auth. + ├─ db + | └─ Typesafe db calls using Drizzle & Supabase + └─ ui + └─ Start of a UI package for the webapp using shadcn-ui +tooling + ├─ eslint + | └─ shared, fine-grained, eslint presets + ├─ prettier + | └─ shared prettier configuration + ├─ tailwind + | └─ shared tailwind configuration + └─ typescript + └─ shared tsconfig you can extend from +``` + +> In this template, we use `@acme` as a placeholder for package names. As a user, you might want to replace it with your own organization or project name. You can use find-and-replace to change all the instances of `@acme` to something like `@my-company` or `@project-name`. + +## Quick Start + +> **Note** +> The [db](./packages/db) package is preconfigured to use Supabase and is **edge-bound** with the [Vercel Postgres](https://github.com/vercel/storage/tree/main/packages/postgres) driver. If you're using something else, make the necessary modifications to the [schema](./packages/db/src/schema) as well as the [client](./packages/db/src/index.ts) and the [drizzle config](./packages/db/drizzle.config.ts). If you want to switch to non-edge database driver, remove `export const runtime = "edge";` [from all pages and api routes](https://github.com/t3-oss/create-t3-turbo/issues/634#issuecomment-1730240214). + +To get it running, follow the steps below: + +### 1. Setup dependencies + +```bash +# Install dependencies +pnpm i + +# Configure environment variables +# There is an `.env.example` in the root directory you can use for reference +cp .env.example .env + +# Push the Drizzle schema to the database +pnpm db:push +``` + +### 2. Configure Expo `dev`-script + +#### Use iOS Simulator + +1. Make sure you have XCode and XCommand Line Tools installed [as shown on expo docs](https://docs.expo.dev/workflow/ios-simulator). + + > **NOTE:** If you just installed XCode, or if you have updated it, you need to open the simulator manually once. Run `npx expo start` from `apps/expo`, and then enter `I` to launch Expo Go. After the manual launch, you can run `pnpm dev` in the root directory. + + ```diff + + "dev": "expo start --ios", + ``` + +2. Run `pnpm dev` at the project root folder. + +#### Use Android Emulator + +1. Install Android Studio tools [as shown on expo docs](https://docs.expo.dev/workflow/android-studio-emulator). + +2. Change the `dev` script at `apps/expo/package.json` to open the Android emulator. + + ```diff + + "dev": "expo start --android", + ``` + +3. Run `pnpm dev` at the project root folder. + +### 3. Configuring Next-Auth to work with Expo + +In order to get Next-Auth to work with Expo, you must either: + +#### Deploy the Auth Proxy (RECOMMENDED) + +In [apps/auth-proxy](./apps/auth-proxy) you can find a Nitro server that proxies OAuth requests. By deploying this and setting the `AUTH_REDIRECT_PROXY_URL` environment variable to the URL of this proxy, you can get OAuth working in preview deployments and development for Expo apps. See more deployment instructions in the [auth proxy README](./apps/auth-proxy/README.md). + +By using the proxy server, the Next.js apps will forward any auth requests to the proxy server, which will handle the OAuth flow and then redirect back to the Next.js app. This makes it easy to get OAuth working since you'll have a stable URL that is publically accessible and doesn't change for every deployment and doesn't rely on what port the app is running on. So if port 3000 is taken and your Next.js app starts at port 3001 instead, your auth should still work without having to reconfigure the OAuth provider. + +#### Add your local IP to your OAuth provider + +You can alternatively add your local IP (e.g. `192.168.x.y:$PORT`) to your OAuth provider. This may not be as reliable as your local IP may change when you change networks. Some OAuth providers may also only support a single callback URL for each app making this approach unviable for some providers (e.g. GitHub). + +### 4a. When it's time to add a new UI component + +Run the `ui-add` script to add a new UI component using the interactive `shadcn/ui` CLI: + +```bash +pnpm ui-add +``` + +When the component(s) has been installed, you should be good to go and start using it in your app. + +### 4b. When it's time to add a new package + +To add a new package, simply run `pnpm turbo gen init` in the monorepo root. This will prompt you for a package name as well as if you want to install any dependencies to the new package (of course you can also do this yourself later). + +The generator sets up the `package.json`, `tsconfig.json` and a `index.ts`, as well as configures all the necessary configurations for tooling around your package such as formatting, linting and typechecking. When the package is created, you're ready to go build out the package. + +## FAQ + +### Does the starter include Solito? + +No. Solito will not be included in this repo. It is a great tool if you want to share code between your Next.js and Expo app. However, the main purpose of this repo is not the integration between Next.js and Expo — it's the code splitting of your T3 App into a monorepo. The Expo app is just a bonus example of how you can utilize the monorepo with multiple apps but can just as well be any app such as Vite, Electron, etc. + +Integrating Solito into this repo isn't hard, and there are a few [official templates](https://github.com/nandorojo/solito/tree/master/example-monorepos) by the creators of Solito that you can use as a reference. + +### Does this pattern leak backend code to my client applications? + +No, it does not. The `api` package should only be a production dependency in the Next.js application where it's served. The Expo app, and all other apps you may add in the future, should only add the `api` package as a dev dependency. This lets you have full typesafety in your client applications, while keeping your backend code safe. + +If you need to share runtime code between the client and server, such as input validation schemas, you can create a separate `shared` package for this and import it on both sides. + +## Deployment + +### Next.js + +#### Prerequisites + +> **Note** +> Please note that the Next.js application with tRPC must be deployed in order for the Expo app to communicate with the server in a production environment. + +#### Deploy to Vercel + +Let's deploy the Next.js application to [Vercel](https://vercel.com). If you've never deployed a Turborepo app there, don't worry, the steps are quite straightforward. You can also read the [official Turborepo guide](https://vercel.com/docs/concepts/monorepos/turborepo) on deploying to Vercel. + +1. Create a new project on Vercel, select the `apps/nextjs` folder as the root directory. Vercel's zero-config system should handle all configurations for you. + +2. Add your `DATABASE_URL` environment variable. + +3. Done! Your app should successfully deploy. Assign your domain and use that instead of `localhost` for the `url` in the Expo app so that your Expo app can communicate with your backend when you are not in development. + +### Auth Proxy + +The auth proxy is a Nitro server that proxies OAuth requests in preview deployments. This is required for the Next.js app to be able to authenticate users in preview deployments. The auth proxy is not used for OAuth requests in production deployments. To get it running, it's easiest to use Vercel Edge functions. See the [Nitro docs](https://nitro.unjs.io/deploy/providers/vercel#vercel-edge-functions) for how to deploy Nitro to Vercel. + +Then, there are some environment variables you need to set in order to get OAuth working: + +- For the Next.js app, set `AUTH_REDIRECT_PROXY_URL` to the URL of the auth proxy. +- For the auth proxy server, set `AUTH_REDIRECT_PROXY_URL` to the same as above, as well as `AUTH_DISCORD_ID`, `AUTH_DISCORD_SECRET` (or the equivalent for your OAuth provider(s)). Lastly, set `AUTH_SECRET` **to the same value as in the Next.js app** for preview environments. + +Read more about the setup in [the auth proxy README](./apps/auth-proxy/README.md). + +### Expo + +Deploying your Expo application works slightly differently compared to Next.js on the web. Instead of "deploying" your app online, you need to submit production builds of your app to app stores, like [Apple App Store](https://www.apple.com/app-store) and [Google Play](https://play.google.com/store/apps). You can read the full [guide to distributing your app](https://docs.expo.dev/distribution/introduction), including best practices, in the Expo docs. + +1. Make sure to modify the `getBaseUrl` function to point to your backend's production URL: + + + +2. Let's start by setting up [EAS Build](https://docs.expo.dev/build/introduction), which is short for Expo Application Services. The build service helps you create builds of your app, without requiring a full native development setup. The commands below are a summary of [Creating your first build](https://docs.expo.dev/build/setup). + + ```bash + # Install the EAS CLI + pnpm add -g eas-cli + + # Log in with your Expo account + eas login + + # Configure your Expo app + cd apps/expo + eas build:configure + ``` + +3. After the initial setup, you can create your first build. You can build for Android and iOS platforms and use different [`eas.json` build profiles](https://docs.expo.dev/build-reference/eas-json) to create production builds or development, or test builds. Let's make a production build for iOS. + + ```bash + eas build --platform ios --profile production + ``` + + > If you don't specify the `--profile` flag, EAS uses the `production` profile by default. + +4. Now that you have your first production build, you can submit this to the stores. [EAS Submit](https://docs.expo.dev/submit/introduction) can help you send the build to the stores. + + ```bash + eas submit --platform ios --latest + ``` + + > You can also combine build and submit in a single command, using `eas build ... --auto-submit`. + +5. Before you can get your app in the hands of your users, you'll have to provide additional information to the app stores. This includes screenshots, app information, privacy policies, etc. _While still in preview_, [EAS Metadata](https://docs.expo.dev/eas/metadata) can help you with most of this information. + +6. Once everything is approved, your users can finally enjoy your app. Let's say you spotted a small typo; you'll have to create a new build, submit it to the stores, and wait for approval before you can resolve this issue. In these cases, you can use EAS Update to quickly send a small bugfix to your users without going through this long process. Let's start by setting up EAS Update. + + The steps below summarize the [Getting started with EAS Update](https://docs.expo.dev/eas-update/getting-started/#configure-your-project) guide. + + ```bash + # Add the `expo-updates` library to your Expo app + cd apps/expo + pnpm expo install expo-updates + + # Configure EAS Update + eas update:configure + ``` + +7. Before we can send out updates to your app, you have to create a new build and submit it to the app stores. For every change that includes native APIs, you have to rebuild the app and submit the update to the app stores. See steps 2 and 3. + +8. Now that everything is ready for updates, let's create a new update for `production` builds. With the `--auto` flag, EAS Update uses your current git branch name and commit message for this update. See [How EAS Update works](https://docs.expo.dev/eas-update/how-eas-update-works/#publishing-an-update) for more information. + + ```bash + cd apps/expo + eas update --auto + ``` + + > Your OTA (Over The Air) updates must always follow the app store's rules. You can't change your app's primary functionality without getting app store approval. But this is a fast way to update your app for minor changes and bug fixes. + +9. Done! Now that you have created your production build, submitted it to the stores, and installed EAS Update, you are ready for anything! + +## References + +The stack originates from [create-t3-app](https://github.com/t3-oss/create-t3-app). + +A [blog post](https://jumr.dev/blog/t3-turbo) where I wrote how to migrate a T3 app into this. diff --git a/apps/auth-proxy/.env.example b/apps/auth-proxy/.env.example new file mode 100644 index 0000000..bdb4d55 --- /dev/null +++ b/apps/auth-proxy/.env.example @@ -0,0 +1,7 @@ + +AUTH_SECRET="" +AUTH_DISCORD_ID="" +AUTH_DISCORD_SECRET="" +AUTH_REDIRECT_PROXY_URL="" + +NITRO_PRESET="vercel_edge" \ No newline at end of file diff --git a/apps/auth-proxy/README.md b/apps/auth-proxy/README.md new file mode 100644 index 0000000..2e02b7a --- /dev/null +++ b/apps/auth-proxy/README.md @@ -0,0 +1,26 @@ +# Auth Proxy + +This is a simple proxy server that enables OAuth authentication for preview environments and Expo apps. + +## Setup + +Deploy it somewhere (Vercel is a one-click, zero-config option) and set the following environment variables: + +- `AUTH_DISCORD_ID` - The Discord OAuth client ID +- `AUTH_DISCORD_SECRET` - The Discord OAuth client secret +- `AUTH_REDIRECT_PROXY_URL` - The URL of this proxy server (e.g. ) +- `AUTH_SECRET` - Your secret + +Make sure the `AUTH_SECRET` and `AUTH_REDIRECT_PROXY_URL` match the values set for the main application's deployment for preview environments, and that you're using the same OAuth credentials for the proxy and the application's preview environment. +`AUTH_REDIRECT_PROXY_URL` should only be set for the main application's preview environment. Do not set it for the production environment. +The lines below shows what values should match eachother in both deployments. + +> [!NOTE] +> +> For using the proxy for local development set the `AUTH_REDIRECT_PROXY_URL` in the `.env` file as well. + +![Environment variables setup](https://github.com/t3-oss/create-t3-turbo/assets/51714798/5fadd3f5-f705-459a-82ab-559a3df881d0) + +For providers that require an origin and a redirect URL, set them to `{AUTH_REDIRECT_PROXY_URL}` and `{AUTH_REDIRECT_PROXY_URL}/r/callback/{provider}` accordingly. + +![Google credentials setup](https://github.com/ahkhanjani/create-t3-turbo/assets/72540492/eaa88685-6fc2-4c23-b7ac-737eb172fa0e) diff --git a/apps/auth-proxy/eslint.config.js b/apps/auth-proxy/eslint.config.js new file mode 100644 index 0000000..f008170 --- /dev/null +++ b/apps/auth-proxy/eslint.config.js @@ -0,0 +1,9 @@ +import baseConfig from "@acme/eslint-config/base"; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: [".nitro/**", ".output/**"], + }, + ...baseConfig, +]; diff --git a/apps/auth-proxy/package.json b/apps/auth-proxy/package.json new file mode 100644 index 0000000..8d9f395 --- /dev/null +++ b/apps/auth-proxy/package.json @@ -0,0 +1,28 @@ +{ + "name": "@acme/auth-proxy", + "private": true, + "type": "module", + "scripts": { + "build": "nitro build", + "clean": "rm -rf .turbo node_modules", + "lint": "eslint", + "format": "prettier --check . --ignore-path ../../.gitignore", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@auth/core": "0.32.0" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tailwind-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "@types/node": "^20.12.9", + "eslint": "^9.4.0", + "h3": "^1.11.1", + "nitropack": "^2.9.6", + "prettier": "^3.3.1", + "typescript": "^5.4.5" + }, + "prettier": "@acme/prettier-config" +} diff --git a/apps/auth-proxy/routes/r/[...auth].ts b/apps/auth-proxy/routes/r/[...auth].ts new file mode 100644 index 0000000..39db9f6 --- /dev/null +++ b/apps/auth-proxy/routes/r/[...auth].ts @@ -0,0 +1,18 @@ +import { Auth } from "@auth/core"; +import Discord from "@auth/core/providers/discord"; +import { eventHandler, toWebRequest } from "h3"; + +export default eventHandler(async (event) => + Auth(toWebRequest(event), { + basePath: "/r", + secret: process.env.AUTH_SECRET, + trustHost: !!process.env.VERCEL, + redirectProxyUrl: process.env.AUTH_REDIRECT_PROXY_URL, + providers: [ + Discord({ + clientId: process.env.AUTH_DISCORD_ID, + clientSecret: process.env.AUTH_DISCORD_SECRET, + }), + ], + }), +); diff --git a/apps/auth-proxy/tsconfig.json b/apps/auth-proxy/tsconfig.json new file mode 100644 index 0000000..a2aaadc --- /dev/null +++ b/apps/auth-proxy/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "@acme/tsconfig/base.json", + "include": ["routes"] +} diff --git a/apps/expo/.expo-shared/assets.json b/apps/expo/.expo-shared/assets.json new file mode 100644 index 0000000..1e6decf --- /dev/null +++ b/apps/expo/.expo-shared/assets.json @@ -0,0 +1,4 @@ +{ + "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true, + "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true +} diff --git a/apps/expo/app.config.ts b/apps/expo/app.config.ts new file mode 100644 index 0000000..053fcb3 --- /dev/null +++ b/apps/expo/app.config.ts @@ -0,0 +1,42 @@ +import type { ConfigContext, ExpoConfig } from "expo/config"; + +export default ({ config }: ConfigContext): ExpoConfig => ({ + ...config, + name: "expo", + slug: "expo", + scheme: "expo", + version: "0.1.0", + orientation: "portrait", + icon: "./assets/icon.png", + userInterfaceStyle: "automatic", + splash: { + image: "./assets/icon.png", + resizeMode: "contain", + backgroundColor: "#1F104A", + }, + updates: { + fallbackToCacheTimeout: 0, + }, + assetBundlePatterns: ["**/*"], + ios: { + bundleIdentifier: "your.bundle.identifier", + supportsTablet: true, + }, + android: { + package: "your.bundle.identifier", + adaptiveIcon: { + foregroundImage: "./assets/icon.png", + backgroundColor: "#1F104A", + }, + }, + // extra: { + // eas: { + // projectId: "your-eas-project-id", + // }, + // }, + experiments: { + tsconfigPaths: true, + typedRoutes: true, + }, + plugins: ["expo-router"], +}); diff --git a/apps/expo/assets/icon.png b/apps/expo/assets/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..67917f52aec973e6248c22a58f4e36503c09a351 GIT binary patch literal 10788 zcmeHsc|6qZ`!7${gceJZY#}k$v5hTjWS2D!4KtW9BQs-=o$|C$@z^7&WNS$Fv6Ql8 z$(DU9vhNuQ;oPHVJ?Hm3=X_tUbN+k0Ui0yp`@XL0zOMIut=uvx%Y73E=&`Q35DGv?~pb-=LSd!_l__ zOg}a_)Wg-BKPhLul&{vh=X7}SU8(9s5h9)@r#k%}9w*>E?vU76#`9>twEQ zWXsw}o!urxKAGe^DyH%>-)k>$xwIPhYVWYKaE7PxyH1+T$GSaqL>uyqVc$TKd(2gq z&9djWC=8fEdyGcrt_?6P60M_SZm6U4hc&>4hd~ci4c?k_+}z88Xk;t*YrPZHAr#%Y zt=xN-!6oZh zK74O)bZ>eXNAuVomBM*}CIyq4Y-QOxX0%n&wE}nAU|Ly|`ta(< z*iHq*$ME{lP=kk8ZlaH254U>`GE4`JpOI)eyQ;DpX-I!m(+9r#JsS5O73QYj=INTQ zd_gjy(r(t-Mp0oLJ)V?1`Os*9YKqJ+KY!yso zOuTha?r4JmAJoMFQ!AGM4;K}rkfz2#H9r^-;Dy2?1pK@_F*ul?y3oE{7gg<0zA|1JW2Qx|f_LGyRZ&rqmXVW|lY;;X2+kjaNBBW7IAN-YpE7h&I2RwZHy(|}2vB7roUsJF zx{wgq7x+UzFK-i*KgDBkzoP)~koH4(OUp{hNPBrn|D6Me*YgEJepl$f0xb&H1|`fc;Oo|DgWE_I+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cq7+0Q73i%$4-d=jT zBgY2ay>sA_o%}LrC?yS*l$7#l3X;;_`R0O~u@3GDvzqa~*WI5^TC*Xh;5?m?)^Kd+ zwk2pN6J0SFF0I6*QkTHjM}2v&Qar8v3l_tFS;m7l7Nu+^Z$)f3avDiycpu@JTL{Jv z1M*gL5hEWW@!}`1llH=WqAz9%_Tft|gy&Xi6x1Vq-%I}Y7qy>KgVT`G@pZ`f2h=}9 zzZEVT2{%=YdEs))_f^&RRw#wqgXZJgKp%SmvIi}CATl_jT;zI6{@@8Xujrm-7W?46 zzRRYKy8ZF*zy;4^7Z41Ol?rvq)HnOGMGw4Jd2x4>F}GATXbYq6EImohMP2hu18uQ* z-n4YoLy8bM)}Ex&Fu=(X5KEo0iZZg2Pd(@3M|E|WjFD$O?Z1h@uNS;st(~pN8gVMl z2y1Zq0e|`+nc>a)#HGwv$5VXcmOB>8b_5I@mI7e*mvUh(3S|~`9v^;9R}SoN6yV9@ zGFFhcHX%y5l~Y2NPKb~Y+3w}v2&*iD&MF`_0-SRztZGBrM#xJyMOh_oF+3ZtJNn-? fsQ=rIGx2-ublKvTN6XlXsDy@krn)5UE8+hGU;oga literal 0 HcmV?d00001 diff --git a/apps/expo/babel.config.js b/apps/expo/babel.config.js new file mode 100644 index 0000000..95b1393 --- /dev/null +++ b/apps/expo/babel.config.js @@ -0,0 +1,11 @@ +/** @type {import("@babel/core").ConfigFunction} */ +module.exports = (api) => { + api.cache(true); + return { + presets: [ + ["babel-preset-expo", { jsxImportSource: "nativewind" }], + "nativewind/babel", + ], + plugins: ["react-native-reanimated/plugin"], + }; +}; diff --git a/apps/expo/eas.json b/apps/expo/eas.json new file mode 100644 index 0000000..607de32 --- /dev/null +++ b/apps/expo/eas.json @@ -0,0 +1,31 @@ +{ + "cli": { + "version": ">= 4.1.2" + }, + "build": { + "base": { + "node": "18.16.1", + "ios": { + "resourceClass": "m-medium" + } + }, + "development": { + "extends": "base", + "developmentClient": true, + "distribution": "internal" + }, + "preview": { + "extends": "base", + "distribution": "internal", + "ios": { + "simulator": true + } + }, + "production": { + "extends": "base" + } + }, + "submit": { + "production": {} + } +} diff --git a/apps/expo/eslint.config.mjs b/apps/expo/eslint.config.mjs new file mode 100644 index 0000000..e264359 --- /dev/null +++ b/apps/expo/eslint.config.mjs @@ -0,0 +1,11 @@ +import baseConfig from "@acme/eslint-config/base"; +import reactConfig from "@acme/eslint-config/react"; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: [".expo/**", "expo-plugins/**"], + }, + ...baseConfig, + ...reactConfig, +]; diff --git a/apps/expo/metro.config.js b/apps/expo/metro.config.js new file mode 100644 index 0000000..4944183 --- /dev/null +++ b/apps/expo/metro.config.js @@ -0,0 +1,55 @@ +// Learn more: https://docs.expo.dev/guides/monorepos/ +const { getDefaultConfig } = require("expo/metro-config"); +const { FileStore } = require("metro-cache"); +const { withNativeWind } = require("nativewind/metro"); + +const path = require("path"); + +module.exports = withTurborepoManagedCache( + withMonorepoPaths( + withNativeWind(getDefaultConfig(__dirname), { + input: "./src/styles.css", + configPath: "./tailwind.config.ts", + }), + ), +); + +/** + * Add the monorepo paths to the Metro config. + * This allows Metro to resolve modules from the monorepo. + * + * @see https://docs.expo.dev/guides/monorepos/#modify-the-metro-config + * @param {import('expo/metro-config').MetroConfig} config + * @returns {import('expo/metro-config').MetroConfig} + */ +function withMonorepoPaths(config) { + const projectRoot = __dirname; + const workspaceRoot = path.resolve(projectRoot, "../.."); + + // #1 - Watch all files in the monorepo + config.watchFolders = [workspaceRoot]; + + // #2 - Resolve modules within the project's `node_modules` first, then all monorepo modules + config.resolver.nodeModulesPaths = [ + path.resolve(projectRoot, "node_modules"), + path.resolve(workspaceRoot, "node_modules"), + ]; + + return config; +} + +/** + * Move the Metro cache to the `node_modules/.cache/metro` folder. + * This repository configured Turborepo to use this cache location as well. + * If you have any environment variables, you can configure Turborepo to invalidate it when needed. + * + * @see https://turbo.build/repo/docs/reference/configuration#env + * @param {import('expo/metro-config').MetroConfig} config + * @returns {import('expo/metro-config').MetroConfig} + */ +function withTurborepoManagedCache(config) { + config.cacheStores = [ + new FileStore({ root: path.join(__dirname, "node_modules/.cache/metro") }), + ]; + return config; +} diff --git a/apps/expo/package.json b/apps/expo/package.json new file mode 100644 index 0000000..534b6ab --- /dev/null +++ b/apps/expo/package.json @@ -0,0 +1,62 @@ +{ + "name": "@acme/expo", + "version": "0.1.0", + "private": true, + "main": "expo-router/entry", + "scripts": { + "clean": "git clean -xdf .expo .turbo node_modules", + "dev": "expo start", + "dev:android": "expo start --android", + "dev:ios": "expo start --ios", + "android": "expo run:android", + "ios": "expo run:ios", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@bacons/text-decoder": "^0.0.0", + "@expo/metro-config": "^0.18.3", + "@shopify/flash-list": "1.6.4", + "@tanstack/react-query": "^5.35.5", + "@trpc/client": "11.0.0-rc.364", + "@trpc/react-query": "11.0.0-rc.364", + "@trpc/server": "11.0.0-rc.364", + "expo": "~51.0.2", + "expo-constants": "~16.0.1", + "expo-dev-client": "~4.0.13", + "expo-linking": "~6.3.1", + "expo-router": "~3.5.11", + "expo-secure-store": "^13.0.1", + "expo-splash-screen": "~0.27.4", + "expo-status-bar": "~1.12.1", + "expo-web-browser": "^13.0.3", + "nativewind": "~4.0.36", + "react": "18.3.1", + "react-dom": "18.3.1", + "react-native": "~0.74.1", + "react-native-css-interop": "~0.0.34", + "react-native-gesture-handler": "~2.16.2", + "react-native-reanimated": "~3.10.1", + "react-native-safe-area-context": "~4.10.1", + "react-native-screens": "~3.31.1", + "superjson": "2.2.1" + }, + "devDependencies": { + "@acme/api": "workspace:*", + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tailwind-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "@babel/core": "^7.24.7", + "@babel/preset-env": "^7.24.7", + "@babel/runtime": "^7.24.7", + "@types/babel__core": "^7.20.5", + "@types/react": "^18.3.3", + "eslint": "^9.4.0", + "prettier": "^3.3.1", + "tailwindcss": "^3.4.3", + "typescript": "^5.4.5" + }, + "prettier": "@acme/prettier-config" +} diff --git a/apps/expo/src/app/_layout.tsx b/apps/expo/src/app/_layout.tsx new file mode 100644 index 0000000..0aa2746 --- /dev/null +++ b/apps/expo/src/app/_layout.tsx @@ -0,0 +1,34 @@ +import "@bacons/text-decoder/install"; + +import { Stack } from "expo-router"; +import { StatusBar } from "expo-status-bar"; +import { useColorScheme } from "nativewind"; + +import { TRPCProvider } from "~/utils/api"; + +import "../styles.css"; + +// This is the main layout of the app +// It wraps your pages with the providers they need +export default function RootLayout() { + const { colorScheme } = useColorScheme(); + return ( + + {/* + The Stack component displays the current page. + It also allows you to configure your screens + */} + + + + ); +} diff --git a/apps/expo/src/app/index.tsx b/apps/expo/src/app/index.tsx new file mode 100644 index 0000000..e9f1e24 --- /dev/null +++ b/apps/expo/src/app/index.tsx @@ -0,0 +1,159 @@ +import { useState } from "react"; +import { Button, Pressable, Text, TextInput, View } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { Link, Stack } from "expo-router"; +import { FlashList } from "@shopify/flash-list"; + +import type { RouterOutputs } from "~/utils/api"; +import { api } from "~/utils/api"; +import { useSignIn, useSignOut, useUser } from "~/utils/auth"; + +function PostCard(props: { + post: RouterOutputs["post"]["all"][number]; + onDelete: () => void; +}) { + return ( + + + + + + {props.post.title} + + {props.post.content} + + + + + Delete + + + ); +} + +function CreatePost() { + const utils = api.useUtils(); + + const [title, setTitle] = useState(""); + const [content, setContent] = useState(""); + + const { mutate, error } = api.post.create.useMutation({ + async onSuccess() { + setTitle(""); + setContent(""); + await utils.post.all.invalidate(); + }, + }); + + return ( + + + {error?.data?.zodError?.fieldErrors.title && ( + + {error.data.zodError.fieldErrors.title} + + )} + + {error?.data?.zodError?.fieldErrors.content && ( + + {error.data.zodError.fieldErrors.content} + + )} + { + mutate({ + title, + content, + }); + }} + > + Create + + {error?.data?.code === "UNAUTHORIZED" && ( + + You need to be logged in to create a post + + )} + + ); +} + +function MobileAuth() { + const user = useUser(); + const signIn = useSignIn(); + const signOut = useSignOut(); + + return ( + <> + + {user?.name ?? "Not logged in"} + + + + ); + } + + return ( +
+

+ Logged in as {session.user.name} +

+ +
+ +
+
+ ); +} diff --git a/apps/nextjs/src/app/_components/posts.tsx b/apps/nextjs/src/app/_components/posts.tsx new file mode 100644 index 0000000..71fb627 --- /dev/null +++ b/apps/nextjs/src/app/_components/posts.tsx @@ -0,0 +1,176 @@ +"use client"; + +import { use } from "react"; + +import type { RouterOutputs } from "@acme/api"; +import { CreatePostSchema } from "@acme/db/schema"; +import { cn } from "@acme/ui"; +import { Button } from "@acme/ui/button"; +import { + Form, + FormControl, + FormField, + FormItem, + FormMessage, + useForm, +} from "@acme/ui/form"; +import { Input } from "@acme/ui/input"; +import { toast } from "@acme/ui/toast"; + +import { api } from "~/trpc/react"; + +export function CreatePostForm() { + const form = useForm({ + schema: CreatePostSchema, + defaultValues: { + content: "", + title: "", + }, + }); + + const utils = api.useUtils(); + const createPost = api.post.create.useMutation({ + onSuccess: async () => { + form.reset(); + await utils.post.invalidate(); + }, + onError: (err) => { + toast.error( + err.data?.code === "UNAUTHORIZED" + ? "You must be logged in to post" + : "Failed to create post", + ); + }, + }); + + return ( +
+ { + createPost.mutate(data); + })} + > + ( + + + + + + + )} + /> + ( + + + + + + + )} + /> + + + + ); +} + +export function PostList(props: { + posts: Promise; +}) { + // TODO: Make `useSuspenseQuery` work without having to pass a promise from RSC + const initialData = use(props.posts); + const { data: posts } = api.post.all.useQuery(undefined, { + initialData, + }); + + if (posts.length === 0) { + return ( +
+ + + + +
+

No posts yet

+
+
+ ); + } + + return ( +
+ {posts.map((p) => { + return ; + })} +
+ ); +} + +export function PostCard(props: { + post: RouterOutputs["post"]["all"][number]; +}) { + const utils = api.useUtils(); + const deletePost = api.post.delete.useMutation({ + onSuccess: async () => { + await utils.post.invalidate(); + }, + onError: (err) => { + toast.error( + err.data?.code === "UNAUTHORIZED" + ? "You must be logged in to delete a post" + : "Failed to delete post", + ); + }, + }); + + return ( +
+
+

{props.post.title}

+

{props.post.content}

+
+
+ +
+
+ ); +} + +export function PostCardSkeleton(props: { pulse?: boolean }) { + const { pulse = true } = props; + return ( +
+
+

+   +

+

+   +

+
+
+ ); +} diff --git a/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts b/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts new file mode 100644 index 0000000..22ddf2c --- /dev/null +++ b/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts @@ -0,0 +1,81 @@ +import { cookies } from "next/headers"; +import { NextRequest, NextResponse } from "next/server"; + +import { handlers, isSecureContext } from "@acme/auth"; + +export const runtime = "edge"; + +const EXPO_COOKIE_NAME = "__acme-expo-redirect-state"; +const AUTH_COOKIE_PATTERN = /authjs\.session-token=([^;]+)/; + +/** + * Noop in production. + * + * In development, rewrite the request URL to use localhost instead of host IP address + * so that Expo Auth works without getting trapped by Next.js CSRF protection. + * @param req The request to modify + * @returns The modified request. + */ +function rewriteRequestUrlInDevelopment(req: NextRequest) { + if (isSecureContext) return req; + + const host = req.headers.get("host"); + const newURL = new URL(req.url); + newURL.host = host ?? req.nextUrl.host; + return new NextRequest(newURL, req); +} + +export const POST = async (_req: NextRequest) => { + // First step must be to correct the request URL. + const req = rewriteRequestUrlInDevelopment(_req); + return handlers.POST(req); +}; + +export const GET = async ( + _req: NextRequest, + props: { params: { nextauth: string[] } }, +) => { + // First step must be to correct the request URL. + const req = rewriteRequestUrlInDevelopment(_req); + + const nextauthAction = props.params.nextauth[0]; + const isExpoSignIn = req.nextUrl.searchParams.get("expo-redirect"); + const isExpoCallback = cookies().get(EXPO_COOKIE_NAME); + + if (nextauthAction === "signin" && !!isExpoSignIn) { + // set a cookie we can read in the callback + // to know to send the user back to expo + cookies().set({ + name: EXPO_COOKIE_NAME, + value: isExpoSignIn, + maxAge: 60 * 10, // 10 min + path: "/", + }); + } + + if (nextauthAction === "callback" && !!isExpoCallback) { + cookies().delete(EXPO_COOKIE_NAME); + + // Run original handler, then extract the session token from the response + // Send it back via a query param in the Expo deep link. The Expo app + // will then get that and set it in the session storage. + const authResponse = await handlers.GET(req); + const setCookie = authResponse.headers + .getSetCookie() + .find((cookie) => AUTH_COOKIE_PATTERN.test(cookie)); + const match = setCookie?.match(AUTH_COOKIE_PATTERN)?.[1]; + + if (!match) + throw new Error( + "Unable to find session cookie: " + + JSON.stringify(authResponse.headers.getSetCookie()), + ); + + const url = new URL(isExpoCallback.value); + url.searchParams.set("session_token", match); + return NextResponse.redirect(url); + } + + // Every other request just calls the default handler + return handlers.GET(req); +}; diff --git a/apps/nextjs/src/app/api/trpc/[trpc]/route.ts b/apps/nextjs/src/app/api/trpc/[trpc]/route.ts new file mode 100644 index 0000000..4a0ef6c --- /dev/null +++ b/apps/nextjs/src/app/api/trpc/[trpc]/route.ts @@ -0,0 +1,46 @@ +import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; + +import { appRouter, createTRPCContext } from "@acme/api"; +import { auth } from "@acme/auth"; + +export const runtime = "edge"; + +/** + * Configure basic CORS headers + * You should extend this to match your needs + */ +const setCorsHeaders = (res: Response) => { + res.headers.set("Access-Control-Allow-Origin", "*"); + res.headers.set("Access-Control-Request-Method", "*"); + res.headers.set("Access-Control-Allow-Methods", "OPTIONS, GET, POST"); + res.headers.set("Access-Control-Allow-Headers", "*"); +}; + +export const OPTIONS = () => { + const response = new Response(null, { + status: 204, + }); + setCorsHeaders(response); + return response; +}; + +const handler = auth(async (req) => { + const response = await fetchRequestHandler({ + endpoint: "/api/trpc", + router: appRouter, + req, + createContext: () => + createTRPCContext({ + session: req.auth, + headers: req.headers, + }), + onError({ error, path }) { + console.error(`>>> tRPC Error on '${path}'`, error); + }, + }); + + setCorsHeaders(response); + return response; +}); + +export { handler as GET, handler as POST }; diff --git a/apps/nextjs/src/app/globals.css b/apps/nextjs/src/app/globals.css new file mode 100644 index 0000000..b9d992f --- /dev/null +++ b/apps/nextjs/src/app/globals.css @@ -0,0 +1,50 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 240 10% 3.9%; + --card: 0 0% 100%; + --card-foreground: 240 10% 3.9%; + --popover: 0 0% 100%; + --popover-foreground: 240 10% 3.9%; + --primary: 327 66% 69%; + --primary-foreground: 337 65.5% 17.1%; + --secondary: 240 4.8% 95.9%; + --secondary-foreground: 240 5.9% 10%; + --muted: 240 4.8% 95.9%; + --muted-foreground: 240 3.8% 46.1%; + --accent: 240 4.8% 95.9%; + --accent-foreground: 240 5.9% 10%; + --destructive: 0 72.22% 50.59%; + --destructive-foreground: 0 0% 98%; + --border: 240 5.9% 90%; + --input: 240 5.9% 90%; + --ring: 240 5% 64.9%; + --radius: 0.5rem; + } + + .dark { + --background: 240 10% 3.9%; + --foreground: 0 0% 98%; + --card: 240 10% 3.9%; + --card-foreground: 0 0% 98%; + --popover: 240 10% 3.9%; + --popover-foreground: 0 0% 98%; + --primary: 327 66% 69%; + --primary-foreground: 337 65.5% 17.1%; + --secondary: 240 3.7% 15.9%; + --secondary-foreground: 0 0% 98%; + --muted: 240 3.7% 15.9%; + --muted-foreground: 240 5% 64.9%; + --accent: 240 3.7% 15.9%; + --accent-foreground: 0 0% 98%; + --destructive: 0 62.8% 30.6%; + --destructive-foreground: 0 85.7% 97.3%; + --border: 240 3.7% 15.9%; + --input: 240 3.7% 15.9%; + --ring: 240 4.9% 83.9%; + } +} diff --git a/apps/nextjs/src/app/layout.tsx b/apps/nextjs/src/app/layout.tsx new file mode 100644 index 0000000..a7e6253 --- /dev/null +++ b/apps/nextjs/src/app/layout.tsx @@ -0,0 +1,63 @@ +import type { Metadata, Viewport } from "next"; +import { GeistMono } from "geist/font/mono"; +import { GeistSans } from "geist/font/sans"; + +import { cn } from "@acme/ui"; +import { ThemeProvider, ThemeToggle } from "@acme/ui/theme"; +import { Toaster } from "@acme/ui/toast"; + +import { TRPCReactProvider } from "~/trpc/react"; + +import "~/app/globals.css"; + +import { env } from "~/env"; + +export const metadata: Metadata = { + metadataBase: new URL( + env.VERCEL_ENV === "production" + ? "https://turbo.t3.gg" + : "http://localhost:3000", + ), + title: "Create T3 Turbo", + description: "Simple monorepo with shared backend for web & mobile apps", + openGraph: { + title: "Create T3 Turbo", + description: "Simple monorepo with shared backend for web & mobile apps", + url: "https://create-t3-turbo.vercel.app", + siteName: "Create T3 Turbo", + }, + twitter: { + card: "summary_large_image", + site: "@jullerino", + creator: "@jullerino", + }, +}; + +export const viewport: Viewport = { + themeColor: [ + { media: "(prefers-color-scheme: light)", color: "white" }, + { media: "(prefers-color-scheme: dark)", color: "black" }, + ], +}; + +export default function RootLayout(props: { children: React.ReactNode }) { + return ( + + + + {props.children} +
+ +
+ +
+ + + ); +} diff --git a/apps/nextjs/src/app/page.tsx b/apps/nextjs/src/app/page.tsx new file mode 100644 index 0000000..5c61c1a --- /dev/null +++ b/apps/nextjs/src/app/page.tsx @@ -0,0 +1,42 @@ +import { Suspense } from "react"; + +import { api } from "~/trpc/server"; +import { AuthShowcase } from "./_components/auth-showcase"; +import { + CreatePostForm, + PostCardSkeleton, + PostList, +} from "./_components/posts"; + +export const runtime = "edge"; + +export default function HomePage() { + // You can await this here if you don't want to show Suspense fallback below + const posts = api.post.all(); + + return ( +
+
+

+ Create T3 Turbo +

+ + + +
+ + + + +
+ } + > + + +
+ +
+ ); +} diff --git a/apps/nextjs/src/env.ts b/apps/nextjs/src/env.ts new file mode 100644 index 0000000..ba55d46 --- /dev/null +++ b/apps/nextjs/src/env.ts @@ -0,0 +1,40 @@ +/* eslint-disable no-restricted-properties */ +import { createEnv } from "@t3-oss/env-nextjs"; +import { vercel } from "@t3-oss/env-nextjs/presets"; +import { z } from "zod"; + +import { env as authEnv } from "@acme/auth/env"; + +export const env = createEnv({ + extends: [authEnv, vercel()], + shared: { + NODE_ENV: z + .enum(["development", "production", "test"]) + .default("development"), + }, + /** + * Specify your server-side environment variables schema here. + * This way you can ensure the app isn't built with invalid env vars. + */ + server: { + POSTGRES_URL: z.string().url(), + }, + + /** + * Specify your client-side environment variables schema here. + * For them to be exposed to the client, prefix them with `NEXT_PUBLIC_`. + */ + client: { + // NEXT_PUBLIC_CLIENTVAR: z.string(), + }, + /** + * Destructure all variables from `process.env` to make sure they aren't tree-shaken away. + */ + experimental__runtimeEnv: { + NODE_ENV: process.env.NODE_ENV, + + // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, + }, + skipValidation: + !!process.env.CI || process.env.npm_lifecycle_event === "lint", +}); diff --git a/apps/nextjs/src/middleware.ts b/apps/nextjs/src/middleware.ts new file mode 100644 index 0000000..a2c8032 --- /dev/null +++ b/apps/nextjs/src/middleware.ts @@ -0,0 +1,11 @@ +export { auth as middleware } from "@acme/auth"; + +// Or like this if you need to do something here. +// export default auth((req) => { +// console.log(req.auth) // { session: { user: { ... } } } +// }) + +// Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher +export const config = { + matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], +}; diff --git a/apps/nextjs/src/trpc/react.tsx b/apps/nextjs/src/trpc/react.tsx new file mode 100644 index 0000000..c4df827 --- /dev/null +++ b/apps/nextjs/src/trpc/react.tsx @@ -0,0 +1,75 @@ +"use client"; + +import { useState } from "react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { loggerLink, unstable_httpBatchStreamLink } from "@trpc/client"; +import { createTRPCReact } from "@trpc/react-query"; +import SuperJSON from "superjson"; + +import type { AppRouter } from "@acme/api"; + +import { env } from "~/env"; + +const createQueryClient = () => + new QueryClient({ + defaultOptions: { + queries: { + // With SSR, we usually want to set some default staleTime + // above 0 to avoid refetching immediately on the client + staleTime: 30 * 1000, + }, + }, + }); + +let clientQueryClientSingleton: QueryClient | undefined = undefined; +const getQueryClient = () => { + if (typeof window === "undefined") { + // Server: always make a new query client + return createQueryClient(); + } else { + // Browser: use singleton pattern to keep the same query client + return (clientQueryClientSingleton ??= createQueryClient()); + } +}; + +export const api = createTRPCReact(); + +export function TRPCReactProvider(props: { children: React.ReactNode }) { + const queryClient = getQueryClient(); + + const [trpcClient] = useState(() => + api.createClient({ + links: [ + loggerLink({ + enabled: (op) => + env.NODE_ENV === "development" || + (op.direction === "down" && op.result instanceof Error), + }), + unstable_httpBatchStreamLink({ + transformer: SuperJSON, + url: getBaseUrl() + "/api/trpc", + headers() { + const headers = new Headers(); + headers.set("x-trpc-source", "nextjs-react"); + return headers; + }, + }), + ], + }), + ); + + return ( + + + {props.children} + + + ); +} + +const getBaseUrl = () => { + if (typeof window !== "undefined") return window.location.origin; + if (env.VERCEL_URL) return `https://${env.VERCEL_URL}`; + // eslint-disable-next-line no-restricted-properties + return `http://localhost:${process.env.PORT ?? 3000}`; +}; diff --git a/apps/nextjs/src/trpc/server.ts b/apps/nextjs/src/trpc/server.ts new file mode 100644 index 0000000..7ce8d34 --- /dev/null +++ b/apps/nextjs/src/trpc/server.ts @@ -0,0 +1,21 @@ +import { cache } from "react"; +import { headers } from "next/headers"; + +import { createCaller, createTRPCContext } from "@acme/api"; +import { auth } from "@acme/auth"; + +/** + * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when + * handling a tRPC call from a React Server Component. + */ +const createContext = cache(async () => { + const heads = new Headers(headers()); + heads.set("x-trpc-source", "rsc"); + + return createTRPCContext({ + session: await auth(), + headers: heads, + }); +}); + +export const api = createCaller(createContext); diff --git a/apps/nextjs/tailwind.config.ts b/apps/nextjs/tailwind.config.ts new file mode 100644 index 0000000..4d5d815 --- /dev/null +++ b/apps/nextjs/tailwind.config.ts @@ -0,0 +1,19 @@ +import type { Config } from "tailwindcss"; +import { fontFamily } from "tailwindcss/defaultTheme"; + +import baseConfig from "@acme/tailwind-config/web"; + +export default { + // We need to append the path to the UI package to the content array so that + // those classes are included correctly. + content: [...baseConfig.content, "../../packages/ui/**/*.{ts,tsx}"], + presets: [baseConfig], + theme: { + extend: { + fontFamily: { + sans: ["var(--font-geist-sans)", ...fontFamily.sans], + mono: ["var(--font-geist-mono)", ...fontFamily.mono], + }, + }, + }, +} satisfies Config; diff --git a/apps/nextjs/tsconfig.json b/apps/nextjs/tsconfig.json new file mode 100644 index 0000000..646a682 --- /dev/null +++ b/apps/nextjs/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "@acme/tsconfig/base.json", + "compilerOptions": { + "lib": ["es2022", "dom", "dom.iterable"], + "jsx": "preserve", + "baseUrl": ".", + "paths": { + "~/*": ["./src/*"] + }, + "plugins": [{ "name": "next" }], + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json", + "module": "esnext" + }, + "include": [".", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..df5e5e3 --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "create-t3-turbo", + "private": true, + "engines": { + "node": ">=20.12.0" + }, + "packageManager": "pnpm@9.2.0", + "scripts": { + "build": "turbo run build", + "clean": "git clean -xdf node_modules", + "clean:workspaces": "turbo run clean", + "db:push": "turbo -F @acme/db push", + "db:studio": "turbo -F @acme/db studio", + "dev": "turbo watch dev", + "dev:next": "turbo watch dev -F @acme/nextjs...", + "format": "turbo run format --continue -- --cache --cache-location node_modules/.cache/.prettiercache", + "format:fix": "turbo run format --continue -- --write --cache --cache-location node_modules/.cache/.prettiercache", + "lint": "turbo run lint --continue -- --cache --cache-location node_modules/.cache/.eslintcache", + "lint:fix": "turbo run lint --continue -- --fix --cache --cache-location node_modules/.cache/.eslintcache", + "lint:ws": "pnpm dlx sherif@latest", + "postinstall": "pnpm lint:ws", + "typecheck": "turbo run typecheck", + "ui-add": "turbo run ui-add" + }, + "devDependencies": { + "@acme/prettier-config": "workspace:*", + "@turbo/gen": "^2.0.3", + "prettier": "^3.3.1", + "turbo": "^2.0.3", + "typescript": "^5.4.5" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/api/eslint.config.js b/packages/api/eslint.config.js new file mode 100644 index 0000000..b87792c --- /dev/null +++ b/packages/api/eslint.config.js @@ -0,0 +1,9 @@ +import baseConfig from "@acme/eslint-config/base"; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: ["dist/**"], + }, + ...baseConfig, +]; diff --git a/packages/api/package.json b/packages/api/package.json new file mode 100644 index 0000000..9334891 --- /dev/null +++ b/packages/api/package.json @@ -0,0 +1,38 @@ +{ + "name": "@acme/api", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./src/index.ts" + } + }, + "license": "MIT", + "scripts": { + "build": "tsc", + "dev": "tsc --watch", + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint", + "typecheck": "tsc --noEmit --emitDeclarationOnly false" + }, + "dependencies": { + "@acme/auth": "workspace:*", + "@acme/db": "workspace:*", + "@acme/validators": "workspace:*", + "@trpc/server": "11.0.0-rc.364", + "superjson": "2.2.1", + "zod": "^3.23.8" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "eslint": "^9.4.0", + "prettier": "^3.3.1", + "typescript": "^5.4.5" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts new file mode 100644 index 0000000..1cbe6fd --- /dev/null +++ b/packages/api/src/index.ts @@ -0,0 +1,33 @@ +import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server"; + +import type { AppRouter } from "./root"; +import { appRouter } from "./root"; +import { createCallerFactory, createTRPCContext } from "./trpc"; + +/** + * Create a server-side caller for the tRPC API + * @example + * const trpc = createCaller(createContext); + * const res = await trpc.post.all(); + * ^? Post[] + */ +const createCaller = createCallerFactory(appRouter); + +/** + * Inference helpers for input types + * @example + * type PostByIdInput = RouterInputs['post']['byId'] + * ^? { id: number } + **/ +type RouterInputs = inferRouterInputs; + +/** + * Inference helpers for output types + * @example + * type AllPostsOutput = RouterOutputs['post']['all'] + * ^? Post[] + **/ +type RouterOutputs = inferRouterOutputs; + +export { createTRPCContext, appRouter, createCaller }; +export type { AppRouter, RouterInputs, RouterOutputs }; diff --git a/packages/api/src/root.ts b/packages/api/src/root.ts new file mode 100644 index 0000000..730251c --- /dev/null +++ b/packages/api/src/root.ts @@ -0,0 +1,11 @@ +import { authRouter } from "./router/auth"; +import { postRouter } from "./router/post"; +import { createTRPCRouter } from "./trpc"; + +export const appRouter = createTRPCRouter({ + auth: authRouter, + post: postRouter, +}); + +// export type definition of API +export type AppRouter = typeof appRouter; diff --git a/packages/api/src/router/auth.ts b/packages/api/src/router/auth.ts new file mode 100644 index 0000000..ad53a60 --- /dev/null +++ b/packages/api/src/router/auth.ts @@ -0,0 +1,21 @@ +import type { TRPCRouterRecord } from "@trpc/server"; + +import { invalidateSessionToken } from "@acme/auth"; + +import { protectedProcedure, publicProcedure } from "../trpc"; + +export const authRouter = { + getSession: publicProcedure.query(({ ctx }) => { + return ctx.session; + }), + getSecretMessage: protectedProcedure.query(() => { + return "you can see this secret message!"; + }), + signOut: protectedProcedure.mutation(async (opts) => { + if (!opts.ctx.token) { + return { success: false }; + } + await invalidateSessionToken(opts.ctx.token); + return { success: true }; + }), +} satisfies TRPCRouterRecord; diff --git a/packages/api/src/router/post.ts b/packages/api/src/router/post.ts new file mode 100644 index 0000000..9ab103e --- /dev/null +++ b/packages/api/src/router/post.ts @@ -0,0 +1,40 @@ +import type { TRPCRouterRecord } from "@trpc/server"; +import { z } from "zod"; + +import { desc, eq } from "@acme/db"; +import { CreatePostSchema, Post } from "@acme/db/schema"; + +import { protectedProcedure, publicProcedure } from "../trpc"; + +export const postRouter = { + all: publicProcedure.query(({ ctx }) => { + // return ctx.db.select().from(schema.post).orderBy(desc(schema.post.id)); + return ctx.db.query.Post.findMany({ + orderBy: desc(Post.id), + limit: 10, + }); + }), + + byId: publicProcedure + .input(z.object({ id: z.string() })) + .query(({ ctx, input }) => { + // return ctx.db + // .select() + // .from(schema.post) + // .where(eq(schema.post.id, input.id)); + + return ctx.db.query.Post.findFirst({ + where: eq(Post.id, input.id), + }); + }), + + create: protectedProcedure + .input(CreatePostSchema) + .mutation(({ ctx, input }) => { + return ctx.db.insert(Post).values(input); + }), + + delete: protectedProcedure.input(z.string()).mutation(({ ctx, input }) => { + return ctx.db.delete(Post).where(eq(Post.id, input)); + }), +} satisfies TRPCRouterRecord; diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.ts new file mode 100644 index 0000000..9d85d44 --- /dev/null +++ b/packages/api/src/trpc.ts @@ -0,0 +1,120 @@ +/** + * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: + * 1. You want to modify request context (see Part 1) + * 2. You want to create a new middleware or type of procedure (see Part 3) + * + * tl;dr - this is where all the tRPC server stuff is created and plugged in. + * The pieces you will need to use are documented accordingly near the end + */ +import { initTRPC, TRPCError } from "@trpc/server"; +import superjson from "superjson"; +import { ZodError } from "zod"; + +import type { Session } from "@acme/auth"; +import { auth, validateToken } from "@acme/auth"; +import { db } from "@acme/db/client"; + +/** + * Isomorphic Session getter for API requests + * - Expo requests will have a session token in the Authorization header + * - Next.js requests will have a session token in cookies + */ +const isomorphicGetSession = async (headers: Headers) => { + const authToken = headers.get("Authorization") ?? null; + if (authToken) return validateToken(authToken); + return auth(); +}; + +/** + * 1. CONTEXT + * + * This section defines the "contexts" that are available in the backend API. + * + * These allow you to access things when processing a request, like the database, the session, etc. + * + * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each + * wrap this and provides the required context. + * + * @see https://trpc.io/docs/server/context + */ +export const createTRPCContext = async (opts: { + headers: Headers; + session: Session | null; +}) => { + const authToken = opts.headers.get("Authorization") ?? null; + const session = await isomorphicGetSession(opts.headers); + + const source = opts.headers.get("x-trpc-source") ?? "unknown"; + console.log(">>> tRPC Request from", source, "by", session?.user); + + return { + session, + db, + token: authToken, + }; +}; + +/** + * 2. INITIALIZATION + * + * This is where the trpc api is initialized, connecting the context and + * transformer + */ +const t = initTRPC.context().create({ + transformer: superjson, + errorFormatter: ({ shape, error }) => ({ + ...shape, + data: { + ...shape.data, + zodError: error.cause instanceof ZodError ? error.cause.flatten() : null, + }, + }), +}); + +/** + * Create a server-side caller + * @see https://trpc.io/docs/server/server-side-calls + */ +export const createCallerFactory = t.createCallerFactory; + +/** + * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) + * + * These are the pieces you use to build your tRPC API. You should import these + * a lot in the /src/server/api/routers folder + */ + +/** + * This is how you create new routers and subrouters in your tRPC API + * @see https://trpc.io/docs/router + */ +export const createTRPCRouter = t.router; + +/** + * Public (unauthed) procedure + * + * This is the base piece you use to build new queries and mutations on your + * tRPC API. It does not guarantee that a user querying is authorized, but you + * can still access user session data if they are logged in + */ +export const publicProcedure = t.procedure; + +/** + * Protected (authenticated) procedure + * + * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies + * the session is valid and guarantees `ctx.session.user` is not null. + * + * @see https://trpc.io/docs/procedures + */ +export const protectedProcedure = t.procedure.use(({ ctx, next }) => { + if (!ctx.session?.user) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + return next({ + ctx: { + // infers the `session` as non-nullable + session: { ...ctx.session, user: ctx.session.user }, + }, + }); +}); diff --git a/packages/api/tsconfig.json b/packages/api/tsconfig.json new file mode 100644 index 0000000..ed40c5d --- /dev/null +++ b/packages/api/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@acme/tsconfig/internal-package.json", + "compilerOptions": { + "outDir": "dist", + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": ["src"], + "exclude": ["node_modules"] +} diff --git a/packages/auth/env.ts b/packages/auth/env.ts new file mode 100644 index 0000000..bbd2209 --- /dev/null +++ b/packages/auth/env.ts @@ -0,0 +1,19 @@ +/* eslint-disable no-restricted-properties */ +import { createEnv } from "@t3-oss/env-nextjs"; +import { z } from "zod"; + +export const env = createEnv({ + server: { + AUTH_DISCORD_ID: z.string().min(1), + AUTH_DISCORD_SECRET: z.string().min(1), + AUTH_SECRET: + process.env.NODE_ENV === "production" + ? z.string().min(1) + : z.string().min(1).optional(), + NODE_ENV: z.enum(["development", "production"]).optional(), + }, + client: {}, + experimental__runtimeEnv: {}, + skipValidation: + !!process.env.CI || process.env.npm_lifecycle_event === "lint", +}); diff --git a/packages/auth/eslint.config.js b/packages/auth/eslint.config.js new file mode 100644 index 0000000..61cafcb --- /dev/null +++ b/packages/auth/eslint.config.js @@ -0,0 +1,10 @@ +import baseConfig, { restrictEnvAccess } from "@acme/eslint-config/base"; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: [], + }, + ...baseConfig, + ...restrictEnvAccess, +]; diff --git a/packages/auth/package.json b/packages/auth/package.json new file mode 100644 index 0000000..2b8a906 --- /dev/null +++ b/packages/auth/package.json @@ -0,0 +1,40 @@ +{ + "name": "@acme/auth", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": { + "react-server": "./src/index.rsc.ts", + "default": "./src/index.ts" + }, + "./env": "./env.ts" + }, + "license": "MIT", + "scripts": { + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@acme/db": "workspace:*", + "@auth/core": "0.32.0", + "@auth/drizzle-adapter": "^1.2.0", + "@t3-oss/env-nextjs": "^0.10.1", + "next": "^14.2.3", + "next-auth": "5.0.0-beta.19", + "react": "18.3.1", + "react-dom": "18.3.1", + "zod": "^3.23.8" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "eslint": "^9.4.0", + "prettier": "^3.3.1", + "typescript": "^5.4.5" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.ts new file mode 100644 index 0000000..e2ddda3 --- /dev/null +++ b/packages/auth/src/config.ts @@ -0,0 +1,75 @@ +import type { + DefaultSession, + NextAuthConfig, + Session as NextAuthSession, +} from "next-auth"; +import { skipCSRFCheck } from "@auth/core"; +import { DrizzleAdapter } from "@auth/drizzle-adapter"; +import Discord from "next-auth/providers/discord"; + +import { db } from "@acme/db/client"; +import { Account, Session, User } from "@acme/db/schema"; + +import { env } from "../env"; + +declare module "next-auth" { + interface Session { + user: { + id: string; + } & DefaultSession["user"]; + } +} + +const adapter = DrizzleAdapter(db, { + usersTable: User, + accountsTable: Account, + sessionsTable: Session, +}); + +export const isSecureContext = env.NODE_ENV !== "development"; + +export const authConfig = { + adapter, + // In development, we need to skip checks to allow Expo to work + ...(!isSecureContext + ? { + skipCSRFCheck: skipCSRFCheck, + trustHost: true, + } + : {}), + secret: env.AUTH_SECRET, + providers: [Discord], + callbacks: { + session: (opts) => { + if (!("user" in opts)) + throw new Error("unreachable with session strategy"); + + return { + ...opts.session, + user: { + ...opts.session.user, + id: opts.user.id, + }, + }; + }, + }, +} satisfies NextAuthConfig; + +export const validateToken = async ( + token: string, +): Promise => { + const sessionToken = token.slice("Bearer ".length); + const session = await adapter.getSessionAndUser?.(sessionToken); + return session + ? { + user: { + ...session.user, + }, + expires: session.session.expires.toISOString(), + } + : null; +}; + +export const invalidateSessionToken = async (token: string) => { + await adapter.deleteSession?.(token); +}; diff --git a/packages/auth/src/index.rsc.ts b/packages/auth/src/index.rsc.ts new file mode 100644 index 0000000..0373b25 --- /dev/null +++ b/packages/auth/src/index.rsc.ts @@ -0,0 +1,22 @@ +import { cache } from "react"; +import NextAuth from "next-auth"; + +import { authConfig } from "./config"; + +export type { Session } from "next-auth"; + +const { handlers, auth: defaultAuth, signIn, signOut } = NextAuth(authConfig); + +/** + * This is the main way to get session data for your RSCs. + * This will de-duplicate all calls to next-auth's default `auth()` function and only call it once per request + */ +const auth = cache(defaultAuth); + +export { handlers, auth, signIn, signOut }; + +export { + invalidateSessionToken, + validateToken, + isSecureContext, +} from "./config"; diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts new file mode 100644 index 0000000..f9f39f6 --- /dev/null +++ b/packages/auth/src/index.ts @@ -0,0 +1,15 @@ +import NextAuth from "next-auth"; + +import { authConfig } from "./config"; + +export type { Session } from "next-auth"; + +const { handlers, auth, signIn, signOut } = NextAuth(authConfig); + +export { handlers, auth, signIn, signOut }; + +export { + invalidateSessionToken, + validateToken, + isSecureContext, +} from "./config"; diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.json new file mode 100644 index 0000000..8bbf4dc --- /dev/null +++ b/packages/auth/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@acme/tsconfig/base.json", + "compilerOptions": { + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": ["src", "*.ts"], + "exclude": ["node_modules"] +} diff --git a/packages/db/drizzle.config.ts b/packages/db/drizzle.config.ts new file mode 100644 index 0000000..27cb8e5 --- /dev/null +++ b/packages/db/drizzle.config.ts @@ -0,0 +1,13 @@ +import type { Config } from "drizzle-kit"; + +if (!process.env.POSTGRES_URL) { + throw new Error("Missing POSTGRES_URL"); +} + +const nonPoolingUrl = process.env.POSTGRES_URL.replace(":6543", ":5432"); + +export default { + schema: "./src/schema.ts", + dialect: "postgresql", + dbCredentials: { url: nonPoolingUrl }, +} satisfies Config; diff --git a/packages/db/eslint.config.js b/packages/db/eslint.config.js new file mode 100644 index 0000000..4fa9384 --- /dev/null +++ b/packages/db/eslint.config.js @@ -0,0 +1,10 @@ +import baseConfig, { restrictEnvAccess } from "@acme/eslint-config/base"; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: ["dist/**"], + }, + ...baseConfig, + ...restrictEnvAccess, +]; diff --git a/packages/db/package.json b/packages/db/package.json new file mode 100644 index 0000000..ab9a4be --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,50 @@ +{ + "name": "@acme/db", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./src/index.ts" + }, + "./client": { + "types": "./dist/client.d.ts", + "default": "./src/client.ts" + }, + "./schema": { + "types": "./dist/schema.d.ts", + "default": "./src/schema.ts" + } + }, + "license": "MIT", + "scripts": { + "build": "tsc", + "dev": "tsc --watch", + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint", + "push": "pnpm with-env drizzle-kit push", + "studio": "pnpm with-env drizzle-kit studio", + "typecheck": "tsc --noEmit --emitDeclarationOnly false", + "with-env": "dotenv -e ../../.env --" + }, + "dependencies": { + "@vercel/postgres": "^0.8.0", + "@t3-oss/env-core": "^0.10.1", + "drizzle-orm": "^0.31.2", + "drizzle-zod": "^0.5.1", + "zod": "^3.23.8" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "dotenv-cli": "^7.4.2", + "drizzle-kit": "^0.22.6", + "eslint": "^9.4.0", + "prettier": "^3.3.1", + "typescript": "^5.4.5" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts new file mode 100644 index 0000000..671359a --- /dev/null +++ b/packages/db/src/client.ts @@ -0,0 +1,6 @@ +import { sql } from "@vercel/postgres"; +import { drizzle } from "drizzle-orm/vercel-postgres"; + +import * as schema from "./schema"; + +export const db = drizzle(sql, { schema }); diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..f0585be --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,2 @@ +export * from "drizzle-orm/sql"; +export { alias } from "drizzle-orm/pg-core"; diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts new file mode 100644 index 0000000..6bb2730 --- /dev/null +++ b/packages/db/src/schema.ts @@ -0,0 +1,92 @@ +import { relations, sql } from "drizzle-orm"; +import { + integer, + pgTable, + primaryKey, + text, + timestamp, + uuid, + varchar, +} from "drizzle-orm/pg-core"; +import { createInsertSchema } from "drizzle-zod"; +import { z } from "zod"; + +export const Post = pgTable("post", { + id: uuid("id").notNull().primaryKey().defaultRandom(), + title: varchar("name", { length: 256 }).notNull(), + content: text("content").notNull(), + createdAt: timestamp("created_at").defaultNow().notNull(), + updatedAt: timestamp("updatedAt", { + mode: "date", + withTimezone: true, + }).$onUpdateFn(() => sql`now()`), +}); + +export const CreatePostSchema = createInsertSchema(Post, { + title: z.string().max(256), + content: z.string().max(256), +}).omit({ + id: true, + createdAt: true, + updatedAt: true, +}); + +export const User = pgTable("user", { + id: uuid("id").notNull().primaryKey().defaultRandom(), + name: varchar("name", { length: 255 }), + email: varchar("email", { length: 255 }).notNull(), + emailVerified: timestamp("emailVerified", { + mode: "date", + withTimezone: true, + }), + image: varchar("image", { length: 255 }), +}); + +export const UserRelations = relations(User, ({ many }) => ({ + accounts: many(Account), +})); + +export const Account = pgTable( + "account", + { + userId: uuid("userId") + .notNull() + .references(() => User.id, { onDelete: "cascade" }), + type: varchar("type", { length: 255 }) + .$type<"email" | "oauth" | "oidc" | "webauthn">() + .notNull(), + provider: varchar("provider", { length: 255 }).notNull(), + providerAccountId: varchar("providerAccountId", { length: 255 }).notNull(), + refresh_token: varchar("refresh_token", { length: 255 }), + access_token: text("access_token"), + expires_at: integer("expires_at"), + token_type: varchar("token_type", { length: 255 }), + scope: varchar("scope", { length: 255 }), + id_token: text("id_token"), + session_state: varchar("session_state", { length: 255 }), + }, + (account) => ({ + compoundKey: primaryKey({ + columns: [account.provider, account.providerAccountId], + }), + }), +); + +export const AccountRelations = relations(Account, ({ one }) => ({ + user: one(User, { fields: [Account.userId], references: [User.id] }), +})); + +export const Session = pgTable("session", { + sessionToken: varchar("sessionToken", { length: 255 }).notNull().primaryKey(), + userId: uuid("userId") + .notNull() + .references(() => User.id, { onDelete: "cascade" }), + expires: timestamp("expires", { + mode: "date", + withTimezone: true, + }).notNull(), +}); + +export const SessionRelations = relations(Session, ({ one }) => ({ + user: one(User, { fields: [Session.userId], references: [User.id] }), +})); diff --git a/packages/db/tsconfig.json b/packages/db/tsconfig.json new file mode 100644 index 0000000..ed40c5d --- /dev/null +++ b/packages/db/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@acme/tsconfig/internal-package.json", + "compilerOptions": { + "outDir": "dist", + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": ["src"], + "exclude": ["node_modules"] +} diff --git a/packages/ui/components.json b/packages/ui/components.json new file mode 100644 index 0000000..c262488 --- /dev/null +++ b/packages/ui/components.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "./tailwind.config.ts", + "css": "unused.css", + "baseColor": "zinc", + "cssVariables": true + }, + "aliases": { + "utils": "@acme/ui", + "components": "src/", + "ui": "src/" + } +} diff --git a/packages/ui/eslint.config.js b/packages/ui/eslint.config.js new file mode 100644 index 0000000..9d74300 --- /dev/null +++ b/packages/ui/eslint.config.js @@ -0,0 +1,11 @@ +import baseConfig from "@acme/eslint-config/base"; +import reactConfig from "@acme/eslint-config/react"; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: [], + }, + ...baseConfig, + ...reactConfig, +]; diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 0000000..ed5d632 --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,52 @@ +{ + "name": "@acme/ui", + "private": true, + "version": "0.1.0", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./*": [ + "./src/*.tsx", + "./src/*.ts" + ] + }, + "license": "MIT", + "scripts": { + "clean": "rm -rf .turbo node_modules", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint", + "typecheck": "tsc --noEmit --emitDeclarationOnly false", + "ui-add": "pnpm dlx shadcn-ui add && prettier src --write --list-different" + }, + "dependencies": { + "@hookform/resolvers": "^3.3.4", + "@radix-ui/react-dropdown-menu": "^2.0.6", + "@radix-ui/react-icons": "^1.3.0", + "@radix-ui/react-label": "^2.0.2", + "@radix-ui/react-slot": "^1.0.2", + "class-variance-authority": "^0.7.0", + "next-themes": "^0.3.0", + "react-hook-form": "^7.51.4", + "sonner": "^1.4.41", + "tailwind-merge": "^2.3.0", + "tailwindcss-animate": "^1.0.7" + }, + "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tailwind-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "@types/react": "^18.3.3", + "eslint": "^9.4.0", + "prettier": "^3.3.1", + "react": "18.3.1", + "tailwindcss": "^3.4.3", + "typescript": "^5.4.5", + "zod": "^3.23.8" + }, + "peerDependencies": { + "react": "18.3.1", + "zod": "^3.23.8" + }, + "prettier": "@acme/prettier-config" +} diff --git a/packages/ui/src/button.tsx b/packages/ui/src/button.tsx new file mode 100644 index 0000000..6f5c3c6 --- /dev/null +++ b/packages/ui/src/button.tsx @@ -0,0 +1,58 @@ +import type { VariantProps } from "class-variance-authority"; +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva } from "class-variance-authority"; + +import { cn } from "@acme/ui"; + +const buttonVariants = cva( + "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", + { + variants: { + variant: { + primary: + "bg-primary text-primary-foreground shadow hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", + outline: + "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + sm: "h-8 rounded-md px-3 text-xs", + md: "h-9 px-4 py-2", + lg: "h-10 rounded-md px-8", + icon: "size-9", + }, + }, + defaultVariants: { + variant: "primary", + size: "md", + }, + }, +); + +interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean; +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button"; + return ( + + ); + }, +); +Button.displayName = "Button"; + +export { Button, buttonVariants }; diff --git a/packages/ui/src/dropdown-menu.tsx b/packages/ui/src/dropdown-menu.tsx new file mode 100644 index 0000000..ecca776 --- /dev/null +++ b/packages/ui/src/dropdown-menu.tsx @@ -0,0 +1,200 @@ +"use client"; + +import * as React from "react"; +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import { + CheckIcon, + ChevronRightIcon, + DotFilledIcon, +} from "@radix-ui/react-icons"; + +import { cn } from "@acme/ui"; + +const DropdownMenu = DropdownMenuPrimitive.Root; +const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; +const DropdownMenuGroup = DropdownMenuPrimitive.Group; +const DropdownMenuPortal = DropdownMenuPrimitive.Portal; +const DropdownMenuSub = DropdownMenuPrimitive.Sub; +const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup; + +const DropdownMenuSubTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, children, ...props }, ref) => ( + + {children} + + +)); +DropdownMenuSubTrigger.displayName = + DropdownMenuPrimitive.SubTrigger.displayName; + +const DropdownMenuSubContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSubContent.displayName = + DropdownMenuPrimitive.SubContent.displayName; + +const DropdownMenuContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, sideOffset = 4, ...props }, ref) => ( + + + +)); +DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName; + +const DropdownMenuItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName; + +const DropdownMenuCheckboxItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, checked, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuCheckboxItem.displayName = + DropdownMenuPrimitive.CheckboxItem.displayName; + +const DropdownMenuRadioItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName; + +const DropdownMenuLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName; + +const DropdownMenuSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName; + +const DropdownMenuShortcut = ({ + className, + ...props +}: React.HTMLAttributes) => { + return ( + + ); +}; +DropdownMenuShortcut.displayName = "DropdownMenuShortcut"; + +export { + DropdownMenu, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuCheckboxItem, + DropdownMenuRadioItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuGroup, + DropdownMenuPortal, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuRadioGroup, +}; diff --git a/packages/ui/src/form.tsx b/packages/ui/src/form.tsx new file mode 100644 index 0000000..2deabe2 --- /dev/null +++ b/packages/ui/src/form.tsx @@ -0,0 +1,201 @@ +"use client"; + +import type * as LabelPrimitive from "@radix-ui/react-label"; +import type { + ControllerProps, + FieldPath, + FieldValues, + UseFormProps, +} from "react-hook-form"; +import type { ZodType, ZodTypeDef } from "zod"; +import * as React from "react"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Slot } from "@radix-ui/react-slot"; +import { + useForm as __useForm, + Controller, + FormProvider, + useFormContext, +} from "react-hook-form"; + +import { cn } from "@acme/ui"; + +import { Label } from "./label"; + +const useForm = ( + props: Omit, "resolver"> & { + schema: ZodType; + }, +) => { + const form = __useForm({ + ...props, + resolver: zodResolver(props.schema, undefined), + }); + + return form; +}; + +const Form = FormProvider; + +interface FormFieldContextValue< + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath, +> { + name: TName; +} + +const FormFieldContext = React.createContext( + null, +); + +const FormField = < + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath, +>({ + ...props +}: ControllerProps) => { + return ( + + + + ); +}; + +const useFormField = () => { + const fieldContext = React.useContext(FormFieldContext); + const itemContext = React.useContext(FormItemContext); + const { getFieldState, formState } = useFormContext(); + + if (!fieldContext) { + throw new Error("useFormField should be used within "); + } + const fieldState = getFieldState(fieldContext.name, formState); + + const { id } = itemContext; + + return { + id, + name: fieldContext.name, + formItemId: `${id}-form-item`, + formDescriptionId: `${id}-form-item-description`, + formMessageId: `${id}-form-item-message`, + ...fieldState, + }; +}; + +interface FormItemContextValue { + id: string; +} + +const FormItemContext = React.createContext( + {} as FormItemContextValue, +); + +const FormItem = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => { + const id = React.useId(); + + return ( + +
+ + ); +}); +FormItem.displayName = "FormItem"; + +const FormLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => { + const { error, formItemId } = useFormField(); + + return ( +