trigger.dev 3.0.0-beta.44 → 3.0.0-beta.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -794,12 +794,11 @@ import { readFileSync as readFileSync2 } from "node:fs";
794
794
  import { copyFile, mkdir, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
795
795
  import { dirname, join as join6, posix, relative as relative3 } from "node:path";
796
796
  import { setTimeout as setTimeout2 } from "node:timers/promises";
797
- import terminalLink2 from "terminal-link";
798
797
  import invariant from "tiny-invariant";
799
798
  import { z as z4 } from "zod";
800
799
 
801
800
  // package.json
802
- var version = "3.0.0-beta.44";
801
+ var version = "3.0.0-beta.46";
803
802
  var dependencies = {
804
803
  "@anatine/esbuild-decorators": "^0.2.19",
805
804
  "@clack/prompts": "^0.7.0",
@@ -816,7 +815,7 @@ var dependencies = {
816
815
  "@opentelemetry/sdk-trace-base": "^1.22.0",
817
816
  "@opentelemetry/sdk-trace-node": "^1.22.0",
818
817
  "@opentelemetry/semantic-conventions": "^1.22.0",
819
- "@trigger.dev/core": "workspace:3.0.0-beta.44",
818
+ "@trigger.dev/core": "workspace:3.0.0-beta.46",
820
819
  "@types/degit": "^2.8.3",
821
820
  chalk: "^5.2.0",
822
821
  chokidar: "^3.5.3",
@@ -846,17 +845,16 @@ var dependencies = {
846
845
  "react-error-boundary": "^4.0.12",
847
846
  semver: "^7.5.0",
848
847
  "simple-git": "^3.19.0",
849
- "socket.io-client": "^4.7.4",
850
848
  "source-map-support": "^0.5.21",
851
849
  "terminal-link": "^3.0.0",
852
850
  "tiny-invariant": "^1.2.0",
853
851
  "tsconfig-paths": "^4.2.0",
852
+ typescript: "^5.4.0",
854
853
  "update-check": "^1.5.4",
855
854
  url: "^0.11.1",
856
855
  ws: "^8.12.0",
857
856
  zod: "3.22.3",
858
- "zod-validation-error": "^1.5.0",
859
- typescript: "^5.4.0"
857
+ "zod-validation-error": "^1.5.0"
860
858
  };
861
859
  var package_default = {
862
860
  name: "trigger.dev",
@@ -909,7 +907,7 @@ var package_default = {
909
907
  "npm-run-all": "^4.1.5",
910
908
  open: "^10.0.3",
911
909
  "p-retry": "^6.1.0",
912
- rimraf: "^3.0.2",
910
+ rimraf: "^5.0.7",
913
911
  tsup: "^8.0.1",
914
912
  "type-fest": "^3.6.0",
915
913
  typescript: "^5.3.3",
@@ -1357,6 +1355,7 @@ import { outro } from "@clack/prompts";
1357
1355
  // src/utilities/cliOutput.ts
1358
1356
  import { log } from "@clack/prompts";
1359
1357
  import chalk2 from "chalk";
1358
+ import terminalLink from "terminal-link";
1360
1359
  var green = "#4FFF54";
1361
1360
  var purple = "#735BF3";
1362
1361
  function chalkGreen(text3) {
@@ -1428,6 +1427,12 @@ function prettyWarning(header, body, footer) {
1428
1427
  `${prettyPrefix}${header}${prettyBody ? `${spacing}${prettyBody}` : ""}${prettyFooter ? `${spacing}${prettyFooter}` : ""}`
1429
1428
  );
1430
1429
  }
1430
+ function cliLink(text3, url, options) {
1431
+ return terminalLink(text3, url, {
1432
+ fallback: (text4, url2) => `${text4} ${url2}`,
1433
+ ...options
1434
+ });
1435
+ }
1431
1436
 
1432
1437
  // src/cli/common.ts
1433
1438
  var CommonCommandOptions = z.object({
@@ -3125,7 +3130,6 @@ function getLoaderForFile(file) {
3125
3130
  import chalk4 from "chalk";
3126
3131
  import { relative as relative2 } from "node:path";
3127
3132
  import { groupTaskMetadataIssuesByTask } from "@trigger.dev/core/v3";
3128
- import terminalLink from "terminal-link";
3129
3133
 
3130
3134
  // src/utilities/links.ts
3131
3135
  var docs = {
@@ -3222,7 +3226,7 @@ ${chalkGrey("\u25CB")} Dynamically import the module in your code: ${chalkGrey(
3222
3226
  );
3223
3227
  }
3224
3228
  logger.log(
3225
- `${chalkGrey("\u25CB")} For more info see the ${terminalLink("relevant docs", docs.config.esm)}.
3229
+ `${chalkGrey("\u25CB")} For more info see the ${cliLink("relevant docs", docs.config.esm)}.
3226
3230
  `
3227
3231
  );
3228
3232
  }
@@ -3294,6 +3298,13 @@ import { join as join4 } from "node:path";
3294
3298
  // src/utilities/getUserPackageManager.ts
3295
3299
  import { findUp as findUp2 } from "find-up";
3296
3300
  import { basename } from "path";
3301
+ var LOCKFILES = {
3302
+ npm: "package-lock.json",
3303
+ npmShrinkwrap: "npm-shrinkwrap.json",
3304
+ pnpm: "pnpm-lock.yaml",
3305
+ yarn: "yarn.lock",
3306
+ bun: "bun.lockb"
3307
+ };
3297
3308
  async function getUserPackageManager(path7) {
3298
3309
  const packageManager = await detectPackageManager(path7);
3299
3310
  logger.debug("Detected package manager", { packageManager });
@@ -3321,24 +3332,24 @@ function detectPackageManagerFromCurrentCommand() {
3321
3332
  }
3322
3333
  }
3323
3334
  async function detectPackageManagerFromArtifacts(path7) {
3324
- const artifacts = {
3325
- yarn: "yarn.lock",
3326
- pnpm: "pnpm-lock.yaml",
3327
- npm: "package-lock.json",
3328
- npmShrinkwrap: "npm-shrinkwrap.json"
3329
- };
3330
- const foundPath = await findUp2(Object.values(artifacts), { cwd: path7 });
3335
+ const foundPath = await findUp2(Object.values(LOCKFILES), { cwd: path7 });
3331
3336
  if (!foundPath) {
3332
3337
  throw new Error("Could not detect package manager from artifacts");
3333
3338
  }
3334
3339
  logger.debug("Found path from package manager artifacts", { foundPath });
3335
3340
  switch (basename(foundPath)) {
3336
- case artifacts.yarn:
3341
+ case LOCKFILES.yarn:
3342
+ logger.debug("Found yarn artifact", { foundPath });
3337
3343
  return "yarn";
3338
- case artifacts.pnpm:
3344
+ case LOCKFILES.pnpm:
3345
+ logger.debug("Found pnpm artifact", { foundPath });
3339
3346
  return "pnpm";
3340
- case artifacts.npm:
3341
- case artifacts.npmShrinkwrap:
3347
+ case LOCKFILES.npm:
3348
+ case LOCKFILES.npmShrinkwrap:
3349
+ logger.debug("Found npm artifact", { foundPath });
3350
+ return "npm";
3351
+ case LOCKFILES.bun:
3352
+ logger.debug("Found bun artifact", { foundPath });
3342
3353
  return "npm";
3343
3354
  default:
3344
3355
  throw new Error(`Unhandled package manager detection path: ${foundPath}`);
@@ -3366,10 +3377,53 @@ var JavascriptProject = class {
3366
3377
  }
3367
3378
  return this._packageJson;
3368
3379
  }
3380
+ get allowedPackageJson() {
3381
+ const disallowedKeys = [
3382
+ "scripts",
3383
+ "devDependencies",
3384
+ "dependencies",
3385
+ "peerDependencies",
3386
+ "author",
3387
+ "contributors",
3388
+ "funding",
3389
+ "bugs",
3390
+ "files",
3391
+ "keywords",
3392
+ "main",
3393
+ "module",
3394
+ "type",
3395
+ "bin",
3396
+ "browser",
3397
+ "man",
3398
+ "directories",
3399
+ "repository",
3400
+ "peerDependenciesMeta",
3401
+ "optionalDependencies",
3402
+ "engines",
3403
+ "os",
3404
+ "cpu",
3405
+ "private",
3406
+ "publishConfig",
3407
+ "workspaces"
3408
+ ];
3409
+ return Object.keys(this.packageJson).reduce(
3410
+ (acc, key) => {
3411
+ if (!disallowedKeys.includes(key)) {
3412
+ acc[key] = this.packageJson[key];
3413
+ }
3414
+ return acc;
3415
+ },
3416
+ {}
3417
+ );
3418
+ }
3369
3419
  get scripts() {
3370
- return {
3371
- postinstall: this.packageJson.scripts?.postinstall ?? ""
3372
- };
3420
+ return this.#filterScripts();
3421
+ }
3422
+ #filterScripts() {
3423
+ if (!this.packageJson.scripts || typeof this.packageJson.scripts !== "object") {
3424
+ return {};
3425
+ }
3426
+ return this.packageJson.scripts;
3373
3427
  }
3374
3428
  async install() {
3375
3429
  const command = await this.#getCommand();
@@ -3735,27 +3789,49 @@ Latest: ${newCliVersion}`,
3735
3789
  }
3736
3790
  const triggerDependencies = getTriggerDependencies(packageJson);
3737
3791
  function getVersionMismatches(deps, targetVersion) {
3738
- const mismatches = [];
3792
+ const mismatches2 = [];
3739
3793
  for (const dep of deps) {
3740
3794
  if (dep.version === targetVersion) {
3741
3795
  continue;
3742
3796
  }
3743
- mismatches.push(dep);
3797
+ mismatches2.push(dep);
3798
+ }
3799
+ const extractRelease = (version2) => {
3800
+ const release = Number(version2.split("3.0.0-beta.")[1]);
3801
+ return release || void 0;
3802
+ };
3803
+ let isDowngrade2 = false;
3804
+ const targetRelease = extractRelease(targetVersion);
3805
+ if (targetRelease) {
3806
+ isDowngrade2 = mismatches2.some((dep) => {
3807
+ const depRelease = extractRelease(dep.version);
3808
+ if (!depRelease) {
3809
+ return false;
3810
+ }
3811
+ return depRelease > targetRelease;
3812
+ });
3744
3813
  }
3745
- return mismatches;
3814
+ return {
3815
+ mismatches: mismatches2,
3816
+ isDowngrade: isDowngrade2
3817
+ };
3746
3818
  }
3747
- const versionMismatches = getVersionMismatches(triggerDependencies, cliVersion);
3748
- if (versionMismatches.length === 0) {
3819
+ const { mismatches, isDowngrade } = getVersionMismatches(triggerDependencies, cliVersion);
3820
+ if (mismatches.length === 0) {
3749
3821
  if (!embedded) {
3750
3822
  outro4(`Nothing to do${newCliVersion ? " ..but you should really update your CLI!" : ""}`);
3751
3823
  return hasOutput;
3752
3824
  }
3753
3825
  return hasOutput;
3754
3826
  }
3755
- prettyWarning(
3756
- "Mismatch between your CLI version and installed packages",
3757
- "We recommend pinned versions for guaranteed compatibility"
3758
- );
3827
+ if (isDowngrade) {
3828
+ prettyError("Some of the installed @trigger.dev packages are newer than your CLI version");
3829
+ } else {
3830
+ prettyWarning(
3831
+ "Mismatch between your CLI version and installed packages",
3832
+ "We recommend pinned versions for guaranteed compatibility"
3833
+ );
3834
+ }
3759
3835
  if (!process.stdout.isTTY) {
3760
3836
  outro4("Deploy failed");
3761
3837
  console.log(
@@ -3768,13 +3844,24 @@ Latest: ${newCliVersion}`,
3768
3844
  CLI version: ${cliVersion}
3769
3845
 
3770
3846
  Current package versions that don't match the CLI:
3771
- ${versionMismatches.map((dep) => `- ${dep.name}@${dep.version}`).join("\n")}
3847
+ ${mismatches.map((dep) => `- ${dep.name}@${dep.version}`).join("\n")}
3848
+ `
3849
+ );
3850
+ process.exit(1);
3851
+ }
3852
+ if (isDowngrade) {
3853
+ printUpdateTable("Versions", mismatches, cliVersion, "installed", "CLI");
3854
+ outro4("CLI update required!");
3855
+ logger.log(
3856
+ `${chalkError(
3857
+ "X Error:"
3858
+ )} Please update your CLI. Alternatively, use \`--skip-update-check\` at your own risk.
3772
3859
  `
3773
3860
  );
3774
3861
  process.exit(1);
3775
3862
  }
3776
3863
  log4.message("");
3777
- const userWantsToUpdate = await updateConfirmation(versionMismatches, cliVersion);
3864
+ const userWantsToUpdate = await updateConfirmation(mismatches, cliVersion);
3778
3865
  if (isCancel(userWantsToUpdate)) {
3779
3866
  throw new OutroCommandError();
3780
3867
  }
@@ -3804,7 +3891,7 @@ Latest: ${newCliVersion}`,
3804
3891
  );
3805
3892
  };
3806
3893
  process.prependOnceListener("exit", exitHandler);
3807
- mutatePackageJsonWithUpdatedPackages(packageJson, versionMismatches, cliVersion);
3894
+ mutatePackageJsonWithUpdatedPackages(packageJson, mismatches, cliVersion);
3808
3895
  await writeJSONFile(packageJsonPath, packageJson, true);
3809
3896
  async function revertPackageJsonChanges() {
3810
3897
  await writeJSONFile(packageJsonPath, readonlyPackageJson, true);
@@ -3867,17 +3954,17 @@ function mutatePackageJsonWithUpdatedPackages(packageJson, depsToUpdate, targetV
3867
3954
  packageJson[type][name] = targetVersion;
3868
3955
  }
3869
3956
  }
3870
- function printUpdateTable(depsToUpdate, targetVersion) {
3871
- log4.message("Suggested updates");
3957
+ function printUpdateTable(heading, depsToUpdate, targetVersion, oldColumn = "old", newColumn = "new") {
3958
+ log4.message(heading);
3872
3959
  const tableData = depsToUpdate.map((dep) => ({
3873
3960
  package: dep.name,
3874
- old: dep.version,
3875
- new: targetVersion
3961
+ [oldColumn]: dep.version,
3962
+ [newColumn]: targetVersion
3876
3963
  }));
3877
3964
  logger.table(tableData);
3878
3965
  }
3879
3966
  async function updateConfirmation(depsToUpdate, targetVersion) {
3880
- printUpdateTable(depsToUpdate, targetVersion);
3967
+ printUpdateTable("Suggested updates", depsToUpdate, targetVersion);
3881
3968
  let confirmMessage = "Would you like to apply those updates?";
3882
3969
  return await confirm({
3883
3970
  message: confirmMessage
@@ -4215,10 +4302,14 @@ ${authorization.error}`
4215
4302
  await preExitTasks();
4216
4303
  throw new SkipLoggingError(`Deployment failed to complete: ${finishedDeployment}`);
4217
4304
  }
4218
- const deploymentLink = terminalLink2(
4305
+ const deploymentLink = cliLink(
4219
4306
  "View deployment",
4220
4307
  `${authorization.dashboardUrl}/projects/v3/${resolvedConfig.config.project}/deployments/${finishedDeployment.shortCode}`
4221
4308
  );
4309
+ const testLink = cliLink(
4310
+ "Test tasks",
4311
+ `${authorization.dashboardUrl}/projects/v3/${resolvedConfig.config.project}/test?environment=${options.env === "prod" ? "prod" : "stg"}`
4312
+ );
4222
4313
  switch (finishedDeployment.status) {
4223
4314
  case "DEPLOYED": {
4224
4315
  if (warnings.warnings.length > 0) {
@@ -4234,7 +4325,7 @@ ${authorization.error}`
4234
4325
  );
4235
4326
  } else {
4236
4327
  outro5(
4237
- `Version ${version2} deployed with ${taskCount} detected task${taskCount === 1 ? "" : "s"} ${deploymentLink}`
4328
+ `Version ${version2} deployed with ${taskCount} detected task${taskCount === 1 ? "" : "s"} | ${deploymentLink} | ${testLink}`
4238
4329
  );
4239
4330
  }
4240
4331
  break;
@@ -4305,7 +4396,7 @@ function checkLogsForWarnings(logs) {
4305
4396
  const warnings = [
4306
4397
  {
4307
4398
  regex: /prisma:warn We could not find your Prisma schema/,
4308
- message: `Prisma generate failed to find the default schema. Did you include it in config.additionalFiles? ${terminalLink2(
4399
+ message: `Prisma generate failed to find the default schema. Did you include it in config.additionalFiles? ${cliLink(
4309
4400
  "Config docs",
4310
4401
  docs.config.prisma
4311
4402
  )}
@@ -4347,7 +4438,7 @@ function checkLogsForErrors(logs) {
4347
4438
  {
4348
4439
  regex: /Error: Provided --schema at (?<schema>.*) doesn't exist/,
4349
4440
  message: `Prisma generate failed to find the specified schema at "$schema".
4350
- Did you include it in config.additionalFiles? ${terminalLink2(
4441
+ Did you include it in config.additionalFiles? ${cliLink(
4351
4442
  "Config docs",
4352
4443
  docs.config.prisma
4353
4444
  )}`
@@ -4356,11 +4447,11 @@ Did you include it in config.additionalFiles? ${terminalLink2(
4356
4447
  regex: /sh: 1: (?<packageOrBinary>.*): not found/,
4357
4448
  message: `$packageOrBinary not found
4358
4449
 
4359
- If it's a package: Include it in ${terminalLink2(
4450
+ If it's a package: Include it in ${cliLink(
4360
4451
  "config.additionalPackages",
4361
4452
  docs.config.prisma
4362
4453
  )}
4363
- If it's a binary: Please ${terminalLink2(
4454
+ If it's a binary: Please ${cliLink(
4364
4455
  "get in touch",
4365
4456
  getInTouch
4366
4457
  )} and we'll see what we can do!`
@@ -4838,12 +4929,11 @@ async function compileProject(config, options, configPath) {
4838
4929
  const dependencies2 = await resolveRequiredDependencies(allImports, config, javascriptProject);
4839
4930
  logger.debug("gatherRequiredDependencies()", { dependencies: dependencies2 });
4840
4931
  const packageJsonContents = {
4841
- name: "trigger-worker",
4842
- version: "0.0.0",
4843
- description: "",
4932
+ ...javascriptProject.allowedPackageJson,
4844
4933
  dependencies: dependencies2,
4845
4934
  scripts: {
4846
- ...javascriptProject.scripts
4935
+ ...javascriptProject.scripts,
4936
+ ...typeof config.postInstall === "string" ? { postinstall: config.postInstall } : {}
4847
4937
  }
4848
4938
  };
4849
4939
  span.setAttributes({
@@ -4858,7 +4948,7 @@ async function compileProject(config, options, configPath) {
4858
4948
 
4859
4949
  ${copyResult.noMatches.map((glob) => `- "${glob}"`).join("\n")}
4860
4950
 
4861
- If this is unexpected you should check your ${terminalLink2(
4951
+ If this is unexpected you should check your ${cliLink(
4862
4952
  "glob patterns",
4863
4953
  "https://github.com/isaacs/node-glob?tab=readme-ov-file#glob-primer"
4864
4954
  )} are valid.`
@@ -4876,14 +4966,6 @@ If this is unexpected you should check your ${terminalLink2(
4876
4966
  }
4877
4967
  const containerFilePath = join6(cliRootPath(), "Containerfile.prod");
4878
4968
  let containerFileContents = readFileSync2(containerFilePath, "utf-8");
4879
- if (config.postInstall) {
4880
- containerFileContents = containerFileContents.replace(
4881
- "__POST_INSTALL__",
4882
- `RUN ${config.postInstall}`
4883
- );
4884
- } else {
4885
- containerFileContents = containerFileContents.replace("__POST_INSTALL__", "");
4886
- }
4887
4969
  await writeFile2(join6(tempDir, "Containerfile"), containerFileContents);
4888
4970
  const contentHasher = createHash("sha256");
4889
4971
  contentHasher.update(Buffer.from(entryPointOutputFile.text));
@@ -4911,9 +4993,9 @@ async function resolveEnvironmentVariables(config, apiClient2, options) {
4911
4993
  }
4912
4994
  const projectConfig = config.config;
4913
4995
  return await tracer.startActiveSpan("resolveEnvironmentVariables", async (span) => {
4996
+ const $spinner = spinner();
4997
+ $spinner.start("Resolving environment variables");
4914
4998
  try {
4915
- const $spinner = spinner();
4916
- $spinner.start("Resolving environment variables");
4917
4999
  let processEnv = {
4918
5000
  ...process.env
4919
5001
  };
@@ -4957,9 +5039,12 @@ async function resolveEnvironmentVariables(config, apiClient2, options) {
4957
5039
  $spinner.stop("No environment variables to sync");
4958
5040
  return;
4959
5041
  }
5042
+ } else {
5043
+ $spinner.stop("No environment variables to sync");
4960
5044
  }
4961
5045
  $spinner.stop("Environment variables resolved");
4962
5046
  } catch (e) {
5047
+ $spinner.stop("Failed to resolve environment variables");
4963
5048
  recordSpanException5(span, e);
4964
5049
  throw e;
4965
5050
  } finally {
@@ -5316,9 +5401,11 @@ var TaskMetadataParseError = class extends Error {
5316
5401
  }
5317
5402
  };
5318
5403
  var UnexpectedExitError = class extends Error {
5319
- constructor(code) {
5404
+ constructor(code, signal, stderr) {
5320
5405
  super(`Unexpected exit with code ${code}`);
5321
5406
  this.code = code;
5407
+ this.signal = signal;
5408
+ this.stderr = stderr;
5322
5409
  this.name = "UnexpectedExitError";
5323
5410
  }
5324
5411
  };
@@ -5340,6 +5427,32 @@ var SigKillTimeoutProcessError = class extends Error {
5340
5427
  this.name = "SigKillTimeoutProcessError";
5341
5428
  }
5342
5429
  };
5430
+ function getFriendlyErrorMessage(code, signal, stderr, dockerMode = true) {
5431
+ const message = (text3) => {
5432
+ if (signal) {
5433
+ return `[${signal}] ${text3}`;
5434
+ } else {
5435
+ return text3;
5436
+ }
5437
+ };
5438
+ if (code === 137) {
5439
+ if (dockerMode) {
5440
+ return message(
5441
+ "Process ran out of memory! Try choosing a machine preset with more memory for this task."
5442
+ );
5443
+ } else {
5444
+ return message(
5445
+ "Process most likely ran out of memory, but we can't be certain. Try choosing a machine preset with more memory for this task."
5446
+ );
5447
+ }
5448
+ }
5449
+ if (stderr?.includes("OOMErrorHandler")) {
5450
+ return message(
5451
+ "Process ran out of memory! Try choosing a machine preset with more memory for this task."
5452
+ );
5453
+ }
5454
+ return message(`Process exited with code ${code}.`);
5455
+ }
5343
5456
 
5344
5457
  // src/workers/dev/backgroundWorker.ts
5345
5458
  import {
@@ -5355,7 +5468,6 @@ import dotenv from "dotenv";
5355
5468
  import { Evt } from "evt";
5356
5469
  import { fork } from "node:child_process";
5357
5470
  import { dirname as dirname2, resolve as resolve4 } from "node:path";
5358
- import terminalLink3 from "terminal-link";
5359
5471
  var BackgroundWorkerCoordinator = class {
5360
5472
  constructor(baseURL) {
5361
5473
  this.baseURL = baseURL;
@@ -5592,7 +5704,7 @@ var BackgroundWorker = class {
5592
5704
  resolved = true;
5593
5705
  child.kill();
5594
5706
  reject(new Error("Worker timed out"));
5595
- }, 5e3);
5707
+ }, 2e4);
5596
5708
  child.on("message", async (msg) => {
5597
5709
  const message = this._handler.parseMessage(msg);
5598
5710
  if (message.type === "TASKS_READY" && !resolved) {
@@ -5762,7 +5874,7 @@ var BackgroundWorker = class {
5762
5874
  const logsUrl = `${baseURL}/runs/${execution.run.id}`;
5763
5875
  const pipe = chalkGrey("|");
5764
5876
  const bullet = chalkGrey("\u25CB");
5765
- const link = chalkLink(terminalLink3("View logs", logsUrl));
5877
+ const link = chalkLink(cliLink("View logs", logsUrl));
5766
5878
  let timestampPrefix = chalkGrey(prettyPrintDate(payload.execution.attempt.startedAt));
5767
5879
  const workerPrefix = chalkWorker(this.metadata.version);
5768
5880
  const taskPrefix = chalkTask(execution.task.id);
@@ -5839,7 +5951,9 @@ var BackgroundWorker = class {
5839
5951
  retry: void 0,
5840
5952
  error: {
5841
5953
  type: "INTERNAL_ERROR",
5842
- code: TaskRunErrorCodes.TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE
5954
+ code: TaskRunErrorCodes.TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE,
5955
+ message: getFriendlyErrorMessage(e.code, e.signal, e.stderr),
5956
+ stackTrace: e.stderr
5843
5957
  }
5844
5958
  };
5845
5959
  }
@@ -5901,6 +6015,7 @@ var TaskRunProcess = class {
5901
6015
  _currentExecution;
5902
6016
  _isBeingKilled = false;
5903
6017
  _isBeingCancelled = false;
6018
+ _stderr = [];
5904
6019
  /**
5905
6020
  * @deprecated use onTaskRunHeartbeat instead
5906
6021
  */
@@ -6060,7 +6175,13 @@ var TaskRunProcess = class {
6060
6175
  } else if (this._isBeingKilled) {
6061
6176
  rejecter(new CleanupProcessError());
6062
6177
  } else {
6063
- rejecter(new UnexpectedExitError(code ?? -1));
6178
+ rejecter(
6179
+ new UnexpectedExitError(
6180
+ code ?? -1,
6181
+ signal,
6182
+ this._stderr.length ? this._stderr.join("\n") : void 0
6183
+ )
6184
+ );
6064
6185
  }
6065
6186
  }
6066
6187
  }
@@ -6089,9 +6210,14 @@ var TaskRunProcess = class {
6089
6210
  const runId = chalkRun(
6090
6211
  `${this._currentExecution.run.id}.${this._currentExecution.attempt.number}`
6091
6212
  );
6213
+ const errorLine = data.toString();
6092
6214
  logger.log(
6093
- `${chalkError("\u25CB")} ${chalkGrey(prettyPrintDate(/* @__PURE__ */ new Date()))} ${runId} ${data.toString()}`
6215
+ `${chalkError("\u25CB")} ${chalkGrey(prettyPrintDate(/* @__PURE__ */ new Date()))} ${runId} ${errorLine}`
6094
6216
  );
6217
+ if (this._stderr.length > 100) {
6218
+ this._stderr.shift();
6219
+ }
6220
+ this._stderr.push(errorLine);
6095
6221
  }
6096
6222
  #kill() {
6097
6223
  logger.debug(`[${this.runId}] #kill()`, { pid: this.pid });
@@ -6611,12 +6737,18 @@ function useDev({
6611
6737
  throw new Error(backgroundWorkerRecord.error);
6612
6738
  }
6613
6739
  backgroundWorker.metadata = backgroundWorkerRecord.data;
6740
+ backgroundWorker;
6741
+ const testUrl = `${dashboardUrl}/projects/v3/${config.project}/test?environment=dev`;
6742
+ const runsUrl = `${dashboardUrl}/projects/v3/${config.project}/runs?envSlug=dev`;
6743
+ const pipe = chalkGrey("|");
6744
+ const bullet = chalkGrey("\u25CB");
6745
+ const arrow = chalkGrey("->");
6746
+ const testLink = chalkLink(cliLink("Test tasks", testUrl));
6747
+ const runsLink = chalkLink(cliLink("View runs", runsUrl));
6748
+ const workerStarted = chalkGrey("Background worker started");
6749
+ const workerVersion = chalkWorker(backgroundWorkerRecord.data.version);
6614
6750
  logger.log(
6615
- `${chalkGrey(
6616
- `\u25CB Background worker started -> ${chalkWorker(
6617
- backgroundWorkerRecord.data.version
6618
- )}`
6619
- )}`
6751
+ `${bullet} ${workerStarted} ${arrow} ${workerVersion} ${pipe} ${testLink} ${pipe} ${runsLink}`
6620
6752
  );
6621
6753
  firstBuild = false;
6622
6754
  await backgroundWorkerCoordinator.registerWorker(
@@ -6709,13 +6841,18 @@ ${stderr}`);
6709
6841
  logger.error(error);
6710
6842
  });
6711
6843
  return () => {
6712
- logger.debug(`Shutting down dev session for ${config.project}`);
6713
- taskFileWatcher.close();
6714
- websocket?.close();
6715
- backgroundWorkerCoordinator.close();
6716
- ctx?.dispose().catch((error) => {
6717
- console.error(error);
6718
- });
6844
+ const cleanup = async () => {
6845
+ logger.debug(`Shutting down dev session for ${config.project}`);
6846
+ const start = Date.now();
6847
+ await taskFileWatcher.close();
6848
+ websocket?.close();
6849
+ backgroundWorkerCoordinator.close();
6850
+ ctx?.dispose().catch((error) => {
6851
+ console.error(error);
6852
+ });
6853
+ logger.debug(`Shutdown completed in ${Date.now() - start}ms`);
6854
+ };
6855
+ cleanup();
6719
6856
  };
6720
6857
  }, [config, apiUrl, apiKey, environmentClient]);
6721
6858
  }
@@ -6857,11 +6994,10 @@ import { context as context3, trace as trace3 } from "@opentelemetry/api";
6857
6994
  import { flattenAttributes as flattenAttributes4 } from "@trigger.dev/core/v3";
6858
6995
  import { recordSpanException as recordSpanException6 } from "@trigger.dev/core/v3/workers";
6859
6996
  import chalk5 from "chalk";
6860
- import { execa as execa3 } from "execa";
6997
+ import { ExecaError as ExecaError2, execa as execa3 } from "execa";
6861
6998
  import { applyEdits, modify, findNodeAtLocation, parseTree, getNodeValue } from "jsonc-parser";
6862
6999
  import { writeFile as writeFile3 } from "node:fs/promises";
6863
7000
  import { join as join8, relative as relative4, resolve as resolve5 } from "node:path";
6864
- import terminalLink4 from "terminal-link";
6865
7001
  import { z as z6 } from "zod";
6866
7002
 
6867
7003
  // src/utilities/createFileFromTemplate.ts
@@ -6910,7 +7046,8 @@ var InitCommandOptions = CommonCommandOptions.extend({
6910
7046
  projectRef: z6.string().optional(),
6911
7047
  overrideConfig: z6.boolean().default(false),
6912
7048
  tag: z6.string().default("beta"),
6913
- skipPackageInstall: z6.boolean().default(false)
7049
+ skipPackageInstall: z6.boolean().default(false),
7050
+ pkgArgs: z6.string().optional()
6914
7051
  });
6915
7052
  function configureInitCommand(program2) {
6916
7053
  return commonOptions(
@@ -6921,7 +7058,10 @@ function configureInitCommand(program2) {
6921
7058
  "-t, --tag <package tag>",
6922
7059
  "The version of the @trigger.dev/sdk package to install",
6923
7060
  version
6924
- ).option("--skip-package-install", "Skip installing the @trigger.dev/sdk package").option("--override-config", "Override the existing config file if it exists")
7061
+ ).option("--skip-package-install", "Skip installing the @trigger.dev/sdk package").option("--override-config", "Override the existing config file if it exists").option(
7062
+ "--pkg-args <args>",
7063
+ "Additional arguments to pass to the package manager, accepts CSV for multiple args"
7064
+ )
6925
7065
  ).action(async (path7, options) => {
6926
7066
  await handleTelemetry(async () => {
6927
7067
  await printStandloneInitialBanner(true);
@@ -6937,6 +7077,7 @@ async function initCommand(dir, options) {
6937
7077
  async function _initCommand(dir, options) {
6938
7078
  const span = trace3.getSpan(context3.active());
6939
7079
  intro5("Initializing project");
7080
+ await detectTsConfig(dir, options);
6940
7081
  const authorization = await login({
6941
7082
  embedded: true,
6942
7083
  defaultApiUrl: options.apiUrl,
@@ -6987,7 +7128,7 @@ async function _initCommand(dir, options) {
6987
7128
  await writeConfigFile(dir, selectedProject, options, triggerDir);
6988
7129
  await addConfigFileToTsConfig(dir, options);
6989
7130
  await gitIgnoreDotTriggerDir(dir, options);
6990
- const projectDashboard = terminalLink4(
7131
+ const projectDashboard = cliLink(
6991
7132
  "project dashboard",
6992
7133
  `${authorization.dashboardUrl}/projects/v3/${selectedProject.externalRef}`
6993
7134
  );
@@ -7000,13 +7141,10 @@ async function _initCommand(dir, options) {
7000
7141
  );
7001
7142
  log6.info(` 2. Visit your ${projectDashboard} to view your newly created tasks.`);
7002
7143
  log6.info(
7003
- ` 3. Head over to our ${terminalLink4(
7004
- "v3 docs",
7005
- "https://trigger.dev/docs/v3"
7006
- )} to learn more.`
7144
+ ` 3. Head over to our ${cliLink("v3 docs", "https://trigger.dev/docs/v3")} to learn more.`
7007
7145
  );
7008
7146
  log6.info(
7009
- ` 4. Need help? Join our ${terminalLink4(
7147
+ ` 4. Need help? Join our ${cliLink(
7010
7148
  "Discord community",
7011
7149
  "https://trigger.dev/discord"
7012
7150
  )} or email us at ${chalk5.cyan("help@trigger.dev")}`
@@ -7111,8 +7249,39 @@ async function gitIgnoreDotTriggerDir(dir, options) {
7111
7249
  }
7112
7250
  });
7113
7251
  }
7252
+ async function detectTsConfig(dir, options) {
7253
+ return await tracer.startActiveSpan("detectTsConfig", async (span) => {
7254
+ try {
7255
+ const projectDir = resolve5(process.cwd(), dir);
7256
+ const tsconfigPath = join8(projectDir, "tsconfig.json");
7257
+ span.setAttributes({
7258
+ "cli.projectDir": projectDir,
7259
+ "cli.tsconfigPath": tsconfigPath
7260
+ });
7261
+ const tsconfigExists = await pathExists(tsconfigPath);
7262
+ if (!tsconfigExists) {
7263
+ prettyError(
7264
+ "No tsconfig.json found",
7265
+ `The init command needs to be run in a TypeScript project. You can create one like this:`,
7266
+ `npm install typescript --save-dev
7267
+ npx tsc --init
7268
+ `
7269
+ );
7270
+ throw new Error("TypeScript required");
7271
+ }
7272
+ logger.debug("tsconfig.json exists", { tsconfigPath });
7273
+ span.end();
7274
+ } catch (e) {
7275
+ if (!(e instanceof SkipCommandError)) {
7276
+ recordSpanException6(span, e);
7277
+ }
7278
+ span.end();
7279
+ throw e;
7280
+ }
7281
+ });
7282
+ }
7114
7283
  async function addConfigFileToTsConfig(dir, options) {
7115
- return await tracer.startActiveSpan("createTriggerDir", async (span) => {
7284
+ return await tracer.startActiveSpan("addConfigFileToTsConfig", async (span) => {
7116
7285
  try {
7117
7286
  const projectDir = resolve5(process.cwd(), dir);
7118
7287
  const tsconfigPath = join8(projectDir, "tsconfig.json");
@@ -7163,49 +7332,58 @@ async function addConfigFileToTsConfig(dir, options) {
7163
7332
  async function installPackages2(dir, options) {
7164
7333
  return await tracer.startActiveSpan("installPackages", async (span) => {
7165
7334
  const installSpinner = spinner();
7335
+ let pkgManager;
7166
7336
  try {
7167
7337
  const projectDir = resolve5(process.cwd(), dir);
7168
- const pkgManager = await getUserPackageManager(projectDir);
7338
+ pkgManager = await getUserPackageManager(projectDir);
7169
7339
  span.setAttributes({
7170
7340
  "cli.projectDir": projectDir,
7171
7341
  "cli.packageManager": pkgManager,
7172
7342
  "cli.tag": options.tag
7173
7343
  });
7344
+ const userArgs = options.pkgArgs?.split(",") ?? [];
7345
+ const execaOptions = { cwd: projectDir };
7346
+ let installProcess;
7347
+ let args;
7174
7348
  switch (pkgManager) {
7175
7349
  case "npm": {
7176
- installSpinner.start(`Running npm install @trigger.dev/sdk@${options.tag}`);
7177
- await execa3("npm", ["install", "--save-exact", `@trigger.dev/sdk@${options.tag}`], {
7178
- cwd: projectDir,
7179
- stdio: options.logLevel === "debug" ? "inherit" : "ignore"
7180
- });
7181
- break;
7182
- }
7183
- case "pnpm": {
7184
- installSpinner.start(`Running pnpm add @trigger.dev/sdk@${options.tag}`);
7185
- await execa3("pnpm", ["add", `@trigger.dev/sdk@${options.tag}`], {
7186
- cwd: projectDir,
7187
- stdio: options.logLevel === "debug" ? "inherit" : "ignore"
7188
- });
7350
+ args = ["install", "--save-exact", ...userArgs, `@trigger.dev/sdk@${options.tag}`];
7189
7351
  break;
7190
7352
  }
7353
+ case "pnpm":
7191
7354
  case "yarn": {
7192
- installSpinner.start(`Running yarn add @trigger.dev/sdk@${options.tag}`);
7193
- await execa3("yarn", ["add", `@trigger.dev/sdk@${options.tag}`], {
7194
- cwd: projectDir,
7195
- stdio: options.logLevel === "debug" ? "inherit" : "ignore"
7196
- });
7355
+ args = ["add", ...userArgs, `@trigger.dev/sdk@${options.tag}`];
7197
7356
  break;
7198
7357
  }
7199
7358
  }
7359
+ installSpinner.start(`Running ${pkgManager} ${args.join(" ")}`);
7360
+ installProcess = execa3(pkgManager, args, execaOptions);
7361
+ const handleProcessOutput = (data) => {
7362
+ logger.debug(data.toString());
7363
+ };
7364
+ installProcess.stderr?.on("data", handleProcessOutput);
7365
+ installProcess.stdout?.on("data", handleProcessOutput);
7366
+ await installProcess;
7200
7367
  installSpinner.stop(`@trigger.dev/sdk@${options.tag} installed`);
7201
7368
  span.end();
7202
7369
  } catch (e) {
7203
- installSpinner.stop(
7204
- `Failed to install @trigger.dev/sdk@${options.tag}. Rerun command with --log-level debug for more details.`
7205
- );
7370
+ if (options.logLevel === "debug") {
7371
+ installSpinner.stop(`Failed to install @trigger.dev/sdk@${options.tag}.`);
7372
+ } else {
7373
+ installSpinner.stop(
7374
+ `Failed to install @trigger.dev/sdk@${options.tag}. Rerun command with --log-level debug for more details.`
7375
+ );
7376
+ }
7206
7377
  if (!(e instanceof SkipCommandError)) {
7207
7378
  recordSpanException6(span, e);
7208
7379
  }
7380
+ if (e instanceof ExecaError2) {
7381
+ if (pkgManager) {
7382
+ e.message += `
7383
+
7384
+ Note: You can pass additional args to ${pkgManager} by using --pkg-args. For example: trigger.dev init --pkg-args="--workspace-root"`;
7385
+ }
7386
+ }
7209
7387
  span.end();
7210
7388
  throw e;
7211
7389
  }
@@ -7274,7 +7452,7 @@ async function selectProject(apiClient2, dashboardUrl, projectRef) {
7274
7452
  throw new Error(`Failed to get projects: ${projectsResponse.error}`);
7275
7453
  }
7276
7454
  if (projectsResponse.data.length === 0) {
7277
- const newProjectLink = terminalLink4(
7455
+ const newProjectLink = cliLink(
7278
7456
  "Create new project",
7279
7457
  `${dashboardUrl}/projects/new?version=v3`
7280
7458
  );