This commit is contained in:
Andras Bacsai 2022-12-12 08:44:23 +01:00
parent f55b861849
commit c445fc0f8a
44 changed files with 3130 additions and 53 deletions

1
.gitignore vendored
View File

@ -8,7 +8,6 @@ package
.env.*
!.env.example
dist
client
apps/api/db/*.db
apps/api/db/migration.db-journal
apps/api/core*

View File

@ -25,7 +25,7 @@ CREATE TABLE "new_Setting" (
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
INSERT INTO "new_Setting" ("DNSServers", "applicationStoragePathMigrationFinished", "arch", "concurrentBuilds", "createdAt", "doNotTrack", "dualCerts", "fqdn", "id", "ipv4", "ipv6", "isAPIDebuggingEnabled", "isAutoUpdateEnabled", "isDNSCheckEnabled", "isRegistrationEnabled", "isTraefikUsed", "maxPort", "minPort", "numberOfDockerImagesKeptLocally", "proxyDefaultRedirect", "sentryDSN", "updatedAt") SELECT "DNSServers", "applicationStoragePathMigrationFinished", "arch", "concurrentBuilds", "createdAt", "doNotTrack", "dualCerts", "fqdn", "id", "ipv4", "ipv6", "isAPIDebuggingEnabled", "isAutoUpdateEnabled", "isDNSCheckEnabled", "isRegistrationEnabled", "isTraefikUsed", "maxPort", "minPort", "numberOfDockerImagesKeptLocally", "proxyDefaultRedirect", "sentryDSN", "updatedAt" FROM "Setting";
INSERT INTO "new_Setting" ("DNSServers", "applicationStoragePathMigrationFinished", "arch", "concurrentBuilds", "createdAt", "doNotTrack", "dualCerts", "fqdn", "id", "ipv4", "ipv6", "isAPIDebuggingEnabled", "isAutoUpdateEnabled", "isDNSCheckEnabled", "isRegistrationEnabled", "isTraefikUsed", "maxPort", "minPort", "numberOfDockerImagesKeptLocally", "proxyDefaultRedirect", "sentryDSN", "updatedAt") SELECT "DNSServers", "applicationStoragePathMigrationFinished", "arch", "concurrentBuilds", "createdAt", "doNotTrack", "dualCerts", "fqdn", "id", "ipv4", "ipv6", "isAPIDebuggingEnabled", "isAutoUpdateEnabled", "isDNSCheckEnabled", "isRegistrationEnabled", "isTraefikUsed", "maxPort", "minPort", 3, "proxyDefaultRedirect", "sentryDSN", "updatedAt" FROM "Setting";
DROP TABLE "Setting";
ALTER TABLE "new_Setting" RENAME TO "Setting";
CREATE UNIQUE INDEX "Setting_fqdn_key" ON "Setting"("fqdn");

13
apps/client/.eslintignore Normal file
View File

@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

20
apps/client/.eslintrc.cjs Normal file
View File

@ -0,0 +1,20 @@
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
plugins: ['svelte3', '@typescript-eslint'],
ignorePatterns: ['*.cjs'],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
},
env: {
browser: true,
es2017: true,
node: true
}
};

10
apps/client/.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
apps/client/.npmrc Normal file
View File

@ -0,0 +1 @@
engine-strict=true

View File

@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

9
apps/client/.prettierrc Normal file
View File

@ -0,0 +1,9 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"pluginSearchDirs": ["."],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

1
apps/client/README.md Normal file
View File

@ -0,0 +1 @@
# SvelteKit Static site

46
apps/client/package.json Normal file
View File

@ -0,0 +1,46 @@
{
"name": "client",
"description": "Coolify's SvelteKit UI",
"license": "Apache-2.0",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build && cp -Pr build/ ../../build/public",
"preview": "vite preview",
"test": "playwright test",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --plugin-search-dir . --check . && eslint .",
"format": "prettier --plugin-search-dir . --write ."
},
"devDependencies": {
"@playwright/test": "1.28.1",
"@sveltejs/adapter-static": "1.0.0-next.48",
"@sveltejs/kit": "1.0.0-next.572",
"@typescript-eslint/eslint-plugin": "5.44.0",
"@typescript-eslint/parser": "5.44.0",
"autoprefixer": "10.4.13",
"eslint": "8.28.0",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-svelte3": "4.0.0",
"postcss": "8.4.19",
"postcss-load-config": "4.0.1",
"prettier": "2.8.0",
"prettier-plugin-svelte": "2.8.1",
"svelte": "3.53.1",
"svelte-check": "2.9.2",
"svelte-preprocess": "^4.10.7",
"tailwindcss": "3.2.4",
"tslib": "2.4.1",
"typescript": "4.9.3",
"vite": "3.2.4"
},
"type": "module",
"dependencies": {
"js-cookie": "3.0.1",
"@trpc/client": "10.1.0",
"@trpc/server": "10.1.0",
"server": "workspace:*",
"superjson": "1.11.0"
}
}

View File

@ -0,0 +1,10 @@
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
webServer: {
command: 'npm run build && npm run preview',
port: 4173
}
};
export default config;

1793
apps/client/pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
const tailwindcss = require('tailwindcss');
const autoprefixer = require('autoprefixer');
const config = {
plugins: [
//Some plugins, like tailwindcss/nesting, need to run before Tailwind,
tailwindcss(),
//But others, like autoprefixer, need to run after,
autoprefixer
]
};
module.exports = config;

9
apps/client/src/app.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
declare namespace App {
// interface Locals {}
// interface PageData {}
// interface Error {}
// interface Platform {}
}

12
apps/client/src/app.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<body>
<div class="h-screen">%sveltekit.body%</div>
</body>
</html>

View File

@ -0,0 +1,14 @@
/* Write your global styles here, in PostCSS syntax */
@tailwind base;
@tailwind components;
@tailwind utilities;
html {
@apply bg-black text-white;
}
input {
@apply bg-black border;
}
button {
@apply border px-2 p-1 bg-green-500;
}

View File

@ -0,0 +1,22 @@
import { writable, readable, type Writable, type Readable } from 'svelte/store';
import superjson from 'superjson';
import type { AppRouter } from 'server/src/router';
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { browser, dev } from '$app/environment';
import Cookies from 'js-cookie';
const serverBaseUrl = dev ? `http://${browser && window.location.hostname}:2022` : '';
export let token: string = Cookies.get('token') || '';
export const t = createTRPCProxyClient<AppRouter>({
transformer: superjson,
links: [
httpBatchLink({
url: `${serverBaseUrl}/trpc`,
headers() {
return {
Authorization: token
};
}
})
]
});

View File

@ -0,0 +1,7 @@
<script lang="ts">
import '../app.postcss';
</script>
<div class="h-full">
<slot />
</div>

View File

@ -0,0 +1,10 @@
<script lang="ts">
import { t } from '$lib/store';
import { onMount } from 'svelte';
onMount(async () => {
const a = await t.api.getConnection.query();
console.log(a);
});
</script>
<div>hello</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,21 @@
import adapter from '@sveltejs/adapter-static';
import preprocess from 'svelte-preprocess';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: [
preprocess({
postcss: true
})
],
kit: {
adapter: adapter({
pages: 'build',
assets: 'build',
fallback: 'index.html',
precompress: true
})
}
};
export default config;

View File

@ -0,0 +1,11 @@
const config = {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {}
},
plugins: []
};
module.exports = config;

View File

@ -0,0 +1,6 @@
import { expect, test } from '@playwright/test';
test('index page has expected h1', async ({ page }) => {
await page.goto('/');
expect(await page.textContent('h1')).toBe('Welcome to SvelteKit');
});

21
apps/client/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": false,
"paths": {
"$lib": [
"src/lib"
],
"$lib/*": [
"src/lib/*"
],
}
}
}

View File

@ -0,0 +1,11 @@
import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';
const config: UserConfig = {
server: {
host: '0.0.0.0',
},
plugins: [sveltekit()]
};
export default config;

View File

@ -0,0 +1,2 @@
NODE_ENV="development"
DATABASE_URL="file:../db/dev.db"

9
apps/server/.prettierrc Normal file
View File

@ -0,0 +1,9 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"pluginSearchDirs": ["."],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

0
apps/server/db/.gitkeep Normal file
View File

56
apps/server/package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "server",
"description": "Coolify's Fastify API",
"license": "Apache-2.0",
"scripts": {
"build": "rimraf ../../build && tsc --outDir ../../build",
"dev": "tsx watch --clear-screen=false src",
"lint": "prettier --plugin-search-dir . --check . && eslint .",
"format": "prettier --plugin-search-dir . --write .",
"test-dev": "start-server-and-test 'tsx src/server' http-get://localhost:2022 'tsx src/client'",
"test-start": "start-server-and-test 'node dist/server' http-get://localhost:2022 'node dist/client'",
"db:generate": "prisma generate",
"db:push": "prisma db push && prisma generate",
"db:seed": "prisma db seed",
"db:studio": "prisma studio",
"db:migrate": "DATABASE_URL=file:../db/migration.db prisma migrate dev --skip-seed --name"
},
"dependencies": {
"jsonwebtoken": "8.5.1",
"@fastify/autoload": "5.6.0",
"@fastify/cors": "8.2.0",
"@fastify/env": "4.1.0",
"@fastify/jwt": "6.5.0",
"@fastify/static": "6.6.0",
"@fastify/websocket": "7.1.1",
"@prisma/client": "4.6.1",
"@trpc/client": "10.1.0",
"@trpc/server": "10.1.0",
"abort-controller": "3.0.0",
"fastify": "4.10.2",
"fastify-plugin": "4.4.0",
"node-fetch": "3.3.0",
"prisma": "4.6.1",
"superjson": "1.11.0",
"tslib": "2.4.1",
"ws": "8.11.0",
"zod": "3.19.1"
},
"devDependencies": {
"@types/node": "18.11.9",
"@types/node-fetch": "2.6.2",
"@types/ws": "8.5.3",
"npm-run-all": "4.1.5",
"rimraf": "3.0.2",
"start-server-and-test": "1.14.0",
"tsx": "3.12.1",
"typescript": "4.9.3",
"wait-port": "1.0.4"
},
"publishConfig": {
"access": "restricted"
},
"prisma": {
"seed": "tsx prisma/seed.ts"
}
}

View File

@ -0,0 +1,21 @@
-- CreateTable
CREATE TABLE "Category" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT NOT NULL,
"budget" INTEGER NOT NULL,
"customIcon" TEXT,
"period" TEXT NOT NULL DEFAULT 'month',
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
-- CreateTable
CREATE TABLE "Transaction" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"amount" INTEGER NOT NULL,
"description" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"categoryId" INTEGER NOT NULL,
CONSTRAINT "Transaction_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);

View File

@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "sqlite"

View File

@ -0,0 +1,11 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}

View File

@ -0,0 +1,7 @@
import type { ServerOptions } from '../server';
export const serverConfig: ServerOptions = {
dev: false,
port: 2022,
prefix: '/trpc'
};

15
apps/server/src/env.js Normal file
View File

@ -0,0 +1,15 @@
const { z } = require('zod');
/*eslint sort-keys: "error"*/
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']),
COOLIFY_SECRET_KEY: z.string()
});
const env = envSchema.safeParse(process.env);
if (!env.success) {
console.error('❌ Invalid environment variables:', JSON.stringify(env.error.format(), null, 4));
process.exit(1);
}
module.exports.env = env.data;

7
apps/server/src/index.ts Normal file
View File

@ -0,0 +1,7 @@
import { serverConfig } from './config';
import { createServer } from './server';
const server = createServer(serverConfig);
server.start();

21
apps/server/src/prisma.ts Normal file
View File

@ -0,0 +1,21 @@
/**
* Instantiates a single instance PrismaClient and save it on the global object.
* @link https://www.prisma.io/docs/support/help-articles/nextjs-prisma-client-dev-practices
*/
import { env } from './env';
import { PrismaClient } from '@prisma/client';
const prismaGlobal = global as typeof global & {
prisma?: PrismaClient;
};
export const prisma: PrismaClient =
prismaGlobal.prisma ||
new PrismaClient({
log:
env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
if (env.NODE_ENV !== 'production') {
prismaGlobal.prisma = prisma;
}

View File

@ -0,0 +1,19 @@
import { inferAsyncReturnType } from '@trpc/server';
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import jwt from 'jsonwebtoken';
import { env } from '../env';
export interface User {
name: string | string[];
}
export function createContext({ req, res }: CreateFastifyContextOptions) {
const token = req.headers.authorization;
if (token) {
const user = jwt.verify(token, env.COOLIFY_SECRET_KEY);
console.log(user);
}
return { req, res };
}
export type Context = inferAsyncReturnType<typeof createContext>;

View File

@ -0,0 +1,8 @@
import { apiRouter } from './routers/api';
import { router } from './trpc';
export const appRouter = router({
api: apiRouter,
});
export type AppRouter = typeof appRouter;

View File

@ -0,0 +1,18 @@
// import { z } from 'zod';
import { publicProcedure, router } from '../trpc';
// import { prisma } from '../../prisma';
import { TRPCError } from '@trpc/server';
export const apiRouter = router({
getConnection: publicProcedure.query(async () => {
try {
return { success: true };
} catch (error) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected error occurred, please try again later.',
cause: error
});
}
})
});

View File

@ -0,0 +1,13 @@
import { initTRPC } from '@trpc/server';
import superjson from 'superjson';
import { Context } from './context';
const t = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter({ shape }) {
return shape;
},
});
export const router = t.router;
export const publicProcedure = t.procedure;

58
apps/server/src/server.ts Normal file
View File

@ -0,0 +1,58 @@
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import fastify from 'fastify';
import { appRouter } from './router';
import { createContext } from './router/context';
import cors from '@fastify/cors';
import * as path from 'node:path';
import serve from '@fastify/static';
// import { prisma } from './prisma';
const isDev = process.env['NODE_ENV'] === 'development';
export interface ServerOptions {
dev?: boolean;
port?: number;
prefix?: string;
}
export function createServer(opts: ServerOptions) {
const dev = opts.dev ?? true;
const port = opts.port ?? 3000;
const prefix = opts.prefix ?? '/trpc';
const server = fastify({ logger: dev, trustProxy: true });
server.register(cors);
server.register(fastifyTRPCPlugin, {
prefix,
trpcOptions: { router: appRouter, createContext }
});
// Serve static files in production. Static files are generated by `yarn build` in the client folder by SvelteKit.
if (!isDev) {
server.register(serve, {
root: path.join(__dirname, './public'),
preCompressed: true
});
server.setNotFoundHandler(async function (request, reply) {
if (request.raw.url && request.raw.url.startsWith('/api')) {
return reply.status(404).send({
success: false
});
}
return reply.status(200).sendFile('index.html');
});
}
server.get('/api', async () => {
return { status: 'ok' };
});
const stop = () => server.close();
const start = async () => {
try {
await server.listen({ host: '0.0.0.0', port });
console.log('Server is listening on port', port);
} catch (err) {
server.log.error(err);
process.exit(1);
}
};
return { server, start, stop };
}

43
apps/server/tsconfig.json Normal file
View File

@ -0,0 +1,43 @@
{
"include": ["src", "server/src/config.ts"],
"exclude": ["node_modules"],
"compilerOptions": {
"module": "commonjs",
"target": "esnext",
"outDir": "dist",
// [ Basics ]
"strict": true,
"checkJs": true,
"sourceMap": true,
"importHelpers": true,
"removeComments": true,
// "rootDir": "./",
// "declaration": true,
// "declarationMap": true,
// "declarationDir": "types",
// [ Additional Checks ]
"noUnusedLocals": true,
"noImplicitReturns": true,
"noUnusedParameters": true,
"noImplicitOverride": true,
"allowUnreachableCode": false,
"noUncheckedIndexedAccess": true,
"noFallthroughCasesInSwitch": true,
"noPropertyAccessFromIndexSignature": true,
// [ Module Resolution ]
"esModuleInterop": true,
"resolveJsonModule": true,
"moduleResolution": "node",
// [ Advanced ]
// "skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
// [ Build ]
"listFiles": false,
"listEmittedFiles": true
}
}

View File

@ -18,9 +18,14 @@
"lint": "run-p -l -n lint:*",
"lint:api": "NODE_ENV=development pnpm run --filter api lint",
"dev:container": "docker-compose -f docker-compose-dev.yaml up --build || docker compose -f docker-compose-dev.yaml up --build",
"dev:trpc": "NODE_ENV=development run-p -l -n dev:server dev:client",
"dev": "run-p -l -n dev:api dev:ui",
"dev:api": "NODE_ENV=development pnpm run --filter api dev",
"dev:server": "NODE_ENV=development pnpm run --filter server dev",
"dev:client": "NODE_ENV=development pnpm run --filter client dev",
"dev:ui": "NODE_ENV=development pnpm run --filter ui dev",
"build:trpc": "NODE_ENV=production pnpm run --filter server build && pnpm run --filter client build && cp ./apps/server/package.json build/ && cd build/ && pnpm install -p .",
"start:trpc": "NODE_ENV=production node build/index.js",
"build": "NODE_ENV=production run-p -n build:*",
"build:api": "NODE_ENV=production pnpm run --filter api build",
"build:ui": "NODE_ENV=production pnpm run --filter ui build",

File diff suppressed because it is too large Load Diff