diff --git a/apps/api/.env.example b/apps/api/.env.example new file mode 100644 index 0000000..9ca697f --- /dev/null +++ b/apps/api/.env.example @@ -0,0 +1,33 @@ +# Every key here is optional: with none set the app runs — Clerk as a sample +# user, BaseHub as sample content, the rest switched off — and says what to +# connect. For `next dev`, copy this to .env.local. Under `wrangler dev` +# (`pnpm preview`) the server-only keys go in .dev.vars instead. Deployed, +# each is an Orun secret of the same name (component.yaml). +# Server +CLERK_SECRET_KEY="" +CLERK_WEBHOOK_SECRET="" +RESEND_FROM="" +DATABASE_URL="postgres://postgres:postgres@localhost:54322/postgres" +RESEND_TOKEN="" +STRIPE_SECRET_KEY="" +STRIPE_WEBHOOK_SECRET="" +BETTERSTACK_API_KEY="" +BETTERSTACK_URL="" +FLAGS_SECRET="" +SVIX_TOKEN="" +LIVEBLOCKS_SECRET="" +BASEHUB_TOKEN="" +KNOCK_API_KEY="" +KNOCK_FEED_CHANNEL_ID="" + +# Client +NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="" +NEXT_PUBLIC_CLERK_SIGN_IN_URL="/sign-in" +NEXT_PUBLIC_CLERK_SIGN_UP_URL="/sign-up" +NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL="/" +NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL="/" +NEXT_PUBLIC_GA_MEASUREMENT_ID="" +NEXT_PUBLIC_POSTHOG_KEY="" +NEXT_PUBLIC_POSTHOG_HOST="" +NEXT_PUBLIC_APP_URL="http://localhost:3000" +NEXT_PUBLIC_WEB_URL="http://localhost:3001" diff --git a/apps/api/.env.production b/apps/api/.env.production new file mode 100644 index 0000000..5041fcd --- /dev/null +++ b/apps/api/.env.production @@ -0,0 +1,7 @@ +# The origins the three Workers link to each other by, inlined at build time +# (NEXT_PUBLIC_). These are stage's workers.dev URLs, for a local +# `pnpm build`; every Orun lane builds with its own environment's +# (component.yaml's buildCommand), which wins over this file. +NEXT_PUBLIC_APP_URL=https://next-forge-app-stage.your-workers-subdomain.workers.dev +NEXT_PUBLIC_WEB_URL=https://next-forge-web-stage.your-workers-subdomain.workers.dev +NEXT_PUBLIC_API_URL=https://next-forge-api-stage.your-workers-subdomain.workers.dev diff --git a/apps/api/.gitignore b/apps/api/.gitignore new file mode 100644 index 0000000..7f3818c --- /dev/null +++ b/apps/api/.gitignore @@ -0,0 +1,4 @@ +# local state wrangler and the Cloudflare adapter write +.wrangler/ +.open-next/ +.dev.vars diff --git a/apps/api/app/apple-icon.png b/apps/api/app/apple-icon.png new file mode 100644 index 0000000..d185929 Binary files /dev/null and b/apps/api/app/apple-icon.png differ diff --git a/apps/api/app/cron/keep-alive/route.ts b/apps/api/app/cron/keep-alive/route.ts new file mode 100644 index 0000000..38900d7 --- /dev/null +++ b/apps/api/app/cron/keep-alive/route.ts @@ -0,0 +1,17 @@ +import { database } from "@repo/database"; + +export const GET = async () => { + const newPage = await database.page.create({ + data: { + name: "cron-temp", + }, + }); + + await database.page.delete({ + where: { + id: newPage.id, + }, + }); + + return new Response("OK", { status: 200 }); +}; diff --git a/apps/api/app/global-error.tsx b/apps/api/app/global-error.tsx new file mode 100644 index 0000000..faaf4a1 --- /dev/null +++ b/apps/api/app/global-error.tsx @@ -0,0 +1,29 @@ +"use client"; + +import { Button } from "@repo/design-system/components/ui/button"; +import { fonts } from "@repo/design-system/lib/fonts"; +import { captureException } from "@repo/observability/sentry"; +import type NextError from "next/error"; +import { useEffect } from "react"; + +interface GlobalErrorProperties { + readonly error: NextError & { digest?: string }; + readonly reset: () => void; +} + +const GlobalError = ({ error, reset }: GlobalErrorProperties) => { + useEffect(() => { + captureException(error); + }, [error]); + + return ( + + +

Oops, something went wrong

+ + + + ); +}; + +export default GlobalError; diff --git a/apps/api/app/health/route.ts b/apps/api/app/health/route.ts new file mode 100644 index 0000000..942ddf2 --- /dev/null +++ b/apps/api/app/health/route.ts @@ -0,0 +1 @@ +export const GET = (): Response => new Response("OK", { status: 200 }); diff --git a/apps/api/app/icon.png b/apps/api/app/icon.png new file mode 100644 index 0000000..d798285 Binary files /dev/null and b/apps/api/app/icon.png differ diff --git a/apps/api/app/layout.tsx b/apps/api/app/layout.tsx new file mode 100644 index 0000000..2dce3e9 --- /dev/null +++ b/apps/api/app/layout.tsx @@ -0,0 +1,16 @@ +import { AnalyticsProvider } from "@repo/analytics/provider"; +import type { ReactNode } from "react"; + +interface RootLayoutProperties { + readonly children: ReactNode; +} + +const RootLayout = ({ children }: RootLayoutProperties) => ( + + + {children} + + +); + +export default RootLayout; diff --git a/apps/api/app/opengraph-image.png b/apps/api/app/opengraph-image.png new file mode 100644 index 0000000..c79169f Binary files /dev/null and b/apps/api/app/opengraph-image.png differ diff --git a/apps/api/app/webhooks/auth/route.ts b/apps/api/app/webhooks/auth/route.ts new file mode 100644 index 0000000..04828b7 --- /dev/null +++ b/apps/api/app/webhooks/auth/route.ts @@ -0,0 +1,233 @@ +import { analytics } from "@repo/analytics/server"; +import type { + DeletedObjectJSON, + OrganizationJSON, + OrganizationMembershipJSON, + UserJSON, + WebhookEvent, +} from "@repo/auth/server"; +import { log } from "@repo/observability/log"; +import { headers } from "next/headers"; +import { NextResponse } from "next/server"; +import { Webhook } from "svix"; +import { env } from "@/env"; + +const handleUserCreated = (data: UserJSON) => { + analytics?.identify({ + distinctId: data.id, + properties: { + email: data.email_addresses.at(0)?.email_address, + firstName: data.first_name, + lastName: data.last_name, + createdAt: new Date(data.created_at), + avatar: data.image_url, + phoneNumber: data.phone_numbers.at(0)?.phone_number, + }, + }); + + analytics?.capture({ + event: "User Created", + distinctId: data.id, + }); + + return new Response("User created", { status: 201 }); +}; + +const handleUserUpdated = (data: UserJSON) => { + analytics?.identify({ + distinctId: data.id, + properties: { + email: data.email_addresses.at(0)?.email_address, + firstName: data.first_name, + lastName: data.last_name, + createdAt: new Date(data.created_at), + avatar: data.image_url, + phoneNumber: data.phone_numbers.at(0)?.phone_number, + }, + }); + + analytics?.capture({ + event: "User Updated", + distinctId: data.id, + }); + + return new Response("User updated", { status: 201 }); +}; + +const handleUserDeleted = (data: DeletedObjectJSON) => { + if (data.id) { + analytics?.identify({ + distinctId: data.id, + properties: { + deleted: new Date(), + }, + }); + + analytics?.capture({ + event: "User Deleted", + distinctId: data.id, + }); + } + + return new Response("User deleted", { status: 201 }); +}; + +const handleOrganizationCreated = (data: OrganizationJSON) => { + analytics?.groupIdentify({ + groupKey: data.id, + groupType: "company", + distinctId: data.created_by, + properties: { + name: data.name, + avatar: data.image_url, + }, + }); + + if (data.created_by) { + analytics?.capture({ + event: "Organization Created", + distinctId: data.created_by, + }); + } + + return new Response("Organization created", { status: 201 }); +}; + +const handleOrganizationUpdated = (data: OrganizationJSON) => { + analytics?.groupIdentify({ + groupKey: data.id, + groupType: "company", + distinctId: data.created_by, + properties: { + name: data.name, + avatar: data.image_url, + }, + }); + + if (data.created_by) { + analytics?.capture({ + event: "Organization Updated", + distinctId: data.created_by, + }); + } + + return new Response("Organization updated", { status: 201 }); +}; + +const handleOrganizationMembershipCreated = ( + data: OrganizationMembershipJSON +) => { + analytics?.groupIdentify({ + groupKey: data.organization.id, + groupType: "company", + distinctId: data.public_user_data.user_id, + }); + + analytics?.capture({ + event: "Organization Member Created", + distinctId: data.public_user_data.user_id, + }); + + return new Response("Organization membership created", { status: 201 }); +}; + +const handleOrganizationMembershipDeleted = ( + data: OrganizationMembershipJSON +) => { + // Need to unlink the user from the group + + analytics?.capture({ + event: "Organization Member Deleted", + distinctId: data.public_user_data.user_id, + }); + + return new Response("Organization membership deleted", { status: 201 }); +}; + +export const POST = async (request: Request): Promise => { + if (!env.CLERK_WEBHOOK_SECRET) { + return NextResponse.json({ message: "Not configured", ok: false }); + } + + // Get the headers + const headerPayload = await headers(); + const svixId = headerPayload.get("svix-id"); + const svixTimestamp = headerPayload.get("svix-timestamp"); + const svixSignature = headerPayload.get("svix-signature"); + + // If there are no headers, error out + if (!(svixId && svixTimestamp && svixSignature)) { + return new Response("Error occured -- no svix headers", { + status: 400, + }); + } + + // Get the body + const payload = (await request.json()) as object; + const body = JSON.stringify(payload); + + // Create a new SVIX instance with your secret. + const webhook = new Webhook(env.CLERK_WEBHOOK_SECRET); + + let event: WebhookEvent | undefined; + + // Verify the payload with the headers + try { + event = webhook.verify(body, { + "svix-id": svixId, + "svix-timestamp": svixTimestamp, + "svix-signature": svixSignature, + }) as WebhookEvent; + } catch (error) { + log.error("Error verifying webhook:", { error }); + return new Response("Error occured", { + status: 400, + }); + } + + // Get the ID and type + const { id } = event.data; + const eventType = event.type; + + log.info("Webhook", { id, eventType, body }); + + let response: Response = new Response("", { status: 201 }); + + switch (eventType) { + case "user.created": { + response = handleUserCreated(event.data); + break; + } + case "user.updated": { + response = handleUserUpdated(event.data); + break; + } + case "user.deleted": { + response = handleUserDeleted(event.data); + break; + } + case "organization.created": { + response = handleOrganizationCreated(event.data); + break; + } + case "organization.updated": { + response = handleOrganizationUpdated(event.data); + break; + } + case "organizationMembership.created": { + response = handleOrganizationMembershipCreated(event.data); + break; + } + case "organizationMembership.deleted": { + response = handleOrganizationMembershipDeleted(event.data); + break; + } + default: { + break; + } + } + + await analytics?.shutdown(); + + return response; +}; diff --git a/apps/api/app/webhooks/payments/route.ts b/apps/api/app/webhooks/payments/route.ts new file mode 100644 index 0000000..2a0c719 --- /dev/null +++ b/apps/api/app/webhooks/payments/route.ts @@ -0,0 +1,117 @@ +import { analytics } from "@repo/analytics/server"; +import { clerkClient } from "@repo/auth/server"; +import { parseError } from "@repo/observability/error"; +import { log } from "@repo/observability/log"; +import type { Stripe } from "@repo/payments"; +import { cryptoProvider, stripe } from "@repo/payments"; +import { headers } from "next/headers"; +import { NextResponse } from "next/server"; +import { env } from "@/env"; + +const getUserFromCustomerId = async (customerId: string) => { + const clerk = await clerkClient(); + const users = await clerk.users.getUserList(); + + const user = users.data.find( + (currentUser) => currentUser.privateMetadata.stripeCustomerId === customerId + ); + + return user; +}; + +const handleCheckoutSessionCompleted = async ( + data: Stripe.Checkout.Session +) => { + if (!data.customer) { + return; + } + + const customerId = + typeof data.customer === "string" ? data.customer : data.customer.id; + const user = await getUserFromCustomerId(customerId); + + if (!user) { + return; + } + + analytics?.capture({ + event: "User Subscribed", + distinctId: user.id, + }); +}; + +const handleSubscriptionScheduleCanceled = async ( + data: Stripe.SubscriptionSchedule +) => { + if (!data.customer) { + return; + } + + const customerId = + typeof data.customer === "string" ? data.customer : data.customer.id; + const user = await getUserFromCustomerId(customerId); + + if (!user) { + return; + } + + analytics?.capture({ + event: "User Unsubscribed", + distinctId: user.id, + }); +}; + +export const POST = async (request: Request): Promise => { + if (!(stripe && env.STRIPE_WEBHOOK_SECRET)) { + return NextResponse.json({ message: "Not configured", ok: false }); + } + + try { + const body = await request.text(); + const headerPayload = await headers(); + const signature = headerPayload.get("stripe-signature"); + + if (!signature) { + throw new Error("missing stripe-signature header"); + } + + // The async form, over SubtleCrypto: Workers have no Node crypto. + const event = await stripe.webhooks.constructEventAsync( + body, + signature, + env.STRIPE_WEBHOOK_SECRET, + undefined, + cryptoProvider + ); + + switch (event.type) { + case "checkout.session.completed": { + await handleCheckoutSessionCompleted(event.data.object); + break; + } + case "subscription_schedule.canceled": { + await handleSubscriptionScheduleCanceled(event.data.object); + break; + } + default: { + log.warn(`Unhandled event type ${event.type}`); + } + } + + await analytics?.shutdown(); + + return NextResponse.json({ result: event, ok: true }); + } catch (error) { + const message = parseError(error); + + log.error(message); + + return NextResponse.json( + { + message: "something went wrong", + ok: false, + }, + { status: 500 } + ); + } +}; diff --git a/apps/api/cloudflare-env.d.ts b/apps/api/cloudflare-env.d.ts new file mode 100644 index 0000000..a9c2782 --- /dev/null +++ b/apps/api/cloudflare-env.d.ts @@ -0,0 +1,33 @@ +// The bindings wrangler.jsonc declares, as the Worker (and `next dev` through +// the platform proxy) sees them, plus the slice of the Workers runtime the +// custom entry (worker.ts) uses. Hand-typed rather than +// `@cloudflare/workers-types` as a global, whose `Body.json()` merges ahead +// of lib.dom's and breaks untyped `res.json()` calls. +interface CloudflareEnv { + HYPERDRIVE: { connectionString: string }; + ASSETS: { fetch(input: RequestInfo | URL, init?: RequestInit): Promise }; +} + +interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} + +interface ScheduledController { + readonly cron: string; + readonly scheduledTime: number; + noRetry(): void; +} + +interface ExportedHandler { + fetch?( + request: Request, + env: Env, + ctx: ExecutionContext + ): Response | Promise; + scheduled?( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext + ): void | Promise; +} diff --git a/apps/api/component.yaml b/apps/api/component.yaml new file mode 100644 index 0000000..6ab45cd --- /dev/null +++ b/apps/api/component.yaml @@ -0,0 +1,107 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: api + description: The API — Stripe and Clerk webhooks, health, and the daily keep-alive on a Cron Trigger (Next.js route handlers on Cloudflare Workers via @opennextjs/cloudflare, per environment) +spec: + type: cloudflare-workers-assets-turbo + lifecycle: production + owner: platform + # `product`, not `api`: a domain and a component share one name space in the + # catalog, and a domain named after a component hides it. + domain: product + path: apps/api + # Its own lane per environment: the Next.js build is the longest job in the + # plan, and a shared lane would wait on it. + lane: isolated + # THE PACKAGES IT IS BUILT FROM. The app compiles the `@repo/*` packages + # into its Worker, so a change to any of them, or to the lockfile, re-plans + # it: they belong to no component of their own. + change: + inputs: + - packages/** + - pnpm-lock.yaml + # Every SaaS the template wires is OPTIONAL, an Orun secret per environment + # that the product's owner stores when they sign up (README, "Connecting a + # service"). Best-effort, wire-now-seed-later: a key nobody has stored is + # skipped when the job resolves its secrets (no env var, no failure), and + # the Worker serves without it, saying on the page what to connect. + optionalSecretEnv: + # Public, inlined into the bundle at build time (NEXT_PUBLIC_). + NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: "secret://next-forge/next-forge/{{ .environment }}/NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY" + NEXT_PUBLIC_POSTHOG_KEY: "secret://next-forge/next-forge/{{ .environment }}/NEXT_PUBLIC_POSTHOG_KEY" + NEXT_PUBLIC_POSTHOG_HOST: "secret://next-forge/next-forge/{{ .environment }}/NEXT_PUBLIC_POSTHOG_HOST" + NEXT_PUBLIC_SENTRY_DSN: "secret://next-forge/next-forge/{{ .environment }}/NEXT_PUBLIC_SENTRY_DSN" + # Server-only: kept out of the build (`env -u` below) and handed to the + # Worker as Worker secrets before the composition deploys it. + CLERK_SECRET_KEY: "secret://next-forge/next-forge/{{ .environment }}/CLERK_SECRET_KEY" + CLERK_WEBHOOK_SECRET: "secret://next-forge/next-forge/{{ .environment }}/CLERK_WEBHOOK_SECRET" + STRIPE_SECRET_KEY: "secret://next-forge/next-forge/{{ .environment }}/STRIPE_SECRET_KEY" + STRIPE_WEBHOOK_SECRET: "secret://next-forge/next-forge/{{ .environment }}/STRIPE_WEBHOOK_SECRET" + BETTERSTACK_API_KEY: "secret://next-forge/next-forge/{{ .environment }}/BETTERSTACK_API_KEY" + BETTERSTACK_URL: "secret://next-forge/next-forge/{{ .environment }}/BETTERSTACK_URL" + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/api" + wranglerConfig: wrangler.jsonc + + # @opennextjs/cloudflare emits a Worker entrypoint plus a static-assets + # directory bound via ASSETS — both deploy in one `wrangler deploy`. The entry here is the custom worker (fetch from the generated worker + the Cron Trigger's scheduled handler); wrangler bundles the generated one into it. + workerEntrypoint: worker.ts + assetsDir: .open-next/assets + + # Per-env worker name: next-forge-api-{dev,stage,prod}. + workerName: next-forge-api + environmentAwareWorkerName: true + + # The account's workers.dev subdomain; exported to the smoke step as + # ${WORKERS_DEV_SUBDOMAIN} and used to build ${DEPLOYED_URL}. + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # Render this environment's wrangler config, then build, then hand the + # Worker its secrets. Stage and prod render from the wiring documents + # their infra applies published (secretEnv, resolved before the job's + # first step); dev, which no root applies to and which only verifies, + # renders from the committed fixture. The build is given the three + # Workers' origins for this environment (the NEXT_PUBLIC_*_URL each app + # links the others by; APP_URL, WEB_URL, API_URL override them for a + # custom domain) and none of the server secrets; then each server secret + # the environment has goes to the Worker with `wrangler secret bulk` + # (tooling/wire/worker-secrets.mjs, the values over stdin). Only the deploy + # lane holds a Cloudflare credential, so a verify lane builds the same and + # pushes nothing. + buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && env -u CLERK_SECRET_KEY -u CLERK_WEBHOOK_SECRET -u STRIPE_SECRET_KEY -u STRIPE_WEBHOOK_SECRET -u BETTERSTACK_API_KEY -u BETTERSTACK_URL NEXT_PUBLIC_APP_URL="${APP_URL:-https://next-forge-app-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" NEXT_PUBLIC_WEB_URL="${WEB_URL:-https://next-forge-web-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" NEXT_PUBLIC_API_URL="${API_URL:-https://next-forge-api-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" pnpm exec turbo run build --filter=@app/api && node ../../tooling/wire/worker-secrets.mjs --secret CLERK_SECRET_KEY --secret CLERK_WEBHOOK_SECRET --secret STRIPE_SECRET_KEY --secret STRIPE_WEBHOOK_SECRET --secret BETTERSTACK_API_KEY --secret BETTERSTACK_URL --worker "next-forge-api-${ORUN_ENVIRONMENT}" --config wrangler.jsonc + + # Smoke: /health answers OK, and /cron/keep-alive — the route the daily + # Cron Trigger runs — answers OK, which only this Worker can, by writing + # one row into the migrated "Page" table through its HYPERDRIVE binding + # and deleting the same row: what the trigger does every day, leaving + # nothing behind. + smokeCommand: "test \"$(curl -sf \"${DEPLOYED_URL}/health\")\" = OK && test \"$(curl -sf \"${DEPLOYED_URL}/cron/keep-alive\")\" = OK" + labels: + team: platform + layer: delivery + surface: api + runtime: cloudflare diff --git a/apps/api/env.ts b/apps/api/env.ts new file mode 100644 index 0000000..0bf0abc --- /dev/null +++ b/apps/api/env.ts @@ -0,0 +1,24 @@ +import { keys as analytics } from "@repo/analytics/keys"; +import { keys as auth } from "@repo/auth/keys"; +import { keys as database } from "@repo/database/keys"; +import { keys as email } from "@repo/email/keys"; +import { keys as core } from "@repo/next-config/keys"; +import { keys as observability } from "@repo/observability/keys"; +import { keys as payments } from "@repo/payments/keys"; +import { createEnv } from "@t3-oss/env-nextjs"; + +export const env = createEnv({ + skipValidation: process.env.SKIP_ENV_VALIDATION === "true", + extends: [ + auth(), + analytics(), + core(), + database(), + email(), + observability(), + payments(), + ], + server: {}, + client: {}, + runtimeEnv: {}, +}); diff --git a/apps/api/eslint.config.mjs b/apps/api/eslint.config.mjs new file mode 100644 index 0000000..c67a2a6 --- /dev/null +++ b/apps/api/eslint.config.mjs @@ -0,0 +1,29 @@ +// next-forge lints with Biome (ultracite); a baseline lints with ESLint 9. +// eslint-config-next 16's flat configs, as `create-next-app` generates them. +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +export default defineConfig([ + ...nextVitals, + ...nextTs, + { + rules: { + // worker.ts imports the generated `.open-next/worker.js` the way the + // OpenNext custom-worker guide does: `@ts-ignore` with a reason, + // because the file does not exist before the build and an + // `@ts-expect-error` would be "unused" after it. + "@typescript-eslint/ban-ts-comment": [ + "error", + { "ts-ignore": "allow-with-description" }, + ], + }, + }, + globalIgnores([ + ".next/**", + ".open-next/**", + ".wrangler/**", + "next-env.d.ts", + "cloudflare-env.d.ts", + ]), +]); diff --git a/apps/api/instrumentation-client.ts b/apps/api/instrumentation-client.ts new file mode 100644 index 0000000..7e1e65c --- /dev/null +++ b/apps/api/instrumentation-client.ts @@ -0,0 +1,7 @@ +import { initializeAnalytics } from "@repo/analytics/instrumentation-client"; +import { initializeSentry } from "@repo/observability/client"; + +initializeSentry(); +initializeAnalytics(); + +export { onRouterTransitionStart } from "@repo/observability/client"; diff --git a/apps/api/instrumentation.ts b/apps/api/instrumentation.ts new file mode 100644 index 0000000..e4bdd87 --- /dev/null +++ b/apps/api/instrumentation.ts @@ -0,0 +1,4 @@ +import { initializeSentry } from "@repo/observability/instrumentation"; + +export const register = initializeSentry; +export { onRequestError } from "@repo/observability/instrumentation"; diff --git a/apps/api/next.config.ts b/apps/api/next.config.ts new file mode 100644 index 0000000..3e52d40 --- /dev/null +++ b/apps/api/next.config.ts @@ -0,0 +1,35 @@ +import path from "node:path"; +import { initOpenNextCloudflareForDev } from "@opennextjs/cloudflare"; +import { config, withAnalyzer } from "@repo/next-config"; +import { workspacePackages } from "@repo/next-config/transpile"; +import type { NextConfig } from "next"; +import { PHASE_DEVELOPMENT_SERVER } from "next/constants"; +import { env } from "@/env"; + +// Upstream wraps the config in BetterStack and (on Vercel) Sentry; neither +// runs on Workers (@repo/observability). +let nextConfig: NextConfig = { + ...config, + // Required by @opennextjs/cloudflare, which bundles `.next/standalone/**` + // into the Worker. Traced from the monorepo root so the workspace packages + // resolve from the root node_modules. + output: "standalone", + outputFileTracingRoot: path.join(__dirname, "../.."), + transpilePackages: workspacePackages(__dirname), +}; + +if (env.ANALYZE === "true") { + nextConfig = withAnalyzer(nextConfig); +} + +// `next dev` reaches the Worker's bindings (HYPERDRIVE) through wrangler's +// platform proxy, from apps/api/wrangler.jsonc. +// Only under `next dev`: the proxy would open its session at `next build` +// too (Workers AI has no local mode, so a remote one, which needs a +// Cloudflare login), and the build reads no binding. +export default (phase: string): NextConfig => { + if (phase === PHASE_DEVELOPMENT_SERVER) { + initOpenNextCloudflareForDev(); + } + return nextConfig; +}; diff --git a/apps/api/open-next.config.ts b/apps/api/open-next.config.ts new file mode 100644 index 0000000..8e2568b --- /dev/null +++ b/apps/api/open-next.config.ts @@ -0,0 +1,15 @@ +// OpenNext Cloudflare adapter config. +// +// Every route of this template renders per request — the root layout reads +// the session cookie, the pricing page reads Stripe — so the build +// pre-renders nothing and no incremental cache is exercised. The read-only +// static-assets cache is kept as the default that costs nothing to +// provision: a page that becomes static later is served from it, and a page +// that revalidates for real (ISR, `revalidateTag`) is the signal to swap in +// the R2 incremental cache plus a tag cache. +import { defineCloudflareConfig } from '@opennextjs/cloudflare/config'; +import staticAssetsIncrementalCache from '@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache'; + +export default defineCloudflareConfig({ + incrementalCache: staticAssetsIncrementalCache +}); diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..e728508 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,41 @@ +{ + "name": "@app/api", + "private": true, + "scripts": { + "dev": "next dev -p 3002", + "build": "next build --webpack && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck", + "start": "next start -p 3002", + "preview": "opennextjs-cloudflare preview", + "typecheck": "tsc --noEmit", + "lint": "eslint .", + "wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json --env stage" + }, + "dependencies": { + "@opennextjs/cloudflare": "1.20.13", + "@repo/analytics": "workspace:*", + "@repo/auth": "workspace:*", + "@repo/database": "workspace:*", + "@repo/design-system": "workspace:*", + "@repo/email": "workspace:*", + "@repo/next-config": "workspace:*", + "@repo/observability": "workspace:*", + "@repo/payments": "workspace:*", + "@t3-oss/env-nextjs": "^0.13.10", + "next": "16.4.3", + "react": "19.2.4", + "react-dom": "19.2.4", + "svix": "^1.86.0", + "zod": "^4.3.6" + }, + "devDependencies": { + "@repo/typescript-config": "workspace:*", + "@types/node": "25.3.5", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "typescript": "^5.9.3", + "wrangler": "^4.151.0", + "@app/eslint-config": "workspace:*", + "eslint": "^9.27.0", + "eslint-config-next": "16.4.3" + } +} diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..75ccf4a --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,26 @@ +{ + "extends": "@repo/typescript-config/nextjs.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@/*": [ + "./*" + ], + "@repo/*": [ + "../../packages/*" + ] + } + }, + "include": [ + "next-env.d.ts", + "cloudflare-env.d.ts", + "next.config.ts", + "**/*.ts", + "**/*.tsx", + ".next/types/**/*.ts" + ], + "exclude": [ + "node_modules", + ".open-next" + ] +} diff --git a/apps/api/turbo.json b/apps/api/turbo.json new file mode 100644 index 0000000..f5fe99c --- /dev/null +++ b/apps/api/turbo.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://turbo.build/schema.json", + "extends": ["//"], + "tasks": { + "build": { + "dependsOn": ["^build"], + "outputs": [".open-next/**", ".next/**", "!.next/cache/**"] + } + } +} diff --git a/apps/api/wiring.fixture.json b/apps/api/wiring.fixture.json new file mode 100644 index 0000000..58999bb --- /dev/null +++ b/apps/api/wiring.fixture.json @@ -0,0 +1,14 @@ +{ + "cloudflare-hyperdrive/dev": { + "hyperdrive_id": "00000000000000000000000000000002", + "hyperdrive_name": "dev-next-forge-dev" + }, + "cloudflare-hyperdrive/stage": { + "hyperdrive_id": "00000000000000000000000000000001", + "hyperdrive_name": "stg-next-forge-stage" + }, + "cloudflare-hyperdrive/prod": { + "hyperdrive_id": "00000000000000000000000000000003", + "hyperdrive_name": "prod-next-forge-prod" + } +} diff --git a/apps/api/worker.ts b/apps/api/worker.ts new file mode 100644 index 0000000..5ef6296 --- /dev/null +++ b/apps/api/worker.ts @@ -0,0 +1,36 @@ +// The API Worker's entry (wrangler `main`). @opennextjs/cloudflare generates a +// worker that exports only `fetch`; this keeps that handler and adds the +// `scheduled` handler the Cron Trigger calls, as the adapter's custom-worker +// guide describes (https://opennext.js.org/cloudflare/howtos/custom-worker). +// +// Upstream's vercel.json ran GET /cron/keep-alive once a day; the Cron Trigger +// (wrangler.jsonc `triggers.crons`) runs the same route, through the same +// fetch handler, so the route stays the one place the work is. +// @ts-ignore -- `.open-next/worker.js` is generated at build time (an +// expect-error directive would be unused once it exists) +import { default as handler } from "./.open-next/worker.js"; + +// A Worker module exports handlers only, so the path is not exported. +const KEEP_ALIVE_PATH = "/cron/keep-alive"; + +const worker = { + fetch: handler.fetch, + async scheduled( + _controller: ScheduledController, + env: CloudflareEnv, + ctx: ExecutionContext + ) { + const response = await handler.fetch( + new Request(`https://cron.internal${KEEP_ALIVE_PATH}`, { + headers: { "user-agent": "cloudflare-cron" }, + }), + env, + ctx + ); + if (!response.ok) { + throw new Error(`${KEEP_ALIVE_PATH} answered ${response.status}`); + } + }, +} satisfies ExportedHandler; + +export default worker; diff --git a/apps/api/wrangler.jsonc b/apps/api/wrangler.jsonc new file mode 100644 index 0000000..2fe8717 --- /dev/null +++ b/apps/api/wrangler.jsonc @@ -0,0 +1,37 @@ +// GENERATED from wrangler.template.jsonc by tooling/wire — edit the +// template, not this file. The committed copy is the fixture render +// (`pnpm run wire:fixture`); every Orun lane renders its own environment. +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "next-forge-api", + // The custom entry: the fetch handler @opennextjs/cloudflare generates plus + // the `scheduled` handler the Cron Trigger calls (worker.ts). + "main": "worker.ts", + "compatibility_date": "2026-10-01", + "compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"], + "assets": { + "directory": ".open-next/assets", + "binding": "ASSETS" + }, + // Workers Logs: where upstream's Sentry and BetterStack logging went + // (@repo/observability). + "observability": { "enabled": true }, + // Upstream's vercel.json cron, daily at midnight UTC: /cron/keep-alive + // writes and deletes a row, so a Supabase free project (which pauses after + // a week idle, as Neon's did) stays awake. One trigger per Worker — two for + // stage and prod — fits Workers Free's five per account. + "triggers": { + "crons": ["0 0 * * *"] + }, + // The Supabase project's Postgres, fronted by Hyperdrive (@repo/database). + "hyperdrive": [ + { + "binding": "HYPERDRIVE", + "id": "00000000000000000000000000000001", + "localConnectionString": "postgres://postgres:postgres@localhost:54322/postgres" + } + ] + // Secrets are never vars. Stripe's and Clerk's webhook secrets, Stripe's + // key, PostHog, Sentry and BetterStack are optional: Orun secrets the + // deploy hands to this Worker (component.yaml). Locally, .dev.vars. +} diff --git a/apps/api/wrangler.template.jsonc b/apps/api/wrangler.template.jsonc new file mode 100644 index 0000000..60f1721 --- /dev/null +++ b/apps/api/wrangler.template.jsonc @@ -0,0 +1,43 @@ +// The source of wrangler.jsonc, which tooling/wire renders from it: from +// wiring.fixture.json for local work (`pnpm run wire:fixture`, committed as +// that render), and on every Orun lane from the wiring document the +// `cloudflare-hyperdrive` Terraform root lease-publishes +// (WIRING_CLOUDFLARE_HYPERDRIVE_) — dev, which no root applies to, from +// the fixture (component.yaml's buildCommand). Edit this file, never +// wrangler.jsonc. The workers-assets composition deploys one environment per +// job with no wrangler `--env`, so `__ENV__` names the environment this is +// rendered for. +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "next-forge-api", + // The custom entry: the fetch handler @opennextjs/cloudflare generates plus + // the `scheduled` handler the Cron Trigger calls (worker.ts). + "main": "worker.ts", + "compatibility_date": "2026-10-01", + "compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"], + "assets": { + "directory": ".open-next/assets", + "binding": "ASSETS" + }, + // Workers Logs: where upstream's Sentry and BetterStack logging went + // (@repo/observability). + "observability": { "enabled": true }, + // Upstream's vercel.json cron, daily at midnight UTC: /cron/keep-alive + // writes and deletes a row, so a Supabase free project (which pauses after + // a week idle, as Neon's did) stays awake. One trigger per Worker — two for + // stage and prod — fits Workers Free's five per account. + "triggers": { + "crons": ["0 0 * * *"] + }, + // The Supabase project's Postgres, fronted by Hyperdrive (@repo/database). + "hyperdrive": [ + { + "binding": "HYPERDRIVE", + "id": "@@wiring(cloudflare-hyperdrive/__ENV__:hyperdrive_id)@@", + "localConnectionString": "postgres://postgres:postgres@localhost:54322/postgres" + } + ] + // Secrets are never vars. Stripe's and Clerk's webhook secrets, Stripe's + // key, PostHog, Sentry and BetterStack are optional: Orun secrets the + // deploy hands to this Worker (component.yaml). Locally, .dev.vars. +} diff --git a/apps/app/.env.example b/apps/app/.env.example new file mode 100644 index 0000000..dafb63f --- /dev/null +++ b/apps/app/.env.example @@ -0,0 +1,36 @@ +# Every key here is optional: with none set the app runs — Clerk as a sample +# user, BaseHub as sample content, the rest switched off — and says what to +# connect. For `next dev`, copy this to .env.local. Under `wrangler dev` +# (`pnpm preview`) the server-only keys go in .dev.vars instead. Deployed, +# each is an Orun secret of the same name (component.yaml). +# Server +CLERK_SECRET_KEY="" +CLERK_WEBHOOK_SECRET="" +RESEND_FROM="" +DATABASE_URL="postgres://postgres:postgres@localhost:54322/postgres" +RESEND_TOKEN="" +STRIPE_SECRET_KEY="" +STRIPE_WEBHOOK_SECRET="" +BETTERSTACK_API_KEY="" +BETTERSTACK_URL="" +FLAGS_SECRET="" +SVIX_TOKEN="" +LIVEBLOCKS_SECRET="" +BASEHUB_TOKEN="" +KNOCK_API_KEY="" +KNOCK_FEED_CHANNEL_ID="" +KNOCK_SECRET_API_KEY="" + +# Client +NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="" +NEXT_PUBLIC_CLERK_SIGN_IN_URL="/sign-in" +NEXT_PUBLIC_CLERK_SIGN_UP_URL="/sign-up" +NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL="/" +NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL="/" +NEXT_PUBLIC_GA_MEASUREMENT_ID="" +NEXT_PUBLIC_KNOCK_API_KEY="" +NEXT_PUBLIC_KNOCK_FEED_CHANNEL_ID="" +NEXT_PUBLIC_POSTHOG_KEY="" +NEXT_PUBLIC_POSTHOG_HOST="" +NEXT_PUBLIC_APP_URL="http://localhost:3000" +NEXT_PUBLIC_WEB_URL="http://localhost:3001" diff --git a/apps/app/.env.production b/apps/app/.env.production new file mode 100644 index 0000000..5041fcd --- /dev/null +++ b/apps/app/.env.production @@ -0,0 +1,7 @@ +# The origins the three Workers link to each other by, inlined at build time +# (NEXT_PUBLIC_). These are stage's workers.dev URLs, for a local +# `pnpm build`; every Orun lane builds with its own environment's +# (component.yaml's buildCommand), which wins over this file. +NEXT_PUBLIC_APP_URL=https://next-forge-app-stage.your-workers-subdomain.workers.dev +NEXT_PUBLIC_WEB_URL=https://next-forge-web-stage.your-workers-subdomain.workers.dev +NEXT_PUBLIC_API_URL=https://next-forge-api-stage.your-workers-subdomain.workers.dev diff --git a/apps/app/.gitignore b/apps/app/.gitignore new file mode 100644 index 0000000..7f3818c --- /dev/null +++ b/apps/app/.gitignore @@ -0,0 +1,4 @@ +# local state wrangler and the Cloudflare adapter write +.wrangler/ +.open-next/ +.dev.vars diff --git a/apps/app/app/(authenticated)/components/avatar-stack.tsx b/apps/app/app/(authenticated)/components/avatar-stack.tsx new file mode 100644 index 0000000..840b7b1 --- /dev/null +++ b/apps/app/app/(authenticated)/components/avatar-stack.tsx @@ -0,0 +1,58 @@ +"use client"; + +import { useOthers, useSelf } from "@repo/collaboration/hooks"; +import { + Avatar, + AvatarFallback, + AvatarImage, +} from "@repo/design-system/components/ui/avatar"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@repo/design-system/components/ui/tooltip"; + +interface PresenceAvatarProps { + info?: Liveblocks["UserMeta"]["info"]; +} + +const PresenceAvatar = ({ info }: PresenceAvatarProps) => ( + + + + + + {info?.name?.slice(0, 2)} + + + + +

{info?.name ?? "Unknown"}

+
+
+); + +export const AvatarStack = () => { + const others = useOthers(); + const self = useSelf(); + const hasMoreUsers = others.length > 3; + + return ( +
+ {others.slice(0, 3).map(({ connectionId, info }) => ( + + ))} + + {hasMoreUsers && ( + + )} + + {self && } +
+ ); +}; diff --git a/apps/app/app/(authenticated)/components/collaboration-provider.tsx b/apps/app/app/(authenticated)/components/collaboration-provider.tsx new file mode 100644 index 0000000..7ea8219 --- /dev/null +++ b/apps/app/app/(authenticated)/components/collaboration-provider.tsx @@ -0,0 +1,48 @@ +"use client"; + +import { Room } from "@repo/collaboration/room"; +import type { ReactNode } from "react"; +import { getUsers } from "@/app/actions/users/get"; +import { searchUsers } from "@/app/actions/users/search"; + +export const CollaborationProvider = ({ + orgId, + children, +}: { + orgId: string; + children: ReactNode; +}) => { + const resolveUsers = async ({ userIds }: { userIds: string[] }) => { + const response = await getUsers(userIds); + + if ("error" in response) { + throw new Error("Problem resolving users"); + } + + return response.data; + }; + + const resolveMentionSuggestions = async ({ text }: { text: string }) => { + const response = await searchUsers(text); + + if ("error" in response) { + throw new Error("Problem resolving mention suggestions"); + } + + return response.data; + }; + + return ( + Loading... + } + id={`${orgId}:presence`} + resolveMentionSuggestions={resolveMentionSuggestions} + resolveUsers={resolveUsers} + > + {children} + + ); +}; diff --git a/apps/app/app/(authenticated)/components/cursors.tsx b/apps/app/app/(authenticated)/components/cursors.tsx new file mode 100644 index 0000000..40bcad2 --- /dev/null +++ b/apps/app/app/(authenticated)/components/cursors.tsx @@ -0,0 +1,106 @@ +"use client"; + +import { useMyPresence, useOthers } from "@repo/collaboration/hooks"; +import { useEffect } from "react"; + +const Cursor = ({ + name, + color, + x, + y, +}: { + name: string | undefined; + color: string; + x: number; + y: number; +}) => ( +
+ + Cursor + + +
+ {name} +
+
+); + +export const Cursors = () => { + /** + * useMyPresence returns the presence of the current user and a function to update it. + * updateMyPresence is different than the setState function returned by the useState hook from React. + * You don't need to pass the full presence object to update it. + * See https://liveblocks.io/docs/api-reference/liveblocks-react#useMyPresence for more information + */ + const [_cursor, updateMyPresence] = useMyPresence(); + + /** + * Return all the other users in the room and their presence (a cursor position in this case) + */ + const others = useOthers(); + + useEffect(() => { + const onPointerMove = (event: PointerEvent) => { + // Update the user cursor position on every pointer move + updateMyPresence({ + cursor: { + x: Math.round(event.clientX), + y: Math.round(event.clientY), + }, + }); + }; + + const onPointerLeave = () => { + // When the pointer goes out, set cursor to null + updateMyPresence({ + cursor: null, + }); + }; + + document.body.addEventListener("pointermove", onPointerMove); + document.body.addEventListener("pointerleave", onPointerLeave); + + return () => { + document.body.removeEventListener("pointermove", onPointerMove); + document.body.removeEventListener("pointerleave", onPointerLeave); + }; + }, [updateMyPresence]); + + return others.map(({ connectionId, presence, info }) => { + if (!presence.cursor) { + return null; + } + + return ( + + ); + }); +}; diff --git a/apps/app/app/(authenticated)/components/header.tsx b/apps/app/app/(authenticated)/components/header.tsx new file mode 100644 index 0000000..4bc1ca7 --- /dev/null +++ b/apps/app/app/(authenticated)/components/header.tsx @@ -0,0 +1,43 @@ +import { + Breadcrumb, + BreadcrumbItem, + BreadcrumbLink, + BreadcrumbList, + BreadcrumbPage, + BreadcrumbSeparator, +} from "@repo/design-system/components/ui/breadcrumb"; +import { Separator } from "@repo/design-system/components/ui/separator"; +import { SidebarTrigger } from "@repo/design-system/components/ui/sidebar"; +import { Fragment, type ReactNode } from "react"; + +interface HeaderProps { + children?: ReactNode; + page: string; + pages: string[]; +} + +export const Header = ({ pages, page, children }: HeaderProps) => ( +
+
+ + + + + {pages.map((page, index) => ( + + {index > 0 && } + + {page} + + + ))} + + + {page} + + + +
+ {children} +
+); diff --git a/apps/app/app/(authenticated)/components/notifications-provider.tsx b/apps/app/app/(authenticated)/components/notifications-provider.tsx new file mode 100644 index 0000000..eaf7ab9 --- /dev/null +++ b/apps/app/app/(authenticated)/components/notifications-provider.tsx @@ -0,0 +1,26 @@ +"use client"; + +import { NotificationsProvider as RawNotificationsProvider } from "@repo/notifications/components/provider"; +import { useTheme } from "next-themes"; +import type { ReactNode } from "react"; + +interface NotificationsProviderProperties { + children: ReactNode; + userId: string; +} + +export const NotificationsProvider = ({ + children, + userId, +}: NotificationsProviderProperties) => { + const { resolvedTheme } = useTheme(); + + return ( + + {children} + + ); +}; diff --git a/apps/app/app/(authenticated)/components/search.tsx b/apps/app/app/(authenticated)/components/search.tsx new file mode 100644 index 0000000..5562eb6 --- /dev/null +++ b/apps/app/app/(authenticated)/components/search.tsx @@ -0,0 +1,26 @@ +import { Button } from "@repo/design-system/components/ui/button"; +import { Input } from "@repo/design-system/components/ui/input"; +import { ArrowRightIcon, SearchIcon } from "lucide-react"; + +export const Search = () => ( +
+
+
+ +
+ + +
+
+); diff --git a/apps/app/app/(authenticated)/components/sidebar.tsx b/apps/app/app/(authenticated)/components/sidebar.tsx new file mode 100644 index 0000000..b79d859 --- /dev/null +++ b/apps/app/app/(authenticated)/components/sidebar.tsx @@ -0,0 +1,359 @@ +"use client"; + +import { OrganizationSwitcher, UserButton } from "@repo/auth/client"; +import { ModeToggle } from "@repo/design-system/components/mode-toggle"; +import { Button } from "@repo/design-system/components/ui/button"; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@repo/design-system/components/ui/collapsible"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@repo/design-system/components/ui/dropdown-menu"; +import { + Sidebar, + SidebarContent, + SidebarFooter, + SidebarGroup, + SidebarGroupContent, + SidebarGroupLabel, + SidebarHeader, + SidebarInset, + SidebarMenu, + SidebarMenuAction, + SidebarMenuButton, + SidebarMenuItem, + SidebarMenuSub, + SidebarMenuSubButton, + SidebarMenuSubItem, + useSidebar, +} from "@repo/design-system/components/ui/sidebar"; +import { cn } from "@repo/design-system/lib/utils"; +import { NotificationsTrigger } from "@repo/notifications/components/trigger"; +import { + AnchorIcon, + BookOpenIcon, + BotIcon, + ChevronRightIcon, + FolderIcon, + FrameIcon, + LifeBuoyIcon, + MapIcon, + MoreHorizontalIcon, + PieChartIcon, + SendIcon, + Settings2Icon, + ShareIcon, + SquareTerminalIcon, + Trash2Icon, +} from "lucide-react"; +import Link from "next/link"; +import type { ReactNode } from "react"; +import { Search } from "./search"; + +interface GlobalSidebarProperties { + readonly children: ReactNode; +} + +const data = { + user: { + name: "shadcn", + email: "m@example.com", + avatar: "/avatars/shadcn.jpg", + }, + navMain: [ + { + title: "Playground", + url: "#", + icon: SquareTerminalIcon, + isActive: true, + items: [ + { + title: "History", + url: "#", + }, + { + title: "Starred", + url: "#", + }, + { + title: "Settings", + url: "#", + }, + ], + }, + { + title: "Models", + url: "#", + icon: BotIcon, + items: [ + { + title: "Genesis", + url: "#", + }, + { + title: "Explorer", + url: "#", + }, + { + title: "Quantum", + url: "#", + }, + ], + }, + { + title: "Documentation", + url: "#", + icon: BookOpenIcon, + items: [ + { + title: "Introduction", + url: "#", + }, + { + title: "Get Started", + url: "#", + }, + { + title: "Tutorials", + url: "#", + }, + { + title: "Changelog", + url: "#", + }, + ], + }, + { + title: "Settings", + url: "#", + icon: Settings2Icon, + items: [ + { + title: "General", + url: "#", + }, + { + title: "Team", + url: "#", + }, + { + title: "Billing", + url: "#", + }, + { + title: "Limits", + url: "#", + }, + ], + }, + ], + navSecondary: [ + { + title: "Webhooks", + url: "/webhooks", + icon: AnchorIcon, + }, + { + title: "Support", + url: "#", + icon: LifeBuoyIcon, + }, + { + title: "Feedback", + url: "#", + icon: SendIcon, + }, + ], + projects: [ + { + name: "Design Engineering", + url: "#", + icon: FrameIcon, + }, + { + name: "Sales & Marketing", + url: "#", + icon: PieChartIcon, + }, + { + name: "Travel", + url: "#", + icon: MapIcon, + }, + ], +}; + +export const GlobalSidebar = ({ children }: GlobalSidebarProperties) => { + const sidebar = useSidebar(); + + return ( + <> + + + + +
div]:w-full", + sidebar.open ? "" : "-mx-1" + )} + > + +
+
+
+
+ + + + Platform + + {data.navMain.map((item) => ( + + + + + + {item.title} + + + {item.items?.length ? ( + <> + + + + Toggle + + + + + {item.items?.map((subItem) => ( + + + + {subItem.title} + + + + ))} + + + + ) : null} + + + ))} + + + + Projects + + {data.projects.map((item) => ( + + + + + {item.name} + + + + + + + More + + + + + + View Project + + + + Share Project + + + + + Delete Project + + + + + ))} + + + + More + + + + + + + + {data.navSecondary.map((item) => ( + + + + + {item.title} + + + + ))} + + + + + + + + +
+ + +
+
+
+
+
+ {children} + + ); +}; diff --git a/apps/app/app/(authenticated)/layout.tsx b/apps/app/app/(authenticated)/layout.tsx new file mode 100644 index 0000000..475d521 --- /dev/null +++ b/apps/app/app/(authenticated)/layout.tsx @@ -0,0 +1,43 @@ +import { SampleUserNotice } from "@repo/auth/components/not-connected"; +import { auth, currentUser, isClerkConfigured } from "@repo/auth/server"; +import { SidebarProvider } from "@repo/design-system/components/ui/sidebar"; +import { showBetaFeature } from "@repo/feature-flags"; +import type { ReactNode } from "react"; +import { NotificationsProvider } from "./components/notifications-provider"; +import { GlobalSidebar } from "./components/sidebar"; + +interface AppLayoutProperties { + readonly children: ReactNode; +} + +const AppLayout = async ({ children }: AppLayoutProperties) => { + const user = await currentUser(); + const { redirectToSignIn } = await auth(); + const betaFeature = await showBetaFeature(); + + if (!user) { + return redirectToSignIn(); + } + + return ( + + + + {!isClerkConfigured() && ( +
+ +
+ )} + {betaFeature && ( +
+ Beta feature now available +
+ )} + {children} +
+
+
+ ); +}; + +export default AppLayout; diff --git a/apps/app/app/(authenticated)/page.tsx b/apps/app/app/(authenticated)/page.tsx new file mode 100644 index 0000000..9eb23b6 --- /dev/null +++ b/apps/app/app/(authenticated)/page.tsx @@ -0,0 +1,60 @@ +import { auth } from "@repo/auth/server"; +import { database } from "@repo/database"; +import type { Metadata } from "next"; +import dynamic from "next/dynamic"; +import { notFound } from "next/navigation"; +import { env } from "@/env"; +import { AvatarStack } from "./components/avatar-stack"; +import { Cursors } from "./components/cursors"; +import { Header } from "./components/header"; + +const title = "Acme Inc"; +const description = "My application."; + +const CollaborationProvider = dynamic(() => + import("./components/collaboration-provider").then( + (mod) => mod.CollaborationProvider + ) +); + +export const metadata: Metadata = { + title, + description, +}; + +const App = async () => { + const pages = await database.page.findMany(); + const { orgId } = await auth(); + + if (!orgId) { + notFound(); + } + + return ( + <> +
+ {env.LIVEBLOCKS_SECRET && ( + + + + + )} +
+
+
+ {pages.map((page) => ( +
+ {page.name} +
+ ))} +
+
+
+ + ); +}; + +export default App; diff --git a/apps/app/app/(authenticated)/search/page.tsx b/apps/app/app/(authenticated)/search/page.tsx new file mode 100644 index 0000000..4082800 --- /dev/null +++ b/apps/app/app/(authenticated)/search/page.tsx @@ -0,0 +1,59 @@ +import { auth } from "@repo/auth/server"; +import { database } from "@repo/database"; +import { notFound, redirect } from "next/navigation"; +import { Header } from "../components/header"; + +interface SearchPageProperties { + searchParams: Promise<{ + q: string; + }>; +} + +export const generateMetadata = async ({ + searchParams, +}: SearchPageProperties) => { + const { q } = await searchParams; + + return { + title: `${q} - Search results`, + description: `Search results for ${q}`, + }; +}; + +const SearchPage = async ({ searchParams }: SearchPageProperties) => { + const { q } = await searchParams; + const pages = await database.page.findMany({ + where: { + name: { + contains: q, + }, + }, + }); + const { orgId } = await auth(); + + if (!orgId) { + notFound(); + } + + if (!q) { + redirect("/"); + } + + return ( + <> +
+
+
+ {pages.map((page) => ( +
+ {page.name} +
+ ))} +
+
+
+ + ); +}; + +export default SearchPage; diff --git a/apps/app/app/(authenticated)/webhooks/page.tsx b/apps/app/app/(authenticated)/webhooks/page.tsx new file mode 100644 index 0000000..854ad18 --- /dev/null +++ b/apps/app/app/(authenticated)/webhooks/page.tsx @@ -0,0 +1,43 @@ +import { isWebhooksConfigured, webhooks } from "@repo/webhooks"; +import { notFound } from "next/navigation"; + +export const metadata = { + title: "Webhooks", + description: "Send webhooks to your users.", +}; + +const WebhooksPage = async () => { + if (!isWebhooksConfigured()) { + return ( +
+ Webhooks are not connected: store a Svix API key as this + product's SVIX_TOKEN secret to give your users a + webhooks portal here. +
+ ); + } + + const response = await webhooks.getAppPortal(); + + if (!response?.url) { + notFound(); + } + + return ( +
+