Skip to content

v3: misc CLI improvements #1173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/spicy-frogs-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"trigger.dev": patch
---

- Prevent downgrades during update check and advise to upgrade CLI
- Detect bun and use npm instead
- During init, fail early and advise if not a TypeScript project
- During init, allow specifying custom package manager args
- Add links to dev worker started message
- Fix links in unsupported terminals
8 changes: 7 additions & 1 deletion apps/webapp/app/models/api-key.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ export function createPkApiKeyForEnv(envType: RuntimeEnvironment["type"]) {
return `pk_${envSlug(envType)}_${apiKeyId(20)}`;
}

export function envSlug(environmentType: RuntimeEnvironment["type"]) {
export type EnvSlug = "dev" | "stg" | "prod" | "prev";

export function envSlug(environmentType: RuntimeEnvironment["type"]): EnvSlug {
switch (environmentType) {
case "DEVELOPMENT": {
return "dev";
Expand All @@ -100,3 +102,7 @@ export function envSlug(environmentType: RuntimeEnvironment["type"]) {
}
}
}

export function isEnvSlug(maybeSlug: string): maybeSlug is EnvSlug {
return ["dev", "stg", "prod", "prev"].includes(maybeSlug);
}
74 changes: 74 additions & 0 deletions apps/webapp/app/routes/projects.v3.$projectRef.runs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { LoaderFunctionArgs, redirect } from "@remix-run/server-runtime";
import { z } from "zod";
import { prisma } from "~/db.server";
import { EnvSlug, isEnvSlug } from "~/models/api-key.server";
import { requireUserId } from "~/services/session.server";

const ParamsSchema = z.object({
projectRef: z.string(),
});

export async function loader({ params, request }: LoaderFunctionArgs) {
const userId = await requireUserId(request);

const { projectRef } = ParamsSchema.parse(params);

const project = await prisma.project.findFirst({
where: {
externalRef: projectRef,
organization: {
members: {
some: {
userId,
},
},
},
},
include: {
organization: true,
},
});

if (!project) {
return new Response("Project not found", { status: 404 });
}

const url = new URL(request.url);
const envSlug = url.searchParams.get("envSlug");

// Get the environment from the slug
if (envSlug && isEnvSlug(envSlug)) {
const env = await getEnvFromSlug(project.id, userId, envSlug);

if (env) {
url.searchParams.set("environments", env.id);
}

url.searchParams.delete("envSlug");
}

return redirect(
`/orgs/${project.organization.slug}/projects/v3/${project.slug}/runs${url.search}`
);
}

async function getEnvFromSlug(projectId: string, userId: string, envSlug: EnvSlug) {
if (envSlug === "dev") {
return await prisma.runtimeEnvironment.findFirst({
where: {
projectId,
slug: envSlug,
orgMember: {
userId,
},
},
});
}

return await prisma.runtimeEnvironment.findFirst({
where: {
projectId,
slug: envSlug,
},
});
}
40 changes: 40 additions & 0 deletions apps/webapp/app/routes/projects.v3.$projectRef.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { LoaderFunctionArgs, redirect } from "@remix-run/server-runtime";
import { z } from "zod";
import { prisma } from "~/db.server";
import { requireUserId } from "~/services/session.server";

const ParamsSchema = z.object({
projectRef: z.string(),
});

export async function loader({ params, request }: LoaderFunctionArgs) {
const userId = await requireUserId(request);

const validatedParams = ParamsSchema.parse(params);

const project = await prisma.project.findFirst({
where: {
externalRef: validatedParams.projectRef,
organization: {
members: {
some: {
userId,
},
},
},
},
include: {
organization: true,
},
});

if (!project) {
return new Response("Not found", { status: 404 });
}

const url = new URL(request.url);

return redirect(
`/orgs/${project.organization.slug}/projects/v3/${project.slug}/test${url.search}`
);
}
4 changes: 2 additions & 2 deletions packages/cli-v3/e2e/handleDependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { log } from "@clack/prompts";
import { Metafile } from "esbuild";
import { join } from "node:path";
import terminalLink from "terminal-link";

import { SkipLoggingError } from "../src/cli/common.js";
import {
Expand All @@ -16,6 +15,7 @@ import { writeJSONFile } from "../src/utilities/fileSystem.js";
import { PackageManager } from "../src/utilities/getUserPackageManager.js";
import { JavascriptProject } from "../src/utilities/javascriptProject.js";
import { logger } from "../src/utilities/logger.js";
import { cliLink } from "../src/utilities/cliOutput.js";

type HandleDependenciesOptions = {
entryPointMetaOutput: Metafile["outputs"]["out/stdin.js"];
Expand Down Expand Up @@ -81,7 +81,7 @@ export async function handleDependencies(options: HandleDependenciesOptions) {
log.warn(
`No additionalFiles matches for:\n\n${copyResult.noMatches
.map((glob) => `- "${glob}"`)
.join("\n")}\n\nIf this is unexpected you should check your ${terminalLink(
.join("\n")}\n\nIf this is unexpected you should check your ${cliLink(
"glob patterns",
"https://github.com/isaacs/node-glob?tab=readme-ov-file#glob-primer"
)} are valid.`
Expand Down
15 changes: 7 additions & 8 deletions packages/cli-v3/src/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { readFileSync } from "node:fs";
import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join, posix, relative, resolve } from "node:path";
import { setTimeout } from "node:timers/promises";
import terminalLink from "terminal-link";
import invariant from "tiny-invariant";
import { z } from "zod";
import * as packageJson from "../../package.json";
Expand Down Expand Up @@ -50,7 +49,7 @@ import {
mockServerOnlyPlugin,
workerSetupImportConfigPlugin,
} from "../utilities/build";
import { chalkError, chalkPurple, chalkWarning } from "../utilities/cliOutput";
import { chalkError, chalkPurple, chalkWarning, cliLink } from "../utilities/cliOutput";
import {
logESMRequireError,
logTaskMetadataParseError,
Expand Down Expand Up @@ -437,7 +436,7 @@ async function _deployCommand(dir: string, options: DeployCommandOptions) {
throw new SkipLoggingError(`Deployment failed to complete: ${finishedDeployment}`);
}

const deploymentLink = terminalLink(
const deploymentLink = cliLink(
"View deployment",
`${authorization.dashboardUrl}/projects/v3/${resolvedConfig.config.project}/deployments/${finishedDeployment.shortCode}`
);
Expand Down Expand Up @@ -576,7 +575,7 @@ function checkLogsForWarnings(logs: string): WarningsCheckReturn {
const warnings: LogParserOptions = [
{
regex: /prisma:warn We could not find your Prisma schema/,
message: `Prisma generate failed to find the default schema. Did you include it in config.additionalFiles? ${terminalLink(
message: `Prisma generate failed to find the default schema. Did you include it in config.additionalFiles? ${cliLink(
"Config docs",
docs.config.prisma
)}\nCustom schema paths require a postinstall script like this: \`prisma generate --schema=./custom/path/to/schema.prisma\``,
Expand Down Expand Up @@ -626,17 +625,17 @@ function checkLogsForErrors(logs: string) {
const errors: LogParserOptions = [
{
regex: /Error: Provided --schema at (?<schema>.*) doesn't exist/,
message: `Prisma generate failed to find the specified schema at "$schema".\nDid you include it in config.additionalFiles? ${terminalLink(
message: `Prisma generate failed to find the specified schema at "$schema".\nDid you include it in config.additionalFiles? ${cliLink(
"Config docs",
docs.config.prisma
)}`,
},
{
regex: /sh: 1: (?<packageOrBinary>.*): not found/,
message: `$packageOrBinary not found\n\nIf it's a package: Include it in ${terminalLink(
message: `$packageOrBinary not found\n\nIf it's a package: Include it in ${cliLink(
"config.additionalPackages",
docs.config.prisma
)}\nIf it's a binary: Please ${terminalLink(
)}\nIf it's a binary: Please ${cliLink(
"get in touch",
getInTouch
)} and we'll see what we can do!`,
Expand Down Expand Up @@ -1341,7 +1340,7 @@ async function compileProject(
log.warn(
`No additionalFiles matches for:\n\n${copyResult.noMatches
.map((glob) => `- "${glob}"`)
.join("\n")}\n\nIf this is unexpected you should check your ${terminalLink(
.join("\n")}\n\nIf this is unexpected you should check your ${cliLink(
"glob patterns",
"https://github.com/isaacs/node-glob?tab=readme-ov-file#glob-primer"
)} are valid.`
Expand Down
30 changes: 24 additions & 6 deletions packages/cli-v3/src/commands/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,15 @@ import {
mockServerOnlyPlugin,
workerSetupImportConfigPlugin,
} from "../utilities/build";
import { chalkError, chalkGrey, chalkPurple, chalkTask, chalkWorker } from "../utilities/cliOutput";
import {
chalkError,
chalkGrey,
chalkLink,
chalkPurple,
chalkTask,
chalkWorker,
cliLink,
} from "../utilities/cliOutput";
import { readConfig } from "../utilities/configFiles";
import { readJSONFile } from "../utilities/fileSystem";
import { printDevBanner, printStandloneInitialBanner } from "../utilities/initialBanner.js";
Expand Down Expand Up @@ -624,13 +632,23 @@ function useDev({
}

backgroundWorker.metadata = backgroundWorkerRecord.data;
backgroundWorker;

const testUrl = `${dashboardUrl}/projects/v3/${config.project}/test?environment=dev`;
const runsUrl = `${dashboardUrl}/projects/v3/${config.project}/runs?envSlug=dev`;

const pipe = chalkGrey("|");
const bullet = chalkGrey("○");
const arrow = chalkGrey("->");

const testLink = chalkLink(cliLink("Test tasks", testUrl));
const runsLink = chalkLink(cliLink("View runs", runsUrl));

const workerStarted = chalkGrey("Background worker started");
const workerVersion = chalkWorker(backgroundWorkerRecord.data.version);

logger.log(
`${chalkGrey(
`○ Background worker started -> ${chalkWorker(
backgroundWorkerRecord.data.version
)}`
)}`
`${bullet} ${workerStarted} ${arrow} ${workerVersion} ${pipe} ${testLink} ${pipe} ${runsLink}`
);

firstBuild = false;
Expand Down
Loading
Loading