init studio admin backend

This commit is contained in:
2026-07-01 17:30:04 +09:00
commit 4437d9980d
144 changed files with 44964 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
import { Body, Controller, Post, Req } from '@nestjs/common';
import { AdminAuthService } from './admin-auth.service';
import { Public } from './decorators/admin-auth.decorators';
import { AdminLoginDto } from './dto';
@Controller('auth/admin')
export class AdminAuthController {
constructor(private readonly adminAuthService: AdminAuthService) {}
@Public()
@Post('login')
login(
@Body() body: AdminLoginDto,
@Req() request: { ip?: string; headers: Record<string, string | string[] | undefined> },
) {
const userAgent = request.headers['user-agent'];
return this.adminAuthService.login(body, {
ipAddress: request.ip,
userAgent: Array.isArray(userAgent) ? userAgent.join(', ') : userAgent,
});
}
}
+93
View File
@@ -0,0 +1,93 @@
import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { createHash } from 'node:crypto';
import { AdminRole } from '../admins/admin-role';
import { PrismaService } from '../prisma/prisma.service';
import { ADMIN_PUBLIC_KEY, ADMIN_ROLES_KEY } from './decorators/admin-auth.decorators';
type RequestWithAdmin = {
method?: string;
headers?: Record<string, string | string[] | undefined>;
admin?: {
id: string;
email: string;
name: string;
role: AdminRole;
};
};
@Injectable()
export class AdminAuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly prisma: PrismaService,
) {}
async canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(ADMIN_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
const request = context.switchToHttp().getRequest<RequestWithAdmin>();
if (request.method?.toUpperCase() === 'OPTIONS') return true;
const token = getBearerToken(request.headers?.authorization);
if (!token) {
throw new UnauthorizedException('관리자 로그인이 필요합니다.');
}
const tokenHash = createHash('sha256').update(token).digest('hex');
const session = await this.prisma.adminSession.findUnique({
where: { tokenHash },
include: {
admin: {
select: {
id: true,
email: true,
name: true,
role: true,
isActive: true,
},
},
},
});
const now = new Date();
if (!session || session.revokedAt || session.expiresAt <= now || !session.admin.isActive) {
throw new UnauthorizedException('관리자 세션이 유효하지 않습니다.');
}
request.admin = {
id: session.admin.id,
email: session.admin.email,
name: session.admin.name,
role: session.admin.role,
};
const roles = this.reflector.getAllAndOverride<AdminRole[]>(ADMIN_ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (roles?.length && !roles.includes(session.admin.role)) {
throw new ForbiddenException('권한이 없습니다.');
}
const method = request.method?.toUpperCase();
if (session.admin.role === AdminRole.VIEWER && method && !['GET', 'HEAD', 'OPTIONS'].includes(method)) {
throw new ForbiddenException('조회 권한만 허용됩니다.');
}
return true;
}
}
function getBearerToken(value: string | string[] | undefined) {
const header = Array.isArray(value) ? value[0] : value;
const match = header?.match(/^Bearer\s+(.+)$/i);
return match?.[1]?.trim() || '';
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../prisma/prisma.module';
import { AdminAuthController } from './admin-auth.controller';
import { AdminAuthService } from './admin-auth.service';
@Module({
imports: [PrismaModule],
controllers: [AdminAuthController],
providers: [AdminAuthService],
})
export class AdminAuthModule {}
+83
View File
@@ -0,0 +1,83 @@
import { randomBytes, scryptSync, timingSafeEqual, createHash } from 'node:crypto';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AdminLoginDto } from './dto';
@Injectable()
export class AdminAuthService {
constructor(private readonly prisma: PrismaService) {}
async login(
body: AdminLoginDto,
context: { ipAddress?: string; userAgent?: string },
) {
const admin = await this.prisma.admin.findUnique({
where: { email: body.email.trim().toLowerCase() },
select: {
id: true,
email: true,
name: true,
role: true,
isActive: true,
passwordHash: true,
},
});
if (!admin || !admin.isActive || !verifyPassword(body.password, admin.passwordHash)) {
throw new UnauthorizedException('이메일 또는 비밀번호가 올바르지 않습니다.');
}
const token = randomBytes(32).toString('hex');
const tokenHash = hashToken(token);
const expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 12);
await this.prisma.$transaction([
this.prisma.admin.update({
where: { id: admin.id },
data: { lastLoginAt: new Date() },
}),
this.prisma.adminSession.create({
data: {
adminId: admin.id,
tokenHash,
ipAddress: context.ipAddress,
userAgent: context.userAgent,
expiresAt,
},
}),
]);
return {
token,
expiresAt,
admin: {
id: admin.id,
email: admin.email,
name: admin.name,
role: admin.role,
},
};
}
}
function verifyPassword(password: string, passwordHash: string) {
const [scheme, salt, storedHash] = passwordHash.split(':');
if (scheme !== 'scrypt' || !salt || !storedHash) {
return false;
}
const currentHash = scryptSync(password, salt, 64);
const storedBuffer = Buffer.from(storedHash, 'hex');
if (storedBuffer.length !== currentHash.length) {
return false;
}
return timingSafeEqual(storedBuffer, currentHash);
}
function hashToken(token: string) {
return createHash('sha256').update(token).digest('hex');
}
@@ -0,0 +1,8 @@
import { SetMetadata } from '@nestjs/common';
import { AdminRole } from '../../admins/admin-role';
export const ADMIN_PUBLIC_KEY = 'adminPublic';
export const ADMIN_ROLES_KEY = 'adminRoles';
export const Public = () => SetMetadata(ADMIN_PUBLIC_KEY, true);
export const AdminRoles = (...roles: AdminRole[]) => SetMetadata(ADMIN_ROLES_KEY, roles);
+9
View File
@@ -0,0 +1,9 @@
import { IsEmail, IsString } from 'class-validator';
export class AdminLoginDto {
@IsEmail()
email!: string;
@IsString()
password!: string;
}
+8
View File
@@ -0,0 +1,8 @@
export const AdminRole = {
OWNER: 'OWNER',
ADMIN: 'ADMIN',
OPERATOR: 'OPERATOR',
VIEWER: 'VIEWER',
} as const;
export type AdminRole = (typeof AdminRole)[keyof typeof AdminRole];
+58
View File
@@ -0,0 +1,58 @@
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
import {
CreateAdminSshKeyDto,
CreateAdminDto,
ResetAdminPasswordDto,
UpdateAdminRoleDto,
UpdateAdminStatusDto,
} from './dto';
import { AdminRoles } from '../admin-auth/decorators/admin-auth.decorators';
import { AdminRole } from './admin-role';
import { AdminsService } from './admins.service';
@AdminRoles(AdminRole.OWNER)
@Controller('admins')
export class AdminsController {
constructor(private readonly adminsService: AdminsService) {}
@Get('roles')
listRoles() {
return this.adminsService.listRoles();
}
@Get()
list() {
return this.adminsService.list();
}
@Post()
create(@Body() body: CreateAdminDto) {
return this.adminsService.create(body);
}
@Patch(':id/status')
updateStatus(@Param('id') id: string, @Body() body: UpdateAdminStatusDto) {
return this.adminsService.updateStatus(id, body);
}
@Patch(':id/role')
updateRole(@Param('id') id: string, @Body() body: UpdateAdminRoleDto) {
return this.adminsService.updateRole(id, body);
}
@Patch(':id/password')
resetPassword(@Param('id') id: string, @Body() body: ResetAdminPasswordDto) {
return this.adminsService.resetPassword(id, body);
}
@Post(':id/ssh-keys')
createSshKey(@Param('id') id: string, @Body() body: CreateAdminSshKeyDto) {
return this.adminsService.createSshKey(id, body);
}
@Delete(':id/ssh-keys/:keyId')
deleteSshKey(@Param('id') id: string, @Param('keyId') keyId: string) {
return this.adminsService.deleteSshKey(id, keyId);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { GiteaModule } from '../gitea/gitea.module';
import { PrismaModule } from '../prisma/prisma.module';
import { AdminsController } from './admins.controller';
import { AdminsService } from './admins.service';
@Module({
imports: [GiteaModule, PrismaModule],
controllers: [AdminsController],
providers: [AdminsService],
})
export class AdminsModule {}
+295
View File
@@ -0,0 +1,295 @@
import { createHash, randomBytes, scryptSync } from 'node:crypto';
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { GiteaService } from '../gitea/gitea.service';
import { PrismaService } from '../prisma/prisma.service';
import { AdminRole } from './admin-role';
import {
CreateAdminSshKeyDto,
CreateAdminDto,
ResetAdminPasswordDto,
UpdateAdminRoleDto,
UpdateAdminStatusDto,
} from './dto';
@Injectable()
export class AdminsService {
constructor(
private readonly giteaService: GiteaService,
private readonly prisma: PrismaService,
) {}
async listRoles() {
await this.ensureDefaultRoles();
return this.prisma.adminRoleOption.findMany({
where: { isActive: true },
orderBy: [{ sortOrder: 'asc' }, { code: 'asc' }],
select: {
id: true,
code: true,
name: true,
description: true,
sortOrder: true,
isActive: true,
},
});
}
list() {
return this.prisma.admin.findMany({
orderBy: [{ role: 'asc' }, { createdAt: 'desc' }],
select: {
id: true,
email: true,
name: true,
role: true,
isActive: true,
lastLoginAt: true,
createdAt: true,
updatedAt: true,
sessions: {
orderBy: { createdAt: 'desc' },
take: 1,
select: {
id: true,
expiresAt: true,
revokedAt: true,
createdAt: true,
},
},
sshKeys: {
orderBy: { createdAt: 'desc' },
select: adminSshKeySelect,
},
},
});
}
async create(body: CreateAdminDto) {
await this.ensureRoleEnabled(body.role);
const admin = await this.prisma.admin.create({
data: {
email: body.email.trim().toLowerCase(),
name: body.name.trim(),
role: body.role,
passwordHash: hashPassword(body.temporaryPassword),
},
select: adminSelect,
});
return { admin };
}
async updateStatus(id: string, body: UpdateAdminStatusDto) {
await this.ensureExists(id);
const admin = await this.prisma.admin.update({
where: { id },
data: { isActive: body.isActive },
select: adminSelect,
});
if (!body.isActive) {
await this.prisma.adminSession.updateMany({
where: { adminId: id, revokedAt: null },
data: { revokedAt: new Date() },
});
}
return { admin };
}
async updateRole(id: string, body: UpdateAdminRoleDto) {
await this.ensureExists(id);
await this.ensureRoleEnabled(body.role);
const admin = await this.prisma.admin.update({
where: { id },
data: { role: body.role },
select: adminSelect,
});
return { admin };
}
async resetPassword(id: string, body: ResetAdminPasswordDto) {
await this.ensureExists(id);
const admin = await this.prisma.admin.update({
where: { id },
data: { passwordHash: hashPassword(body.temporaryPassword) },
select: adminSelect,
});
await this.prisma.adminSession.updateMany({
where: { adminId: id, revokedAt: null },
data: { revokedAt: new Date() },
});
return { admin };
}
async createSshKey(adminId: string, body: CreateAdminSshKeyDto) {
await this.ensureExists(adminId);
const parsedKey = parseSshPublicKey(body.publicKey);
const label = body.label?.trim() || `${parsedKey.keyType} ${parsedKey.fingerprint}`;
const giteaUsername = body.giteaUsername?.trim() || null;
let giteaKeyId: number | null = null;
if (giteaUsername) {
const giteaKey = await this.giteaService.createUserSshKey(giteaUsername, {
title: label,
key: parsedKey.normalizedKey,
});
giteaKeyId = giteaKey.id;
}
const sshKey = await this.prisma.adminSshKey.create({
data: {
adminId,
label,
keyType: parsedKey.keyType,
publicKey: parsedKey.normalizedKey,
publicKeyHash: parsedKey.publicKeyHash,
fingerprint: parsedKey.fingerprint,
giteaUsername,
giteaKeyId,
},
select: adminSshKeySelect,
});
return { sshKey };
}
async deleteSshKey(adminId: string, keyId: string) {
await this.ensureExists(adminId);
const sshKey = await this.prisma.adminSshKey.findFirst({
where: { id: keyId, adminId },
select: {
id: true,
giteaUsername: true,
giteaKeyId: true,
},
});
if (!sshKey) {
throw new NotFoundException('SSH 키를 찾을 수 없습니다.');
}
await this.prisma.adminSshKey.delete({ where: { id: keyId } });
if (sshKey.giteaUsername && sshKey.giteaKeyId) {
await this.giteaService.deleteUserSshKey(
sshKey.giteaUsername,
sshKey.giteaKeyId,
);
}
return { deleted: true };
}
private async ensureRoleEnabled(role: AdminRole) {
await this.ensureDefaultRoles();
const roleOption = await this.prisma.adminRoleOption.findUnique({
where: { code: role },
select: { isActive: true },
});
if (!roleOption?.isActive) {
throw new BadRequestException('사용할 수 없는 관리자 권한입니다.');
}
}
private async ensureDefaultRoles() {
await this.prisma.adminRoleOption.createMany({
data: [
{ code: AdminRole.OWNER, name: 'OWNER', description: '전체 관리자 권한', sortOrder: 1 },
{ code: AdminRole.ADMIN, name: 'ADMIN', description: '관리자 권한', sortOrder: 2 },
{ code: AdminRole.VIEWER, name: 'VIEWER', description: '조회 권한', sortOrder: 3 },
],
skipDuplicates: true,
});
}
private async ensureExists(id: string) {
const admin = await this.prisma.admin.findUnique({
where: { id },
select: { id: true },
});
if (!admin) {
throw new NotFoundException('관리자를 찾을 수 없습니다.');
}
}
}
const adminSelect = {
id: true,
email: true,
name: true,
role: true,
isActive: true,
lastLoginAt: true,
createdAt: true,
updatedAt: true,
} as const;
const adminSshKeySelect = {
id: true,
label: true,
keyType: true,
fingerprint: true,
giteaUsername: true,
giteaKeyId: true,
createdAt: true,
} as const;
function hashPassword(password: string) {
const salt = randomBytes(16).toString('hex');
const hash = scryptSync(password, salt, 64).toString('hex');
return `scrypt:${salt}:${hash}`;
}
function parseSshPublicKey(publicKey: string) {
const normalizedKey = publicKey.trim().replace(/\s+/g, ' ');
const [keyType, keyBody] = normalizedKey.split(' ');
if (!keyType || !keyBody || !isSupportedSshKeyType(keyType)) {
throw new BadRequestException('지원하지 않는 SSH 공개키 형식입니다.');
}
let keyBuffer: Buffer;
try {
keyBuffer = Buffer.from(keyBody, 'base64');
} catch {
throw new BadRequestException('SSH 공개키 base64 값을 확인하세요.');
}
if (!keyBuffer.length) {
throw new BadRequestException('SSH 공개키 값이 비어 있습니다.');
}
return {
keyType,
normalizedKey,
publicKeyHash: createHash('sha256').update(normalizedKey).digest('hex'),
fingerprint: `SHA256:${createHash('sha256')
.update(keyBuffer)
.digest('base64')
.replace(/=+$/, '')}`,
};
}
function isSupportedSshKeyType(keyType: string) {
return (
keyType === 'ssh-ed25519' ||
keyType === 'ssh-rsa' ||
keyType.startsWith('ecdsa-sha2-')
);
}
+46
View File
@@ -0,0 +1,46 @@
import { IsBoolean, IsEmail, IsEnum, IsOptional, IsString, MinLength } from 'class-validator';
import { AdminRole } from './admin-role';
export class CreateAdminDto {
@IsEmail()
email!: string;
@IsString()
name!: string;
@IsEnum(AdminRole)
role!: AdminRole;
@IsString()
@MinLength(8)
temporaryPassword!: string;
}
export class UpdateAdminStatusDto {
@IsBoolean()
isActive!: boolean;
}
export class UpdateAdminRoleDto {
@IsEnum(AdminRole)
role!: AdminRole;
}
export class ResetAdminPasswordDto {
@IsString()
@MinLength(8)
temporaryPassword!: string;
}
export class CreateAdminSshKeyDto {
@IsOptional()
@IsString()
label?: string;
@IsString()
publicKey!: string;
@IsOptional()
@IsString()
giteaUsername?: string;
}
+41
View File
@@ -0,0 +1,41 @@
import { Controller, Delete, Get, Param, Patch, Query, Body } from '@nestjs/common';
import {
ListLauncherSshKeysQuery,
ListProvisionedDevicesQuery,
UpdateProvisionedDeviceDto,
} from './dto';
import { AgentsService } from './agents.service';
@Controller('agents')
export class AgentsController {
constructor(private readonly agentsService: AgentsService) {}
@Get('devices')
listDevices(@Query() query: ListProvisionedDevicesQuery) {
return this.agentsService.listDevices(query);
}
@Get('devices/:id')
getDevice(@Param('id') id: string) {
return this.agentsService.getDevice(id);
}
@Patch('devices/:id')
updateDevice(
@Param('id') id: string,
@Body() body: UpdateProvisionedDeviceDto,
) {
return this.agentsService.updateDevice(id, body);
}
@Get('ssh-keys')
listSshKeys(@Query() query: ListLauncherSshKeysQuery) {
return this.agentsService.listSshKeys(query);
}
@Delete('ssh-keys/:id')
removeSshKey(@Param('id') id: string) {
return this.agentsService.removeSshKey(id);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { LauncherPrismaModule } from '../launcher-prisma/launcher-prisma.module';
import { AgentsController } from './agents.controller';
import { AgentsService } from './agents.service';
@Module({
imports: [LauncherPrismaModule],
controllers: [AgentsController],
providers: [AgentsService],
})
export class AgentsModule {}
+136
View File
@@ -0,0 +1,136 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { LauncherPrismaService } from '../launcher-prisma/launcher-prisma.service';
import {
ListLauncherSshKeysQuery,
ListProvisionedDevicesQuery,
UpdateProvisionedDeviceDto,
} from './dto';
@Injectable()
export class AgentsService {
constructor(private readonly launcherPrisma: LauncherPrismaService) {}
async listDevices(query: ListProvisionedDevicesQuery) {
const keyword = query.keyword?.trim();
const devices = await this.launcherPrisma.provisionedDevice.findMany({
where: {
accountEmail: query.accountEmail || undefined,
usageType: query.usageType || undefined,
OR: keyword
? [
{ accountEmail: { contains: keyword, mode: 'insensitive' } },
{ hostname: { contains: keyword, mode: 'insensitive' } },
{
tailscaleHostname: {
contains: keyword,
mode: 'insensitive',
},
},
{ sshUser: { contains: keyword, mode: 'insensitive' } },
{ workspaceRoot: { contains: keyword, mode: 'insensitive' } },
]
: undefined,
},
orderBy: [{ lastProvisionedAt: 'desc' }, { createdAt: 'desc' }],
});
return {
devices: devices.map((device) => ({
...device,
status: getDeviceStatus(device.lastProvisionedAt),
})),
};
}
async getDevice(id: string) {
const device = await this.launcherPrisma.provisionedDevice.findUnique({
where: { id },
});
if (!device) {
throw new NotFoundException('장비를 찾을 수 없습니다.');
}
return { device: { ...device, status: getDeviceStatus(device.lastProvisionedAt) } };
}
async updateDevice(id: string, body: UpdateProvisionedDeviceDto) {
await this.ensureDeviceExists(id);
const device = await this.launcherPrisma.provisionedDevice.update({
where: { id },
data: {
sshUser: body.sshUser,
workspaceRoot: body.workspaceRoot,
usageType: body.usageType,
},
});
return { device };
}
async listSshKeys(query: ListLauncherSshKeysQuery) {
const keyword = query.keyword?.trim();
const sshKeys = await this.launcherPrisma.launcherSshKey.findMany({
where: {
accountEmail: query.accountEmail || undefined,
OR: keyword
? [
{ accountEmail: { contains: keyword, mode: 'insensitive' } },
{ label: { contains: keyword, mode: 'insensitive' } },
{ publicKeyHash: { contains: keyword, mode: 'insensitive' } },
{ keyType: { contains: keyword, mode: 'insensitive' } },
]
: undefined,
},
orderBy: [{ lastProvisionedAt: 'desc' }, { createdAt: 'desc' }],
});
return { sshKeys };
}
async removeSshKey(id: string) {
const sshKey = await this.launcherPrisma.launcherSshKey.findUnique({
where: { id },
select: { id: true },
});
if (!sshKey) {
throw new NotFoundException('SSH 키를 찾을 수 없습니다.');
}
await this.launcherPrisma.launcherSshKey.delete({
where: { id },
});
return { ok: true };
}
private async ensureDeviceExists(id: string) {
const device = await this.launcherPrisma.provisionedDevice.findUnique({
where: { id },
select: { id: true },
});
if (!device) {
throw new NotFoundException('장비를 찾을 수 없습니다.');
}
}
}
function getDeviceStatus(lastProvisionedAt: Date) {
const minutes = (Date.now() - lastProvisionedAt.getTime()) / 1000 / 60;
if (minutes <= 15) {
return '정상';
}
if (minutes <= 1440) {
return '확인 필요';
}
return '장기 미접속';
}
+39
View File
@@ -0,0 +1,39 @@
import { IsOptional, IsString } from 'class-validator';
export class ListProvisionedDevicesQuery {
@IsOptional()
@IsString()
keyword?: string;
@IsOptional()
@IsString()
accountEmail?: string;
@IsOptional()
@IsString()
usageType?: string;
}
export class UpdateProvisionedDeviceDto {
@IsOptional()
@IsString()
sshUser?: string;
@IsOptional()
@IsString()
workspaceRoot?: string;
@IsOptional()
@IsString()
usageType?: string;
}
export class ListLauncherSshKeysQuery {
@IsOptional()
@IsString()
accountEmail?: string;
@IsOptional()
@IsString()
keyword?: string;
}
+44
View File
@@ -0,0 +1,44 @@
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { AdminAuthGuard } from './admin-auth/admin-auth.guard';
import { AdminAuthModule } from './admin-auth/admin-auth.module';
import { AdminsModule } from './admins/admins.module';
import { AgentsModule } from './agents/agents.module';
import { AppsModule } from './apps/apps.module';
import { GiteaModule } from './gitea/gitea.module';
import { HealthModule } from './health/health.module';
import { LauncherModule } from './launcher/launcher.module';
import { LicensesModule } from './licenses/licenses.module';
import { NoticesModule } from './notices/notices.module';
import { PrismaModule } from './prisma/prisma.module';
import { RuntimeModule } from './runtime/runtime.module';
import { UsersModule } from './users/users.module';
@Module({
providers: [
{
provide: APP_GUARD,
useClass: AdminAuthGuard,
},
],
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
AdminAuthModule,
AdminsModule,
AgentsModule,
AppsModule,
GiteaModule,
HealthModule,
LauncherModule,
LicensesModule,
NoticesModule,
PrismaModule,
RuntimeModule,
UsersModule,
],
})
export class AppModule {}
+17
View File
@@ -0,0 +1,17 @@
export const AppStatus = {
ACTIVE: 'ACTIVE',
READY: 'READY',
DISABLED: 'DISABLED',
} as const;
export type AppStatus = (typeof AppStatus)[keyof typeof AppStatus];
export const ComponentType = {
ELECTRON: 'ELECTRON',
CONTAINER: 'CONTAINER',
STATIC_WEB: 'STATIC_WEB',
DATABASE: 'DATABASE',
MIGRATION: 'MIGRATION',
} as const;
export type ComponentType = (typeof ComponentType)[keyof typeof ComponentType];
+190
View File
@@ -0,0 +1,190 @@
import { Body, Controller, Delete, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { LinkComponentSourceDto } from '../gitea/dto';
import { AppsService } from './apps.service';
import {
CreateAppComponentDto,
CreateAppDto,
CreateAppReleaseDto,
CreateBuildJobDto,
CreateDeploymentJobDto,
CreateMigrationJobDto,
CreateRuntimeEnvProfileDto,
CreateRuntimeEnvVariableDto,
CreateRuntimeIngressRuleDto,
EnsureRuntimeNamespaceDto,
} from './dto';
@Controller('apps')
export class AppsController {
constructor(private readonly appsService: AppsService) {}
@Get()
listApps() {
return this.appsService.listApps();
}
@Post()
createApp(@Body() body: CreateAppDto) {
return this.appsService.createApp(body);
}
@Delete(':appId')
deleteApp(@Param('appId') appId: string) {
return this.appsService.deleteApp(appId);
}
@Post(':appId/components')
createComponent(
@Param('appId') appId: string,
@Body() body: CreateAppComponentDto,
) {
return this.appsService.createComponent(appId, body);
}
@Patch('components/:componentId')
updateComponent(
@Param('componentId') componentId: string,
@Body() body: CreateAppComponentDto,
) {
return this.appsService.updateComponent(componentId, body);
}
@Delete('components/:componentId')
deleteComponent(@Param('componentId') componentId: string) {
return this.appsService.deleteComponent(componentId);
}
@Get('sources')
listSources() {
return this.appsService.listSources();
}
@Get('builds')
listBuildJobs(@Query('appKey') appKey?: string) {
return this.appsService.listBuildJobs(appKey);
}
@Post('builds')
createBuildJob(@Body() body: CreateBuildJobDto) {
return this.appsService.createBuildJob(body);
}
@Patch('builds/:buildJobId/cancel')
cancelBuildJob(@Param('buildJobId') buildJobId: string) {
return this.appsService.cancelBuildJob(buildJobId);
}
@Delete('builds/:buildJobId')
deleteBuildJob(@Param('buildJobId') buildJobId: string) {
return this.appsService.deleteBuildJob(buildJobId);
}
@Patch('components/:componentId/source')
linkComponentSource(
@Param('componentId') componentId: string,
@Body() body: LinkComponentSourceDto,
) {
return this.appsService.linkComponentSource(componentId, body);
}
@Get('releases')
listReleases(@Query('appKey') appKey?: string) {
return this.appsService.listReleases(appKey);
}
@Post('releases')
createRelease(@Body() body: CreateAppReleaseDto) {
return this.appsService.createRelease(body);
}
@Get('deployments')
listDeployments(@Query('appKey') appKey?: string) {
return this.appsService.listDeployments(appKey);
}
@Post('deployments')
createDeploymentJob(@Body() body: CreateDeploymentJobDto) {
return this.appsService.createDeploymentJob(body);
}
@Get('migrations')
listMigrationJobs() {
return this.appsService.listMigrationJobs();
}
@Post('migrations')
createMigrationJob(@Body() body: CreateMigrationJobDto) {
return this.appsService.createMigrationJob(body);
}
@Get('runtime-namespaces/:namespace')
checkRuntimeNamespace(@Param('namespace') namespace: string) {
return this.appsService.checkRuntimeNamespace(namespace);
}
@Get('runtime-namespaces/:namespace/resources')
listRuntimeResources(@Param('namespace') namespace: string) {
return this.appsService.listRuntimeResources(namespace);
}
@Post('runtime-namespaces')
ensureRuntimeNamespace(@Body() body: EnsureRuntimeNamespaceDto) {
return this.appsService.ensureRuntimeNamespace(body);
}
@Patch('runtime-deployments/:namespace/:deploymentName/restart')
restartRuntimeDeployment(
@Param('namespace') namespace: string,
@Param('deploymentName') deploymentName: string,
) {
return this.appsService.restartRuntimeDeployment(namespace, deploymentName);
}
@Get('runtime-profiles')
listRuntimeProfiles(@Query('appId') appId?: string) {
return this.appsService.listRuntimeProfiles(appId);
}
@Post('runtime-profiles')
createRuntimeProfile(@Body() body: CreateRuntimeEnvProfileDto) {
return this.appsService.createRuntimeProfile(body);
}
@Post('runtime-profiles/:profileId/variables')
createRuntimeVariable(
@Param('profileId') profileId: string,
@Body() body: CreateRuntimeEnvVariableDto,
) {
return this.appsService.createRuntimeVariable(profileId, body);
}
@Post('runtime-profiles/:profileId/ingress-rules')
createRuntimeIngressRule(
@Param('profileId') profileId: string,
@Body() body: CreateRuntimeIngressRuleDto,
) {
return this.appsService.createRuntimeIngressRule(profileId, body);
}
@Delete('runtime-profiles/:profileId/ingress-rules/:ruleId')
deleteRuntimeIngressRule(
@Param('profileId') profileId: string,
@Param('ruleId') ruleId: string,
) {
return this.appsService.deleteRuntimeIngressRule(profileId, ruleId);
}
@Delete('runtime-profiles/:profileId/variables/:variableId')
deleteRuntimeVariable(
@Param('profileId') profileId: string,
@Param('variableId') variableId: string,
) {
return this.appsService.deleteRuntimeVariable(profileId, variableId);
}
@Patch('runtime-profiles/:profileId/apply')
applyRuntimeProfile(@Param('profileId') profileId: string) {
return this.appsService.applyRuntimeProfile(profileId);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { LauncherModule } from '../launcher/launcher.module';
import { PrismaModule } from '../prisma/prisma.module';
import { AppsController } from './apps.controller';
import { AppsService } from './apps.service';
import { BuildRunnerService } from './build-runner.service';
@Module({
imports: [PrismaModule, LauncherModule],
controllers: [AppsController],
providers: [AppsService, BuildRunnerService],
})
export class AppsModule {}
File diff suppressed because it is too large Load Diff
+782
View File
@@ -0,0 +1,782 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { createHash } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { promises as fs } from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { App, AppComponent, BuildJob } from '@prisma/client';
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { PrismaService } from '../prisma/prisma.service';
type BuildJobWithComponent = BuildJob & {
component: AppComponent & {
app: App;
};
};
@Injectable()
export class BuildRunnerService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(BuildRunnerService.name);
private timer?: NodeJS.Timeout;
private running = false;
private giteaUsername?: string;
private r2Client?: S3Client;
private readonly activeProcesses = new Map<string, ChildProcess>();
constructor(
private readonly prisma: PrismaService,
private readonly configService: ConfigService,
) {}
onModuleInit() {
if (this.configService.get<string>('BUILD_RUNNER_ENABLED', 'true') === 'false') {
this.logger.log('Build runner disabled by BUILD_RUNNER_ENABLED=false');
return;
}
const intervalMs = Number(
this.configService.get<string>('BUILD_RUNNER_INTERVAL_MS', '5000'),
);
this.timer = setInterval(() => void this.tick(), intervalMs);
void this.tick();
}
onModuleDestroy() {
if (this.timer) {
clearInterval(this.timer);
}
for (const child of this.activeProcesses.values()) {
terminateProcess(child);
}
}
cancelJob(jobId: string) {
const child = this.activeProcesses.get(jobId);
if (child) {
terminateProcess(child);
}
}
private async tick() {
if (this.running) return;
this.running = true;
try {
const job = await this.claimNextJob();
if (job) {
await this.runJob(job);
}
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown build runner error';
this.logger.error(message);
} finally {
this.running = false;
}
}
private async claimNextJob() {
const pending = await this.prisma.buildJob.findFirst({
where: { status: 'PENDING' },
orderBy: { createdAt: 'asc' },
include: {
component: {
include: {
app: true,
},
},
},
});
if (!pending) return null;
const claimed = await this.prisma.buildJob.updateMany({
where: { id: pending.id, status: 'PENDING' },
data: {
status: 'RUNNING',
startedAt: new Date(),
},
});
if (claimed.count === 0) return null;
return this.prisma.buildJob.findUnique({
where: { id: pending.id },
include: {
component: {
include: {
app: true,
},
},
},
}) as Promise<BuildJobWithComponent | null>;
}
private async runJob(job: BuildJobWithComponent) {
const lines = splitLogs(job.logs);
const token = this.configService.get<string>('GITEA_ADMIN_TOKEN') || '';
const append = async (line: string) => {
lines.push(redact(line, token));
await this.prisma.buildJob.update({
where: { id: job.id },
data: { logs: truncateLogs(lines.join('\n')) },
});
};
const workRoot = this.configService.get<string>(
'BUILD_WORKDIR',
path.join(os.tmpdir(), 'studio-admin-builds'),
);
const workDir = path.join(workRoot, job.id);
try {
await fs.rm(workDir, { recursive: true, force: true });
await fs.mkdir(workRoot, { recursive: true });
await append(`[running] build runner picked job ${job.id}`);
await this.cloneRepository(job, workDir, append);
await this.executeByComponentType(job, workDir, append);
await append('[done] build job completed');
if (await this.isCanceled(job.id)) {
await append('[cancelled] build job was cancelled');
return;
}
await this.prisma.buildJob.update({
where: { id: job.id },
data: {
status: 'SUCCEEDED',
finishedAt: new Date(),
logs: truncateLogs(lines.join('\n')),
},
});
} catch (error) {
if (await this.isCanceled(job.id)) {
lines.push('[cancelled] build job stopped');
await this.prisma.buildJob.update({
where: { id: job.id },
data: {
status: 'CANCELED',
finishedAt: new Date(),
logs: truncateLogs(lines.join('\n')),
},
});
return;
}
const message = error instanceof Error ? error.message : 'Unknown build failure';
lines.push(`[failed] ${redact(message, token)}`);
await this.prisma.buildJob.update({
where: { id: job.id },
data: {
status: 'FAILED',
finishedAt: new Date(),
logs: truncateLogs(lines.join('\n')),
},
});
} finally {
if (this.configService.get<string>('BUILD_KEEP_WORKDIR', 'false') !== 'true') {
await fs.rm(workDir, { recursive: true, force: true }).catch(() => undefined);
}
}
}
private async isCanceled(jobId: string) {
const job = await this.prisma.buildJob.findUnique({
where: { id: jobId },
select: { status: true },
});
return job?.status === 'CANCELED';
}
private async cloneRepository(
job: BuildJobWithComponent,
workDir: string,
append: (line: string) => Promise<void>,
) {
const safeUrl = this.getHttpCloneUrl(job.component.repository!);
const cloneUrl = await this.getAuthenticatedHttpCloneUrl(
job.component.repository!,
);
await append(`[clone] ${safeUrl}`);
await runCommand({
jobId: job.id,
command: this.configService.get<string>('GIT_BIN', 'git'),
args: ['clone', '--branch', job.branch, cloneUrl, workDir],
safeArgs: ['clone', '--branch', job.branch, safeUrl, workDir],
cwd: process.cwd(),
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
if (job.commitSha) {
await append(`[checkout] ${job.commitSha}`);
await runCommand({
jobId: job.id,
command: this.configService.get<string>('GIT_BIN', 'git'),
args: ['checkout', job.commitSha],
cwd: workDir,
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
}
}
private async executeByComponentType(
job: BuildJobWithComponent,
workDir: string,
append: (line: string) => Promise<void>,
) {
if (job.image) {
await this.buildAndPushImage(job, workDir, append);
return;
}
if (job.component.type === 'MIGRATION') {
await append('[migration] repository checkout verified');
await append('[migration] actual DB migration is handled by deployment step');
return;
}
if (job.component.type === 'ELECTRON') {
await this.buildArtifact(job, workDir, append);
return;
}
await append(`[skip] no build action configured for ${job.component.type}`);
}
private async buildAndPushImage(
job: BuildJobWithComponent,
workDir: string,
append: (line: string) => Promise<void>,
) {
const image = this.resolveImage(job.image!);
const builder = this.configService.get<string>('BUILD_IMAGE_BUILDER', 'docker');
const dockerfile = this.configService.get<string>('BUILD_DOCKERFILE', 'Dockerfile');
const contextPath = this.configService.get<string>('BUILD_CONTEXT_PATH', '.');
const contextDir = path.resolve(workDir, contextPath);
const pushEnabled = this.configService.get<string>('BUILD_PUSH_ENABLED', 'true') !== 'false';
if (image !== job.image) {
await this.prisma.buildJob.update({
where: { id: job.id },
data: { image },
});
await append(`[image] rewritten to ${image}`);
}
if (builder === 'nerdctl') {
const namespace = this.configService.get<string>('BUILD_NERDCTL_NAMESPACE');
const prefix = namespace ? ['--namespace', namespace] : [];
await runCommand({
jobId: job.id,
command: this.configService.get<string>('NERDCTL_BIN', 'nerdctl'),
args: [...prefix, 'build', '-t', image, '-f', dockerfile, '.'],
cwd: contextDir,
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
if (pushEnabled) {
await runCommand({
jobId: job.id,
command: this.configService.get<string>('NERDCTL_BIN', 'nerdctl'),
args: [...prefix, 'push', image],
cwd: contextDir,
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
}
return;
}
await runCommand({
jobId: job.id,
command: this.configService.get<string>('DOCKER_BIN', 'docker'),
args: ['build', '-t', image, '-f', dockerfile, '.'],
cwd: contextDir,
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
if (pushEnabled) {
await runCommand({
jobId: job.id,
command: this.configService.get<string>('DOCKER_BIN', 'docker'),
args: ['push', image],
cwd: contextDir,
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
}
}
private resolveImage(image: string) {
const registry = this.configService.get<string>('BUILD_REGISTRY');
if (!registry) return image;
const imagePath = image.includes('/') ? image.slice(image.indexOf('/') + 1) : image;
return `${registry.replace(/\/$/, '')}/${imagePath}`;
}
private async buildArtifact(
job: BuildJobWithComponent,
workDir: string,
append: (line: string) => Promise<void>,
) {
const installCommand = this.configService.get<string>(
'BUILD_ARTIFACT_INSTALL_COMMAND',
'npm ci',
);
const buildCommand = this.configService.get<string>(
'BUILD_ELECTRON_COMMAND',
'npm run build:linux',
);
const outputDir = this.configService.get<string>(
'BUILD_ARTIFACT_OUTPUT_DIR',
'dist',
);
const artifactDir = this.configService.get<string>(
'BUILD_ARTIFACT_DIR',
path.join(os.tmpdir(), 'studio-admin-artifacts'),
);
await append(`[artifact] install ${installCommand}`);
await runShellCommand({
jobId: job.id,
command: installCommand,
cwd: workDir,
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
await append(`[artifact] build ${buildCommand}`);
await runShellCommand({
jobId: job.id,
command: buildCommand,
cwd: workDir,
append,
onProcess: (child) => this.activeProcesses.set(job.id, child),
onProcessEnd: () => this.activeProcesses.delete(job.id),
});
const artifact = await findNewestArtifact(path.resolve(workDir, outputDir));
if (!artifact) {
throw new Error(`산출물을 찾을 수 없습니다: ${outputDir}`);
}
await fs.mkdir(artifactDir, { recursive: true });
const destinationName = job.artifact || path.basename(artifact);
const destination = path.join(artifactDir, destinationName);
await fs.copyFile(artifact, destination);
const uploadedArtifact = await this.uploadArtifactIfConfigured(
job,
destination,
destinationName,
append,
);
const publicBaseUrl = this.configService.get<string>('BUILD_ARTIFACT_BASE_URL');
const artifactValue = uploadedArtifact
?? (publicBaseUrl
? `${publicBaseUrl.replace(/\/$/, '')}/${encodeURIComponent(destinationName)}`
: destination);
await this.prisma.buildJob.update({
where: { id: job.id },
data: { artifact: artifactValue },
});
job.artifact = artifactValue;
await append(`[artifact] found ${path.relative(workDir, artifact)}`);
await append(`[artifact] copied to ${artifactValue}`);
}
private async uploadArtifactIfConfigured(
job: BuildJobWithComponent,
artifactPath: string,
artifactName: string,
append: (line: string) => Promise<void>,
) {
const bucket = this.configService.get<string>('R2_BUCKET');
const publicBaseUrl = this.configService.get<string>('R2_PUBLIC_BASE_URL');
const accessKeyId = this.configService.get<string>('R2_ACCESS_KEY_ID');
const secretAccessKey = this.configService.get<string>('R2_SECRET_ACCESS_KEY');
if (!bucket || !publicBaseUrl || !accessKeyId || !secretAccessKey) {
return null;
}
const key = this.createArtifactObjectKey(job, artifactName);
const stat = await fs.stat(artifactPath);
const sha256 = await sha256File(artifactPath);
const client = this.getR2Client(accessKeyId, secretAccessKey);
await append(`[r2] upload ${key}`);
await client.send(new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: createReadStream(artifactPath),
ContentLength: stat.size,
ContentType: contentTypeForFile(artifactName),
ContentDisposition: contentDispositionForFile(artifactName),
Metadata: {
sha256,
app: safeMetadataValue(job.component.app.key),
component: safeMetadataValue(job.component.name),
branch: safeMetadataValue(job.branch),
commit: safeMetadataValue(job.commitSha ?? ''),
},
}));
await client.send(new PutObjectCommand({
Bucket: bucket,
Key: `${key}.sha256`,
Body: `${sha256} ${artifactName}\n`,
ContentType: 'text/plain; charset=utf-8',
}));
const url = `${publicBaseUrl.replace(/\/$/, '')}/${encodeObjectKey(key)}`;
await append(`[r2] uploaded ${url}`);
await append(`[r2] sha256 ${sha256}`);
return url;
}
private getR2Client(accessKeyId: string, secretAccessKey: string) {
if (this.r2Client) return this.r2Client;
const endpoint = this.configService.get<string>('R2_ENDPOINT')
|| `https://${this.configService.get<string>('R2_ACCOUNT_ID')}.r2.cloudflarestorage.com`;
this.r2Client = new S3Client({
region: this.configService.get<string>('R2_REGION', 'auto'),
endpoint,
credentials: {
accessKeyId,
secretAccessKey,
},
forcePathStyle: this.configService.get<string>('R2_FORCE_PATH_STYLE', 'true') !== 'false',
});
return this.r2Client;
}
private createArtifactObjectKey(job: BuildJobWithComponent, artifactName: string) {
const prefix = this.configService.get<string>('R2_ARTIFACT_PREFIX', 'studio-artifacts');
const revision = job.commitSha?.trim().slice(0, 7) || job.id;
return [
prefix,
'apps',
job.component.app.key,
job.component.name,
job.branch,
revision,
artifactName,
].map(sanitizeObjectKeyPart).join('/');
}
private getHttpCloneUrl(repository: string) {
return `${this.configService
.get<string>('GITEA_BASE_URL', 'http://localhost:3000')
.replace(/\/$/, '')}/${repository}.git`;
}
private async getAuthenticatedHttpCloneUrl(repository: string) {
const baseUrl = this.getHttpCloneUrl(repository);
const token = this.configService.get<string>('GITEA_ADMIN_TOKEN');
if (!token || this.configService.get<string>('BUILD_GIT_AUTH', 'token') === 'none') {
return baseUrl;
}
const username =
this.configService.get<string>('BUILD_GIT_USERNAME') ??
(await this.getGiteaUsername(token));
const url = new URL(baseUrl);
url.username = username;
url.password = token;
return url.toString();
}
private async getGiteaUsername(token: string) {
if (this.giteaUsername) return this.giteaUsername;
const response = await fetch(
`${this.configService
.get<string>('GITEA_BASE_URL', 'http://localhost:3000')
.replace(/\/$/, '')}/api/v1/user`,
{
headers: {
Accept: 'application/json',
Authorization: `token ${token}`,
},
},
);
if (!response.ok) {
throw new Error(`Gitea 사용자 확인 실패: ${response.status}`);
}
const data = (await response.json()) as { login?: string };
if (!data.login) {
throw new Error('Gitea 토큰 사용자명을 확인할 수 없습니다.');
}
this.giteaUsername = data.login;
return data.login;
}
}
async function runCommand({
jobId,
command,
args,
safeArgs = args,
cwd,
append,
onProcess,
onProcessEnd,
}: {
jobId: string;
command: string;
args: string[];
safeArgs?: string[];
cwd: string;
append: (line: string) => Promise<void>;
onProcess: (child: ChildProcess) => void;
onProcessEnd: () => void;
}) {
await append(`[run] ${command} ${safeArgs.join(' ')}`);
await new Promise<void>((resolve, reject) => {
const child = spawn(command, args, {
cwd,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: true,
});
let output = '';
onProcess(child);
child.stdout.on('data', (chunk: Buffer) => {
output += chunk.toString();
});
child.stderr.on('data', (chunk: Buffer) => {
output += chunk.toString();
});
child.on('error', (error) => {
onProcessEnd();
reject(error);
});
child.on('close', async (code) => {
onProcessEnd();
try {
for (const line of output.split(/\r?\n/).filter(Boolean)) {
await append(`[out] ${line}`);
}
} catch (error) {
reject(error);
return;
}
if (code === 0) {
resolve();
return;
}
reject(new Error(`${command} for job ${jobId} exited with code ${code}`));
});
});
}
async function runShellCommand({
jobId,
command,
cwd,
append,
onProcess,
onProcessEnd,
}: {
jobId: string;
command: string;
cwd: string;
append: (line: string) => Promise<void>;
onProcess: (child: ChildProcess) => void;
onProcessEnd: () => void;
}) {
await append(`[run] ${command}`);
await new Promise<void>((resolve, reject) => {
const child = spawn(command, {
cwd,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: true,
shell: true,
});
let output = '';
onProcess(child);
child.stdout.on('data', (chunk: Buffer) => {
output += chunk.toString();
});
child.stderr.on('data', (chunk: Buffer) => {
output += chunk.toString();
});
child.on('error', (error) => {
onProcessEnd();
reject(error);
});
child.on('close', async (code) => {
onProcessEnd();
try {
for (const line of output.split(/\r?\n/).filter(Boolean)) {
await append(`[out] ${line}`);
}
} catch (error) {
reject(error);
return;
}
if (code === 0) {
resolve();
return;
}
reject(new Error(`${command} for job ${jobId} exited with code ${code}`));
});
});
}
async function findNewestArtifact(dir: string) {
const candidates = await findArtifactCandidates(dir).catch(() => []);
candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
return candidates[0]?.path ?? null;
}
async function findArtifactCandidates(dir: string): Promise<Array<{ path: string; mtimeMs: number }>> {
const entries = await fs.readdir(dir, { withFileTypes: true });
const results: Array<{ path: string; mtimeMs: number }> = [];
for (const entry of entries) {
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...await findArtifactCandidates(entryPath));
continue;
}
if (!/\.(AppImage|deb|rpm|zip|tar\.gz)$/i.test(entry.name)) continue;
const stat = await fs.stat(entryPath);
results.push({ path: entryPath, mtimeMs: stat.mtimeMs });
}
return results;
}
async function sha256File(filePath: string) {
const hash = createHash('sha256');
await new Promise<void>((resolve, reject) => {
const stream = createReadStream(filePath);
stream.on('data', (chunk) => hash.update(chunk));
stream.on('error', reject);
stream.on('end', resolve);
});
return hash.digest('hex');
}
function contentTypeForFile(fileName: string) {
const lowerName = fileName.toLowerCase();
if (lowerName.endsWith('.tar.gz')) return 'application/gzip';
const extension = path.extname(lowerName);
const types: Record<string, string> = {
'.appimage': 'application/octet-stream',
'.deb': 'application/vnd.debian.binary-package',
'.rpm': 'application/x-rpm',
'.zip': 'application/zip',
'.json': 'application/json',
'.txt': 'text/plain; charset=utf-8',
'.yml': 'application/x-yaml',
'.yaml': 'application/x-yaml',
};
return types[extension] ?? 'application/octet-stream';
}
function sanitizeObjectKeyPart(value: string) {
return value
.trim()
.replace(/^\/+|\/+$/g, '')
.replace(/[^a-zA-Z0-9._@+=-]+/g, '-')
|| 'unknown';
}
function encodeObjectKey(key: string) {
return key.split('/').map(encodeURIComponent).join('/');
}
function contentDispositionForFile(fileName: string) {
const fallbackName = fileName.replace(/[\\\"\r\n]/g, '_');
return `attachment; filename="${fallbackName}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
}
function safeMetadataValue(value: string) {
return value.replace(/[^\x20-\x7E]/g, '').slice(0, 512);
}
function terminateProcess(child: ChildProcess) {
if (!child.pid || child.killed) return;
try {
process.kill(-child.pid, 'SIGTERM');
setTimeout(() => {
if (!child.killed && child.pid) {
try {
process.kill(-child.pid, 'SIGKILL');
} catch {
// Process may have already exited.
}
}
}, 3000).unref();
} catch {
child.kill('SIGTERM');
}
}
function splitLogs(logs: string | null) {
return logs ? logs.split('\n').filter(Boolean) : [];
}
function truncateLogs(logs: string) {
return logs.length > 200_000 ? logs.slice(-200_000) : logs;
}
function redact(value: string, secret: string) {
if (!secret) return value;
return value.split(secret).join('<redacted>');
}
+222
View File
@@ -0,0 +1,222 @@
import { ArrayNotEmpty, IsArray, IsBoolean, IsEnum, IsInt, IsOptional, IsString, IsUUID, Min } from 'class-validator';
import { AppStatus, ComponentType } from './app-enums';
export class CreateAppDto {
@IsString()
key!: string;
@IsString()
name!: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsString()
namespace?: string;
@IsOptional()
@IsEnum(AppStatus)
status?: AppStatus;
}
export class CreateAppComponentDto {
@IsString()
name!: string;
@IsEnum(ComponentType)
type!: ComponentType;
@IsOptional()
@IsString()
imageSource?: string;
@IsOptional()
@IsString()
externalImage?: string;
@IsOptional()
@IsString()
workloadType?: string;
@IsOptional()
@IsInt()
@Min(0)
replicas?: number;
@IsOptional()
@IsString()
serviceType?: string;
@IsOptional()
@IsBoolean()
storageEnabled?: boolean;
@IsOptional()
@IsString()
storageSize?: string;
@IsOptional()
@IsString()
storageMountPath?: string;
@IsOptional()
@IsBoolean()
storageRetain?: boolean;
@IsOptional()
@IsString()
repository?: string;
@IsOptional()
@IsString()
branch?: string;
@IsOptional()
@IsString()
buildTarget?: string;
@IsOptional()
@IsInt()
@Min(1)
port?: number;
@IsOptional()
@IsInt()
@Min(1)
targetPort?: number;
@IsOptional()
@IsArray()
ports?: Array<{
name?: string;
port?: number;
targetPort?: number;
protocol?: string;
}>;
}
export class CreateRuntimeIngressRuleDto {
@IsUUID()
componentId!: string;
@IsString()
host!: string;
@IsOptional()
@IsString()
path?: string;
@IsInt()
@Min(1)
servicePort!: number;
@IsOptional()
@IsBoolean()
tlsEnabled?: boolean;
@IsOptional()
@IsString()
tlsSecretName?: string;
}
export class CreateBuildJobDto {
@IsUUID()
componentId!: string;
@IsOptional()
@IsString()
branch?: string;
@IsOptional()
@IsString()
commitSha?: string;
}
export class CreateAppReleaseDto {
@IsUUID()
appId!: string;
@IsString()
version!: string;
@IsOptional()
@IsString()
branch?: string;
@IsArray()
@ArrayNotEmpty()
@IsUUID(undefined, { each: true })
buildJobIds!: string[];
}
export class CreateDeploymentJobDto {
@IsUUID()
releaseId!: string;
@IsString()
environment!: string;
@IsString()
namespace!: string;
@IsOptional()
@IsBoolean()
updateLauncherAppVersion?: boolean;
}
export class CreateRuntimeEnvProfileDto {
@IsUUID()
appId!: string;
@IsString()
name!: string;
@IsString()
environment!: string;
@IsString()
namespace!: string;
}
export class CreateRuntimeEnvVariableDto {
@IsOptional()
@IsUUID()
componentId?: string;
@IsString()
key!: string;
@IsString()
value!: string;
@IsOptional()
@IsBoolean()
isSecret?: boolean;
}
export class EnsureRuntimeNamespaceDto {
@IsString()
namespace!: string;
}
export class CreateMigrationJobDto {
@IsUUID()
releaseId!: string;
@IsUUID()
migrationComponentId!: string;
@IsString()
imageComponentName!: string;
@IsString()
namespace!: string;
@IsString()
command!: string;
@IsString()
envSecretName!: string;
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { AuthPrismaService } from './auth-prisma.service';
@Module({
providers: [AuthPrismaService],
exports: [AuthPrismaService],
})
export class AuthPrismaModule {}
+28
View File
@@ -0,0 +1,28 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaClient } from '@prisma/auth-client';
@Injectable()
export class AuthPrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor(configService: ConfigService) {
super({
datasources: {
db: {
url: configService.getOrThrow<string>('AUTH_DATABASE_URL'),
},
},
});
}
async onModuleInit() {
await this.$connect();
}
async onModuleDestroy() {
await this.$disconnect();
}
}
+1
View File
@@ -0,0 +1 @@
export * from "./index"
+5
View File
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
module.exports = { ...require('.') }
+1
View File
@@ -0,0 +1 @@
export * from "./index"
+5
View File
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
module.exports = { ...require('#main-entry-point') }
+1
View File
@@ -0,0 +1 @@
export * from "./default"
File diff suppressed because one or more lines are too long
+217
View File
@@ -0,0 +1,217 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
Object.defineProperty(exports, "__esModule", { value: true });
const {
Decimal,
objectEnumValues,
makeStrictEnum,
Public,
getRuntime,
skip
} = require('./runtime/index-browser.js')
const Prisma = {}
exports.Prisma = Prisma
exports.$Enums = {}
/**
* Prisma Client JS version: 6.19.3
* Query Engine version: c2990dca591cba766e3b7ef5d9e8a84796e47ab7
*/
Prisma.prismaVersion = {
client: "6.19.3",
engine: "c2990dca591cba766e3b7ef5d9e8a84796e47ab7"
}
Prisma.PrismaClientKnownRequestError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientKnownRequestError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)};
Prisma.PrismaClientUnknownRequestError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientUnknownRequestError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.PrismaClientRustPanicError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientRustPanicError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.PrismaClientInitializationError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientInitializationError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.PrismaClientValidationError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientValidationError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.Decimal = Decimal
/**
* Re-export of sql-template-tag
*/
Prisma.sql = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`sqltag is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.empty = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`empty is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.join = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`join is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.raw = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`raw is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.validator = Public.validator
/**
* Extensions
*/
Prisma.getExtensionContext = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`Extensions.getExtensionContext is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.defineExtension = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`Extensions.defineExtension is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
/**
* Shorthand utilities for JSON filtering
*/
Prisma.DbNull = objectEnumValues.instances.DbNull
Prisma.JsonNull = objectEnumValues.instances.JsonNull
Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = {
DbNull: objectEnumValues.classes.DbNull,
JsonNull: objectEnumValues.classes.JsonNull,
AnyNull: objectEnumValues.classes.AnyNull
}
/**
* Enums
*/
exports.Prisma.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
});
exports.Prisma.UserScalarFieldEnum = {
id: 'id',
email: 'email',
passwordHash: 'passwordHash',
name: 'name',
role: 'role',
isActive: 'isActive',
lastLoginAt: 'lastLoginAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.LicenseScalarFieldEnum = {
id: 'id',
code: 'code',
name: 'name',
description: 'description',
defaultDurationDays: 'defaultDurationDays',
isActive: 'isActive',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.UserLicenseScalarFieldEnum = {
id: 'id',
userId: 'userId',
licenseId: 'licenseId',
startsAt: 'startsAt',
expiresAt: 'expiresAt',
assignedById: 'assignedById',
createdAt: 'createdAt'
};
exports.Prisma.SortOrder = {
asc: 'asc',
desc: 'desc'
};
exports.Prisma.QueryMode = {
default: 'default',
insensitive: 'insensitive'
};
exports.Prisma.NullsOrder = {
first: 'first',
last: 'last'
};
exports.UserRole = exports.$Enums.UserRole = {
ADMIN: 'ADMIN',
USER: 'USER'
};
exports.LicenseCode = exports.$Enums.LicenseCode = {
FREE: 'FREE',
EDUCATION: 'EDUCATION',
PROFESSIONAL: 'PROFESSIONAL'
};
exports.Prisma.ModelName = {
User: 'User',
License: 'License',
UserLicense: 'UserLicense'
};
/**
* This is a stub Prisma Client that will error at runtime if called.
*/
class PrismaClient {
constructor() {
return new Proxy(this, {
get(target, prop) {
let message
const runtime = getRuntime()
if (runtime.isEdge) {
message = `PrismaClient is not configured to run in ${runtime.prettyName}. In order to run Prisma Client on edge runtime, either:
- Use Prisma Accelerate: https://pris.ly/d/accelerate
- Use Driver Adapters: https://pris.ly/d/driver-adapters
`;
} else {
message = 'PrismaClient is unable to run in this browser environment, or has been bundled for the browser (running in `' + runtime.prettyName + '`).'
}
message += `
If this is unexpected, please open an issue: https://pris.ly/prisma-prisma-bug-report`
throw new Error(message)
}
})
}
}
exports.PrismaClient = PrismaClient
Object.assign(exports, Prisma)
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+183
View File
@@ -0,0 +1,183 @@
{
"name": "prisma-client-378612c311cf1c6fac598c21e6ea51068a0548bfbc7fdc08b65098bb7a2e5523",
"main": "index.js",
"types": "index.d.ts",
"browser": "default.js",
"exports": {
"./client": {
"require": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"import": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"default": "./index.js"
},
"./package.json": "./package.json",
".": {
"require": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"import": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"default": "./index.js"
},
"./edge": {
"types": "./edge.d.ts",
"require": "./edge.js",
"import": "./edge.js",
"default": "./edge.js"
},
"./react-native": {
"types": "./react-native.d.ts",
"require": "./react-native.js",
"import": "./react-native.js",
"default": "./react-native.js"
},
"./extension": {
"types": "./extension.d.ts",
"require": "./extension.js",
"import": "./extension.js",
"default": "./extension.js"
},
"./index-browser": {
"types": "./index.d.ts",
"require": "./index-browser.js",
"import": "./index-browser.js",
"default": "./index-browser.js"
},
"./index": {
"types": "./index.d.ts",
"require": "./index.js",
"import": "./index.js",
"default": "./index.js"
},
"./wasm": {
"types": "./wasm.d.ts",
"require": "./wasm.js",
"import": "./wasm.mjs",
"default": "./wasm.mjs"
},
"./runtime/client": {
"types": "./runtime/client.d.ts",
"node": {
"require": "./runtime/client.js",
"default": "./runtime/client.js"
},
"require": "./runtime/client.js",
"import": "./runtime/client.mjs",
"default": "./runtime/client.mjs"
},
"./runtime/library": {
"types": "./runtime/library.d.ts",
"require": "./runtime/library.js",
"import": "./runtime/library.mjs",
"default": "./runtime/library.mjs"
},
"./runtime/binary": {
"types": "./runtime/binary.d.ts",
"require": "./runtime/binary.js",
"import": "./runtime/binary.mjs",
"default": "./runtime/binary.mjs"
},
"./runtime/wasm-engine-edge": {
"types": "./runtime/wasm-engine-edge.d.ts",
"require": "./runtime/wasm-engine-edge.js",
"import": "./runtime/wasm-engine-edge.mjs",
"default": "./runtime/wasm-engine-edge.mjs"
},
"./runtime/wasm-compiler-edge": {
"types": "./runtime/wasm-compiler-edge.d.ts",
"require": "./runtime/wasm-compiler-edge.js",
"import": "./runtime/wasm-compiler-edge.mjs",
"default": "./runtime/wasm-compiler-edge.mjs"
},
"./runtime/edge": {
"types": "./runtime/edge.d.ts",
"require": "./runtime/edge.js",
"import": "./runtime/edge-esm.js",
"default": "./runtime/edge-esm.js"
},
"./runtime/react-native": {
"types": "./runtime/react-native.d.ts",
"require": "./runtime/react-native.js",
"import": "./runtime/react-native.js",
"default": "./runtime/react-native.js"
},
"./runtime/index-browser": {
"types": "./runtime/index-browser.d.ts",
"require": "./runtime/index-browser.js",
"import": "./runtime/index-browser.mjs",
"default": "./runtime/index-browser.mjs"
},
"./generator-build": {
"require": "./generator-build/index.js",
"import": "./generator-build/index.js",
"default": "./generator-build/index.js"
},
"./sql": {
"require": {
"types": "./sql.d.ts",
"node": "./sql.js",
"default": "./sql.js"
},
"import": {
"types": "./sql.d.ts",
"node": "./sql.mjs",
"default": "./sql.mjs"
},
"default": "./sql.js"
},
"./*": "./*"
},
"version": "6.19.3",
"sideEffects": false,
"imports": {
"#wasm-engine-loader": {
"edge-light": "./wasm-edge-light-loader.mjs",
"workerd": "./wasm-worker-loader.mjs",
"worker": "./wasm-worker-loader.mjs",
"default": "./wasm-worker-loader.mjs"
},
"#main-entry-point": {
"require": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"import": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"default": "./index.js"
}
}
}
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+370
View File
@@ -0,0 +1,370 @@
declare class AnyNull extends NullTypesEnumValue {
#private;
}
declare type Args<T, F extends Operation> = T extends {
[K: symbol]: {
types: {
operations: {
[K in F]: {
args: any;
};
};
};
};
} ? T[symbol]['types']['operations'][F]['args'] : any;
declare class DbNull extends NullTypesEnumValue {
#private;
}
export declare function Decimal(n: Decimal.Value): Decimal;
export declare namespace Decimal {
export type Constructor = typeof Decimal;
export type Instance = Decimal;
export type Rounding = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
export type Modulo = Rounding | 9;
export type Value = string | number | Decimal;
// http://mikemcl.github.io/decimal.js/#constructor-properties
export interface Config {
precision?: number;
rounding?: Rounding;
toExpNeg?: number;
toExpPos?: number;
minE?: number;
maxE?: number;
crypto?: boolean;
modulo?: Modulo;
defaults?: boolean;
}
}
export declare class Decimal {
readonly d: number[];
readonly e: number;
readonly s: number;
constructor(n: Decimal.Value);
absoluteValue(): Decimal;
abs(): Decimal;
ceil(): Decimal;
clampedTo(min: Decimal.Value, max: Decimal.Value): Decimal;
clamp(min: Decimal.Value, max: Decimal.Value): Decimal;
comparedTo(n: Decimal.Value): number;
cmp(n: Decimal.Value): number;
cosine(): Decimal;
cos(): Decimal;
cubeRoot(): Decimal;
cbrt(): Decimal;
decimalPlaces(): number;
dp(): number;
dividedBy(n: Decimal.Value): Decimal;
div(n: Decimal.Value): Decimal;
dividedToIntegerBy(n: Decimal.Value): Decimal;
divToInt(n: Decimal.Value): Decimal;
equals(n: Decimal.Value): boolean;
eq(n: Decimal.Value): boolean;
floor(): Decimal;
greaterThan(n: Decimal.Value): boolean;
gt(n: Decimal.Value): boolean;
greaterThanOrEqualTo(n: Decimal.Value): boolean;
gte(n: Decimal.Value): boolean;
hyperbolicCosine(): Decimal;
cosh(): Decimal;
hyperbolicSine(): Decimal;
sinh(): Decimal;
hyperbolicTangent(): Decimal;
tanh(): Decimal;
inverseCosine(): Decimal;
acos(): Decimal;
inverseHyperbolicCosine(): Decimal;
acosh(): Decimal;
inverseHyperbolicSine(): Decimal;
asinh(): Decimal;
inverseHyperbolicTangent(): Decimal;
atanh(): Decimal;
inverseSine(): Decimal;
asin(): Decimal;
inverseTangent(): Decimal;
atan(): Decimal;
isFinite(): boolean;
isInteger(): boolean;
isInt(): boolean;
isNaN(): boolean;
isNegative(): boolean;
isNeg(): boolean;
isPositive(): boolean;
isPos(): boolean;
isZero(): boolean;
lessThan(n: Decimal.Value): boolean;
lt(n: Decimal.Value): boolean;
lessThanOrEqualTo(n: Decimal.Value): boolean;
lte(n: Decimal.Value): boolean;
logarithm(n?: Decimal.Value): Decimal;
log(n?: Decimal.Value): Decimal;
minus(n: Decimal.Value): Decimal;
sub(n: Decimal.Value): Decimal;
modulo(n: Decimal.Value): Decimal;
mod(n: Decimal.Value): Decimal;
naturalExponential(): Decimal;
exp(): Decimal;
naturalLogarithm(): Decimal;
ln(): Decimal;
negated(): Decimal;
neg(): Decimal;
plus(n: Decimal.Value): Decimal;
add(n: Decimal.Value): Decimal;
precision(includeZeros?: boolean): number;
sd(includeZeros?: boolean): number;
round(): Decimal;
sine() : Decimal;
sin() : Decimal;
squareRoot(): Decimal;
sqrt(): Decimal;
tangent() : Decimal;
tan() : Decimal;
times(n: Decimal.Value): Decimal;
mul(n: Decimal.Value) : Decimal;
toBinary(significantDigits?: number): string;
toBinary(significantDigits: number, rounding: Decimal.Rounding): string;
toDecimalPlaces(decimalPlaces?: number): Decimal;
toDecimalPlaces(decimalPlaces: number, rounding: Decimal.Rounding): Decimal;
toDP(decimalPlaces?: number): Decimal;
toDP(decimalPlaces: number, rounding: Decimal.Rounding): Decimal;
toExponential(decimalPlaces?: number): string;
toExponential(decimalPlaces: number, rounding: Decimal.Rounding): string;
toFixed(decimalPlaces?: number): string;
toFixed(decimalPlaces: number, rounding: Decimal.Rounding): string;
toFraction(max_denominator?: Decimal.Value): Decimal[];
toHexadecimal(significantDigits?: number): string;
toHexadecimal(significantDigits: number, rounding: Decimal.Rounding): string;
toHex(significantDigits?: number): string;
toHex(significantDigits: number, rounding?: Decimal.Rounding): string;
toJSON(): string;
toNearest(n: Decimal.Value, rounding?: Decimal.Rounding): Decimal;
toNumber(): number;
toOctal(significantDigits?: number): string;
toOctal(significantDigits: number, rounding: Decimal.Rounding): string;
toPower(n: Decimal.Value): Decimal;
pow(n: Decimal.Value): Decimal;
toPrecision(significantDigits?: number): string;
toPrecision(significantDigits: number, rounding: Decimal.Rounding): string;
toSignificantDigits(significantDigits?: number): Decimal;
toSignificantDigits(significantDigits: number, rounding: Decimal.Rounding): Decimal;
toSD(significantDigits?: number): Decimal;
toSD(significantDigits: number, rounding: Decimal.Rounding): Decimal;
toString(): string;
truncated(): Decimal;
trunc(): Decimal;
valueOf(): string;
static abs(n: Decimal.Value): Decimal;
static acos(n: Decimal.Value): Decimal;
static acosh(n: Decimal.Value): Decimal;
static add(x: Decimal.Value, y: Decimal.Value): Decimal;
static asin(n: Decimal.Value): Decimal;
static asinh(n: Decimal.Value): Decimal;
static atan(n: Decimal.Value): Decimal;
static atanh(n: Decimal.Value): Decimal;
static atan2(y: Decimal.Value, x: Decimal.Value): Decimal;
static cbrt(n: Decimal.Value): Decimal;
static ceil(n: Decimal.Value): Decimal;
static clamp(n: Decimal.Value, min: Decimal.Value, max: Decimal.Value): Decimal;
static clone(object?: Decimal.Config): Decimal.Constructor;
static config(object: Decimal.Config): Decimal.Constructor;
static cos(n: Decimal.Value): Decimal;
static cosh(n: Decimal.Value): Decimal;
static div(x: Decimal.Value, y: Decimal.Value): Decimal;
static exp(n: Decimal.Value): Decimal;
static floor(n: Decimal.Value): Decimal;
static hypot(...n: Decimal.Value[]): Decimal;
static isDecimal(object: any): object is Decimal;
static ln(n: Decimal.Value): Decimal;
static log(n: Decimal.Value, base?: Decimal.Value): Decimal;
static log2(n: Decimal.Value): Decimal;
static log10(n: Decimal.Value): Decimal;
static max(...n: Decimal.Value[]): Decimal;
static min(...n: Decimal.Value[]): Decimal;
static mod(x: Decimal.Value, y: Decimal.Value): Decimal;
static mul(x: Decimal.Value, y: Decimal.Value): Decimal;
static noConflict(): Decimal.Constructor; // Browser only
static pow(base: Decimal.Value, exponent: Decimal.Value): Decimal;
static random(significantDigits?: number): Decimal;
static round(n: Decimal.Value): Decimal;
static set(object: Decimal.Config): Decimal.Constructor;
static sign(n: Decimal.Value): number;
static sin(n: Decimal.Value): Decimal;
static sinh(n: Decimal.Value): Decimal;
static sqrt(n: Decimal.Value): Decimal;
static sub(x: Decimal.Value, y: Decimal.Value): Decimal;
static sum(...n: Decimal.Value[]): Decimal;
static tan(n: Decimal.Value): Decimal;
static tanh(n: Decimal.Value): Decimal;
static trunc(n: Decimal.Value): Decimal;
static readonly default?: Decimal.Constructor;
static readonly Decimal?: Decimal.Constructor;
static readonly precision: number;
static readonly rounding: Decimal.Rounding;
static readonly toExpNeg: number;
static readonly toExpPos: number;
static readonly minE: number;
static readonly maxE: number;
static readonly crypto: boolean;
static readonly modulo: Decimal.Modulo;
static readonly ROUND_UP: 0;
static readonly ROUND_DOWN: 1;
static readonly ROUND_CEIL: 2;
static readonly ROUND_FLOOR: 3;
static readonly ROUND_HALF_UP: 4;
static readonly ROUND_HALF_DOWN: 5;
static readonly ROUND_HALF_EVEN: 6;
static readonly ROUND_HALF_CEIL: 7;
static readonly ROUND_HALF_FLOOR: 8;
static readonly EUCLID: 9;
}
declare type Exact<A, W> = (A extends unknown ? (W extends A ? {
[K in keyof A]: Exact<A[K], W[K]>;
} : W) : never) | (A extends Narrowable ? A : never);
export declare function getRuntime(): GetRuntimeOutput;
declare type GetRuntimeOutput = {
id: RuntimeName;
prettyName: string;
isEdge: boolean;
};
declare class JsonNull extends NullTypesEnumValue {
#private;
}
/**
* Generates more strict variant of an enum which, unlike regular enum,
* throws on non-existing property access. This can be useful in following situations:
* - we have an API, that accepts both `undefined` and `SomeEnumType` as an input
* - enum values are generated dynamically from DMMF.
*
* In that case, if using normal enums and no compile-time typechecking, using non-existing property
* will result in `undefined` value being used, which will be accepted. Using strict enum
* in this case will help to have a runtime exception, telling you that you are probably doing something wrong.
*
* Note: if you need to check for existence of a value in the enum you can still use either
* `in` operator or `hasOwnProperty` function.
*
* @param definition
* @returns
*/
export declare function makeStrictEnum<T extends Record<PropertyKey, string | number>>(definition: T): T;
declare type Narrowable = string | number | bigint | boolean | [];
declare class NullTypesEnumValue extends ObjectEnumValue {
_getNamespace(): string;
}
/**
* Base class for unique values of object-valued enums.
*/
declare abstract class ObjectEnumValue {
constructor(arg?: symbol);
abstract _getNamespace(): string;
_getName(): string;
toString(): string;
}
export declare const objectEnumValues: {
classes: {
DbNull: typeof DbNull;
JsonNull: typeof JsonNull;
AnyNull: typeof AnyNull;
};
instances: {
DbNull: DbNull;
JsonNull: JsonNull;
AnyNull: AnyNull;
};
};
declare type Operation = 'findFirst' | 'findFirstOrThrow' | 'findUnique' | 'findUniqueOrThrow' | 'findMany' | 'create' | 'createMany' | 'createManyAndReturn' | 'update' | 'updateMany' | 'updateManyAndReturn' | 'upsert' | 'delete' | 'deleteMany' | 'aggregate' | 'count' | 'groupBy' | '$queryRaw' | '$executeRaw' | '$queryRawUnsafe' | '$executeRawUnsafe' | 'findRaw' | 'aggregateRaw' | '$runCommandRaw';
declare namespace Public {
export {
validator
}
}
export { Public }
declare type RuntimeName = 'workerd' | 'deno' | 'netlify' | 'node' | 'bun' | 'edge-light' | '';
declare function validator<V>(): <S>(select: Exact<S, V>) => S;
declare function validator<C, M extends Exclude<keyof C, `$${string}`>, O extends keyof C[M] & Operation>(client: C, model: M, operation: O): <S>(select: Exact<S, Args<C[M], O>>) => S;
declare function validator<C, M extends Exclude<keyof C, `$${string}`>, O extends keyof C[M] & Operation, P extends keyof Args<C[M], O>>(client: C, model: M, operation: O, prop: P): <S>(select: Exact<S, Args<C[M], O>[P]>) => S;
export { }
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+66
View File
@@ -0,0 +1,66 @@
generator authClient {
provider = "prisma-client-js"
output = "../src/generated/auth-client"
}
datasource db {
provider = "postgresql"
url = env("AUTH_DATABASE_URL")
}
enum UserRole {
ADMIN
USER
}
enum LicenseCode {
FREE
EDUCATION
PROFESSIONAL
}
model User {
id String @id @default(uuid()) @db.Uuid
email String @unique
passwordHash String @map("password_hash")
name String?
role UserRole @default(USER)
isActive Boolean @default(true) @map("is_active")
lastLoginAt DateTime? @map("last_login_at") @db.Timestamptz(3)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
userLicenses UserLicense[]
@@map("users")
}
model License {
id String @id @default(uuid()) @db.Uuid
code LicenseCode @unique
name String
description String?
defaultDurationDays Int? @default(365) @map("default_duration_days")
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
userLicenses UserLicense[]
@@index([isActive])
@@map("licenses")
}
model UserLicense {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
licenseId String @map("license_id") @db.Uuid
startsAt DateTime @default(now()) @map("starts_at") @db.Timestamptz(3)
expiresAt DateTime? @map("expires_at") @db.Timestamptz(3)
assignedById String? @map("assigned_by") @db.Uuid
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
license License @relation(fields: [licenseId], references: [id], onDelete: Restrict)
@@index([userId, startsAt])
@@index([licenseId])
@@map("user_licenses")
}
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
export default import('./query_engine_bg.wasm?module')
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
export default import('./query_engine_bg.wasm')
+1
View File
@@ -0,0 +1 @@
export * from "./default"
+238
View File
@@ -0,0 +1,238 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
Object.defineProperty(exports, "__esModule", { value: true });
const {
PrismaClientKnownRequestError,
PrismaClientUnknownRequestError,
PrismaClientRustPanicError,
PrismaClientInitializationError,
PrismaClientValidationError,
getPrismaClient,
sqltag,
empty,
join,
raw,
skip,
Decimal,
Debug,
objectEnumValues,
makeStrictEnum,
Extensions,
warnOnce,
defineDmmfProperty,
Public,
getRuntime,
createParam,
} = require('./runtime/wasm-engine-edge.js')
const Prisma = {}
exports.Prisma = Prisma
exports.$Enums = {}
/**
* Prisma Client JS version: 6.19.3
* Query Engine version: c2990dca591cba766e3b7ef5d9e8a84796e47ab7
*/
Prisma.prismaVersion = {
client: "6.19.3",
engine: "c2990dca591cba766e3b7ef5d9e8a84796e47ab7"
}
Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError;
Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError
Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError
Prisma.PrismaClientInitializationError = PrismaClientInitializationError
Prisma.PrismaClientValidationError = PrismaClientValidationError
Prisma.Decimal = Decimal
/**
* Re-export of sql-template-tag
*/
Prisma.sql = sqltag
Prisma.empty = empty
Prisma.join = join
Prisma.raw = raw
Prisma.validator = Public.validator
/**
* Extensions
*/
Prisma.getExtensionContext = Extensions.getExtensionContext
Prisma.defineExtension = Extensions.defineExtension
/**
* Shorthand utilities for JSON filtering
*/
Prisma.DbNull = objectEnumValues.instances.DbNull
Prisma.JsonNull = objectEnumValues.instances.JsonNull
Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = {
DbNull: objectEnumValues.classes.DbNull,
JsonNull: objectEnumValues.classes.JsonNull,
AnyNull: objectEnumValues.classes.AnyNull
}
/**
* Enums
*/
exports.Prisma.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
});
exports.Prisma.UserScalarFieldEnum = {
id: 'id',
email: 'email',
passwordHash: 'passwordHash',
name: 'name',
role: 'role',
isActive: 'isActive',
lastLoginAt: 'lastLoginAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.LicenseScalarFieldEnum = {
id: 'id',
code: 'code',
name: 'name',
description: 'description',
defaultDurationDays: 'defaultDurationDays',
isActive: 'isActive',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.UserLicenseScalarFieldEnum = {
id: 'id',
userId: 'userId',
licenseId: 'licenseId',
startsAt: 'startsAt',
expiresAt: 'expiresAt',
assignedById: 'assignedById',
createdAt: 'createdAt'
};
exports.Prisma.SortOrder = {
asc: 'asc',
desc: 'desc'
};
exports.Prisma.QueryMode = {
default: 'default',
insensitive: 'insensitive'
};
exports.Prisma.NullsOrder = {
first: 'first',
last: 'last'
};
exports.UserRole = exports.$Enums.UserRole = {
ADMIN: 'ADMIN',
USER: 'USER'
};
exports.LicenseCode = exports.$Enums.LicenseCode = {
FREE: 'FREE',
EDUCATION: 'EDUCATION',
PROFESSIONAL: 'PROFESSIONAL'
};
exports.Prisma.ModelName = {
User: 'User',
License: 'License',
UserLicense: 'UserLicense'
};
/**
* Create the Client
*/
const config = {
"generator": {
"name": "authClient",
"provider": {
"fromEnvVar": null,
"value": "prisma-client-js"
},
"output": {
"value": "/home/chyoo/tmp/atnmy-stdo-v2/atnmy-stdo-adm-v2-be/src/generated/auth-client",
"fromEnvVar": null
},
"config": {
"engineType": "library"
},
"binaryTargets": [
{
"fromEnvVar": null,
"value": "debian-openssl-3.0.x",
"native": true
}
],
"previewFeatures": [],
"sourceFilePath": "/home/chyoo/tmp/atnmy-stdo-v2/atnmy-stdo-adm-v2-be/prisma/auth.schema.prisma",
"isCustomOutput": true
},
"relativeEnvPaths": {
"rootEnvPath": null,
"schemaEnvPath": "../../../.env"
},
"relativePath": "../../../prisma",
"clientVersion": "6.19.3",
"engineVersion": "c2990dca591cba766e3b7ef5d9e8a84796e47ab7",
"datasourceNames": [
"db"
],
"activeProvider": "postgresql",
"postinstall": false,
"inlineDatasources": {
"db": {
"url": {
"fromEnvVar": "AUTH_DATABASE_URL",
"value": null
}
}
},
"inlineSchema": "generator authClient {\n provider = \"prisma-client-js\"\n output = \"../src/generated/auth-client\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"AUTH_DATABASE_URL\")\n}\n\nenum UserRole {\n ADMIN\n USER\n}\n\nenum LicenseCode {\n FREE\n EDUCATION\n PROFESSIONAL\n}\n\nmodel User {\n id String @id @default(uuid()) @db.Uuid\n email String @unique\n passwordHash String @map(\"password_hash\")\n name String?\n role UserRole @default(USER)\n isActive Boolean @default(true) @map(\"is_active\")\n lastLoginAt DateTime? @map(\"last_login_at\") @db.Timestamptz(3)\n createdAt DateTime @default(now()) @map(\"created_at\") @db.Timestamptz(3)\n updatedAt DateTime @updatedAt @map(\"updated_at\") @db.Timestamptz(3)\n userLicenses UserLicense[]\n\n @@map(\"users\")\n}\n\nmodel License {\n id String @id @default(uuid()) @db.Uuid\n code LicenseCode @unique\n name String\n description String?\n defaultDurationDays Int? @default(365) @map(\"default_duration_days\")\n isActive Boolean @default(true) @map(\"is_active\")\n createdAt DateTime @default(now()) @map(\"created_at\") @db.Timestamptz(3)\n updatedAt DateTime @updatedAt @map(\"updated_at\") @db.Timestamptz(3)\n userLicenses UserLicense[]\n\n @@index([isActive])\n @@map(\"licenses\")\n}\n\nmodel UserLicense {\n id String @id @default(uuid()) @db.Uuid\n userId String @map(\"user_id\") @db.Uuid\n licenseId String @map(\"license_id\") @db.Uuid\n startsAt DateTime @default(now()) @map(\"starts_at\") @db.Timestamptz(3)\n expiresAt DateTime? @map(\"expires_at\") @db.Timestamptz(3)\n assignedById String? @map(\"assigned_by\") @db.Uuid\n createdAt DateTime @default(now()) @map(\"created_at\") @db.Timestamptz(3)\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n license License @relation(fields: [licenseId], references: [id], onDelete: Restrict)\n\n @@index([userId, startsAt])\n @@index([licenseId])\n @@map(\"user_licenses\")\n}\n",
"inlineSchemaHash": "b41ead22c04f404adbe239bd44c2751b9ed9adf3c5b7b7013be05252086f79d7",
"copyEngine": true
}
config.dirname = '/'
config.runtimeDataModel = JSON.parse("{\"models\":{\"User\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"email\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"passwordHash\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"password_hash\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"role\",\"kind\":\"enum\",\"type\":\"UserRole\"},{\"name\":\"isActive\",\"kind\":\"scalar\",\"type\":\"Boolean\",\"dbName\":\"is_active\"},{\"name\":\"lastLoginAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"last_login_at\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"created_at\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"updated_at\"},{\"name\":\"userLicenses\",\"kind\":\"object\",\"type\":\"UserLicense\",\"relationName\":\"UserToUserLicense\"}],\"dbName\":\"users\"},\"License\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"code\",\"kind\":\"enum\",\"type\":\"LicenseCode\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"description\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"defaultDurationDays\",\"kind\":\"scalar\",\"type\":\"Int\",\"dbName\":\"default_duration_days\"},{\"name\":\"isActive\",\"kind\":\"scalar\",\"type\":\"Boolean\",\"dbName\":\"is_active\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"created_at\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"updated_at\"},{\"name\":\"userLicenses\",\"kind\":\"object\",\"type\":\"UserLicense\",\"relationName\":\"LicenseToUserLicense\"}],\"dbName\":\"licenses\"},\"UserLicense\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"user_id\"},{\"name\":\"licenseId\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"license_id\"},{\"name\":\"startsAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"starts_at\"},{\"name\":\"expiresAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"expires_at\"},{\"name\":\"assignedById\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"assigned_by\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"created_at\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"UserToUserLicense\"},{\"name\":\"license\",\"kind\":\"object\",\"type\":\"License\",\"relationName\":\"LicenseToUserLicense\"}],\"dbName\":\"user_licenses\"}},\"enums\":{},\"types\":{}}")
defineDmmfProperty(exports.Prisma, config.runtimeDataModel)
config.engineWasm = {
getRuntime: async () => require('./query_engine_bg.js'),
getQueryEngineWasmModule: async () => {
const loader = (await import('#wasm-engine-loader')).default
const engine = (await loader).default
return engine
}
}
config.compilerWasm = undefined
config.injectableEdgeEnv = () => ({
parsed: {
AUTH_DATABASE_URL: typeof globalThis !== 'undefined' && globalThis['AUTH_DATABASE_URL'] || typeof process !== 'undefined' && process.env && process.env.AUTH_DATABASE_URL || undefined
}
})
if (typeof globalThis !== 'undefined' && globalThis['DEBUG'] || typeof process !== 'undefined' && process.env && process.env.DEBUG || undefined) {
Debug.enable(typeof globalThis !== 'undefined' && globalThis['DEBUG'] || typeof process !== 'undefined' && process.env && process.env.DEBUG || undefined)
}
const PrismaClient = getPrismaClient(config)
exports.PrismaClient = PrismaClient
Object.assign(exports, Prisma)
+1
View File
@@ -0,0 +1 @@
export * from "./index"
+5
View File
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
module.exports = { ...require('.') }
+1
View File
@@ -0,0 +1 @@
export * from "./index"
+5
View File
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
module.exports = { ...require('#main-entry-point') }
+1
View File
@@ -0,0 +1 @@
export * from "./default"
File diff suppressed because one or more lines are too long
@@ -0,0 +1,233 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
Object.defineProperty(exports, "__esModule", { value: true });
const {
Decimal,
objectEnumValues,
makeStrictEnum,
Public,
getRuntime,
skip
} = require('./runtime/index-browser.js')
const Prisma = {}
exports.Prisma = Prisma
exports.$Enums = {}
/**
* Prisma Client JS version: 6.19.3
* Query Engine version: c2990dca591cba766e3b7ef5d9e8a84796e47ab7
*/
Prisma.prismaVersion = {
client: "6.19.3",
engine: "c2990dca591cba766e3b7ef5d9e8a84796e47ab7"
}
Prisma.PrismaClientKnownRequestError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientKnownRequestError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)};
Prisma.PrismaClientUnknownRequestError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientUnknownRequestError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.PrismaClientRustPanicError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientRustPanicError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.PrismaClientInitializationError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientInitializationError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.PrismaClientValidationError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`PrismaClientValidationError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.Decimal = Decimal
/**
* Re-export of sql-template-tag
*/
Prisma.sql = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`sqltag is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.empty = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`empty is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.join = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`join is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.raw = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`raw is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.validator = Public.validator
/**
* Extensions
*/
Prisma.getExtensionContext = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`Extensions.getExtensionContext is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
Prisma.defineExtension = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(`Extensions.defineExtension is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report`,
)}
/**
* Shorthand utilities for JSON filtering
*/
Prisma.DbNull = objectEnumValues.instances.DbNull
Prisma.JsonNull = objectEnumValues.instances.JsonNull
Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = {
DbNull: objectEnumValues.classes.DbNull,
JsonNull: objectEnumValues.classes.JsonNull,
AnyNull: objectEnumValues.classes.AnyNull
}
/**
* Enums
*/
exports.Prisma.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
});
exports.Prisma.LauncherNoticeScalarFieldEnum = {
id: 'id',
appKey: 'appKey',
title: 'title',
body: 'body',
linkUrl: 'linkUrl',
isActive: 'isActive',
startsAt: 'startsAt',
endsAt: 'endsAt',
priority: 'priority',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.ProvisionedDeviceScalarFieldEnum = {
id: 'id',
accountEmail: 'accountEmail',
authUserId: 'authUserId',
hostname: 'hostname',
tailscaleHostname: 'tailscaleHostname',
sshUser: 'sshUser',
workspaceRoot: 'workspaceRoot',
usageType: 'usageType',
os: 'os',
arch: 'arch',
kernel: 'kernel',
distro: 'distro',
device: 'device',
installedAt: 'installedAt',
lastProvisionedAt: 'lastProvisionedAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.LauncherSshKeyScalarFieldEnum = {
id: 'id',
accountEmail: 'accountEmail',
authUserId: 'authUserId',
publicKey: 'publicKey',
publicKeyHash: 'publicKeyHash',
keyType: 'keyType',
label: 'label',
lastProvisionedAt: 'lastProvisionedAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.SortOrder = {
asc: 'asc',
desc: 'desc'
};
exports.Prisma.NullableJsonNullValueInput = {
DbNull: Prisma.DbNull,
JsonNull: Prisma.JsonNull
};
exports.Prisma.QueryMode = {
default: 'default',
insensitive: 'insensitive'
};
exports.Prisma.NullsOrder = {
first: 'first',
last: 'last'
};
exports.Prisma.JsonNullValueFilter = {
DbNull: Prisma.DbNull,
JsonNull: Prisma.JsonNull,
AnyNull: Prisma.AnyNull
};
exports.Prisma.ModelName = {
LauncherNotice: 'LauncherNotice',
ProvisionedDevice: 'ProvisionedDevice',
LauncherSshKey: 'LauncherSshKey'
};
/**
* This is a stub Prisma Client that will error at runtime if called.
*/
class PrismaClient {
constructor() {
return new Proxy(this, {
get(target, prop) {
let message
const runtime = getRuntime()
if (runtime.isEdge) {
message = `PrismaClient is not configured to run in ${runtime.prettyName}. In order to run Prisma Client on edge runtime, either:
- Use Prisma Accelerate: https://pris.ly/d/accelerate
- Use Driver Adapters: https://pris.ly/d/driver-adapters
`;
} else {
message = 'PrismaClient is unable to run in this browser environment, or has been bundled for the browser (running in `' + runtime.prettyName + '`).'
}
message += `
If this is unexpected, please open an issue: https://pris.ly/prisma-prisma-bug-report`
throw new Error(message)
}
})
}
}
exports.PrismaClient = PrismaClient
Object.assign(exports, Prisma)
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+183
View File
@@ -0,0 +1,183 @@
{
"name": "prisma-client-2cc4fd701019d0254ce12699ae25121c6ed85eba27006e31abbdac7779ae92f0",
"main": "index.js",
"types": "index.d.ts",
"browser": "default.js",
"exports": {
"./client": {
"require": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"import": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"default": "./index.js"
},
"./package.json": "./package.json",
".": {
"require": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"import": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"default": "./index.js"
},
"./edge": {
"types": "./edge.d.ts",
"require": "./edge.js",
"import": "./edge.js",
"default": "./edge.js"
},
"./react-native": {
"types": "./react-native.d.ts",
"require": "./react-native.js",
"import": "./react-native.js",
"default": "./react-native.js"
},
"./extension": {
"types": "./extension.d.ts",
"require": "./extension.js",
"import": "./extension.js",
"default": "./extension.js"
},
"./index-browser": {
"types": "./index.d.ts",
"require": "./index-browser.js",
"import": "./index-browser.js",
"default": "./index-browser.js"
},
"./index": {
"types": "./index.d.ts",
"require": "./index.js",
"import": "./index.js",
"default": "./index.js"
},
"./wasm": {
"types": "./wasm.d.ts",
"require": "./wasm.js",
"import": "./wasm.mjs",
"default": "./wasm.mjs"
},
"./runtime/client": {
"types": "./runtime/client.d.ts",
"node": {
"require": "./runtime/client.js",
"default": "./runtime/client.js"
},
"require": "./runtime/client.js",
"import": "./runtime/client.mjs",
"default": "./runtime/client.mjs"
},
"./runtime/library": {
"types": "./runtime/library.d.ts",
"require": "./runtime/library.js",
"import": "./runtime/library.mjs",
"default": "./runtime/library.mjs"
},
"./runtime/binary": {
"types": "./runtime/binary.d.ts",
"require": "./runtime/binary.js",
"import": "./runtime/binary.mjs",
"default": "./runtime/binary.mjs"
},
"./runtime/wasm-engine-edge": {
"types": "./runtime/wasm-engine-edge.d.ts",
"require": "./runtime/wasm-engine-edge.js",
"import": "./runtime/wasm-engine-edge.mjs",
"default": "./runtime/wasm-engine-edge.mjs"
},
"./runtime/wasm-compiler-edge": {
"types": "./runtime/wasm-compiler-edge.d.ts",
"require": "./runtime/wasm-compiler-edge.js",
"import": "./runtime/wasm-compiler-edge.mjs",
"default": "./runtime/wasm-compiler-edge.mjs"
},
"./runtime/edge": {
"types": "./runtime/edge.d.ts",
"require": "./runtime/edge.js",
"import": "./runtime/edge-esm.js",
"default": "./runtime/edge-esm.js"
},
"./runtime/react-native": {
"types": "./runtime/react-native.d.ts",
"require": "./runtime/react-native.js",
"import": "./runtime/react-native.js",
"default": "./runtime/react-native.js"
},
"./runtime/index-browser": {
"types": "./runtime/index-browser.d.ts",
"require": "./runtime/index-browser.js",
"import": "./runtime/index-browser.mjs",
"default": "./runtime/index-browser.mjs"
},
"./generator-build": {
"require": "./generator-build/index.js",
"import": "./generator-build/index.js",
"default": "./generator-build/index.js"
},
"./sql": {
"require": {
"types": "./sql.d.ts",
"node": "./sql.js",
"default": "./sql.js"
},
"import": {
"types": "./sql.d.ts",
"node": "./sql.mjs",
"default": "./sql.mjs"
},
"default": "./sql.js"
},
"./*": "./*"
},
"version": "6.19.3",
"sideEffects": false,
"imports": {
"#wasm-engine-loader": {
"edge-light": "./wasm-edge-light-loader.mjs",
"workerd": "./wasm-worker-loader.mjs",
"worker": "./wasm-worker-loader.mjs",
"default": "./wasm-worker-loader.mjs"
},
"#main-entry-point": {
"require": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"import": {
"node": "./index.js",
"edge-light": "./wasm.js",
"workerd": "./wasm.js",
"worker": "./wasm.js",
"browser": "./index-browser.js",
"default": "./index.js"
},
"default": "./index.js"
}
}
}
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+370
View File
@@ -0,0 +1,370 @@
declare class AnyNull extends NullTypesEnumValue {
#private;
}
declare type Args<T, F extends Operation> = T extends {
[K: symbol]: {
types: {
operations: {
[K in F]: {
args: any;
};
};
};
};
} ? T[symbol]['types']['operations'][F]['args'] : any;
declare class DbNull extends NullTypesEnumValue {
#private;
}
export declare function Decimal(n: Decimal.Value): Decimal;
export declare namespace Decimal {
export type Constructor = typeof Decimal;
export type Instance = Decimal;
export type Rounding = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
export type Modulo = Rounding | 9;
export type Value = string | number | Decimal;
// http://mikemcl.github.io/decimal.js/#constructor-properties
export interface Config {
precision?: number;
rounding?: Rounding;
toExpNeg?: number;
toExpPos?: number;
minE?: number;
maxE?: number;
crypto?: boolean;
modulo?: Modulo;
defaults?: boolean;
}
}
export declare class Decimal {
readonly d: number[];
readonly e: number;
readonly s: number;
constructor(n: Decimal.Value);
absoluteValue(): Decimal;
abs(): Decimal;
ceil(): Decimal;
clampedTo(min: Decimal.Value, max: Decimal.Value): Decimal;
clamp(min: Decimal.Value, max: Decimal.Value): Decimal;
comparedTo(n: Decimal.Value): number;
cmp(n: Decimal.Value): number;
cosine(): Decimal;
cos(): Decimal;
cubeRoot(): Decimal;
cbrt(): Decimal;
decimalPlaces(): number;
dp(): number;
dividedBy(n: Decimal.Value): Decimal;
div(n: Decimal.Value): Decimal;
dividedToIntegerBy(n: Decimal.Value): Decimal;
divToInt(n: Decimal.Value): Decimal;
equals(n: Decimal.Value): boolean;
eq(n: Decimal.Value): boolean;
floor(): Decimal;
greaterThan(n: Decimal.Value): boolean;
gt(n: Decimal.Value): boolean;
greaterThanOrEqualTo(n: Decimal.Value): boolean;
gte(n: Decimal.Value): boolean;
hyperbolicCosine(): Decimal;
cosh(): Decimal;
hyperbolicSine(): Decimal;
sinh(): Decimal;
hyperbolicTangent(): Decimal;
tanh(): Decimal;
inverseCosine(): Decimal;
acos(): Decimal;
inverseHyperbolicCosine(): Decimal;
acosh(): Decimal;
inverseHyperbolicSine(): Decimal;
asinh(): Decimal;
inverseHyperbolicTangent(): Decimal;
atanh(): Decimal;
inverseSine(): Decimal;
asin(): Decimal;
inverseTangent(): Decimal;
atan(): Decimal;
isFinite(): boolean;
isInteger(): boolean;
isInt(): boolean;
isNaN(): boolean;
isNegative(): boolean;
isNeg(): boolean;
isPositive(): boolean;
isPos(): boolean;
isZero(): boolean;
lessThan(n: Decimal.Value): boolean;
lt(n: Decimal.Value): boolean;
lessThanOrEqualTo(n: Decimal.Value): boolean;
lte(n: Decimal.Value): boolean;
logarithm(n?: Decimal.Value): Decimal;
log(n?: Decimal.Value): Decimal;
minus(n: Decimal.Value): Decimal;
sub(n: Decimal.Value): Decimal;
modulo(n: Decimal.Value): Decimal;
mod(n: Decimal.Value): Decimal;
naturalExponential(): Decimal;
exp(): Decimal;
naturalLogarithm(): Decimal;
ln(): Decimal;
negated(): Decimal;
neg(): Decimal;
plus(n: Decimal.Value): Decimal;
add(n: Decimal.Value): Decimal;
precision(includeZeros?: boolean): number;
sd(includeZeros?: boolean): number;
round(): Decimal;
sine() : Decimal;
sin() : Decimal;
squareRoot(): Decimal;
sqrt(): Decimal;
tangent() : Decimal;
tan() : Decimal;
times(n: Decimal.Value): Decimal;
mul(n: Decimal.Value) : Decimal;
toBinary(significantDigits?: number): string;
toBinary(significantDigits: number, rounding: Decimal.Rounding): string;
toDecimalPlaces(decimalPlaces?: number): Decimal;
toDecimalPlaces(decimalPlaces: number, rounding: Decimal.Rounding): Decimal;
toDP(decimalPlaces?: number): Decimal;
toDP(decimalPlaces: number, rounding: Decimal.Rounding): Decimal;
toExponential(decimalPlaces?: number): string;
toExponential(decimalPlaces: number, rounding: Decimal.Rounding): string;
toFixed(decimalPlaces?: number): string;
toFixed(decimalPlaces: number, rounding: Decimal.Rounding): string;
toFraction(max_denominator?: Decimal.Value): Decimal[];
toHexadecimal(significantDigits?: number): string;
toHexadecimal(significantDigits: number, rounding: Decimal.Rounding): string;
toHex(significantDigits?: number): string;
toHex(significantDigits: number, rounding?: Decimal.Rounding): string;
toJSON(): string;
toNearest(n: Decimal.Value, rounding?: Decimal.Rounding): Decimal;
toNumber(): number;
toOctal(significantDigits?: number): string;
toOctal(significantDigits: number, rounding: Decimal.Rounding): string;
toPower(n: Decimal.Value): Decimal;
pow(n: Decimal.Value): Decimal;
toPrecision(significantDigits?: number): string;
toPrecision(significantDigits: number, rounding: Decimal.Rounding): string;
toSignificantDigits(significantDigits?: number): Decimal;
toSignificantDigits(significantDigits: number, rounding: Decimal.Rounding): Decimal;
toSD(significantDigits?: number): Decimal;
toSD(significantDigits: number, rounding: Decimal.Rounding): Decimal;
toString(): string;
truncated(): Decimal;
trunc(): Decimal;
valueOf(): string;
static abs(n: Decimal.Value): Decimal;
static acos(n: Decimal.Value): Decimal;
static acosh(n: Decimal.Value): Decimal;
static add(x: Decimal.Value, y: Decimal.Value): Decimal;
static asin(n: Decimal.Value): Decimal;
static asinh(n: Decimal.Value): Decimal;
static atan(n: Decimal.Value): Decimal;
static atanh(n: Decimal.Value): Decimal;
static atan2(y: Decimal.Value, x: Decimal.Value): Decimal;
static cbrt(n: Decimal.Value): Decimal;
static ceil(n: Decimal.Value): Decimal;
static clamp(n: Decimal.Value, min: Decimal.Value, max: Decimal.Value): Decimal;
static clone(object?: Decimal.Config): Decimal.Constructor;
static config(object: Decimal.Config): Decimal.Constructor;
static cos(n: Decimal.Value): Decimal;
static cosh(n: Decimal.Value): Decimal;
static div(x: Decimal.Value, y: Decimal.Value): Decimal;
static exp(n: Decimal.Value): Decimal;
static floor(n: Decimal.Value): Decimal;
static hypot(...n: Decimal.Value[]): Decimal;
static isDecimal(object: any): object is Decimal;
static ln(n: Decimal.Value): Decimal;
static log(n: Decimal.Value, base?: Decimal.Value): Decimal;
static log2(n: Decimal.Value): Decimal;
static log10(n: Decimal.Value): Decimal;
static max(...n: Decimal.Value[]): Decimal;
static min(...n: Decimal.Value[]): Decimal;
static mod(x: Decimal.Value, y: Decimal.Value): Decimal;
static mul(x: Decimal.Value, y: Decimal.Value): Decimal;
static noConflict(): Decimal.Constructor; // Browser only
static pow(base: Decimal.Value, exponent: Decimal.Value): Decimal;
static random(significantDigits?: number): Decimal;
static round(n: Decimal.Value): Decimal;
static set(object: Decimal.Config): Decimal.Constructor;
static sign(n: Decimal.Value): number;
static sin(n: Decimal.Value): Decimal;
static sinh(n: Decimal.Value): Decimal;
static sqrt(n: Decimal.Value): Decimal;
static sub(x: Decimal.Value, y: Decimal.Value): Decimal;
static sum(...n: Decimal.Value[]): Decimal;
static tan(n: Decimal.Value): Decimal;
static tanh(n: Decimal.Value): Decimal;
static trunc(n: Decimal.Value): Decimal;
static readonly default?: Decimal.Constructor;
static readonly Decimal?: Decimal.Constructor;
static readonly precision: number;
static readonly rounding: Decimal.Rounding;
static readonly toExpNeg: number;
static readonly toExpPos: number;
static readonly minE: number;
static readonly maxE: number;
static readonly crypto: boolean;
static readonly modulo: Decimal.Modulo;
static readonly ROUND_UP: 0;
static readonly ROUND_DOWN: 1;
static readonly ROUND_CEIL: 2;
static readonly ROUND_FLOOR: 3;
static readonly ROUND_HALF_UP: 4;
static readonly ROUND_HALF_DOWN: 5;
static readonly ROUND_HALF_EVEN: 6;
static readonly ROUND_HALF_CEIL: 7;
static readonly ROUND_HALF_FLOOR: 8;
static readonly EUCLID: 9;
}
declare type Exact<A, W> = (A extends unknown ? (W extends A ? {
[K in keyof A]: Exact<A[K], W[K]>;
} : W) : never) | (A extends Narrowable ? A : never);
export declare function getRuntime(): GetRuntimeOutput;
declare type GetRuntimeOutput = {
id: RuntimeName;
prettyName: string;
isEdge: boolean;
};
declare class JsonNull extends NullTypesEnumValue {
#private;
}
/**
* Generates more strict variant of an enum which, unlike regular enum,
* throws on non-existing property access. This can be useful in following situations:
* - we have an API, that accepts both `undefined` and `SomeEnumType` as an input
* - enum values are generated dynamically from DMMF.
*
* In that case, if using normal enums and no compile-time typechecking, using non-existing property
* will result in `undefined` value being used, which will be accepted. Using strict enum
* in this case will help to have a runtime exception, telling you that you are probably doing something wrong.
*
* Note: if you need to check for existence of a value in the enum you can still use either
* `in` operator or `hasOwnProperty` function.
*
* @param definition
* @returns
*/
export declare function makeStrictEnum<T extends Record<PropertyKey, string | number>>(definition: T): T;
declare type Narrowable = string | number | bigint | boolean | [];
declare class NullTypesEnumValue extends ObjectEnumValue {
_getNamespace(): string;
}
/**
* Base class for unique values of object-valued enums.
*/
declare abstract class ObjectEnumValue {
constructor(arg?: symbol);
abstract _getNamespace(): string;
_getName(): string;
toString(): string;
}
export declare const objectEnumValues: {
classes: {
DbNull: typeof DbNull;
JsonNull: typeof JsonNull;
AnyNull: typeof AnyNull;
};
instances: {
DbNull: DbNull;
JsonNull: JsonNull;
AnyNull: AnyNull;
};
};
declare type Operation = 'findFirst' | 'findFirstOrThrow' | 'findUnique' | 'findUniqueOrThrow' | 'findMany' | 'create' | 'createMany' | 'createManyAndReturn' | 'update' | 'updateMany' | 'updateManyAndReturn' | 'upsert' | 'delete' | 'deleteMany' | 'aggregate' | 'count' | 'groupBy' | '$queryRaw' | '$executeRaw' | '$queryRawUnsafe' | '$executeRawUnsafe' | 'findRaw' | 'aggregateRaw' | '$runCommandRaw';
declare namespace Public {
export {
validator
}
}
export { Public }
declare type RuntimeName = 'workerd' | 'deno' | 'netlify' | 'node' | 'bun' | 'edge-light' | '';
declare function validator<V>(): <S>(select: Exact<S, V>) => S;
declare function validator<C, M extends Exclude<keyof C, `$${string}`>, O extends keyof C[M] & Operation>(client: C, model: M, operation: O): <S>(select: Exact<S, Args<C[M], O>>) => S;
declare function validator<C, M extends Exclude<keyof C, `$${string}`>, O extends keyof C[M] & Operation, P extends keyof Args<C[M], O>>(client: C, model: M, operation: O, prop: P): <S>(select: Exact<S, Args<C[M], O>[P]>) => S;
export { }
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,68 @@
generator launcherClient {
provider = "prisma-client-js"
output = "../src/generated/launcher-client"
}
datasource db {
provider = "postgresql"
url = env("LAUNCHER_DATABASE_URL")
}
model LauncherNotice {
id String @id @default(uuid()) @db.Uuid
appKey String @default("login") @map("app_key")
title String
body String
linkUrl String? @map("link_url")
isActive Boolean @default(true) @map("is_active")
startsAt DateTime? @map("starts_at") @db.Timestamptz(3)
endsAt DateTime? @map("ends_at") @db.Timestamptz(3)
priority Int @default(0)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
@@index([appKey, isActive, priority])
@@map("launcher_notices")
}
model ProvisionedDevice {
id String @id @default(uuid()) @db.Uuid
accountEmail String @map("account_email")
authUserId String? @map("auth_user_id") @db.Uuid
hostname String
tailscaleHostname String @map("tailscale_hostname")
sshUser String? @map("ssh_user")
workspaceRoot String? @map("workspace_root")
usageType String @default("personal") @map("usage_type")
os String?
arch String?
kernel String?
distro String?
device Json?
installedAt DateTime @default(now()) @map("installed_at") @db.Timestamptz(3)
lastProvisionedAt DateTime @default(now()) @map("last_provisioned_at") @db.Timestamptz(3)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
@@unique([accountEmail, tailscaleHostname])
@@index([accountEmail])
@@index([tailscaleHostname])
@@map("provisioned_devices")
}
model LauncherSshKey {
id String @id @default(uuid()) @db.Uuid
accountEmail String @map("account_email")
authUserId String? @map("auth_user_id") @db.Uuid
publicKey String @map("public_key")
publicKeyHash String @map("public_key_hash")
keyType String? @map("key_type")
label String?
lastProvisionedAt DateTime @default(now()) @map("last_provisioned_at") @db.Timestamptz(3)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
@@unique([accountEmail, publicKeyHash])
@@index([accountEmail])
@@map("launcher_ssh_keys")
}
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
export default import('./query_engine_bg.wasm?module')
@@ -0,0 +1,5 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
export default import('./query_engine_bg.wasm')
+1
View File
@@ -0,0 +1 @@
export * from "./default"
+254
View File
@@ -0,0 +1,254 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!!
/* eslint-disable */
// biome-ignore-all lint: generated file
Object.defineProperty(exports, "__esModule", { value: true });
const {
PrismaClientKnownRequestError,
PrismaClientUnknownRequestError,
PrismaClientRustPanicError,
PrismaClientInitializationError,
PrismaClientValidationError,
getPrismaClient,
sqltag,
empty,
join,
raw,
skip,
Decimal,
Debug,
objectEnumValues,
makeStrictEnum,
Extensions,
warnOnce,
defineDmmfProperty,
Public,
getRuntime,
createParam,
} = require('./runtime/wasm-engine-edge.js')
const Prisma = {}
exports.Prisma = Prisma
exports.$Enums = {}
/**
* Prisma Client JS version: 6.19.3
* Query Engine version: c2990dca591cba766e3b7ef5d9e8a84796e47ab7
*/
Prisma.prismaVersion = {
client: "6.19.3",
engine: "c2990dca591cba766e3b7ef5d9e8a84796e47ab7"
}
Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError;
Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError
Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError
Prisma.PrismaClientInitializationError = PrismaClientInitializationError
Prisma.PrismaClientValidationError = PrismaClientValidationError
Prisma.Decimal = Decimal
/**
* Re-export of sql-template-tag
*/
Prisma.sql = sqltag
Prisma.empty = empty
Prisma.join = join
Prisma.raw = raw
Prisma.validator = Public.validator
/**
* Extensions
*/
Prisma.getExtensionContext = Extensions.getExtensionContext
Prisma.defineExtension = Extensions.defineExtension
/**
* Shorthand utilities for JSON filtering
*/
Prisma.DbNull = objectEnumValues.instances.DbNull
Prisma.JsonNull = objectEnumValues.instances.JsonNull
Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = {
DbNull: objectEnumValues.classes.DbNull,
JsonNull: objectEnumValues.classes.JsonNull,
AnyNull: objectEnumValues.classes.AnyNull
}
/**
* Enums
*/
exports.Prisma.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
});
exports.Prisma.LauncherNoticeScalarFieldEnum = {
id: 'id',
appKey: 'appKey',
title: 'title',
body: 'body',
linkUrl: 'linkUrl',
isActive: 'isActive',
startsAt: 'startsAt',
endsAt: 'endsAt',
priority: 'priority',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.ProvisionedDeviceScalarFieldEnum = {
id: 'id',
accountEmail: 'accountEmail',
authUserId: 'authUserId',
hostname: 'hostname',
tailscaleHostname: 'tailscaleHostname',
sshUser: 'sshUser',
workspaceRoot: 'workspaceRoot',
usageType: 'usageType',
os: 'os',
arch: 'arch',
kernel: 'kernel',
distro: 'distro',
device: 'device',
installedAt: 'installedAt',
lastProvisionedAt: 'lastProvisionedAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.LauncherSshKeyScalarFieldEnum = {
id: 'id',
accountEmail: 'accountEmail',
authUserId: 'authUserId',
publicKey: 'publicKey',
publicKeyHash: 'publicKeyHash',
keyType: 'keyType',
label: 'label',
lastProvisionedAt: 'lastProvisionedAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
};
exports.Prisma.SortOrder = {
asc: 'asc',
desc: 'desc'
};
exports.Prisma.NullableJsonNullValueInput = {
DbNull: Prisma.DbNull,
JsonNull: Prisma.JsonNull
};
exports.Prisma.QueryMode = {
default: 'default',
insensitive: 'insensitive'
};
exports.Prisma.NullsOrder = {
first: 'first',
last: 'last'
};
exports.Prisma.JsonNullValueFilter = {
DbNull: Prisma.DbNull,
JsonNull: Prisma.JsonNull,
AnyNull: Prisma.AnyNull
};
exports.Prisma.ModelName = {
LauncherNotice: 'LauncherNotice',
ProvisionedDevice: 'ProvisionedDevice',
LauncherSshKey: 'LauncherSshKey'
};
/**
* Create the Client
*/
const config = {
"generator": {
"name": "launcherClient",
"provider": {
"fromEnvVar": null,
"value": "prisma-client-js"
},
"output": {
"value": "/home/chyoo/tmp/atnmy-stdo-v2/atnmy-stdo-adm-v2-be/src/generated/launcher-client",
"fromEnvVar": null
},
"config": {
"engineType": "library"
},
"binaryTargets": [
{
"fromEnvVar": null,
"value": "debian-openssl-3.0.x",
"native": true
}
],
"previewFeatures": [],
"sourceFilePath": "/home/chyoo/tmp/atnmy-stdo-v2/atnmy-stdo-adm-v2-be/prisma/launcher.schema.prisma",
"isCustomOutput": true
},
"relativeEnvPaths": {
"rootEnvPath": null,
"schemaEnvPath": "../../../.env"
},
"relativePath": "../../../prisma",
"clientVersion": "6.19.3",
"engineVersion": "c2990dca591cba766e3b7ef5d9e8a84796e47ab7",
"datasourceNames": [
"db"
],
"activeProvider": "postgresql",
"postinstall": false,
"inlineDatasources": {
"db": {
"url": {
"fromEnvVar": "LAUNCHER_DATABASE_URL",
"value": null
}
}
},
"inlineSchema": "generator launcherClient {\n provider = \"prisma-client-js\"\n output = \"../src/generated/launcher-client\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"LAUNCHER_DATABASE_URL\")\n}\n\nmodel LauncherNotice {\n id String @id @default(uuid()) @db.Uuid\n appKey String @default(\"login\") @map(\"app_key\")\n title String\n body String\n linkUrl String? @map(\"link_url\")\n isActive Boolean @default(true) @map(\"is_active\")\n startsAt DateTime? @map(\"starts_at\") @db.Timestamptz(3)\n endsAt DateTime? @map(\"ends_at\") @db.Timestamptz(3)\n priority Int @default(0)\n createdAt DateTime @default(now()) @map(\"created_at\") @db.Timestamptz(3)\n updatedAt DateTime @updatedAt @map(\"updated_at\") @db.Timestamptz(3)\n\n @@index([appKey, isActive, priority])\n @@map(\"launcher_notices\")\n}\n\nmodel ProvisionedDevice {\n id String @id @default(uuid()) @db.Uuid\n accountEmail String @map(\"account_email\")\n authUserId String? @map(\"auth_user_id\") @db.Uuid\n hostname String\n tailscaleHostname String @map(\"tailscale_hostname\")\n sshUser String? @map(\"ssh_user\")\n workspaceRoot String? @map(\"workspace_root\")\n usageType String @default(\"personal\") @map(\"usage_type\")\n os String?\n arch String?\n kernel String?\n distro String?\n device Json?\n installedAt DateTime @default(now()) @map(\"installed_at\") @db.Timestamptz(3)\n lastProvisionedAt DateTime @default(now()) @map(\"last_provisioned_at\") @db.Timestamptz(3)\n createdAt DateTime @default(now()) @map(\"created_at\") @db.Timestamptz(3)\n updatedAt DateTime @updatedAt @map(\"updated_at\") @db.Timestamptz(3)\n\n @@unique([accountEmail, tailscaleHostname])\n @@index([accountEmail])\n @@index([tailscaleHostname])\n @@map(\"provisioned_devices\")\n}\n\nmodel LauncherSshKey {\n id String @id @default(uuid()) @db.Uuid\n accountEmail String @map(\"account_email\")\n authUserId String? @map(\"auth_user_id\") @db.Uuid\n publicKey String @map(\"public_key\")\n publicKeyHash String @map(\"public_key_hash\")\n keyType String? @map(\"key_type\")\n label String?\n lastProvisionedAt DateTime @default(now()) @map(\"last_provisioned_at\") @db.Timestamptz(3)\n createdAt DateTime @default(now()) @map(\"created_at\") @db.Timestamptz(3)\n updatedAt DateTime @updatedAt @map(\"updated_at\") @db.Timestamptz(3)\n\n @@unique([accountEmail, publicKeyHash])\n @@index([accountEmail])\n @@map(\"launcher_ssh_keys\")\n}\n",
"inlineSchemaHash": "ad20160732d203c5e1ea82cbcac0488ce94e47432c3136a3833df4661c0a049b",
"copyEngine": true
}
config.dirname = '/'
config.runtimeDataModel = JSON.parse("{\"models\":{\"LauncherNotice\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"appKey\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"app_key\"},{\"name\":\"title\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"body\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"linkUrl\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"link_url\"},{\"name\":\"isActive\",\"kind\":\"scalar\",\"type\":\"Boolean\",\"dbName\":\"is_active\"},{\"name\":\"startsAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"starts_at\"},{\"name\":\"endsAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"ends_at\"},{\"name\":\"priority\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"created_at\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"updated_at\"}],\"dbName\":\"launcher_notices\"},\"ProvisionedDevice\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"accountEmail\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"account_email\"},{\"name\":\"authUserId\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"auth_user_id\"},{\"name\":\"hostname\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"tailscaleHostname\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"tailscale_hostname\"},{\"name\":\"sshUser\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"ssh_user\"},{\"name\":\"workspaceRoot\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"workspace_root\"},{\"name\":\"usageType\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"usage_type\"},{\"name\":\"os\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"arch\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"kernel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"distro\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"device\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"installedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"installed_at\"},{\"name\":\"lastProvisionedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"last_provisioned_at\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"created_at\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"updated_at\"}],\"dbName\":\"provisioned_devices\"},\"LauncherSshKey\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"accountEmail\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"account_email\"},{\"name\":\"authUserId\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"auth_user_id\"},{\"name\":\"publicKey\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"public_key\"},{\"name\":\"publicKeyHash\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"public_key_hash\"},{\"name\":\"keyType\",\"kind\":\"scalar\",\"type\":\"String\",\"dbName\":\"key_type\"},{\"name\":\"label\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"lastProvisionedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"last_provisioned_at\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"created_at\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\",\"dbName\":\"updated_at\"}],\"dbName\":\"launcher_ssh_keys\"}},\"enums\":{},\"types\":{}}")
defineDmmfProperty(exports.Prisma, config.runtimeDataModel)
config.engineWasm = {
getRuntime: async () => require('./query_engine_bg.js'),
getQueryEngineWasmModule: async () => {
const loader = (await import('#wasm-engine-loader')).default
const engine = (await loader).default
return engine
}
}
config.compilerWasm = undefined
config.injectableEdgeEnv = () => ({
parsed: {
LAUNCHER_DATABASE_URL: typeof globalThis !== 'undefined' && globalThis['LAUNCHER_DATABASE_URL'] || typeof process !== 'undefined' && process.env && process.env.LAUNCHER_DATABASE_URL || undefined
}
})
if (typeof globalThis !== 'undefined' && globalThis['DEBUG'] || typeof process !== 'undefined' && process.env && process.env.DEBUG || undefined) {
Debug.enable(typeof globalThis !== 'undefined' && globalThis['DEBUG'] || typeof process !== 'undefined' && process.env && process.env.DEBUG || undefined)
}
const PrismaClient = getPrismaClient(config)
exports.PrismaClient = PrismaClient
Object.assign(exports, Prisma)
+81
View File
@@ -0,0 +1,81 @@
import { IsBoolean, IsInt, IsOptional, IsString, Min } from 'class-validator';
export class ListGiteaReposQuery {
@IsOptional()
@IsString()
keyword?: string;
@IsOptional()
@IsString()
owner?: string;
@IsOptional()
@IsString()
page?: string;
@IsOptional()
@IsString()
limit?: string;
}
export class ListGiteaCommitsQuery {
@IsOptional()
@IsString()
sha?: string;
@IsOptional()
@IsString()
limit?: string;
}
export class ListGiteaTreeQuery {
@IsOptional()
@IsString()
ref?: string;
@IsOptional()
@IsString()
path?: string;
}
export class CreateGiteaRepoDto {
@IsString()
name!: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsBoolean()
private?: boolean;
@IsOptional()
@IsBoolean()
autoInit?: boolean;
@IsOptional()
@IsBoolean()
createDefaultBranches?: boolean;
@IsOptional()
@IsBoolean()
createDevelopBranch?: boolean;
@IsOptional()
@IsBoolean()
createReleaseBranch?: boolean;
}
export class LinkComponentSourceDto {
@IsString()
repository!: string;
@IsOptional()
@IsString()
branch?: string;
@IsOptional()
@IsString()
buildTarget?: string;
}
+67
View File
@@ -0,0 +1,67 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import {
CreateGiteaRepoDto,
ListGiteaCommitsQuery,
ListGiteaReposQuery,
ListGiteaTreeQuery,
} from './dto';
import { GiteaService } from './gitea.service';
@Controller('gitea')
export class GiteaController {
constructor(private readonly giteaService: GiteaService) {}
@Get('version')
getVersion() {
return this.giteaService.getVersion();
}
@Get('repos')
listRepos(@Query() query: ListGiteaReposQuery) {
return this.giteaService.listRepos(query);
}
@Post('repos')
createUserRepo(@Body() body: CreateGiteaRepoDto) {
return this.giteaService.createUserRepo(body);
}
@Post('orgs/:org/repos')
createOrgRepo(@Param('org') org: string, @Body() body: CreateGiteaRepoDto) {
return this.giteaService.createOrgRepo(org, body);
}
@Get('repos/:owner/:repo')
getRepo(@Param('owner') owner: string, @Param('repo') repo: string) {
return this.giteaService.getRepo(owner, repo);
}
@Get('repos/:owner/:repo/branches')
listBranches(@Param('owner') owner: string, @Param('repo') repo: string) {
return this.giteaService.listBranches(owner, repo);
}
@Get('repos/:owner/:repo/commits')
listCommits(
@Param('owner') owner: string,
@Param('repo') repo: string,
@Query() query: ListGiteaCommitsQuery,
) {
return this.giteaService.listCommits(owner, repo, query);
}
@Get('repos/:owner/:repo/releases')
listReleases(@Param('owner') owner: string, @Param('repo') repo: string) {
return this.giteaService.listReleases(owner, repo);
}
@Get('repos/:owner/:repo/tree')
listTree(
@Param('owner') owner: string,
@Param('repo') repo: string,
@Query() query: ListGiteaTreeQuery,
) {
return this.giteaService.listTree(owner, repo, query);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { GiteaController } from './gitea.controller';
import { GiteaService } from './gitea.service';
@Module({
controllers: [GiteaController],
providers: [GiteaService],
exports: [GiteaService],
})
export class GiteaModule {}
+312
View File
@@ -0,0 +1,312 @@
import {
BadGatewayException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
CreateGiteaRepoDto,
ListGiteaCommitsQuery,
ListGiteaReposQuery,
ListGiteaTreeQuery,
} from './dto';
type GiteaRepo = {
id: number;
name: string;
full_name: string;
description: string;
private: boolean;
html_url: string;
clone_url: string;
ssh_url: string;
default_branch: string;
updated_at: string;
owner: { login: string };
language?: string;
branch_count?: number;
release_counter?: number;
};
@Injectable()
export class GiteaService {
private readonly baseUrl: string;
private readonly appOrg: string;
private readonly token?: string;
constructor(configService: ConfigService) {
this.baseUrl = configService
.get<string>('GITEA_BASE_URL', 'http://localhost:3000')
.replace(/\/$/, '');
this.appOrg = configService.get<string>('GITEA_APP_ORG', 'platform');
this.token = configService.get<string>('GITEA_ADMIN_TOKEN') || undefined;
}
async getVersion() {
return this.request<{ version: string }>('/api/v1/version');
}
async listRepos(query: ListGiteaReposQuery) {
const owner = query.owner ?? this.appOrg;
if (owner) {
const repos = await this.request<GiteaRepo[]>(
`/api/v1/orgs/${encodeURIComponent(owner)}/repos`,
);
return {
owner,
repos: repos
.filter((repo) => matchesKeyword(repo, query.keyword))
.map(mapRepo),
};
}
const params = new URLSearchParams();
if (query.keyword) params.set('q', query.keyword);
params.set('page', query.page ?? '1');
params.set('limit', query.limit ?? '30');
const result = await this.request<{ data: GiteaRepo[]; ok: boolean }>(
`/api/v1/repos/search?${params.toString()}`,
);
return {
owner: null,
repos: result.data.map(mapRepo),
};
}
async getRepo(owner: string, repo: string) {
const giteaRepo = await this.request<GiteaRepo>(
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`,
);
return { repo: mapRepo(giteaRepo) };
}
async listBranches(owner: string, repo: string) {
const branches = await this.request<unknown[]>(
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/branches`,
);
return { branches };
}
async listCommits(owner: string, repo: string, query: ListGiteaCommitsQuery) {
const params = new URLSearchParams();
params.set('limit', query.limit ?? '20');
if (query.sha) {
params.set('sha', query.sha);
}
const commits = await this.request<unknown[]>(
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits?${params.toString()}`,
);
return { commits };
}
async listReleases(owner: string, repo: string) {
const releases = await this.request<unknown[]>(
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/releases`,
);
return { releases };
}
async listTree(owner: string, repo: string, query: ListGiteaTreeQuery) {
const ref = query.ref ?? 'main';
const path = query.path ? `/${query.path.replace(/^\/+/, '')}` : '';
const tree = await this.request<unknown>(
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents${path}?ref=${encodeURIComponent(ref)}`,
);
return { tree };
}
async createUserRepo(body: CreateGiteaRepoDto) {
this.assertToken();
const repo = await this.request<GiteaRepo>('/api/v1/user/repos', {
method: 'POST',
body: JSON.stringify(toCreateRepoPayload(body)),
});
if (shouldCreateAnyBranch(body)) {
await this.createDefaultBranches(repo.owner.login, repo.name, repo.default_branch, body);
}
return { repo: mapRepo(repo), branches: await this.listBranches(repo.owner.login, repo.name) };
}
async createOrgRepo(org: string, body: CreateGiteaRepoDto) {
this.assertToken();
const repo = await this.request<GiteaRepo>(`/api/v1/orgs/${encodeURIComponent(org)}/repos`, {
method: 'POST',
body: JSON.stringify(toCreateRepoPayload(body)),
});
if (shouldCreateAnyBranch(body)) {
await this.createDefaultBranches(org, repo.name, repo.default_branch, body);
}
return { repo: mapRepo(repo), branches: await this.listBranches(org, repo.name) };
}
async createUserSshKey(username: string, body: { title: string; key: string }) {
this.assertToken();
return this.request<{ id: number }>(
`/api/v1/admin/users/${encodeURIComponent(username)}/keys`,
{
method: 'POST',
body: JSON.stringify({
title: body.title,
key: body.key,
read_only: false,
}),
},
);
}
async deleteUserSshKey(username: string, keyId: number) {
this.assertToken();
await this.request(
`/api/v1/admin/users/${encodeURIComponent(username)}/keys/${keyId}`,
{
method: 'DELETE',
allowedStatuses: [404],
},
);
}
private async createDefaultBranches(
owner: string,
repo: string,
baseBranch: string,
body: CreateGiteaRepoDto,
) {
const createdBranches = [];
const branches = [
body.createDevelopBranch !== false ? 'develop' : null,
body.createReleaseBranch !== false ? 'release' : null,
].filter((branch): branch is string => Boolean(branch));
for (const branch of branches) {
try {
const created = await this.request(
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/branches`,
{
method: 'POST',
body: JSON.stringify({
new_branch_name: branch,
old_branch_name: baseBranch,
}),
allowedStatuses: [409],
},
);
if (created) {
createdBranches.push(created);
}
} catch (error) {
throw error;
}
}
return createdBranches;
}
private async request<T>(
path: string,
init?: RequestInit & { allowedStatuses?: number[] },
): Promise<T> {
const response = await fetch(`${this.baseUrl}${path}`, {
...init,
headers: {
Accept: 'application/json',
...(init?.body ? { 'Content-Type': 'application/json' } : {}),
...(this.token ? { Authorization: `token ${this.token}` } : {}),
...init?.headers,
},
});
if (init?.allowedStatuses?.includes(response.status)) {
return null as T;
}
if (!response.ok) {
const message = await response.text();
throw new BadGatewayException({
message: 'Gitea API 요청이 실패했습니다.',
status: response.status,
detail: message,
});
}
if (response.status === 204) {
return null as T;
}
return (await response.json()) as T;
}
private assertToken() {
if (!this.token) {
throw new UnauthorizedException(
'GITEA_ADMIN_TOKEN 설정이 필요합니다.',
);
}
}
}
function shouldCreateAnyBranch(body: CreateGiteaRepoDto) {
if (body.createDefaultBranches === false) {
return false;
}
return body.createDevelopBranch !== false || body.createReleaseBranch !== false;
}
function matchesKeyword(repo: GiteaRepo, keyword?: string) {
if (!keyword?.trim()) {
return true;
}
const normalizedKeyword = keyword.trim().toLowerCase();
return [repo.name, repo.full_name, repo.description, repo.language]
.filter((value): value is string => Boolean(value))
.some((value) => value.toLowerCase().includes(normalizedKeyword));
}
function mapRepo(repo: GiteaRepo) {
return {
id: repo.id,
owner: repo.owner.login,
name: repo.name,
fullName: repo.full_name,
description: repo.description,
private: repo.private,
htmlUrl: repo.html_url,
cloneUrl: repo.clone_url,
sshUrl: repo.ssh_url,
defaultBranch: repo.default_branch,
updatedAt: repo.updated_at,
language: repo.language,
branchCount: repo.branch_count,
releaseCount: repo.release_counter,
};
}
function toCreateRepoPayload(body: CreateGiteaRepoDto) {
return {
name: body.name,
description: body.description,
private: body.private ?? true,
auto_init: body.autoInit ?? true,
};
}
+20
View File
@@ -0,0 +1,20 @@
import { Controller, Get } from '@nestjs/common';
import { Public } from '../admin-auth/decorators/admin-auth.decorators';
import { HealthService } from './health.service';
@Public()
@Controller('health')
export class HealthController {
constructor(private readonly healthService: HealthService) {}
@Get()
getHealth() {
return this.healthService.getHealth();
}
@Get('db')
getDbHealth() {
return this.healthService.getDbHealth();
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../prisma/prisma.module';
import { HealthController } from './health.controller';
import { HealthService } from './health.service';
@Module({
imports: [PrismaModule],
controllers: [HealthController],
providers: [HealthService],
})
export class HealthModule {}
+25
View File
@@ -0,0 +1,25 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class HealthService {
constructor(private readonly prisma: PrismaService) {}
getHealth() {
return {
ok: true,
service: 'atnmy-stdo-adm-v2-be',
timestamp: new Date().toISOString(),
};
}
async getDbHealth() {
await this.prisma.$queryRaw`SELECT 1`;
return {
ok: true,
database: 'ok',
timestamp: new Date().toISOString(),
};
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { LauncherPrismaService } from './launcher-prisma.service';
@Module({
providers: [LauncherPrismaService],
exports: [LauncherPrismaService],
})
export class LauncherPrismaModule {}
@@ -0,0 +1,28 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaClient } from '@prisma/launcher-client';
@Injectable()
export class LauncherPrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor(configService: ConfigService) {
super({
datasources: {
db: {
url: configService.getOrThrow<string>('LAUNCHER_DATABASE_URL'),
},
},
});
}
async onModuleInit() {
await this.$connect();
}
async onModuleDestroy() {
await this.$disconnect();
}
}
+261
View File
@@ -0,0 +1,261 @@
import { IsBoolean, IsIn, IsInt, IsOptional, IsString, IsUUID } from 'class-validator';
export class CreateLauncherVersionDto {
@IsString()
version!: string;
@IsOptional()
@IsString()
minimumVersion?: string;
@IsString()
artifact!: string;
@IsString()
downloadUrl!: string;
@IsOptional()
@IsString()
releaseNotes?: string;
@IsOptional()
@IsString()
repository?: string;
@IsOptional()
@IsString()
branch?: string;
@IsOptional()
@IsString()
commitSha?: string;
}
export class UpdateLauncherSourceDto {
@IsString()
repository!: string;
@IsOptional()
@IsString()
branch?: string;
@IsOptional()
@IsString()
commitSha?: string;
}
export class LinkLauncherVersionSourceDto {
@IsString()
repository!: string;
@IsOptional()
@IsString()
branch?: string;
@IsOptional()
@IsString()
commitSha?: string;
}
export class CreateLauncherBuildJobDto {
@IsOptional()
@IsString()
target?: string;
@IsOptional()
@IsString()
repository?: string;
@IsOptional()
@IsString()
branch?: string;
@IsOptional()
@IsString()
commitSha?: string;
@IsString()
version!: string;
@IsString()
artifact!: string;
@IsOptional()
@IsString()
uploadPath?: string;
@IsOptional()
@IsString()
downloadUrl?: string;
}
export class CreateLauncherAppLinkDto {
@IsUUID()
appId!: string;
@IsOptional()
@IsUUID()
releaseId?: string;
@IsOptional()
@IsInt()
displayOrder?: number;
@IsOptional()
@IsString()
displayName?: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsString()
subtitle?: string;
@IsOptional()
@IsString()
detailUrl?: string;
@IsOptional()
@IsString()
videoPath?: string;
@IsOptional()
@IsString()
iconKey?: string;
@IsOptional()
@IsString()
launchUrl?: string;
@IsOptional()
@IsString()
devAppPath?: string;
@IsOptional()
@IsString()
execPath?: string;
@IsOptional()
@IsString()
artifact?: string;
}
export class UpdateLauncherAppLinkDto {
@IsOptional()
@IsUUID()
releaseId?: string;
@IsOptional()
@IsInt()
displayOrder?: number;
@IsOptional()
@IsBoolean()
isEnabled?: boolean;
@IsOptional()
@IsString()
displayName?: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsString()
subtitle?: string;
@IsOptional()
@IsString()
detailUrl?: string;
@IsOptional()
@IsString()
videoPath?: string;
@IsOptional()
@IsString()
iconKey?: string;
@IsOptional()
@IsString()
launchUrl?: string;
@IsOptional()
@IsString()
devAppPath?: string;
@IsOptional()
@IsString()
execPath?: string;
@IsOptional()
@IsString()
artifact?: string;
}
export class MoveLauncherAppLinkDto {
@IsIn(['up', 'down'])
direction!: 'up' | 'down';
}
export class CreateLauncherCommonSettingDto {
@IsString()
key!: string;
@IsString()
name!: string;
@IsString()
type!: string;
@IsString()
value!: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsBoolean()
isActive?: boolean;
@IsOptional()
@IsBoolean()
isSecret?: boolean;
}
export class UpdateLauncherCommonSettingDto {
@IsOptional()
@IsString()
key?: string;
@IsOptional()
@IsString()
name?: string;
@IsOptional()
@IsString()
type?: string;
@IsOptional()
@IsString()
value?: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsBoolean()
isActive?: boolean;
@IsOptional()
@IsBoolean()
isSecret?: boolean;
}
+108
View File
@@ -0,0 +1,108 @@
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
import { CreateLauncherAppLinkDto, CreateLauncherBuildJobDto, CreateLauncherCommonSettingDto, CreateLauncherVersionDto, UpdateLauncherSourceDto, LinkLauncherVersionSourceDto, MoveLauncherAppLinkDto, UpdateLauncherAppLinkDto, UpdateLauncherCommonSettingDto } from './dto';
import { LauncherService } from './launcher.service';
@Controller('launcher')
export class LauncherController {
constructor(private readonly launcherService: LauncherService) {}
@Get('versions')
listVersions() {
return this.launcherService.listVersions();
}
@Post('versions')
createVersion(@Body() body: CreateLauncherVersionDto) {
return this.launcherService.createVersion(body);
}
@Get('source')
getSource() {
return this.launcherService.getSource();
}
@Patch('source')
updateSource(@Body() body: UpdateLauncherSourceDto) {
return this.launcherService.updateSource(body);
}
@Get('builds')
listBuildJobs() {
return this.launcherService.listBuildJobs();
}
@Post('builds')
createBuildJob(@Body() body: CreateLauncherBuildJobDto) {
return this.launcherService.createBuildJob(body);
}
@Get('common-settings')
listCommonSettings() {
return this.launcherService.listCommonSettings();
}
@Post('common-settings')
createCommonSetting(@Body() body: CreateLauncherCommonSettingDto) {
return this.launcherService.createCommonSetting(body);
}
@Patch('common-settings/:id')
updateCommonSetting(
@Param('id') id: string,
@Body() body: UpdateLauncherCommonSettingDto,
) {
return this.launcherService.updateCommonSetting(id, body);
}
@Delete('common-settings/:id')
deleteCommonSetting(@Param('id') id: string) {
return this.launcherService.deleteCommonSetting(id);
}
@Get('app-links')
listAppLinks() {
return this.launcherService.listAppLinks();
}
@Post('app-links')
createAppLink(@Body() body: CreateLauncherAppLinkDto) {
return this.launcherService.createAppLink(body);
}
@Post('app-links/sync-admin-apps')
syncAdminAppsFromLauncher() {
return this.launcherService.syncAdminAppsFromLauncher();
}
@Patch('app-links/:id')
updateAppLink(
@Param('id') id: string,
@Body() body: UpdateLauncherAppLinkDto,
) {
return this.launcherService.updateAppLink(id, body);
}
@Patch('app-links/:id/move')
moveAppLink(
@Param('id') id: string,
@Body() body: MoveLauncherAppLinkDto,
) {
return this.launcherService.moveAppLink(id, body.direction);
}
@Delete('app-links/:id')
deleteAppLink(@Param('id') id: string) {
return this.launcherService.deleteAppLink(id);
}
@Patch('versions/:id/source')
linkVersionSource(
@Param('id') id: string,
@Body() body: LinkLauncherVersionSourceDto,
) {
return this.launcherService.linkVersionSource(id, body);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../prisma/prisma.module';
import { LauncherPrismaModule } from '../launcher-prisma/launcher-prisma.module';
import { LauncherController } from './launcher.controller';
import { LauncherService } from './launcher.service';
@Module({
imports: [PrismaModule, LauncherPrismaModule],
controllers: [LauncherController],
providers: [LauncherService],
exports: [LauncherService],
})
export class LauncherModule {}
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
import { IsEnum, IsISO8601, IsOptional, IsString } from 'class-validator';
import { LicenseCode } from './license-enums';
export class ListUserLicensesQuery {
@IsOptional()
@IsString()
keyword?: string;
@IsOptional()
@IsEnum(LicenseCode)
licenseCode?: LicenseCode;
}
export class AssignLicenseDto {
@IsEnum(LicenseCode)
licenseCode!: LicenseCode;
@IsOptional()
@IsISO8601()
startsAt?: string;
@IsOptional()
@IsISO8601()
expiresAt?: string;
@IsOptional()
@IsString()
assignedById?: string;
}
+7
View File
@@ -0,0 +1,7 @@
export const LicenseCode = {
FREE: 'FREE',
EDU: 'EDU',
PRO: 'PRO',
} as const;
export type LicenseCode = (typeof LicenseCode)[keyof typeof LicenseCode];
+34
View File
@@ -0,0 +1,34 @@
import { Body, Controller, Delete, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { AssignLicenseDto, ListUserLicensesQuery } from './dto';
import { LicensesService } from './licenses.service';
@Controller('licenses')
export class LicensesController {
constructor(private readonly licensesService: LicensesService) {}
@Get('plans')
listPlans() {
return this.licensesService.listPlans();
}
@Get('users')
listUserLicenses(@Query() query: ListUserLicensesQuery) {
return this.licensesService.listUserLicenses(query);
}
@Post('users/:userId')
assign(@Param('userId') userId: string, @Body() body: AssignLicenseDto) {
return this.licensesService.assign(userId, body);
}
@Patch('user-licenses/:id')
update(@Param('id') id: string, @Body() body: AssignLicenseDto) {
return this.licensesService.update(id, body);
}
@Delete('user-licenses/:id')
revoke(@Param('id') id: string) {
return this.licensesService.revoke(id);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { AuthPrismaModule } from '../auth-prisma/auth-prisma.module';
import { LicensesController } from './licenses.controller';
import { LicensesService } from './licenses.service';
@Module({
imports: [AuthPrismaModule],
controllers: [LicensesController],
providers: [LicensesService],
})
export class LicensesModule {}
+220
View File
@@ -0,0 +1,220 @@
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { AuthPrismaService } from '../auth-prisma/auth-prisma.service';
import { AssignLicenseDto, ListUserLicensesQuery } from './dto';
@Injectable()
export class LicensesService {
constructor(private readonly authPrisma: AuthPrismaService) {}
async listPlans() {
const now = new Date();
const plans = await this.authPrisma.license.findMany({
orderBy: { code: 'asc' },
include: {
userLicenses: {
select: {
id: true,
startsAt: true,
expiresAt: true,
},
},
},
});
return {
plans: plans.map((plan) => ({
id: plan.id,
code: plan.code,
name: plan.name,
description: plan.description,
defaultDurationDays: plan.defaultDurationDays,
isActive: plan.isActive,
assignedCount: plan.userLicenses.length,
activeUserCount: plan.userLicenses.filter((license) =>
isActiveLicense(license.startsAt, license.expiresAt, now),
).length,
expiringSoonCount: plan.userLicenses.filter((license) =>
expiresSoon(license.expiresAt, now),
).length,
createdAt: plan.createdAt,
updatedAt: plan.updatedAt,
})),
};
}
async listUserLicenses(query: ListUserLicensesQuery) {
const keyword = query.keyword?.trim();
const users = await this.authPrisma.user.findMany({
where: {
OR: keyword
? [
{ email: { contains: keyword, mode: 'insensitive' } },
{ name: { contains: keyword, mode: 'insensitive' } },
]
: undefined,
userLicenses: query.licenseCode
? { some: { license: { code: query.licenseCode } } }
: undefined,
},
orderBy: { createdAt: 'desc' },
include: {
userLicenses: {
orderBy: { startsAt: 'desc' },
include: { license: true },
},
},
});
const now = new Date();
return {
users: users.map((user) => ({
id: user.id,
email: user.email,
name: user.name,
role: user.role,
isActive: user.isActive,
currentLicense:
user.userLicenses.find((userLicense) =>
isActiveLicense(userLicense.startsAt, userLicense.expiresAt, now),
) ?? null,
licenses: user.userLicenses.map((userLicense) => ({
...userLicense,
status: isActiveLicense(userLicense.startsAt, userLicense.expiresAt, now)
? '활성'
: '만료',
})),
})),
};
}
async assign(userId: string, body: AssignLicenseDto) {
const user = await this.authPrisma.user.findUnique({
where: { id: userId },
select: { id: true },
});
if (!user) {
throw new NotFoundException('사용자를 찾을 수 없습니다.');
}
const activeLicense = await this.authPrisma.userLicense.findFirst({
where: {
userId,
startsAt: { lte: new Date() },
OR: [{ expiresAt: null }, { expiresAt: { gte: new Date() } }],
},
select: { id: true },
});
if (activeLicense) {
throw new ConflictException('이미 활성 라이센스가 있습니다. 기존 이력을 수정하세요.');
}
const license = await this.authPrisma.license.findUnique({
where: { code: body.licenseCode },
});
if (!license) {
throw new NotFoundException('라이센스 플랜을 찾을 수 없습니다.');
}
const startsAt = body.startsAt ? new Date(body.startsAt) : new Date();
const expiresAt = body.expiresAt
? new Date(body.expiresAt)
: calculateExpiresAt(startsAt, license.defaultDurationDays);
const userLicense = await this.authPrisma.userLicense.create({
data: {
userId,
licenseId: license.id,
startsAt,
expiresAt,
assignedById: body.assignedById,
},
include: { license: true, user: true },
});
return { userLicense };
}
async update(id: string, body: AssignLicenseDto) {
const current = await this.authPrisma.userLicense.findUnique({
where: { id },
select: { id: true },
});
if (!current) {
throw new NotFoundException('사용자 라이센스를 찾을 수 없습니다.');
}
const license = await this.authPrisma.license.findUnique({
where: { code: body.licenseCode },
});
if (!license) {
throw new NotFoundException('라이센스 플랜을 찾을 수 없습니다.');
}
const startsAt = body.startsAt ? new Date(body.startsAt) : new Date();
const expiresAt = body.expiresAt
? new Date(body.expiresAt)
: calculateExpiresAt(startsAt, license.defaultDurationDays);
const userLicense = await this.authPrisma.userLicense.update({
where: { id },
data: {
licenseId: license.id,
startsAt,
expiresAt,
assignedById: body.assignedById,
},
include: { license: true, user: true },
});
return { userLicense };
}
async revoke(id: string) {
const userLicense = await this.authPrisma.userLicense.findUnique({
where: { id },
select: { id: true },
});
if (!userLicense) {
throw new NotFoundException('사용자 라이센스를 찾을 수 없습니다.');
}
await this.authPrisma.userLicense.delete({
where: { id },
});
return { ok: true };
}
}
function calculateExpiresAt(startsAt: Date, durationDays?: number | null) {
if (!durationDays) {
return null;
}
const expiresAt = new Date(startsAt);
expiresAt.setDate(expiresAt.getDate() + durationDays);
return expiresAt;
}
function isActiveLicense(startsAt: Date, expiresAt: Date | null, now: Date) {
return startsAt <= now && (!expiresAt || expiresAt >= now);
}
function expiresSoon(expiresAt: Date | null, now: Date) {
if (!expiresAt) {
return false;
}
const diffDays = (expiresAt.getTime() - now.getTime()) / 1000 / 60 / 60 / 24;
return diffDays >= 0 && diffDays <= 30;
}
+59
View File
@@ -0,0 +1,59 @@
import { RequestMethod, ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const port = configService.get<number>('PORT', 4500);
const corsOrigin = configService.get<string>(
'CORS_ORIGIN',
'http://localhost:5173,http://localhost:5174',
);
app.setGlobalPrefix('api', {
exclude: [
{ path: 'health', method: RequestMethod.GET },
{ path: 'health/db', method: RequestMethod.GET },
],
});
app.enableCors({
origin: resolveCorsOrigin(corsOrigin),
credentials: true,
});
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
}),
);
await app.listen(port, '0.0.0.0');
}
void bootstrap();
function resolveCorsOrigin(corsOrigin: string) {
if (corsOrigin === '*') {
return true;
}
const allowedOrigins = corsOrigin.split(',').map((origin) => origin.trim());
return (origin: string | undefined, callback: (error: Error | null, allow?: boolean) => void) => {
if (!origin) {
callback(null, true);
return;
}
if (allowedOrigins.includes(origin) || /^http:\/\/(localhost|127\.0\.0\.1):\d+$/.test(origin)) {
callback(null, true);
return;
}
callback(new Error(`CORS origin is not allowed: ${origin}`));
};
}
+89
View File
@@ -0,0 +1,89 @@
import {
IsBoolean,
IsInt,
IsISO8601,
IsOptional,
IsString,
Min,
} from 'class-validator';
export class ListLauncherNoticesQuery {
@IsOptional()
@IsString()
appKey?: string;
@IsOptional()
@IsString()
keyword?: string;
@IsOptional()
@IsString()
state?: string;
}
export class CreateLauncherNoticeDto {
@IsString()
appKey!: string;
@IsString()
title!: string;
@IsString()
body!: string;
@IsOptional()
@IsString()
linkUrl?: string;
@IsOptional()
@IsBoolean()
isActive?: boolean;
@IsOptional()
@IsISO8601()
startsAt?: string;
@IsOptional()
@IsISO8601()
endsAt?: string;
@IsOptional()
@IsInt()
@Min(0)
priority?: number;
}
export class UpdateLauncherNoticeDto {
@IsOptional()
@IsString()
appKey?: string;
@IsOptional()
@IsString()
title?: string;
@IsOptional()
@IsString()
body?: string;
@IsOptional()
@IsString()
linkUrl?: string;
@IsOptional()
@IsBoolean()
isActive?: boolean;
@IsOptional()
@IsISO8601()
startsAt?: string;
@IsOptional()
@IsISO8601()
endsAt?: string;
@IsOptional()
@IsInt()
@Min(0)
priority?: number;
}
+47
View File
@@ -0,0 +1,47 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
} from '@nestjs/common';
import {
CreateLauncherNoticeDto,
ListLauncherNoticesQuery,
UpdateLauncherNoticeDto,
} from './dto';
import { NoticesService } from './notices.service';
@Controller('notices')
export class NoticesController {
constructor(private readonly noticesService: NoticesService) {}
@Get()
list(@Query() query: ListLauncherNoticesQuery) {
return this.noticesService.list(query);
}
@Get(':id')
get(@Param('id') id: string) {
return this.noticesService.get(id);
}
@Post()
create(@Body() body: CreateLauncherNoticeDto) {
return this.noticesService.create(body);
}
@Patch(':id')
update(@Param('id') id: string, @Body() body: UpdateLauncherNoticeDto) {
return this.noticesService.update(id, body);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.noticesService.remove(id);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { LauncherPrismaModule } from '../launcher-prisma/launcher-prisma.module';
import { NoticesController } from './notices.controller';
import { NoticesService } from './notices.service';
@Module({
imports: [LauncherPrismaModule],
controllers: [NoticesController],
providers: [NoticesService],
})
export class NoticesModule {}

Some files were not shown because too many files have changed in this diff Show More