fix: further typos

This commit is contained in:
Tam Nguyen
2026-03-30 09:01:50 +11:00
parent 290a03ccfb
commit 815b8136fa
37 changed files with 747 additions and 747 deletions
@@ -292,7 +292,7 @@ networks:
dokploy-network: dokploy-network:
`; `;
test("It shoudn't add suffix to dokploy-network", () => { test("It shouldn't add suffix to dokploy-network", () => {
const composeData = parse(composeFile7) as ComposeSpecification; const composeData = parse(composeFile7) as ComposeSpecification;
const suffix = generateRandomHash(); const suffix = generateRandomHash();
@@ -1,7 +1,7 @@
import type { ComposeSpecification } from "@dokploy/server"; import type { ComposeSpecification } from "@dokploy/server";
import { import {
addSuffixToServiceNetworks, addSuffixToServiceNetworks,
generateRandomHash, generateRandomHash,
} from "@dokploy/server"; } from "@dokploy/server";
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { parse } from "yaml"; import { parse } from "yaml";
@@ -23,30 +23,30 @@ services:
`; `;
test("Add suffix to networks in services", () => { test("Add suffix to networks in services", () => {
const composeData = parse(composeFile) as ComposeSpecification; const composeData = parse(composeFile) as ComposeSpecification;
const suffix = generateRandomHash(); const suffix = generateRandomHash();
if (!composeData?.services) { if (!composeData?.services) {
return; return;
} }
const services = addSuffixToServiceNetworks(composeData.services, suffix); const services = addSuffixToServiceNetworks(composeData.services, suffix);
const actualComposeData = { ...composeData, services }; const actualComposeData = { ...composeData, services };
expect(actualComposeData?.services?.web?.networks).toContain( expect(actualComposeData?.services?.web?.networks).toContain(
`frontend-${suffix}`, `frontend-${suffix}`,
); );
expect(actualComposeData?.services?.api?.networks).toContain( expect(actualComposeData?.services?.api?.networks).toContain(
`backend-${suffix}`, `backend-${suffix}`,
); );
const apiNetworks = actualComposeData?.services?.api?.networks; const apiNetworks = actualComposeData?.services?.api?.networks;
expect(apiNetworks).toBeDefined(); expect(apiNetworks).toBeDefined();
expect(actualComposeData?.services?.api?.networks).toContain( expect(actualComposeData?.services?.api?.networks).toContain(
`backend-${suffix}`, `backend-${suffix}`,
); );
}); });
// Caso 2: Objeto con aliases // Caso 2: Objeto con aliases
@@ -67,29 +67,29 @@ networks:
`; `;
test("Add suffix to networks in services with aliases", () => { test("Add suffix to networks in services with aliases", () => {
const composeData = parse(composeFile2) as ComposeSpecification; const composeData = parse(composeFile2) as ComposeSpecification;
const suffix = generateRandomHash(); const suffix = generateRandomHash();
if (!composeData?.services) { if (!composeData?.services) {
return; return;
} }
const services = addSuffixToServiceNetworks(composeData.services, suffix); const services = addSuffixToServiceNetworks(composeData.services, suffix);
const actualComposeData = { ...composeData, services }; const actualComposeData = { ...composeData, services };
expect(actualComposeData.services?.api?.networks).toHaveProperty( expect(actualComposeData.services?.api?.networks).toHaveProperty(
`frontend-${suffix}`, `frontend-${suffix}`,
); );
const networkConfig = actualComposeData?.services?.api?.networks as { const networkConfig = actualComposeData?.services?.api?.networks as {
[key: string]: { aliases?: string[] }; [key: string]: { aliases?: string[] };
}; };
expect(networkConfig[`frontend-${suffix}`]).toBeDefined(); expect(networkConfig[`frontend-${suffix}`]).toBeDefined();
expect(networkConfig[`frontend-${suffix}`]?.aliases).toContain("api"); expect(networkConfig[`frontend-${suffix}`]?.aliases).toContain("api");
expect(actualComposeData.services?.api?.networks).not.toHaveProperty( expect(actualComposeData.services?.api?.networks).not.toHaveProperty(
"frontend-ash", "frontend-ash",
); );
}); });
const composeFile3 = ` const composeFile3 = `
@@ -107,19 +107,19 @@ networks:
`; `;
test("Add suffix to networks in services (Object with simple networks)", () => { test("Add suffix to networks in services (Object with simple networks)", () => {
const composeData = parse(composeFile3) as ComposeSpecification; const composeData = parse(composeFile3) as ComposeSpecification;
const suffix = generateRandomHash(); const suffix = generateRandomHash();
if (!composeData?.services) { if (!composeData?.services) {
return; return;
} }
const services = addSuffixToServiceNetworks(composeData.services, suffix); const services = addSuffixToServiceNetworks(composeData.services, suffix);
const actualComposeData = { ...composeData, services }; const actualComposeData = { ...composeData, services };
expect(actualComposeData.services?.redis?.networks).toHaveProperty( expect(actualComposeData.services?.redis?.networks).toHaveProperty(
`backend-${suffix}`, `backend-${suffix}`,
); );
}); });
const composeFileCombined = ` const composeFileCombined = `
@@ -153,36 +153,36 @@ networks:
`; `;
test("Add suffix to networks in services (combined case)", () => { test("Add suffix to networks in services (combined case)", () => {
const composeData = parse(composeFileCombined) as ComposeSpecification; const composeData = parse(composeFileCombined) as ComposeSpecification;
const suffix = generateRandomHash(); const suffix = generateRandomHash();
if (!composeData?.services) { if (!composeData?.services) {
return; return;
} }
const services = addSuffixToServiceNetworks(composeData.services, suffix); const services = addSuffixToServiceNetworks(composeData.services, suffix);
const actualComposeData = { ...composeData, services }; const actualComposeData = { ...composeData, services };
// Caso 1: ListOfStrings // Caso 1: ListOfStrings
expect(actualComposeData.services?.web?.networks).toContain( expect(actualComposeData.services?.web?.networks).toContain(
`frontend-${suffix}`, `frontend-${suffix}`,
); );
expect(actualComposeData.services?.web?.networks).toContain( expect(actualComposeData.services?.web?.networks).toContain(
`backend-${suffix}`, `backend-${suffix}`,
); );
// Caso 2: Objeto con aliases // Caso 2: Objeto con aliases
const apiNetworks = actualComposeData.services?.api?.networks as { const apiNetworks = actualComposeData.services?.api?.networks as {
[key: string]: unknown; [key: string]: unknown;
}; };
expect(apiNetworks).toHaveProperty(`frontend-${suffix}`); expect(apiNetworks).toHaveProperty(`frontend-${suffix}`);
expect(apiNetworks[`frontend-${suffix}`]).toBeDefined(); expect(apiNetworks[`frontend-${suffix}`]).toBeDefined();
expect(apiNetworks).not.toHaveProperty("frontend"); expect(apiNetworks).not.toHaveProperty("frontend");
// Caso 3: Objeto con redes simples // Caso 3: Objeto con redes simples
const redisNetworks = actualComposeData.services?.redis?.networks; const redisNetworks = actualComposeData.services?.redis?.networks;
expect(redisNetworks).toHaveProperty(`backend-${suffix}`); expect(redisNetworks).toHaveProperty(`backend-${suffix}`);
expect(redisNetworks).not.toHaveProperty("backend"); expect(redisNetworks).not.toHaveProperty("backend");
}); });
const composeFile7 = ` const composeFile7 = `
@@ -195,19 +195,19 @@ services:
- dokploy-network - dokploy-network
`; `;
test("It shoudn't add suffix to dokploy-network in services", () => { test("It shouldn't add suffix to dokploy-network in services", () => {
const composeData = parse(composeFile7) as ComposeSpecification; const composeData = parse(composeFile7) as ComposeSpecification;
const suffix = generateRandomHash(); const suffix = generateRandomHash();
if (!composeData?.services) { if (!composeData?.services) {
return; return;
} }
const networks = addSuffixToServiceNetworks(composeData.services, suffix); const networks = addSuffixToServiceNetworks(composeData.services, suffix);
const service = networks.web; const service = networks.web;
expect(service).toBeDefined(); expect(service).toBeDefined();
expect(service?.networks).toContain("dokploy-network"); expect(service?.networks).toContain("dokploy-network");
}); });
const composeFile8 = ` const composeFile8 = `
@@ -241,35 +241,35 @@ services:
dokploy-network: dokploy-network:
aliases: aliases:
- apid - apid
`; `;
test("It shoudn't add suffix to dokploy-network in services multiples cases", () => { test("It shouldn't add suffix to dokploy-network in services multiples cases", () => {
const composeData = parse(composeFile8) as ComposeSpecification; const composeData = parse(composeFile8) as ComposeSpecification;
const suffix = generateRandomHash(); const suffix = generateRandomHash();
if (!composeData?.services) { if (!composeData?.services) {
return; return;
} }
const networks = addSuffixToServiceNetworks(composeData.services, suffix); const networks = addSuffixToServiceNetworks(composeData.services, suffix);
const service = networks.web; const service = networks.web;
const api = networks.api; const api = networks.api;
const redis = networks.redis; const redis = networks.redis;
const db = networks.db; const db = networks.db;
const dbNetworks = db?.networks as { const dbNetworks = db?.networks as {
[key: string]: unknown; [key: string]: unknown;
}; };
const apiNetworks = api?.networks as { const apiNetworks = api?.networks as {
[key: string]: unknown; [key: string]: unknown;
}; };
expect(service).toBeDefined(); expect(service).toBeDefined();
expect(service?.networks).toContain("dokploy-network"); expect(service?.networks).toContain("dokploy-network");
expect(redis?.networks).toHaveProperty("dokploy-network"); expect(redis?.networks).toHaveProperty("dokploy-network");
expect(dbNetworks["dokploy-network"]).toBeDefined(); expect(dbNetworks["dokploy-network"]).toBeDefined();
expect(apiNetworks["dokploy-network"]).toBeDefined(); expect(apiNetworks["dokploy-network"]).toBeDefined();
}); });
+99 -99
View File
@@ -1,4 +1,4 @@
import { getEnviromentVariablesObject } from "@dokploy/server/index"; import { getEnvironmentVariablesObject } from "@dokploy/server/index";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
const projectEnv = ` const projectEnv = `
@@ -15,29 +15,29 @@ DATABASE_NAME=dev_database
SECRET_KEY=env-secret-123 SECRET_KEY=env-secret-123
`; `;
describe("getEnviromentVariablesObject with environment variables (Stack compose)", () => { describe("getEnvironmentVariablesObject with environment variables (Stack compose)", () => {
it("resolves environment variables correctly for Stack compose", () => { it("resolves environment variables correctly for Stack compose", () => {
const serviceEnv = ` const serviceEnv = `
FOO=\${{environment.NODE_ENV}} FOO=\${{environment.NODE_ENV}}
BAR=\${{environment.API_URL}} BAR=\${{environment.API_URL}}
BAZ=test BAZ=test
`; `;
const result = getEnviromentVariablesObject( const result = getEnvironmentVariablesObject(
serviceEnv, serviceEnv,
projectEnv, projectEnv,
environmentEnv, environmentEnv,
); );
expect(result).toEqual({ expect(result).toEqual({
FOO: "development", FOO: "development",
BAR: "https://api.dev.example.com", BAR: "https://api.dev.example.com",
BAZ: "test", BAZ: "test",
}); });
}); });
it("resolves both project and environment variables for Stack compose", () => { it("resolves both project and environment variables for Stack compose", () => {
const serviceEnv = ` const serviceEnv = `
ENVIRONMENT=\${{project.ENVIRONMENT}} ENVIRONMENT=\${{project.ENVIRONMENT}}
NODE_ENV=\${{environment.NODE_ENV}} NODE_ENV=\${{environment.NODE_ENV}}
API_URL=\${{environment.API_URL}} API_URL=\${{environment.API_URL}}
@@ -45,140 +45,140 @@ DATABASE_URL=\${{project.DATABASE_URL}}
SERVICE_PORT=4000 SERVICE_PORT=4000
`; `;
const result = getEnviromentVariablesObject( const result = getEnvironmentVariablesObject(
serviceEnv, serviceEnv,
projectEnv, projectEnv,
environmentEnv, environmentEnv,
); );
expect(result).toEqual({ expect(result).toEqual({
ENVIRONMENT: "staging", ENVIRONMENT: "staging",
NODE_ENV: "development", NODE_ENV: "development",
API_URL: "https://api.dev.example.com", API_URL: "https://api.dev.example.com",
DATABASE_URL: "postgres://postgres:postgres@localhost:5432/project_db", DATABASE_URL: "postgres://postgres:postgres@localhost:5432/project_db",
SERVICE_PORT: "4000", SERVICE_PORT: "4000",
}); });
}); });
it("handles multiple environment references in single value for Stack compose", () => { it("handles multiple environment references in single value for Stack compose", () => {
const multiRefEnv = ` const multiRefEnv = `
HOST=localhost HOST=localhost
PORT=5432 PORT=5432
USERNAME=postgres USERNAME=postgres
PASSWORD=secret123 PASSWORD=secret123
`; `;
const serviceEnv = ` const serviceEnv = `
DATABASE_URL=postgresql://\${{environment.USERNAME}}:\${{environment.PASSWORD}}@\${{environment.HOST}}:\${{environment.PORT}}/mydb DATABASE_URL=postgresql://\${{environment.USERNAME}}:\${{environment.PASSWORD}}@\${{environment.HOST}}:\${{environment.PORT}}/mydb
`; `;
const result = getEnviromentVariablesObject(serviceEnv, "", multiRefEnv); const result = getEnvironmentVariablesObject(serviceEnv, "", multiRefEnv);
expect(result).toEqual({ expect(result).toEqual({
DATABASE_URL: "postgresql://postgres:secret123@localhost:5432/mydb", DATABASE_URL: "postgresql://postgres:secret123@localhost:5432/mydb",
}); });
}); });
it("throws error for undefined environment variables in Stack compose", () => { it("throws error for undefined environment variables in Stack compose", () => {
const serviceWithUndefined = ` const serviceWithUndefined = `
UNDEFINED_VAR=\${{environment.UNDEFINED_VAR}} UNDEFINED_VAR=\${{environment.UNDEFINED_VAR}}
`; `;
expect(() => expect(() =>
getEnviromentVariablesObject(serviceWithUndefined, "", environmentEnv), getEnvironmentVariablesObject(serviceWithUndefined, "", environmentEnv),
).toThrow("Invalid environment variable: environment.UNDEFINED_VAR"); ).toThrow("Invalid environment variable: environment.UNDEFINED_VAR");
}); });
it("allows service variables to override environment variables in Stack compose", () => { it("allows service variables to override environment variables in Stack compose", () => {
const serviceOverrideEnv = ` const serviceOverrideEnv = `
NODE_ENV=production NODE_ENV=production
API_URL=\${{environment.API_URL}} API_URL=\${{environment.API_URL}}
`; `;
const result = getEnviromentVariablesObject( const result = getEnvironmentVariablesObject(
serviceOverrideEnv, serviceOverrideEnv,
"", "",
environmentEnv, environmentEnv,
); );
expect(result).toEqual({ expect(result).toEqual({
NODE_ENV: "production", NODE_ENV: "production",
API_URL: "https://api.dev.example.com", API_URL: "https://api.dev.example.com",
}); });
}); });
it("resolves complex references with project, environment, and service variables for Stack compose", () => { it("resolves complex references with project, environment, and service variables for Stack compose", () => {
const complexServiceEnv = ` const complexServiceEnv = `
FULL_DATABASE_URL=\${{project.DATABASE_URL}}/\${{environment.DATABASE_NAME}} FULL_DATABASE_URL=\${{project.DATABASE_URL}}/\${{environment.DATABASE_NAME}}
API_ENDPOINT=\${{environment.API_URL}}/\${{project.ENVIRONMENT}}/api API_ENDPOINT=\${{environment.API_URL}}/\${{project.ENVIRONMENT}}/api
SERVICE_NAME=my-service SERVICE_NAME=my-service
COMPLEX_VAR=\${{SERVICE_NAME}}-\${{environment.NODE_ENV}}-\${{project.ENVIRONMENT}} COMPLEX_VAR=\${{SERVICE_NAME}}-\${{environment.NODE_ENV}}-\${{project.ENVIRONMENT}}
`; `;
const result = getEnviromentVariablesObject( const result = getEnvironmentVariablesObject(
complexServiceEnv, complexServiceEnv,
projectEnv, projectEnv,
environmentEnv, environmentEnv,
); );
expect(result).toEqual({ expect(result).toEqual({
FULL_DATABASE_URL: FULL_DATABASE_URL:
"postgres://postgres:postgres@localhost:5432/project_db/dev_database", "postgres://postgres:postgres@localhost:5432/project_db/dev_database",
API_ENDPOINT: "https://api.dev.example.com/staging/api", API_ENDPOINT: "https://api.dev.example.com/staging/api",
SERVICE_NAME: "my-service", SERVICE_NAME: "my-service",
COMPLEX_VAR: "my-service-development-staging", COMPLEX_VAR: "my-service-development-staging",
}); });
}); });
it("maintains precedence: service > environment > project in Stack compose", () => { it("maintains precedence: service > environment > project in Stack compose", () => {
const conflictingProjectEnv = ` const conflictingProjectEnv = `
NODE_ENV=production-project NODE_ENV=production-project
API_URL=https://project.api.com API_URL=https://project.api.com
DATABASE_NAME=project_db DATABASE_NAME=project_db
`; `;
const conflictingEnvironmentEnv = ` const conflictingEnvironmentEnv = `
NODE_ENV=development-environment NODE_ENV=development-environment
API_URL=https://environment.api.com API_URL=https://environment.api.com
DATABASE_NAME=env_db DATABASE_NAME=env_db
`; `;
const serviceWithConflicts = ` const serviceWithConflicts = `
NODE_ENV=service-override NODE_ENV=service-override
PROJECT_ENV=\${{project.NODE_ENV}} PROJECT_ENV=\${{project.NODE_ENV}}
ENV_VAR=\${{environment.API_URL}} ENV_VAR=\${{environment.API_URL}}
DB_NAME=\${{environment.DATABASE_NAME}} DB_NAME=\${{environment.DATABASE_NAME}}
`; `;
const result = getEnviromentVariablesObject( const result = getEnvironmentVariablesObject(
serviceWithConflicts, serviceWithConflicts,
conflictingProjectEnv, conflictingProjectEnv,
conflictingEnvironmentEnv, conflictingEnvironmentEnv,
); );
expect(result).toEqual({ expect(result).toEqual({
NODE_ENV: "service-override", NODE_ENV: "service-override",
PROJECT_ENV: "production-project", PROJECT_ENV: "production-project",
ENV_VAR: "https://environment.api.com", ENV_VAR: "https://environment.api.com",
DB_NAME: "env_db", DB_NAME: "env_db",
}); });
}); });
it("handles empty environment variables in Stack compose", () => { it("handles empty environment variables in Stack compose", () => {
const serviceWithEmpty = ` const serviceWithEmpty = `
SERVICE_VAR=test SERVICE_VAR=test
PROJECT_VAR=\${{project.ENVIRONMENT}} PROJECT_VAR=\${{project.ENVIRONMENT}}
`; `;
const result = getEnviromentVariablesObject( const result = getEnvironmentVariablesObject(
serviceWithEmpty, serviceWithEmpty,
projectEnv, projectEnv,
"", "",
); );
expect(result).toEqual({ expect(result).toEqual({
SERVICE_VAR: "test", SERVICE_VAR: "test",
PROJECT_VAR: "staging", PROJECT_VAR: "staging",
}); });
}); });
}); });
@@ -149,7 +149,7 @@ export const HandleRedirect = ({
const onDialogToggle = (open: boolean) => { const onDialogToggle = (open: boolean) => {
setIsOpen(open); setIsOpen(open);
// commented for the moment because not reseting the form if accidentally closed the dialog can be considered as a feature instead of a bug // commented for the moment because not resetting the form if accidentally closed the dialog can be considered as a feature instead of a bug
// setPresetSelected(""); // setPresetSelected("");
// form.reset(); // form.reset();
}; };
@@ -91,7 +91,7 @@ export const ShowDockerLogs = ({ appName, serverId }: Props) => {
}, [option, services, containers]); }, [option, services, containers]);
const isLoading = option === "native" ? containersLoading : servicesLoading; const isLoading = option === "native" ? containersLoading : servicesLoading;
const containersLenght = const containersLength =
option === "native" ? containers?.length : services?.length; option === "native" ? containers?.length : services?.length;
return ( return (
@@ -167,7 +167,7 @@ export const ShowDockerLogs = ({ appName, serverId }: Props) => {
</> </>
)} )}
<SelectLabel>Containers ({containersLenght})</SelectLabel> <SelectLabel>Containers ({containersLength})</SelectLabel>
</SelectGroup> </SelectGroup>
</SelectContent> </SelectContent>
</Select> </Select>
@@ -77,7 +77,7 @@ export const ShowDockerLogsStack = ({ appName, serverId }: Props) => {
}, [option, services, containers]); }, [option, services, containers]);
const isLoading = option === "native" ? containersLoading : servicesLoading; const isLoading = option === "native" ? containersLoading : servicesLoading;
const containersLenght = const containersLength =
option === "native" ? containers?.length : services?.length; option === "native" ? containers?.length : services?.length;
return ( return (
@@ -152,7 +152,7 @@ export const ShowDockerLogsStack = ({ appName, serverId }: Props) => {
</> </>
)} )}
<SelectLabel>Containers ({containersLenght})</SelectLabel> <SelectLabel>Containers ({containersLength})</SelectLabel>
</SelectGroup> </SelectGroup>
</SelectContent> </SelectContent>
</Select> </Select>
@@ -225,7 +225,7 @@ export const RestoreBackup = ({
resolver: zodResolver(RestoreBackupSchema), resolver: zodResolver(RestoreBackupSchema),
}); });
const destionationId = form.watch("destinationId"); const destinationId = form.watch("destinationId");
const currentDatabaseType = form.watch("databaseType"); const currentDatabaseType = form.watch("databaseType");
const metadata = form.watch("metadata"); const metadata = form.watch("metadata");
@@ -240,12 +240,12 @@ export const RestoreBackup = ({
const { data: files = [], isPending } = api.backup.listBackupFiles.useQuery( const { data: files = [], isPending } = api.backup.listBackupFiles.useQuery(
{ {
destinationId: destionationId, destinationId: destinationId,
search: debouncedSearchTerm, search: debouncedSearchTerm,
serverId: serverId ?? "", serverId: serverId ?? "",
}, },
{ {
enabled: isOpen && !!destionationId, enabled: isOpen && !!destinationId,
}, },
); );
@@ -103,7 +103,7 @@ export function TerminalLine({ log, noTimestamp, searchTerm }: LogLineProps) {
> >
{" "} {" "}
<div className="flex items-start gap-x-2"> <div className="flex items-start gap-x-2">
{/* Icon to expand the log item maybe implement a colapsible later */} {/* Icon to expand the log item maybe implement a collapsible later */}
{/* <Square className="size-4 text-muted-foreground opacity-0 group-hover/logitem:opacity-100 transition-opacity" /> */} {/* <Square className="size-4 text-muted-foreground opacity-0 group-hover/logitem:opacity-100 transition-opacity" /> */}
{tooltip(color, rawTimestamp)} {tooltip(color, rawTimestamp)}
{!noTimestamp && ( {!noTimestamp && (
@@ -35,7 +35,7 @@ import {
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { api, type RouterOutputs } from "@/utils/api"; import { api, type RouterOutputs } from "@/utils/api";
import { columns } from "./colums"; import { columns } from "./columns";
export type Container = NonNullable< export type Container = NonNullable<
RouterOutputs["docker"]["getContainers"] RouterOutputs["docker"]["getContainers"]
>[0]; >[0];
@@ -161,7 +161,7 @@ export const SetupServer = ({ serverId, asButton = false }: Props) => {
<ul> <ul>
<li> <li>
1. Add the public SSH Key when you create a server in your 1. Add the public SSH Key when you create a server in your
preffered provider (Hostinger, Digital Ocean, Hetzner, preferred provider (Hostinger, Digital Ocean, Hetzner,
etc){" "} etc){" "}
</li> </li>
<li>2. Add The SSH Key to Server Manually</li> <li>2. Add The SSH Key to Server Manually</li>
@@ -48,7 +48,7 @@ import { ShowMonitoringModal } from "./show-monitoring-modal";
import { ShowSchedulesModal } from "./show-schedules-modal"; import { ShowSchedulesModal } from "./show-schedules-modal";
import { ShowSwarmOverviewModal } from "./show-swarm-overview-modal"; import { ShowSwarmOverviewModal } from "./show-swarm-overview-modal";
import { ShowTraefikFileSystemModal } from "./show-traefik-file-system-modal"; import { ShowTraefikFileSystemModal } from "./show-traefik-file-system-modal";
import { WelcomeSuscription } from "./welcome-stripe/welcome-suscription"; import { Welcomesubscription } from "./welcome-stripe/welcome-subscription";
export const ShowServers = () => { export const ShowServers = () => {
const router = useRouter(); const router = useRouter();
@@ -63,7 +63,7 @@ export const ShowServers = () => {
return ( return (
<div className="w-full"> <div className="w-full">
{query?.success && isCloud && <WelcomeSuscription />} {query?.success && isCloud && <Welcomesubscription />}
<Card className="h-full p-2.5 rounded-xl max-w-5xl mx-auto"> <Card className="h-full p-2.5 rounded-xl max-w-5xl mx-auto">
<div className="rounded-xl bg-background shadow-md "> <div className="rounded-xl bg-background shadow-md ">
<CardHeader className=""> <CardHeader className="">
@@ -51,7 +51,7 @@ export const { useStepper, steps, Scoped } = defineStepper(
{ id: "complete", title: "Complete", description: "Checkout complete" }, { id: "complete", title: "Complete", description: "Checkout complete" },
); );
export const WelcomeSuscription = () => { export const Welcomesubscription = () => {
const [showConfetti, setShowConfetti] = useState(false); const [showConfetti, setShowConfetti] = useState(false);
const stepper = useStepper(); const stepper = useStepper();
const [isOpen, setIsOpen] = useState(true); const [isOpen, setIsOpen] = useState(true);
+6 -6
View File
@@ -19,7 +19,7 @@ interface TreeDataItem {
type TreeProps = React.HTMLAttributes<HTMLDivElement> & { type TreeProps = React.HTMLAttributes<HTMLDivElement> & {
data: TreeDataItem[] | TreeDataItem; data: TreeDataItem[] | TreeDataItem;
initialSlelectedItemId?: string; initialSelectedItemId?: string;
onSelectChange?: (item: TreeDataItem | undefined) => void; onSelectChange?: (item: TreeDataItem | undefined) => void;
expandAll?: boolean; expandAll?: boolean;
folderIcon?: LucideIcon; folderIcon?: LucideIcon;
@@ -30,7 +30,7 @@ const Tree = React.forwardRef<HTMLDivElement, TreeProps>(
( (
{ {
data, data,
initialSlelectedItemId, initialSelectedItemId,
onSelectChange, onSelectChange,
expandAll, expandAll,
folderIcon, folderIcon,
@@ -42,7 +42,7 @@ const Tree = React.forwardRef<HTMLDivElement, TreeProps>(
) => { ) => {
const [selectedItemId, setSelectedItemId] = React.useState< const [selectedItemId, setSelectedItemId] = React.useState<
string | undefined string | undefined
>(initialSlelectedItemId); >(initialSelectedItemId);
const handleSelectChange = React.useCallback( const handleSelectChange = React.useCallback(
(item: TreeDataItem | undefined) => { (item: TreeDataItem | undefined) => {
@@ -55,7 +55,7 @@ const Tree = React.forwardRef<HTMLDivElement, TreeProps>(
); );
const expandedItemIds = React.useMemo(() => { const expandedItemIds = React.useMemo(() => {
if (!initialSlelectedItemId) { if (!initialSelectedItemId) {
return [] as string[]; return [] as string[];
} }
@@ -81,9 +81,9 @@ const Tree = React.forwardRef<HTMLDivElement, TreeProps>(
} }
} }
walkTreeItems(data, initialSlelectedItemId); walkTreeItems(data, initialSelectedItemId);
return ids; return ids;
}, [data, initialSlelectedItemId]); }, [data, initialSelectedItemId]);
const { ref: refRoot } = useResizeObserver(); const { ref: refRoot } = useResizeObserver();
@@ -196,7 +196,7 @@ export default async function handler(
return; return;
} }
const commitedPaths = await extractCommitedPaths( const committedPaths = await extractCommittedPaths(
req.body, req.body,
application.bitbucket, application.bitbucket,
application.bitbucketRepositorySlug || application.bitbucketRepositorySlug ||
@@ -206,7 +206,7 @@ export default async function handler(
const shouldDeployPaths = shouldDeploy( const shouldDeployPaths = shouldDeploy(
application.watchPaths, application.watchPaths,
commitedPaths, committedPaths,
); );
if (!shouldDeployPaths) { if (!shouldDeployPaths) {
@@ -538,7 +538,7 @@ export const getProviderByHeader = (headers: any) => {
return null; return null;
}; };
export const extractCommitedPaths = async ( export const extractCommittedPaths = async (
body: any, body: any,
bitbucket: Bitbucket | null, bitbucket: Bitbucket | null,
repository: string, repository: string,
@@ -548,7 +548,7 @@ export const extractCommitedPaths = async (
const commitHashes = changes const commitHashes = changes
.map((change: any) => change.new?.target?.hash) .map((change: any) => change.new?.target?.hash)
.filter(Boolean); .filter(Boolean);
const commitedPaths: string[] = []; const committedPaths: string[] = [];
const username = const username =
bitbucket?.bitbucketWorkspaceName || bitbucket?.bitbucketUsername || ""; bitbucket?.bitbucketWorkspaceName || bitbucket?.bitbucketUsername || "";
for (const commit of commitHashes) { for (const commit of commitHashes) {
@@ -559,7 +559,7 @@ export const extractCommitedPaths = async (
}); });
const data = await response.json(); const data = await response.json();
for (const value of data.values) { for (const value of data.values) {
if (value?.new?.path) commitedPaths.push(value.new.path); if (value?.new?.path) committedPaths.push(value.new.path);
} }
} catch (error) { } catch (error) {
console.error( console.error(
@@ -571,5 +571,5 @@ export const extractCommitedPaths = async (
} }
} }
return commitedPaths; return committedPaths;
}; };
@@ -8,7 +8,7 @@ import { myQueue } from "@/server/queues/queueSetup";
import { deploy } from "@/server/utils/deploy"; import { deploy } from "@/server/utils/deploy";
import { import {
extractBranchName, extractBranchName,
extractCommitedPaths, extractCommittedPaths,
extractCommitMessage, extractCommitMessage,
extractHash, extractHash,
getProviderByHeader, getProviderByHeader,
@@ -97,7 +97,7 @@ export default async function handler(
return; return;
} }
const commitedPaths = await extractCommitedPaths( const committedPaths = await extractCommittedPaths(
req.body, req.body,
composeResult.bitbucket, composeResult.bitbucket,
composeResult.bitbucketRepositorySlug || composeResult.bitbucketRepositorySlug ||
@@ -107,7 +107,7 @@ export default async function handler(
const shouldDeployPaths = shouldDeploy( const shouldDeployPaths = shouldDeploy(
composeResult.watchPaths, composeResult.watchPaths,
commitedPaths, committedPaths,
); );
if (!shouldDeployPaths) { if (!shouldDeployPaths) {
+6 -6
View File
@@ -174,27 +174,27 @@ export default async function handler(
case "invoice.payment_succeeded": { case "invoice.payment_succeeded": {
const newInvoice = event.data.object as Stripe.Invoice; const newInvoice = event.data.object as Stripe.Invoice;
const suscription = await stripe.subscriptions.retrieve( const subscription = await stripe.subscriptions.retrieve(
newInvoice.subscription as string, newInvoice.subscription as string,
); );
if (suscription.status !== "active") { if (subscription.status !== "active") {
console.log( console.log(
`Skipping invoice.payment_succeeded for subscription ${suscription.id} with status ${suscription.status}`, `Skipping invoice.payment_succeeded for subscription ${subscription.id} with status ${subscription.status}`,
); );
break; break;
} }
const serversQuantity = getSubscriptionServersQuantity( const serversQuantity = getSubscriptionServersQuantity(
suscription?.items?.data ?? [], subscription?.items?.data ?? [],
); );
await db await db
.update(user) .update(user)
.set({ serversQuantity }) .set({ serversQuantity })
.where(eq(user.stripeCustomerId, suscription.customer as string)); .where(eq(user.stripeCustomerId, subscription.customer as string));
const admin = await findUserByStripeCustomerId( const admin = await findUserByStripeCustomerId(
suscription.customer as string, subscription.customer as string,
); );
if (!admin) { if (!admin) {
@@ -16,7 +16,7 @@ import { ShowImport } from "@/components/dashboard/application/advanced/import/s
import { ShowVolumes } from "@/components/dashboard/application/advanced/volumes/show-volumes"; import { ShowVolumes } from "@/components/dashboard/application/advanced/volumes/show-volumes";
import { ShowDeployments } from "@/components/dashboard/application/deployments/show-deployments"; import { ShowDeployments } from "@/components/dashboard/application/deployments/show-deployments";
import { ShowDomains } from "@/components/dashboard/application/domains/show-domains"; import { ShowDomains } from "@/components/dashboard/application/domains/show-domains";
import { ShowEnvironment } from "@/components/dashboard/application/environment/show-enviroment"; import { ShowEnvironment } from "@/components/dashboard/application/environment/show-environment";
import { ShowPatches } from "@/components/dashboard/application/patches/show-patches"; import { ShowPatches } from "@/components/dashboard/application/patches/show-patches";
import { ShowSchedules } from "@/components/dashboard/application/schedules/show-schedules"; import { ShowSchedules } from "@/components/dashboard/application/schedules/show-schedules";
import { ShowVolumeBackups } from "@/components/dashboard/application/volume-backups/show-volume-backups"; import { ShowVolumeBackups } from "@/components/dashboard/application/volume-backups/show-volume-backups";
@@ -10,7 +10,7 @@ import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { type ReactElement, useState } from "react"; import { type ReactElement, useState } from "react";
import superjson from "superjson"; import superjson from "superjson";
import { ShowEnvironment } from "@/components/dashboard/application/environment/show-enviroment"; import { ShowEnvironment } from "@/components/dashboard/application/environment/show-environment";
import { ShowDockerLogs } from "@/components/dashboard/application/logs/show"; import { ShowDockerLogs } from "@/components/dashboard/application/logs/show";
import { DeleteService } from "@/components/dashboard/compose/delete-service"; import { DeleteService } from "@/components/dashboard/compose/delete-service";
import { ShowBackups } from "@/components/dashboard/database/backups/show-backups"; import { ShowBackups } from "@/components/dashboard/database/backups/show-backups";
@@ -10,7 +10,7 @@ import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { type ReactElement, useState } from "react"; import { type ReactElement, useState } from "react";
import superjson from "superjson"; import superjson from "superjson";
import { ShowEnvironment } from "@/components/dashboard/application/environment/show-enviroment"; import { ShowEnvironment } from "@/components/dashboard/application/environment/show-environment";
import { ShowDockerLogs } from "@/components/dashboard/application/logs/show"; import { ShowDockerLogs } from "@/components/dashboard/application/logs/show";
import { DeleteService } from "@/components/dashboard/compose/delete-service"; import { DeleteService } from "@/components/dashboard/compose/delete-service";
import { ShowBackups } from "@/components/dashboard/database/backups/show-backups"; import { ShowBackups } from "@/components/dashboard/database/backups/show-backups";
@@ -10,7 +10,7 @@ import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { type ReactElement, useState } from "react"; import { type ReactElement, useState } from "react";
import superjson from "superjson"; import superjson from "superjson";
import { ShowEnvironment } from "@/components/dashboard/application/environment/show-enviroment"; import { ShowEnvironment } from "@/components/dashboard/application/environment/show-environment";
import { ShowDockerLogs } from "@/components/dashboard/application/logs/show"; import { ShowDockerLogs } from "@/components/dashboard/application/logs/show";
import { DeleteService } from "@/components/dashboard/compose/delete-service"; import { DeleteService } from "@/components/dashboard/compose/delete-service";
import { ShowBackups } from "@/components/dashboard/database/backups/show-backups"; import { ShowBackups } from "@/components/dashboard/database/backups/show-backups";
@@ -10,7 +10,7 @@ import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { type ReactElement, useState } from "react"; import { type ReactElement, useState } from "react";
import superjson from "superjson"; import superjson from "superjson";
import { ShowEnvironment } from "@/components/dashboard/application/environment/show-enviroment"; import { ShowEnvironment } from "@/components/dashboard/application/environment/show-environment";
import { ShowDockerLogs } from "@/components/dashboard/application/logs/show"; import { ShowDockerLogs } from "@/components/dashboard/application/logs/show";
import { DeleteService } from "@/components/dashboard/compose/delete-service"; import { DeleteService } from "@/components/dashboard/compose/delete-service";
import { ShowBackups } from "@/components/dashboard/database/backups/show-backups"; import { ShowBackups } from "@/components/dashboard/database/backups/show-backups";
@@ -10,7 +10,7 @@ import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { type ReactElement, useState } from "react"; import { type ReactElement, useState } from "react";
import superjson from "superjson"; import superjson from "superjson";
import { ShowEnvironment } from "@/components/dashboard/application/environment/show-enviroment"; import { ShowEnvironment } from "@/components/dashboard/application/environment/show-environment";
import { ShowDockerLogs } from "@/components/dashboard/application/logs/show"; import { ShowDockerLogs } from "@/components/dashboard/application/logs/show";
import { DeleteService } from "@/components/dashboard/compose/delete-service"; import { DeleteService } from "@/components/dashboard/compose/delete-service";
import { ShowBackups } from "@/components/dashboard/database/backups/show-backups"; import { ShowBackups } from "@/components/dashboard/database/backups/show-backups";
@@ -10,7 +10,7 @@ import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { type ReactElement, useState } from "react"; import { type ReactElement, useState } from "react";
import superjson from "superjson"; import superjson from "superjson";
import { ShowEnvironment } from "@/components/dashboard/application/environment/show-enviroment"; import { ShowEnvironment } from "@/components/dashboard/application/environment/show-environment";
import { ShowDockerLogs } from "@/components/dashboard/application/logs/show"; import { ShowDockerLogs } from "@/components/dashboard/application/logs/show";
import { DeleteService } from "@/components/dashboard/compose/delete-service"; import { DeleteService } from "@/components/dashboard/compose/delete-service";
import { ContainerFreeMonitoring } from "@/components/dashboard/monitoring/free/container/show-free-container-monitoring"; import { ContainerFreeMonitoring } from "@/components/dashboard/monitoring/free/container/show-free-container-monitoring";
@@ -1,5 +1,5 @@
import { import {
createDestintation, createDestination,
execAsync, execAsync,
execAsyncRemote, execAsyncRemote,
findDestinationById, findDestinationById,
@@ -25,7 +25,7 @@ export const destinationRouter = createTRPCRouter({
.input(apiCreateDestination) .input(apiCreateDestination)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
try { try {
const result = await createDestintation( const result = await createDestination(
input, input,
ctx.session.activeOrganizationId, ctx.session.activeOrganizationId,
); );
+1 -1
View File
@@ -121,7 +121,7 @@ export * from "./utils/providers/raw";
export * from "./utils/schedules/index"; export * from "./utils/schedules/index";
export * from "./utils/schedules/utils"; export * from "./utils/schedules/utils";
export * from "./utils/servers/remote-docker"; export * from "./utils/servers/remote-docker";
export * from "./utils/startup/cancell-deployments"; export * from "./utils/startup/cancel-deployments";
export * from "./utils/tracking/hubspot"; export * from "./utils/tracking/hubspot";
export * from "./utils/traefik/application"; export * from "./utils/traefik/application";
export * from "./utils/traefik/domain"; export * from "./utils/traefik/domain";
+6 -6
View File
@@ -177,7 +177,7 @@ export const createDeployment = async (
status: "error", status: "error",
logPath: "", logPath: "",
description: deployment.description || "", description: deployment.description || "",
errorMessage: `An error have occured: ${error instanceof Error ? error.message : error}`, errorMessage: `An error have occurred: ${error instanceof Error ? error.message : error}`,
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(), finishedAt: new Date().toISOString(),
}) })
@@ -257,7 +257,7 @@ export const createDeploymentPreview = async (
status: "error", status: "error",
logPath: "", logPath: "",
description: deployment.description || "", description: deployment.description || "",
errorMessage: `An error have occured: ${error instanceof Error ? error.message : error}`, errorMessage: `An error have occurred: ${error instanceof Error ? error.message : error}`,
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(), finishedAt: new Date().toISOString(),
}) })
@@ -334,7 +334,7 @@ echo "Initializing deployment\n" >> ${logFilePath};
status: "error", status: "error",
logPath: "", logPath: "",
description: deployment.description || "", description: deployment.description || "",
errorMessage: `An error have occured: ${error instanceof Error ? error.message : error}`, errorMessage: `An error have occurred: ${error instanceof Error ? error.message : error}`,
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(), finishedAt: new Date().toISOString(),
}) })
@@ -418,7 +418,7 @@ echo "Initializing backup\n" >> ${logFilePath};
status: "error", status: "error",
logPath: "", logPath: "",
description: deployment.description || "", description: deployment.description || "",
errorMessage: `An error have occured: ${error instanceof Error ? error.message : error}`, errorMessage: `An error have occurred: ${error instanceof Error ? error.message : error}`,
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(), finishedAt: new Date().toISOString(),
}) })
@@ -493,7 +493,7 @@ export const createDeploymentSchedule = async (
status: "error", status: "error",
logPath: "", logPath: "",
description: deployment.description || "", description: deployment.description || "",
errorMessage: `An error have occured: ${error instanceof Error ? error.message : error}`, errorMessage: `An error have occurred: ${error instanceof Error ? error.message : error}`,
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(), finishedAt: new Date().toISOString(),
}) })
@@ -578,7 +578,7 @@ export const createDeploymentVolumeBackup = async (
status: "error", status: "error",
logPath: "", logPath: "",
description: deployment.description || "", description: deployment.description || "",
errorMessage: `An error have occured: ${error instanceof Error ? error.message : error}`, errorMessage: `An error have occurred: ${error instanceof Error ? error.message : error}`,
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(), finishedAt: new Date().toISOString(),
}) })
+1 -1
View File
@@ -9,7 +9,7 @@ import type { z } from "zod";
export type Destination = typeof destinations.$inferSelect; export type Destination = typeof destinations.$inferSelect;
export const createDestintation = async ( export const createDestination = async (
input: z.infer<typeof apiCreateDestination>, input: z.infer<typeof apiCreateDestination>,
organizationId: string, organizationId: string,
) => { ) => {
+2 -2
View File
@@ -383,12 +383,12 @@ export const readPorts = async (
const seenPorts = new Set<string>(); const seenPorts = new Set<string>();
for (const key in parsedResult) { for (const key in parsedResult) {
if (Object.hasOwn(parsedResult, key)) { if (Object.hasOwn(parsedResult, key)) {
const containerPortMapppings = parsedResult[key]; const containerPortMappings = parsedResult[key];
const protocol = key.split("/")[1]; const protocol = key.split("/")[1];
const targetPort = Number.parseInt(key.split("/")[0] ?? "0", 10); const targetPort = Number.parseInt(key.split("/")[0] ?? "0", 10);
// Take only the first mapping to avoid duplicates (IPv4 and IPv6) // Take only the first mapping to avoid duplicates (IPv4 and IPv6)
const firstMapping = containerPortMapppings[0]; const firstMapping = containerPortMappings[0];
if (firstMapping) { if (firstMapping) {
const publishedPort = Number.parseInt(firstMapping.HostPort, 10); const publishedPort = Number.parseInt(firstMapping.HostPort, 10);
const portKey = `${targetPort}-${publishedPort}-${protocol}`; const portKey = `${targetPort}-${publishedPort}-${protocol}`;
+339 -339
View File
@@ -7,452 +7,452 @@ import { auth } from "../lib/auth";
export type User = typeof user.$inferSelect; export type User = typeof user.$inferSelect;
export const addNewProject = async ( export const addNewProject = async (
userId: string, userId: string,
projectId: string, projectId: string,
organizationId: string, organizationId: string,
) => { ) => {
const userR = await findMemberById(userId, organizationId); const userR = await findMemberById(userId, organizationId);
await db await db
.update(member) .update(member)
.set({ .set({
accessedProjects: [...userR.accessedProjects, projectId], accessedProjects: [...userR.accessedProjects, projectId],
}) })
.where( .where(
and(eq(member.id, userR.id), eq(member.organizationId, organizationId)), and(eq(member.id, userR.id), eq(member.organizationId, organizationId)),
); );
}; };
export const addNewEnvironment = async ( export const addNewEnvironment = async (
userId: string, userId: string,
environmentId: string, environmentId: string,
organizationId: string, organizationId: string,
) => { ) => {
const userR = await findMemberById(userId, organizationId); const userR = await findMemberById(userId, organizationId);
await db await db
.update(member) .update(member)
.set({ .set({
accessedEnvironments: [...userR.accessedEnvironments, environmentId], accessedEnvironments: [...userR.accessedEnvironments, environmentId],
}) })
.where( .where(
and(eq(member.id, userR.id), eq(member.organizationId, organizationId)), and(eq(member.id, userR.id), eq(member.organizationId, organizationId)),
); );
}; };
export const addNewService = async ( export const addNewService = async (
userId: string, userId: string,
serviceId: string, serviceId: string,
organizationId: string, organizationId: string,
) => { ) => {
const userR = await findMemberById(userId, organizationId); const userR = await findMemberById(userId, organizationId);
await db await db
.update(member) .update(member)
.set({ .set({
accessedServices: [...userR.accessedServices, serviceId], accessedServices: [...userR.accessedServices, serviceId],
}) })
.where( .where(
and(eq(member.id, userR.id), eq(member.organizationId, organizationId)), and(eq(member.id, userR.id), eq(member.organizationId, organizationId)),
); );
}; };
export const canPerformCreationService = async ( export const canPerformCreationService = async (
userId: string, userId: string,
projectId: string, projectId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { accessedProjects, canCreateServices } = await findMemberById( const { accessedProjects, canCreateServices } = await findMemberById(
userId, userId,
organizationId, organizationId,
); );
const haveAccessToProject = accessedProjects.includes(projectId); const haveAccessToProject = accessedProjects.includes(projectId);
if (canCreateServices && haveAccessToProject) { if (canCreateServices && haveAccessToProject) {
return true; return true;
} }
return false; return false;
}; };
export const canPerformAccessService = async ( export const canPerformAccessService = async (
userId: string, userId: string,
serviceId: string, serviceId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { accessedServices } = await findMemberById(userId, organizationId); const { accessedServices } = await findMemberById(userId, organizationId);
const haveAccessToService = accessedServices.includes(serviceId); const haveAccessToService = accessedServices.includes(serviceId);
if (haveAccessToService) { if (haveAccessToService) {
return true; return true;
} }
return false; return false;
}; };
export const canPeformDeleteService = async ( export const canPerformDeleteService = async (
userId: string, userId: string,
serviceId: string, serviceId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { accessedServices, canDeleteServices } = await findMemberById( const { accessedServices, canDeleteServices } = await findMemberById(
userId, userId,
organizationId, organizationId,
); );
const haveAccessToService = accessedServices.includes(serviceId); const haveAccessToService = accessedServices.includes(serviceId);
if (canDeleteServices && haveAccessToService) { if (canDeleteServices && haveAccessToService) {
return true; return true;
} }
return false; return false;
}; };
export const canPerformCreationProject = async ( export const canPerformCreationProject = async (
userId: string, userId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { canCreateProjects } = await findMemberById(userId, organizationId); const { canCreateProjects } = await findMemberById(userId, organizationId);
if (canCreateProjects) { if (canCreateProjects) {
return true; return true;
} }
return false; return false;
}; };
export const canPerformDeleteProject = async ( export const canPerformDeleteProject = async (
userId: string, userId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { canDeleteProjects } = await findMemberById(userId, organizationId); const { canDeleteProjects } = await findMemberById(userId, organizationId);
if (canDeleteProjects) { if (canDeleteProjects) {
return true; return true;
} }
return false; return false;
}; };
export const canPerformAccessProject = async ( export const canPerformAccessProject = async (
userId: string, userId: string,
projectId: string, projectId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { accessedProjects } = await findMemberById(userId, organizationId); const { accessedProjects } = await findMemberById(userId, organizationId);
const haveAccessToProject = accessedProjects.includes(projectId); const haveAccessToProject = accessedProjects.includes(projectId);
if (haveAccessToProject) { if (haveAccessToProject) {
return true; return true;
} }
return false; return false;
}; };
export const canPerformAccessEnvironment = async ( export const canPerformAccessEnvironment = async (
userId: string, userId: string,
environmentId: string, environmentId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { accessedEnvironments } = await findMemberById(userId, organizationId); const { accessedEnvironments } = await findMemberById(userId, organizationId);
const haveAccessToEnvironment = accessedEnvironments.includes(environmentId); const haveAccessToEnvironment = accessedEnvironments.includes(environmentId);
if (haveAccessToEnvironment) { if (haveAccessToEnvironment) {
return true; return true;
} }
return false; return false;
}; };
export const canPerformDeleteEnvironment = async ( export const canPerformDeleteEnvironment = async (
userId: string, userId: string,
projectId: string, projectId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { accessedProjects, canDeleteEnvironments } = await findMemberById( const { accessedProjects, canDeleteEnvironments } = await findMemberById(
userId, userId,
organizationId, organizationId,
); );
const haveAccessToProject = accessedProjects.includes(projectId); const haveAccessToProject = accessedProjects.includes(projectId);
if (canDeleteEnvironments && haveAccessToProject) { if (canDeleteEnvironments && haveAccessToProject) {
return true; return true;
} }
return false; return false;
}; };
export const canAccessToTraefikFiles = async ( export const canAccessToTraefikFiles = async (
userId: string, userId: string,
organizationId: string, organizationId: string,
) => { ) => {
const { canAccessToTraefikFiles } = await findMemberById( const { canAccessToTraefikFiles } = await findMemberById(
userId, userId,
organizationId, organizationId,
); );
return canAccessToTraefikFiles; return canAccessToTraefikFiles;
}; };
export const checkServiceAccess = async ( export const checkServiceAccess = async (
userId: string, userId: string,
serviceId: string, serviceId: string,
organizationId: string, organizationId: string,
action = "access" as "access" | "create" | "delete", action = "access" as "access" | "create" | "delete",
) => { ) => {
let hasPermission = false; let hasPermission = false;
switch (action) { switch (action) {
case "create": case "create":
hasPermission = await canPerformCreationService( hasPermission = await canPerformCreationService(
userId, userId,
serviceId, serviceId,
organizationId, organizationId,
); );
break; break;
case "access": case "access":
hasPermission = await canPerformAccessService( hasPermission = await canPerformAccessService(
userId, userId,
serviceId, serviceId,
organizationId, organizationId,
); );
break; break;
case "delete": case "delete":
hasPermission = await canPeformDeleteService( hasPermission = await canPerformDeleteService(
userId, userId,
serviceId, serviceId,
organizationId, organizationId,
); );
break; break;
default: default:
hasPermission = false; hasPermission = false;
} }
if (!hasPermission) { if (!hasPermission) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "Permission denied", message: "Permission denied",
}); });
} }
}; };
export const checkEnvironmentAccess = async ( export const checkEnvironmentAccess = async (
userId: string, userId: string,
environmentId: string, environmentId: string,
organizationId: string, organizationId: string,
action = "access" as const, action = "access" as const,
) => { ) => {
let hasPermission = false; let hasPermission = false;
switch (action) { switch (action) {
case "access": case "access":
hasPermission = await canPerformAccessEnvironment( hasPermission = await canPerformAccessEnvironment(
userId, userId,
environmentId, environmentId,
organizationId, organizationId,
); );
break; break;
default: default:
hasPermission = false; hasPermission = false;
} }
if (!hasPermission) { if (!hasPermission) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "Permission denied", message: "Permission denied",
}); });
} }
}; };
export const checkEnvironmentDeletionPermission = async ( export const checkEnvironmentDeletionPermission = async (
userId: string, userId: string,
projectId: string, projectId: string,
organizationId: string, organizationId: string,
) => { ) => {
const member = await findMemberById(userId, organizationId); const member = await findMemberById(userId, organizationId);
if (!member) { if (!member) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "User not found in organization", message: "User not found in organization",
}); });
} }
if (member.role === "owner" || member.role === "admin") { if (member.role === "owner" || member.role === "admin") {
return true; return true;
} }
if (!member.canDeleteEnvironments) { if (!member.canDeleteEnvironments) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "You don't have permission to delete environments", message: "You don't have permission to delete environments",
}); });
} }
const hasProjectAccess = member.accessedProjects.includes(projectId); const hasProjectAccess = member.accessedProjects.includes(projectId);
if (!hasProjectAccess) { if (!hasProjectAccess) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "You don't have access to this project", message: "You don't have access to this project",
}); });
} }
return true; return true;
}; };
export const checkProjectAccess = async ( export const checkProjectAccess = async (
authId: string, authId: string,
action: "create" | "delete" | "access", action: "create" | "delete" | "access",
organizationId: string, organizationId: string,
projectId?: string, projectId?: string,
) => { ) => {
let hasPermission = false; let hasPermission = false;
switch (action) { switch (action) {
case "access": case "access":
hasPermission = await canPerformAccessProject( hasPermission = await canPerformAccessProject(
authId, authId,
projectId as string, projectId as string,
organizationId, organizationId,
); );
break; break;
case "create": case "create":
hasPermission = await canPerformCreationProject(authId, organizationId); hasPermission = await canPerformCreationProject(authId, organizationId);
break; break;
case "delete": case "delete":
hasPermission = await canPerformDeleteProject(authId, organizationId); hasPermission = await canPerformDeleteProject(authId, organizationId);
break; break;
default: default:
hasPermission = false; hasPermission = false;
} }
if (!hasPermission) { if (!hasPermission) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "Permission denied", message: "Permission denied",
}); });
} }
}; };
export const checkEnvironmentCreationPermission = async ( export const checkEnvironmentCreationPermission = async (
userId: string, userId: string,
projectId: string, projectId: string,
organizationId: string, organizationId: string,
) => { ) => {
// Get user's member record // Get user's member record
const member = await findMemberById(userId, organizationId); const member = await findMemberById(userId, organizationId);
if (!member) { if (!member) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "User not found in organization", message: "User not found in organization",
}); });
} }
// Owners and admins can always create environments // Owners and admins can always create environments
if (member.role === "owner" || member.role === "admin") { if (member.role === "owner" || member.role === "admin") {
return true; return true;
} }
// Check if user has canCreateEnvironments permission // Check if user has canCreateEnvironments permission
if (!member.canCreateEnvironments) { if (!member.canCreateEnvironments) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "You don't have permission to create environments", message: "You don't have permission to create environments",
}); });
} }
// Check if user has access to the project // Check if user has access to the project
const hasProjectAccess = member.accessedProjects.includes(projectId); const hasProjectAccess = member.accessedProjects.includes(projectId);
if (!hasProjectAccess) { if (!hasProjectAccess) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "You don't have access to this project", message: "You don't have access to this project",
}); });
} }
return true; return true;
}; };
export const findMemberById = async ( export const findMemberById = async (
userId: string, userId: string,
organizationId: string, organizationId: string,
) => { ) => {
const result = await db.query.member.findFirst({ const result = await db.query.member.findFirst({
where: and( where: and(
eq(member.userId, userId), eq(member.userId, userId),
eq(member.organizationId, organizationId), eq(member.organizationId, organizationId),
), ),
with: { with: {
user: true, user: true,
}, },
}); });
if (!result) { if (!result) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "Permission denied", message: "Permission denied",
}); });
} }
return result; return result;
}; };
export const updateUser = async (userId: string, userData: Partial<User>) => { export const updateUser = async (userId: string, userData: Partial<User>) => {
// Validate email if it's being updated // Validate email if it's being updated
if (userData.email !== undefined) { if (userData.email !== undefined) {
if (!userData.email || userData.email.trim() === "") { if (!userData.email || userData.email.trim() === "") {
throw new Error("Email is required and cannot be empty"); throw new Error("Email is required and cannot be empty");
} }
// Basic email format validation // Basic email format validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(userData.email)) { if (!emailRegex.test(userData.email)) {
throw new Error("Please enter a valid email address"); throw new Error("Please enter a valid email address");
} }
} }
const userResult = await db const userResult = await db
.update(user) .update(user)
.set({ .set({
...userData, ...userData,
}) })
.where(eq(user.id, userId)) .where(eq(user.id, userId))
.returning() .returning()
.then((res) => res[0]); .then((res) => res[0]);
return userResult; return userResult;
}; };
export const createApiKey = async ( export const createApiKey = async (
userId: string, userId: string,
input: { input: {
name: string; name: string;
prefix?: string; prefix?: string;
expiresIn?: number; expiresIn?: number;
metadata: { metadata: {
organizationId: string; organizationId: string;
}; };
rateLimitEnabled?: boolean; rateLimitEnabled?: boolean;
rateLimitTimeWindow?: number; rateLimitTimeWindow?: number;
rateLimitMax?: number; rateLimitMax?: number;
remaining?: number; remaining?: number;
refillAmount?: number; refillAmount?: number;
refillInterval?: number; refillInterval?: number;
}, },
) => { ) => {
const result = await auth.createApiKey({ const result = await auth.createApiKey({
body: { body: {
name: input.name, name: input.name,
expiresIn: input.expiresIn, expiresIn: input.expiresIn,
prefix: input.prefix, prefix: input.prefix,
rateLimitEnabled: input.rateLimitEnabled, rateLimitEnabled: input.rateLimitEnabled,
rateLimitTimeWindow: input.rateLimitTimeWindow, rateLimitTimeWindow: input.rateLimitTimeWindow,
rateLimitMax: input.rateLimitMax, rateLimitMax: input.rateLimitMax,
remaining: input.remaining, remaining: input.remaining,
refillAmount: input.refillAmount, refillAmount: input.refillAmount,
refillInterval: input.refillInterval, refillInterval: input.refillInterval,
userId, userId,
}, },
}); });
if (input.metadata) { if (input.metadata) {
await db await db
.update(apikey) .update(apikey)
.set({ metadata: JSON.stringify(input.metadata) }) .set({ metadata: JSON.stringify(input.metadata) })
.where(eq(apikey.id, result.id)); .where(eq(apikey.id, result.id));
} }
return result; return result;
}; };
+4 -4
View File
@@ -3,13 +3,13 @@ import { docker } from "../constants";
export const initializeSwarm = async () => { export const initializeSwarm = async () => {
const swarmInitialized = await dockerSwarmInitialized(); const swarmInitialized = await dockerSwarmInitialized();
if (swarmInitialized) { if (swarmInitialized) {
console.log("Swarm is already initilized"); console.log("Swarm is already initialized");
} else { } else {
await docker.swarmInit({ await docker.swarmInit({
AdvertiseAddr: "127.0.0.1", AdvertiseAddr: "127.0.0.1",
ListenAddr: "0.0.0.0", ListenAddr: "0.0.0.0",
}); });
console.log("Swarm was initilized"); console.log("Swarm was initialized");
} }
}; };
@@ -26,14 +26,14 @@ export const dockerSwarmInitialized = async () => {
export const initializeNetwork = async () => { export const initializeNetwork = async () => {
const networkInitialized = await dockerNetworkInitialized(); const networkInitialized = await dockerNetworkInitialized();
if (networkInitialized) { if (networkInitialized) {
console.log("Network is already initilized"); console.log("Network is already initialized");
} else { } else {
docker.createNetwork({ docker.createNetwork({
Attachable: true, Attachable: true,
Name: "dokploy-network", Name: "dokploy-network",
Driver: "overlay", Driver: "overlay",
}); });
console.log("Network was initilized"); console.log("Network was initialized");
} }
}; };
+76 -76
View File
@@ -5,26 +5,26 @@ import boxen from "boxen";
import { quote } from "shell-quote"; import { quote } from "shell-quote";
import { writeDomainsToCompose } from "../docker/domain"; import { writeDomainsToCompose } from "../docker/domain";
import { import {
encodeBase64, encodeBase64,
getEnviromentVariablesObject, getEnvironmentVariablesObject,
prepareEnvironmentVariables, prepareEnvironmentVariables,
} from "../docker/utils"; } from "../docker/utils";
export type ComposeNested = InferResultType< export type ComposeNested = InferResultType<
"compose", "compose",
{ environment: { with: { project: true } }; mounts: true; domains: true } { environment: { with: { project: true } }; mounts: true; domains: true }
>; >;
export const getBuildComposeCommand = async (compose: ComposeNested) => { export const getBuildComposeCommand = async (compose: ComposeNested) => {
const { COMPOSE_PATH } = paths(!!compose.serverId); const { COMPOSE_PATH } = paths(!!compose.serverId);
const { sourceType, appName, mounts, composeType, domains } = compose; const { sourceType, appName, mounts, composeType, domains } = compose;
const command = createCommand(compose); const command = createCommand(compose);
const envCommand = getCreateEnvFileCommand(compose); const envCommand = getCreateEnvFileCommand(compose);
const projectPath = join(COMPOSE_PATH, compose.appName, "code"); const projectPath = join(COMPOSE_PATH, compose.appName, "code");
const exportEnvCommand = getExportEnvCommand(compose); const exportEnvCommand = getExportEnvCommand(compose);
const newCompose = await writeDomainsToCompose(compose, domains); const newCompose = await writeDomainsToCompose(compose, domains);
const logContent = ` const logContent = `
App Name: ${appName} App Name: ${appName}
Build Compose 🐳 Build Compose 🐳
Detected: ${mounts.length} mounts 📂 Detected: ${mounts.length} mounts 📂
@@ -32,31 +32,31 @@ Command: docker ${command}
Source Type: docker ${sourceType} ✅ Source Type: docker ${sourceType} ✅
Compose Type: ${composeType} ✅`; Compose Type: ${composeType} ✅`;
const logBox = boxen(logContent, { const logBox = boxen(logContent, {
padding: { padding: {
left: 1, left: 1,
right: 1, right: 1,
bottom: 1, bottom: 1,
}, },
width: 80, width: 80,
borderStyle: "double", borderStyle: "double",
}); });
const bashCommand = ` const bashCommand = `
set -e set -e
{ {
echo "${logBox}"; echo "${logBox}";
${newCompose} ${newCompose}
${envCommand} ${envCommand}
cd "${projectPath}"; cd "${projectPath}";
${compose.isolatedDeployment ? `docker network inspect ${compose.appName} >/dev/null 2>&1 || docker network create ${compose.composeType === "stack" ? "--driver overlay" : ""} --attachable ${compose.appName}` : ""} ${compose.isolatedDeployment ? `docker network inspect ${compose.appName} >/dev/null 2>&1 || docker network create ${compose.composeType === "stack" ? "--driver overlay" : ""} --attachable ${compose.appName}` : ""}
env -i PATH="$PATH" ${exportEnvCommand} docker ${command.split(" ").join(" ")} 2>&1 || { echo "Error: ❌ Docker command failed"; exit 1; } env -i PATH="$PATH" ${exportEnvCommand} docker ${command.split(" ").join(" ")} 2>&1 || { echo "Error: ❌ Docker command failed"; exit 1; }
${compose.isolatedDeployment ? `docker network connect ${compose.appName} $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1` : ""} ${compose.isolatedDeployment ? `docker network connect ${compose.appName} $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1` : ""}
echo "Docker Compose Deployed: ✅"; echo "Docker Compose Deployed: ✅";
} || { } || {
echo "Error: ❌ Script execution failed"; echo "Error: ❌ Script execution failed";
@@ -64,81 +64,81 @@ Compose Type: ${composeType} ✅`;
} }
`; `;
return bashCommand; return bashCommand;
}; };
const sanitizeCommand = (command: string) => { const sanitizeCommand = (command: string) => {
const sanitizedCommand = command.trim(); const sanitizedCommand = command.trim();
const parts = sanitizedCommand.split(/\s+/); const parts = sanitizedCommand.split(/\s+/);
const restCommand = parts.map((arg) => arg.replace(/^"(.*)"$/, "$1")); const restCommand = parts.map((arg) => arg.replace(/^"(.*)"$/, "$1"));
return restCommand.join(" "); return restCommand.join(" ");
}; };
export const createCommand = (compose: ComposeNested) => { export const createCommand = (compose: ComposeNested) => {
const { composeType, appName, sourceType } = compose; const { composeType, appName, sourceType } = compose;
if (compose.command) { if (compose.command) {
return `${sanitizeCommand(compose.command)}`; return `${sanitizeCommand(compose.command)}`;
} }
const path = const path =
sourceType === "raw" ? "docker-compose.yml" : compose.composePath; sourceType === "raw" ? "docker-compose.yml" : compose.composePath;
let command = ""; let command = "";
if (composeType === "docker-compose") { if (composeType === "docker-compose") {
command = `compose -p ${appName} -f ${path} up -d --build --remove-orphans`; command = `compose -p ${appName} -f ${path} up -d --build --remove-orphans`;
} else if (composeType === "stack") { } else if (composeType === "stack") {
command = `stack deploy -c ${path} ${appName} --prune --with-registry-auth`; command = `stack deploy -c ${path} ${appName} --prune --with-registry-auth`;
} }
return command; return command;
}; };
export const getCreateEnvFileCommand = (compose: ComposeNested) => { export const getCreateEnvFileCommand = (compose: ComposeNested) => {
const { COMPOSE_PATH } = paths(!!compose.serverId); const { COMPOSE_PATH } = paths(!!compose.serverId);
const { env, composePath, appName } = compose; const { env, composePath, appName } = compose;
const composeFilePath = const composeFilePath =
join(COMPOSE_PATH, appName, "code", composePath) || join(COMPOSE_PATH, appName, "code", composePath) ||
join(COMPOSE_PATH, appName, "code", "docker-compose.yml"); join(COMPOSE_PATH, appName, "code", "docker-compose.yml");
const envFilePath = join(dirname(composeFilePath), ".env"); const envFilePath = join(dirname(composeFilePath), ".env");
let envContent = `APP_NAME=${appName}\n`; let envContent = `APP_NAME=${appName}\n`;
envContent += env || ""; envContent += env || "";
if (!envContent.includes("DOCKER_CONFIG")) { if (!envContent.includes("DOCKER_CONFIG")) {
envContent += "\nDOCKER_CONFIG=/root/.docker"; envContent += "\nDOCKER_CONFIG=/root/.docker";
} }
if (compose.randomize) { if (compose.randomize) {
envContent += `\nCOMPOSE_PREFIX=${compose.suffix}`; envContent += `\nCOMPOSE_PREFIX=${compose.suffix}`;
} }
const envFileContent = prepareEnvironmentVariables( const envFileContent = prepareEnvironmentVariables(
envContent, envContent,
compose.environment.project.env, compose.environment.project.env,
compose.environment.env, compose.environment.env,
).join("\n"); ).join("\n");
const encodedContent = encodeBase64(envFileContent); const encodedContent = encodeBase64(envFileContent);
return ` return `
touch ${envFilePath}; touch ${envFilePath};
echo "${encodedContent}" | base64 -d > "${envFilePath}"; echo "${encodedContent}" | base64 -d > "${envFilePath}";
`; `;
}; };
const getExportEnvCommand = (compose: ComposeNested) => { const getExportEnvCommand = (compose: ComposeNested) => {
if (compose.composeType !== "stack") return ""; if (compose.composeType !== "stack") return "";
const envVars = getEnviromentVariablesObject( const envVars = getEnvironmentVariablesObject(
compose.env, compose.env,
compose.environment.project.env, compose.environment.project.env,
compose.environment.env, compose.environment.env,
); );
const exports = Object.entries(envVars) const exports = Object.entries(envVars)
.map(([key, value]) => `${key}=${quote([value])}`) .map(([key, value]) => `${key}=${quote([value])}`)
.join(" "); .join(" ");
return exports ? `${exports}` : ""; return exports ? `${exports}` : "";
}; };
@@ -1,105 +1,105 @@
import { import {
getEnviromentVariablesObject, getEnvironmentVariablesObject,
prepareEnvironmentVariablesForShell, prepareEnvironmentVariablesForShell,
} from "@dokploy/server/utils/docker/utils"; } from "@dokploy/server/utils/docker/utils";
import { quote } from "shell-quote"; import { quote } from "shell-quote";
import { import {
getBuildAppDirectory, getBuildAppDirectory,
getDockerContextPath, getDockerContextPath,
} from "../filesystem/directory"; } from "../filesystem/directory";
import type { ApplicationNested } from "."; import type { ApplicationNested } from ".";
import { createEnvFileCommand } from "./utils"; import { createEnvFileCommand } from "./utils";
export const getDockerCommand = (application: ApplicationNested) => { export const getDockerCommand = (application: ApplicationNested) => {
const { const {
appName, appName,
env, env,
publishDirectory, publishDirectory,
buildArgs, buildArgs,
buildSecrets, buildSecrets,
dockerBuildStage, dockerBuildStage,
cleanCache, cleanCache,
createEnvFile, createEnvFile,
} = application; } = application;
const dockerFilePath = getBuildAppDirectory(application); const dockerFilePath = getBuildAppDirectory(application);
try { try {
const image = `${appName}`; const image = `${appName}`;
const defaultContextPath = const defaultContextPath =
dockerFilePath.substring(0, dockerFilePath.lastIndexOf("/") + 1) || "."; dockerFilePath.substring(0, dockerFilePath.lastIndexOf("/") + 1) || ".";
const dockerContextPath = const dockerContextPath =
getDockerContextPath(application) || defaultContextPath; getDockerContextPath(application) || defaultContextPath;
const commandArgs = ["build", "-t", image, "-f", dockerFilePath, "."]; const commandArgs = ["build", "-t", image, "-f", dockerFilePath, "."];
if (dockerBuildStage) { if (dockerBuildStage) {
commandArgs.push("--target", dockerBuildStage); commandArgs.push("--target", dockerBuildStage);
} }
if (cleanCache) { if (cleanCache) {
commandArgs.push("--no-cache"); commandArgs.push("--no-cache");
} }
const args = prepareEnvironmentVariablesForShell( const args = prepareEnvironmentVariablesForShell(
buildArgs, buildArgs,
application.environment.project.env, application.environment.project.env,
application.environment.env, application.environment.env,
); );
for (const arg of args) { for (const arg of args) {
commandArgs.push("--build-arg", arg); commandArgs.push("--build-arg", arg);
} }
const secrets = getEnviromentVariablesObject( const secrets = getEnvironmentVariablesObject(
buildSecrets, buildSecrets,
application.environment.project.env, application.environment.project.env,
application.environment.env, application.environment.env,
); );
const joinedSecrets = Object.entries(secrets) const joinedSecrets = Object.entries(secrets)
.map(([key, value]) => `${key}=${quote([value])}`) .map(([key, value]) => `${key}=${quote([value])}`)
.join(" "); .join(" ");
/* /*
Do not generate an environment file when publishDirectory is specified, Do not generate an environment file when publishDirectory is specified,
as it could be publicly exposed. as it could be publicly exposed.
Also respect the createEnvFile flag. Also respect the createEnvFile flag.
*/ */
let command = ""; let command = "";
if (!publishDirectory && createEnvFile) { if (!publishDirectory && createEnvFile) {
command += createEnvFileCommand( command += createEnvFileCommand(
dockerFilePath, dockerFilePath,
env, env,
application.environment.project.env, application.environment.project.env,
application.environment.env, application.environment.env,
); );
} }
for (const key in secrets) { for (const key in secrets) {
// Although buildx is smart enough to know we may be referring to an environment variable name, // Although buildx is smart enough to know we may be referring to an environment variable name,
// we still make sure it doesn't fall back to `type=file`. // we still make sure it doesn't fall back to `type=file`.
// See: https://docs.docker.com/reference/cli/docker/buildx/build/#secret // See: https://docs.docker.com/reference/cli/docker/buildx/build/#secret
commandArgs.push("--secret", `type=env,id=${key}`); commandArgs.push("--secret", `type=env,id=${key}`);
} }
command += ` command += `
echo "Building ${appName}" ; echo "Building ${appName}" ;
cd ${dockerContextPath} || { cd ${dockerContextPath} || {
echo "❌ The path ${dockerContextPath} does not exist" ; echo "❌ The path ${dockerContextPath} does not exist" ;
exit 1; exit 1;
} }
${joinedSecrets} docker ${commandArgs.join(" ")} || { ${joinedSecrets} docker ${commandArgs.join(" ")} || {
echo "❌ Docker build failed" ; echo "❌ Docker build failed" ;
exit 1; exit 1;
} }
echo "✅ Docker build completed." ; echo "✅ Docker build completed." ;
`; `;
return command; return command;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };
+1 -1
View File
@@ -434,7 +434,7 @@ export const parseEnvironmentKeyValuePair = (
return [key, valueParts.join("=")]; return [key, valueParts.join("=")];
}; };
export const getEnviromentVariablesObject = ( export const getEnvironmentVariablesObject = (
input: string | null, input: string | null,
projectEnv?: string | null, projectEnv?: string | null,
environmentEnv?: string | null, environmentEnv?: string | null,