diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 043f0f9b..66c4bfeb 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,3 +1,3 @@ # These are supported funding model platforms -github: juliusmarminge +github: codingcodax diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 85006621..4ad13291 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,3 +55,14 @@ jobs: - name: Typecheck run: pnpm typecheck + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup + uses: ./tooling/github/setup + + - name: Build + run: pnpm build diff --git a/README.md b/README.md index 45140942..573e05c6 100644 --- a/README.md +++ b/README.md @@ -1,267 +1 @@ -# 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. +# kosori diff --git a/apps/auth-proxy/.env.example b/apps/auth-proxy/.env.example deleted file mode 100644 index bdb4d554..00000000 --- a/apps/auth-proxy/.env.example +++ /dev/null @@ -1,7 +0,0 @@ - -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 deleted file mode 100644 index 2e02b7af..00000000 --- a/apps/auth-proxy/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# 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 deleted file mode 100644 index f008170f..00000000 --- a/apps/auth-proxy/eslint.config.js +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e690a292..00000000 --- a/apps/auth-proxy/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "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.14.9", - "eslint": "catalog:", - "h3": "^1.12.0", - "nitropack": "^2.9.7", - "prettier": "catalog:", - "typescript": "catalog:" - }, - "prettier": "@acme/prettier-config" -} diff --git a/apps/auth-proxy/routes/r/[...auth].ts b/apps/auth-proxy/routes/r/[...auth].ts deleted file mode 100644 index 39db9f65..00000000 --- a/apps/auth-proxy/routes/r/[...auth].ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index a2aaadcd..00000000 --- a/apps/auth-proxy/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "@acme/tsconfig/base.json", - "include": ["routes"] -} diff --git a/apps/auth-proxy/turbo.json b/apps/auth-proxy/turbo.json deleted file mode 100644 index 4508ede4..00000000 --- a/apps/auth-proxy/turbo.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "https://turborepo.org/schema.json", - "extends": ["//"], - "tasks": { - "build": { - "dependsOn": ["^build"], - "outputs": [".nitro/**", ".output/**", ".vercel/**"] - }, - "dev": { - "persistent": true - } - } -} diff --git a/apps/expo/.expo-shared/assets.json b/apps/expo/.expo-shared/assets.json deleted file mode 100644 index 1e6decfb..00000000 --- a/apps/expo/.expo-shared/assets.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true, - "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true -} diff --git a/apps/expo/app.config.ts b/apps/expo/app.config.ts deleted file mode 100644 index 053fcb39..00000000 --- a/apps/expo/app.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 67917f52..00000000 Binary files a/apps/expo/assets/icon.png and /dev/null differ diff --git a/apps/expo/babel.config.js b/apps/expo/babel.config.js deleted file mode 100644 index 95b13939..00000000 --- a/apps/expo/babel.config.js +++ /dev/null @@ -1,11 +0,0 @@ -/** @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 deleted file mode 100644 index 70c73d57..00000000 --- a/apps/expo/eas.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "cli": { - "version": ">= 4.1.2" - }, - "build": { - "base": { - "node": "20.15.0", - "pnpm": "9.6.0", - "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 deleted file mode 100644 index e264359d..00000000 --- a/apps/expo/eslint.config.mjs +++ /dev/null @@ -1,11 +0,0 @@ -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/index.ts b/apps/expo/index.ts deleted file mode 100644 index 80d3d998..00000000 --- a/apps/expo/index.ts +++ /dev/null @@ -1 +0,0 @@ -import "expo-router/entry"; diff --git a/apps/expo/metro.config.js b/apps/expo/metro.config.js deleted file mode 100644 index ea877dac..00000000 --- a/apps/expo/metro.config.js +++ /dev/null @@ -1,61 +0,0 @@ -// 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"); - -const config = withTurborepoManagedCache( - withMonorepoPaths( - withNativeWind(getDefaultConfig(__dirname), { - input: "./src/styles.css", - configPath: "./tailwind.config.ts", - }), - ), -); - -// XXX: Resolve our exports in workspace packages -// https://github.com/expo/expo/issues/26926 -config.resolver.unstable_enablePackageExports = true; - -module.exports = config; - -/** - * 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 deleted file mode 100644 index 04e8ae7c..00000000 --- a/apps/expo/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "@acme/expo", - "version": "0.1.0", - "private": true, - "main": "index.ts", - "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.8", - "@shopify/flash-list": "1.6.4", - "@tanstack/react-query": "catalog:", - "@trpc/client": "catalog:", - "@trpc/react-query": "catalog:", - "@trpc/server": "catalog:", - "expo": "~51.0.18", - "expo-constants": "~16.0.2", - "expo-dev-client": "~4.0.19", - "expo-linking": "~6.3.1", - "expo-router": "~3.5.17", - "expo-secure-store": "^13.0.2", - "expo-splash-screen": "~0.27.5", - "expo-status-bar": "~1.12.1", - "expo-web-browser": "^13.0.3", - "nativewind": "~4.0.36", - "react": "catalog:react18", - "react-dom": "catalog:react18", - "react-native": "~0.74.3", - "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": "catalog:react18", - "eslint": "catalog:", - "prettier": "catalog:", - "tailwindcss": "^3.4.4", - "typescript": "catalog:" - }, - "prettier": "@acme/prettier-config" -} diff --git a/apps/expo/src/app/_layout.tsx b/apps/expo/src/app/_layout.tsx deleted file mode 100644 index 0aa2746e..00000000 --- a/apps/expo/src/app/_layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 0bbd651a..00000000 --- a/apps/expo/src/app/index.tsx +++ /dev/null @@ -1,159 +0,0 @@ -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 deleted file mode 100644 index ca419a99..00000000 --- a/apps/nextjs/src/app/_components/posts.tsx +++ /dev/null @@ -1,168 +0,0 @@ -"use client"; - -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() { - const [posts] = api.post.all.useSuspenseQuery(); - - 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 deleted file mode 100644 index 22ddf2c4..00000000 --- a/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts +++ /dev/null @@ -1,81 +0,0 @@ -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 deleted file mode 100644 index 4a0ef6c4..00000000 --- a/apps/nextjs/src/app/api/trpc/[trpc]/route.ts +++ /dev/null @@ -1,46 +0,0 @@ -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/layout.tsx b/apps/nextjs/src/app/layout.tsx deleted file mode 100644 index a7e62530..00000000 --- a/apps/nextjs/src/app/layout.tsx +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index 0e4df9fb..00000000 --- a/apps/nextjs/src/app/page.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { Suspense } from "react"; - -import { api, HydrateClient } 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 - void api.post.all.prefetch(); - - return ( - -
-
-

- Create T3 Turbo -

- - - -
- - - - -
- } - > - - -
- -
-
- ); -} diff --git a/apps/nextjs/src/middleware.ts b/apps/nextjs/src/middleware.ts deleted file mode 100644 index a2c8032b..00000000 --- a/apps/nextjs/src/middleware.ts +++ /dev/null @@ -1,11 +0,0 @@ -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/query-client.ts b/apps/nextjs/src/trpc/query-client.ts deleted file mode 100644 index bda64397..00000000 --- a/apps/nextjs/src/trpc/query-client.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { - defaultShouldDehydrateQuery, - QueryClient, -} from "@tanstack/react-query"; -import SuperJSON from "superjson"; - -export 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, - }, - dehydrate: { - serializeData: SuperJSON.serialize, - shouldDehydrateQuery: (query) => - defaultShouldDehydrateQuery(query) || - query.state.status === "pending", - }, - hydrate: { - deserializeData: SuperJSON.deserialize, - }, - }, - }); diff --git a/apps/nextjs/src/trpc/react.tsx b/apps/nextjs/src/trpc/react.tsx deleted file mode 100644 index b3a6d339..00000000 --- a/apps/nextjs/src/trpc/react.tsx +++ /dev/null @@ -1,66 +0,0 @@ -"use client"; - -import type { QueryClient } from "@tanstack/react-query"; -import { useState } from "react"; -import { 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"; -import { createQueryClient } from "./query-client"; - -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 deleted file mode 100644 index 16ff4ad9..00000000 --- a/apps/nextjs/src/trpc/server.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { cache } from "react"; -import { headers } from "next/headers"; -import { createHydrationHelpers } from "@trpc/react-query/rsc"; - -import type { AppRouter } from "@acme/api"; -import { createCaller, createTRPCContext } from "@acme/api"; -import { auth } from "@acme/auth"; - -import { createQueryClient } from "./query-client"; - -/** - * 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, - }); -}); - -const getQueryClient = cache(createQueryClient); -const caller = createCaller(createContext); - -export const { trpc: api, HydrateClient } = createHydrationHelpers( - caller, - getQueryClient, -); diff --git a/apps/nextjs/tailwind.config.ts b/apps/nextjs/tailwind.config.ts deleted file mode 100644 index 4d5d8157..00000000 --- a/apps/nextjs/tailwind.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -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/www/README.md b/apps/www/README.md new file mode 100644 index 00000000..b0311b1e --- /dev/null +++ b/apps/www/README.md @@ -0,0 +1 @@ +# kosori/ui diff --git a/apps/www/eslint.config.js b/apps/www/eslint.config.js new file mode 100644 index 00000000..432af2d5 --- /dev/null +++ b/apps/www/eslint.config.js @@ -0,0 +1,14 @@ +import baseConfig, { restrictEnvAccess } from '@kosori/eslint-config/base'; +import nextjsConfig from '@kosori/eslint-config/nextjs'; +import reactConfig from '@kosori/eslint-config/react'; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: ['.next/**'], + }, + ...baseConfig, + ...reactConfig, + ...nextjsConfig, + ...restrictEnvAccess, +]; diff --git a/apps/nextjs/next.config.js b/apps/www/next.config.js similarity index 66% rename from apps/nextjs/next.config.js rename to apps/www/next.config.js index 861c5268..f449de15 100644 --- a/apps/nextjs/next.config.js +++ b/apps/www/next.config.js @@ -1,8 +1,8 @@ -import { fileURLToPath } from "url"; -import createJiti from "jiti"; +import { fileURLToPath } from 'url'; +import createJiti from 'jiti'; // Import env files to validate at build time. Use jiti so we can load .ts files in here. -createJiti(fileURLToPath(import.meta.url))("./src/env"); +createJiti(fileURLToPath(import.meta.url))('./src/env'); /** @type {import("next").NextConfig} */ const config = { @@ -10,11 +10,11 @@ const config = { /** Enables hot reloading for local packages without a build step */ transpilePackages: [ - "@acme/api", - "@acme/auth", - "@acme/db", - "@acme/ui", - "@acme/validators", + '@kosori/api', + '@kosori/auth', + '@kosori/db', + '@kosori/ui', + '@kosori/validators', ], /** We already do linting and typechecking as separate tasks in CI */ diff --git a/apps/nextjs/package.json b/apps/www/package.json similarity index 73% rename from apps/nextjs/package.json rename to apps/www/package.json index 19a1db88..59746f0b 100644 --- a/apps/nextjs/package.json +++ b/apps/www/package.json @@ -1,5 +1,5 @@ { - "name": "@acme/nextjs", + "name": "@kosori/www", "version": "0.1.0", "private": true, "type": "module", @@ -14,11 +14,7 @@ "with-env": "dotenv -e ../../.env --" }, "dependencies": { - "@acme/api": "workspace:*", - "@acme/auth": "workspace:*", - "@acme/db": "workspace:*", - "@acme/ui": "workspace:*", - "@acme/validators": "workspace:*", + "@kosori/ui": "workspace:*", "@t3-oss/env-nextjs": "^0.10.1", "@tanstack/react-query": "catalog:", "@trpc/client": "catalog:", @@ -32,10 +28,10 @@ "zod": "catalog:" }, "devDependencies": { - "@acme/eslint-config": "workspace:*", - "@acme/prettier-config": "workspace:*", - "@acme/tailwind-config": "workspace:*", - "@acme/tsconfig": "workspace:*", + "@kosori/eslint-config": "workspace:*", + "@kosori/prettier-config": "workspace:*", + "@kosori/tailwind-config": "workspace:*", + "@kosori/tsconfig": "workspace:*", "@types/node": "^20.14.9", "@types/react": "catalog:react18", "@types/react-dom": "catalog:react18", @@ -46,5 +42,5 @@ "tailwindcss": "^3.4.4", "typescript": "catalog:" }, - "prettier": "@acme/prettier-config" + "prettier": "@kosori/prettier-config" } diff --git a/apps/nextjs/postcss.config.cjs b/apps/www/postcss.config.cjs similarity index 100% rename from apps/nextjs/postcss.config.cjs rename to apps/www/postcss.config.cjs diff --git a/apps/nextjs/public/favicon.ico b/apps/www/public/favicon.ico similarity index 100% rename from apps/nextjs/public/favicon.ico rename to apps/www/public/favicon.ico diff --git a/apps/nextjs/public/t3-icon.svg b/apps/www/public/t3-icon.svg similarity index 100% rename from apps/nextjs/public/t3-icon.svg rename to apps/www/public/t3-icon.svg diff --git a/apps/nextjs/src/app/globals.css b/apps/www/src/app/globals.css similarity index 100% rename from apps/nextjs/src/app/globals.css rename to apps/www/src/app/globals.css diff --git a/apps/www/src/app/layout.tsx b/apps/www/src/app/layout.tsx new file mode 100644 index 00000000..6f38549d --- /dev/null +++ b/apps/www/src/app/layout.tsx @@ -0,0 +1,49 @@ +import type { Metadata, Viewport } from 'next'; +import { GeistMono } from 'geist/font/mono'; +import { GeistSans } from 'geist/font/sans'; + +import { cn } from '@kosori/ui'; +import { ThemeProvider } from '@kosori/ui/theme'; + +import '~/app/globals.css'; + +export const metadata: Metadata = { + title: 'kosori/ui', + description: 'Build high quality and accessible apps in a short time.', + openGraph: { + title: 'kosori/ui', + description: 'Build high quality and accessible apps in a short time.', + url: 'https://ui.codingcodax.dev', + siteName: 'kosori/ui', + }, + twitter: { + card: 'summary_large_image', + site: '@codingcodax', + creator: '@codingcodax', + }, +}; + +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/www/src/app/page.tsx b/apps/www/src/app/page.tsx new file mode 100644 index 00000000..acb640ea --- /dev/null +++ b/apps/www/src/app/page.tsx @@ -0,0 +1,11 @@ +import type { NextPage } from 'next'; + +const Home: NextPage = () => { + return ( +
+

home page

+
+ ); +}; + +export default Home; diff --git a/apps/nextjs/src/env.ts b/apps/www/src/env.ts similarity index 64% rename from apps/nextjs/src/env.ts rename to apps/www/src/env.ts index ba55d468..1c54fce8 100644 --- a/apps/nextjs/src/env.ts +++ b/apps/www/src/env.ts @@ -1,24 +1,20 @@ /* 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"; +import { createEnv } from '@t3-oss/env-nextjs'; +import { vercel } from '@t3-oss/env-nextjs/presets'; +import { z } from 'zod'; export const env = createEnv({ - extends: [authEnv, vercel()], + extends: [vercel()], shared: { NODE_ENV: z - .enum(["development", "production", "test"]) - .default("development"), + .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(), - }, + server: {}, /** * Specify your client-side environment variables schema here. @@ -36,5 +32,5 @@ export const env = createEnv({ // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, }, skipValidation: - !!process.env.CI || process.env.npm_lifecycle_event === "lint", + !!process.env.CI || process.env.npm_lifecycle_event === 'lint', }); diff --git a/apps/www/tailwind.config.ts b/apps/www/tailwind.config.ts new file mode 100644 index 00000000..ce94993e --- /dev/null +++ b/apps/www/tailwind.config.ts @@ -0,0 +1,19 @@ +import type { Config } from 'tailwindcss'; +import { fontFamily } from 'tailwindcss/defaultTheme'; + +import baseConfig from '@kosori/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/www/tsconfig.json similarity index 89% rename from apps/nextjs/tsconfig.json rename to apps/www/tsconfig.json index 646a6828..cd947aad 100644 --- a/apps/nextjs/tsconfig.json +++ b/apps/www/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "@acme/tsconfig/base.json", + "extends": "@kosori/tsconfig/base.json", "compilerOptions": { "lib": ["es2022", "dom", "dom.iterable"], "jsx": "preserve", diff --git a/apps/nextjs/turbo.json b/apps/www/turbo.json similarity index 100% rename from apps/nextjs/turbo.json rename to apps/www/turbo.json diff --git a/package.json b/package.json index 21e1b28b..19b69991 100644 --- a/package.json +++ b/package.json @@ -9,10 +9,8 @@ "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...", + "dev:www": "turbo watch dev -F @kosori/www...", "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", @@ -23,11 +21,11 @@ "ui-add": "turbo run ui-add" }, "devDependencies": { - "@acme/prettier-config": "workspace:*", + "@kosori/prettier-config": "workspace:*", "@turbo/gen": "^2.0.8", "prettier": "catalog:", "turbo": "^2.0.8", "typescript": "catalog:" }, - "prettier": "@acme/prettier-config" + "prettier": "@kosori/prettier-config" } diff --git a/packages/api/eslint.config.js b/packages/api/eslint.config.js deleted file mode 100644 index b87792cf..00000000 --- a/packages/api/eslint.config.js +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 60a165ae..00000000 --- a/packages/api/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "@acme/api", - "version": "0.1.0", - "private": true, - "type": "module", - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - } - }, - "license": "MIT", - "scripts": { - "build": "tsc", - "clean": "rm -rf .turbo dist node_modules", - "dev": "tsc", - "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": "catalog:", - "superjson": "2.2.1", - "zod": "catalog:" - }, - "devDependencies": { - "@acme/eslint-config": "workspace:*", - "@acme/prettier-config": "workspace:*", - "@acme/tsconfig": "workspace:*", - "eslint": "catalog:", - "prettier": "catalog:", - "typescript": "catalog:" - }, - "prettier": "@acme/prettier-config" -} diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts deleted file mode 100644 index 1cbe6fdd..00000000 --- a/packages/api/src/index.ts +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 730251c7..00000000 --- a/packages/api/src/root.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index ad53a60a..00000000 --- a/packages/api/src/router/auth.ts +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 9ab103e1..00000000 --- a/packages/api/src/router/post.ts +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index cc596fcc..00000000 --- a/packages/api/src/trpc.ts +++ /dev/null @@ -1,145 +0,0 @@ -/** - * 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; - -/** - * Middleware for timing procedure execution and adding an articifial delay in development. - * - * You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating - * network latency that would occur in production but not in local development. - */ -const timingMiddleware = t.middleware(async ({ next, path }) => { - const start = Date.now(); - - if (t._config.isDev) { - // artificial delay in dev 100-500ms - const waitMs = Math.floor(Math.random() * 400) + 100; - await new Promise((resolve) => setTimeout(resolve, waitMs)); - } - - const result = await next(); - - const end = Date.now(); - console.log(`[TRPC] ${path} took ${end - start}ms to execute`); - - return result; -}); - -/** - * 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.use(timingMiddleware); - -/** - * 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(timingMiddleware) - .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 deleted file mode 100644 index ed40c5d9..00000000 --- a/packages/api/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "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 deleted file mode 100644 index bbd2209f..00000000 --- a/packages/auth/env.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* 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 deleted file mode 100644 index 61cafcb2..00000000 --- a/packages/auth/eslint.config.js +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index e9409554..00000000 --- a/packages/auth/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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.4.1", - "@t3-oss/env-nextjs": "^0.10.1", - "next": "^14.2.4", - "next-auth": "5.0.0-beta.19", - "react": "catalog:react18", - "react-dom": "catalog:react18", - "zod": "catalog:" - }, - "devDependencies": { - "@acme/eslint-config": "workspace:*", - "@acme/prettier-config": "workspace:*", - "@acme/tsconfig": "workspace:*", - "eslint": "catalog:", - "prettier": "catalog:", - "typescript": "catalog:" - }, - "prettier": "@acme/prettier-config" -} diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.ts deleted file mode 100644 index e2ddda31..00000000 --- a/packages/auth/src/config.ts +++ /dev/null @@ -1,75 +0,0 @@ -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 deleted file mode 100644 index 0373b25c..00000000 --- a/packages/auth/src/index.rsc.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index f9f39f62..00000000 --- a/packages/auth/src/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index fe755642..00000000 --- a/packages/auth/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "@acme/tsconfig/base.json", - "compilerOptions": {}, - "include": ["src", "*.ts"], - "exclude": ["node_modules"] -} diff --git a/packages/db/drizzle.config.ts b/packages/db/drizzle.config.ts deleted file mode 100644 index 27cb8e5b..00000000 --- a/packages/db/drizzle.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 4fa93849..00000000 --- a/packages/db/eslint.config.js +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index cbc60c5e..00000000 --- a/packages/db/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "@acme/db", - "version": "0.1.0", - "private": true, - "type": "module", - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./client": { - "types": "./dist/client.d.ts", - "default": "./dist/client.js" - }, - "./schema": { - "types": "./dist/schema.d.ts", - "default": "./dist/schema.js" - } - }, - "license": "MIT", - "scripts": { - "build": "tsc", - "dev": "tsc", - "clean": "rm -rf .turbo dist 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": { - "@t3-oss/env-core": "^0.10.1", - "@vercel/postgres": "^0.9.0", - "drizzle-orm": "^0.31.2", - "drizzle-zod": "^0.5.1", - "zod": "catalog:" - }, - "devDependencies": { - "@acme/eslint-config": "workspace:*", - "@acme/prettier-config": "workspace:*", - "@acme/tsconfig": "workspace:*", - "dotenv-cli": "^7.4.2", - "drizzle-kit": "^0.22.8", - "eslint": "catalog:", - "prettier": "catalog:", - "typescript": "catalog:" - }, - "prettier": "@acme/prettier-config" -} diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts deleted file mode 100644 index 671359ae..00000000 --- a/packages/db/src/client.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index f0585be4..00000000 --- a/packages/db/src/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -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 deleted file mode 100644 index 6bb27308..00000000 --- a/packages/db/src/schema.ts +++ /dev/null @@ -1,92 +0,0 @@ -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 deleted file mode 100644 index 565686d3..00000000 --- a/packages/db/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "@acme/tsconfig/internal-package.json", - "compilerOptions": {}, - "include": ["src"], - "exclude": ["node_modules"] -} diff --git a/packages/ui/components.json b/packages/ui/components.json index c2624886..68e6ddf4 100644 --- a/packages/ui/components.json +++ b/packages/ui/components.json @@ -10,7 +10,7 @@ "cssVariables": true }, "aliases": { - "utils": "@acme/ui", + "utils": "@kosori/ui", "components": "src/", "ui": "src/" } diff --git a/packages/ui/eslint.config.js b/packages/ui/eslint.config.js index 9d74300f..d7486937 100644 --- a/packages/ui/eslint.config.js +++ b/packages/ui/eslint.config.js @@ -1,5 +1,5 @@ -import baseConfig from "@acme/eslint-config/base"; -import reactConfig from "@acme/eslint-config/react"; +import baseConfig from '@kosori/eslint-config/base'; +import reactConfig from '@kosori/eslint-config/react'; /** @type {import('typescript-eslint').Config} */ export default [ diff --git a/packages/ui/package.json b/packages/ui/package.json index e57c2b5a..5e276ad4 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,5 +1,5 @@ { - "name": "@acme/ui", + "name": "@kosori/ui", "private": true, "version": "0.1.0", "type": "module", @@ -37,10 +37,10 @@ "tailwindcss-animate": "^1.0.7" }, "devDependencies": { - "@acme/eslint-config": "workspace:*", - "@acme/prettier-config": "workspace:*", - "@acme/tailwind-config": "workspace:*", - "@acme/tsconfig": "workspace:*", + "@kosori/eslint-config": "workspace:*", + "@kosori/prettier-config": "workspace:*", + "@kosori/tailwind-config": "workspace:*", + "@kosori/tsconfig": "workspace:*", "@types/react": "catalog:react18", "eslint": "catalog:", "prettier": "catalog:", @@ -53,5 +53,5 @@ "react": "catalog:react18", "zod": "catalog:" }, - "prettier": "@acme/prettier-config" + "prettier": "@kosori/prettier-config" } diff --git a/packages/ui/src/button.tsx b/packages/ui/src/button.tsx index 6f5c3c69..5d9d5cd9 100644 --- a/packages/ui/src/button.tsx +++ b/packages/ui/src/button.tsx @@ -1,58 +1,57 @@ -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 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"; +import { cn } from '@kosori/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", + '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", + 'bg-primary text-primary-foreground shadow hover:bg-primary/90', destructive: - "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", + '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", + '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", + '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", + 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", + variant: 'primary', + size: 'md', }, }, ); -interface ButtonProps - extends React.ButtonHTMLAttributes, - VariantProps { +type ButtonProps = { asChild?: boolean; -} +} & React.ButtonHTMLAttributes & + VariantProps; const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { - const Comp = asChild ? Slot : "button"; + const Comp = asChild ? Slot : 'button'; return ( ); }, ); -Button.displayName = "Button"; +Button.displayName = 'Button'; export { Button, buttonVariants }; diff --git a/packages/ui/src/dropdown-menu.tsx b/packages/ui/src/dropdown-menu.tsx index ecca776c..d929fa5f 100644 --- a/packages/ui/src/dropdown-menu.tsx +++ b/packages/ui/src/dropdown-menu.tsx @@ -1,14 +1,14 @@ -"use client"; +'use client'; -import * as React from "react"; -import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import * as React from 'react'; +import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'; import { CheckIcon, ChevronRightIcon, DotFilledIcon, -} from "@radix-ui/react-icons"; +} from '@radix-ui/react-icons'; -import { cn } from "@acme/ui"; +import { cn } from '@kosori/ui'; const DropdownMenu = DropdownMenuPrimitive.Root; const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; @@ -26,14 +26,14 @@ const DropdownMenuSubTrigger = React.forwardRef< {children} - + )); DropdownMenuSubTrigger.displayName = @@ -46,7 +46,7 @@ const DropdownMenuSubContent = React.forwardRef< @@ -83,8 +83,8 @@ const DropdownMenuItem = React.forwardRef< (({ className, children, checked, ...props }, ref) => ( - + - + {children} @@ -123,14 +123,14 @@ const DropdownMenuRadioItem = React.forwardRef< - + - + {children} @@ -147,8 +147,8 @@ const DropdownMenuLabel = React.forwardRef< (({ className, ...props }, ref) => ( )); @@ -174,12 +174,12 @@ const DropdownMenuShortcut = ({ }: React.HTMLAttributes) => { return ( ); }; -DropdownMenuShortcut.displayName = "DropdownMenuShortcut"; +DropdownMenuShortcut.displayName = 'DropdownMenuShortcut'; export { DropdownMenu, diff --git a/packages/ui/src/form.tsx b/packages/ui/src/form.tsx index ac0c191a..ed92bd22 100644 --- a/packages/ui/src/form.tsx +++ b/packages/ui/src/form.tsx @@ -1,33 +1,33 @@ -"use client"; +'use client'; -import type * as LabelPrimitive from "@radix-ui/react-label"; +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"; +} 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"; +} from 'react-hook-form'; -import { cn } from "@acme/ui"; +import { cn } from '@kosori/ui'; -import { Label } from "./label"; +import { Label } from './label'; const useForm = < TOut extends FieldValues, TDef extends ZodTypeDef, TIn extends FieldValues, >( - props: Omit, "resolver"> & { + props: Omit, 'resolver'> & { schema: ZodType; }, ) => { @@ -41,12 +41,12 @@ const useForm = < const Form = FormProvider; -interface FormFieldContextValue< +type FormFieldContextValue< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, -> { +> = { name: TName; -} +}; const FormFieldContext = React.createContext( null, @@ -71,7 +71,7 @@ const useFormField = () => { const { getFieldState, formState } = useFormContext(); if (!fieldContext) { - throw new Error("useFormField should be used within "); + throw new Error('useFormField should be used within '); } const fieldState = getFieldState(fieldContext.name, formState); @@ -87,9 +87,9 @@ const useFormField = () => { }; }; -interface FormItemContextValue { +type FormItemContextValue = { id: string; -} +}; const FormItemContext = React.createContext( {} as FormItemContextValue, @@ -103,11 +103,11 @@ const FormItem = React.forwardRef< return ( -
+
); }); -FormItem.displayName = "FormItem"; +FormItem.displayName = 'FormItem'; const FormLabel = React.forwardRef< React.ElementRef, @@ -118,13 +118,13 @@ const FormLabel = React.forwardRef< return (