Repository navigation
feat(cli,browser): maple sourcemaps inject/upload and exception debug ids #3021
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
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
c88a4d0
feat(cli,browser): maple sourcemaps inject/upload and exception debug…
Makisuo 02ba106
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo c5308ec
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo a849fcb
fix(cli): debug ids over JS and map, register before app code, safe m…
Makisuo 23d1fbc
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo f4ccee3
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo 8fec0c0
fix(cli): skip source maps over 10 MiB, the server's new upload cap
Makisuo 9b4c553
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo a43066e
fix(cli): skip index source maps at upload, which the server now refuses
Makisuo 9a7fd5b
perf(browser): count registered debug ids before building entries
Makisuo 05c3ef4
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo 6f5b351
fix(cli): read a file's directive prologue without a backtracking pat…
Makisuo 0e3dc5c
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo dfc6b6a
fix(cli): write the map before the JS, move it once, take the size ca…
Makisuo 2b01817
test(cli): use effect String helpers in the inject failure test
Makisuo cb8f47f
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo 9641f9b
test(cli): run command-level tests in the CLI test task
Makisuo 50a4656
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo ab4dcfb
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo 92c77d9
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo 55d6ad6
Merge branch 'sourcemaps/backend' into sourcemaps/cli-sdk
Makisuo 8e3e728
feat(web): source-mapped stack trace on the error issue page (#3022)
Makisuo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@maple-dev/alchemy": minor | ||
| --- | ||
|
|
||
| Automatic source map uploads. `@maple-dev/alchemy/vite` exports `mapleSourceMaps()`, a Vite plugin that turns on hidden source maps, gives each built JS file a debug id and moves the maps out of the deployed output into `.maple/sourcemaps/<outDir>` with a manifest. The new `Maple.SourceMaps` resource uploads them through `POST /v2/source_maps` after the build, again only when the maps changed; deleting it keeps the uploaded maps, which earlier releases still need. `matchBy: "release"` uploads without debug ids, for telemetry that reports none. `MapleApiContract` gains `upload` for raw request bodies. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@maple-dev/browser": minor | ||
| --- | ||
|
|
||
| Exception events now carry `maple.exception.debug_ids`: for each script in the error's stack that registered a debug id (through `maple sourcemaps inject`, or Sentry's debug id tooling), its URL and id, so the matching source map is found by id rather than by file path. Absent when no script in the stack has one. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@maple/cli": minor | ||
| --- | ||
|
|
||
| New `maple sourcemaps inject <dir>` and `maple sourcemaps upload <dir>`. `inject` gives every built JS file that has a source map a debug id (derived from the file and its map, so re-running changes nothing), registers it on the file's first line so errors thrown while the file loads still carry it, and writes it into the map; `--dry-run` reports without writing. Maps outside the build directory are never touched. `upload` sends each map to the logged-in workspace, once per JS file that uses it, matched by debug id or by `--service`, `--release` (defaults to the build directory's git commit) and the file path, with `--url-prefix` for the path the files are served under. Maps over 10 MiB (the largest Maple can symbolicate with) and index maps (`sections`) are skipped with a warning, and a run that uploads nothing fails. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import { afterEach, beforeEach, describe, expect, test } from "bun:test" | ||
| import * as BunServices from "@effect/platform-bun/BunServices" | ||
| import { Effect, Option, String as Str } from "effect" | ||
| import { execFileSync } from "node:child_process" | ||
| import { mkdtempSync, rmSync, writeFileSync } from "node:fs" | ||
| import { tmpdir } from "node:os" | ||
| import { join } from "node:path" | ||
| import { SourceMapUploadError } from "../core/sourcemaps-upload" | ||
| import { checkUploadOutcomes, gitHead } from "./sourcemaps" | ||
|
|
||
| let dir = "" | ||
| beforeEach(() => { | ||
| dir = mkdtempSync(join(tmpdir(), "maple-sourcemaps-cmd-")) | ||
| }) | ||
| afterEach(() => rmSync(dir, { recursive: true, force: true })) | ||
|
|
||
| const git = (...args: ReadonlyArray<string>) => | ||
| Str.trim(execFileSync("git", [...args], { cwd: dir, encoding: "utf8" })) | ||
|
|
||
| describe("gitHead", () => { | ||
| test("reads the commit of the build directory's checkout, not the shell's", async () => { | ||
| git("init", "-q") | ||
| writeFileSync(join(dir, "a.txt"), "a") | ||
| git("add", "a.txt") | ||
| git("-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "-m", "init") | ||
| const buildHead = git("rev-parse", "HEAD") | ||
| const shellHead = Str.trim(execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" })) | ||
|
|
||
| const head = await Effect.runPromise(Effect.provide(gitHead(dir), BunServices.layer)) | ||
|
|
||
| expect(Option.getOrNull(head)).toBe(buildHead) | ||
| expect(buildHead).not.toBe(shellHead) | ||
| }) | ||
|
|
||
| test("is none outside a git work tree", async () => { | ||
| const head = await Effect.runPromise(Effect.provide(gitHead(dir), BunServices.layer)) | ||
| expect(Option.isNone(head)).toBe(true) | ||
| }) | ||
| }) | ||
|
|
||
| describe("checkUploadOutcomes", () => { | ||
| const skipped = { _tag: "skipped", minifiedPath: "a.js", reason: "no debug id" } as const | ||
| const uploaded = { | ||
| _tag: "uploaded", | ||
| minifiedPath: "b.js", | ||
| debugId: Option.none(), | ||
| sizeBytes: 1, | ||
| id: Option.none(), | ||
| } as const | ||
|
|
||
| test("fails when every map was skipped, so CI does not go on without maps", async () => { | ||
| const error = await Effect.runPromise(Effect.flip(checkUploadOutcomes("dist", [skipped, skipped]))) | ||
| expect(error._tag).toBe("@maple/cli/UsageError") | ||
| expect(error.message).toBe("no source maps were uploaded; every matching map was skipped") | ||
| }) | ||
|
|
||
| test("passes when at least one map went up, and reports a failed one", async () => { | ||
| await Effect.runPromise(checkUploadOutcomes("dist", [skipped, uploaded])) | ||
| const failed = { | ||
| _tag: "failed", | ||
| minifiedPath: "c.js", | ||
| error: new SourceMapUploadError({ message: "HTTP 400: bad", minifiedPath: "c.js", status: 400 }), | ||
| } as const | ||
| const error = await Effect.runPromise(Effect.flip(checkUploadOutcomes("dist", [uploaded, failed]))) | ||
| expect(error._tag).not.toBe("@maple/cli/UsageError") | ||
| }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| import * as Argument from "effect/cli/Argument" | ||
| import * as Command from "effect/cli/Command" | ||
| import * as Flag from "effect/cli/Flag" | ||
| import { Array as Arr, Console, Effect, Option, Redacted, Stream, String as Str } from "effect" | ||
| import * as ChildProcess from "effect/process/ChildProcess" | ||
| import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner" | ||
| import { MapleConfig } from "../core/config" | ||
| import { injectDirectory, type InjectResult } from "../core/sourcemaps" | ||
| import { uploadDirectory, type UploadOutcome } from "../core/sourcemaps-upload" | ||
| import { ApiResponseError, ApiTransportError } from "./api" | ||
| import { CliUsageError } from "../lib/errors" | ||
|
|
||
| const dirArg = Argument.Directory("dir", { mustExist: true }).pipe( | ||
| Argument.withDescription("Build output directory, e.g. dist"), | ||
| ) | ||
|
|
||
| const inject = Command.make("inject", { | ||
| dir: dirArg, | ||
| dryRun: Flag.Boolean("dry-run").pipe( | ||
| Flag.withDescription("Report what would change without writing any file"), | ||
| Flag.withDefault(false), | ||
| ), | ||
| }).pipe( | ||
| Command.withDescription( | ||
| "Add a debug id to every built JS file that has a source map, and to its map. Run after the build, before deploying and uploading; re-running changes nothing", | ||
| ), | ||
| Command.withHandler(({ dir, dryRun }) => | ||
| Effect.gen(function* () { | ||
| const results = yield* injectDirectory(dir, { dryRun }) | ||
| const verb = dryRun ? "would inject" : "injected" | ||
| const mapOf = (r: InjectResult) => Option.getOrElse(r.mapPath, () => "") | ||
| yield* Effect.forEach(results, (r) => { | ||
| switch (r.status) { | ||
| case "invalid_map": | ||
| return Console.error( | ||
| `warning: skipped ${r.file}: its source map ${mapOf(r)} is not a version 3 JSON object`, | ||
| ) | ||
| case "unsafe_map": | ||
| return Console.error( | ||
| `warning: skipped ${r.file}: its source map ${mapOf(r)} is outside ${dir}`, | ||
| ) | ||
| case "injected": | ||
| return Console.log(`${verb} ${r.file} (${Option.getOrElse(r.debugId, () => "")})`) | ||
| default: | ||
| return Effect.void | ||
| } | ||
| }) | ||
| const count = (status: string) => Arr.filter(results, (r) => r.status === status).length | ||
| yield* Console.log( | ||
| `${dryRun ? "Would inject" : "Injected"} ${count("injected")} file(s); skipped ${count("already_injected")} already injected, ${count("no_map")} without a source map` + | ||
| (count("invalid_map") > 0 ? `, ${count("invalid_map")} with an unreadable map` : "") + | ||
| (count("unsafe_map") > 0 ? `, ${count("unsafe_map")} with a map outside ${dir}` : ""), | ||
| ) | ||
| }), | ||
| ), | ||
| ) | ||
|
|
||
| /** The commit checked out where `dir` is, when it is inside a git work tree. */ | ||
| export const gitHead = (dir: string) => | ||
| Effect.gen(function* () { | ||
| const spawner = yield* ChildProcessSpawner | ||
| const handle = yield* spawner.spawn( | ||
| ChildProcess.make("git", ["rev-parse", "HEAD"], { | ||
| cwd: dir, | ||
| stdin: "ignore", | ||
| stdout: "pipe", | ||
| stderr: "ignore", | ||
| }), | ||
| ) | ||
| const [exitCode, stdout] = yield* Effect.all( | ||
| [handle.exitCode, Stream.mkString(Stream.decodeText(handle.stdout))], | ||
| { concurrency: "unbounded" }, | ||
| ) | ||
| const sha = Str.trim(stdout) | ||
| return exitCode === 0 && /^[0-9a-f]{40,64}$/.test(sha) ? Option.some(sha) : Option.none<string>() | ||
| }).pipe( | ||
| Effect.scoped, | ||
| Effect.orElseSucceed(() => Option.none<string>()), | ||
| ) | ||
|
|
||
| const remoteTarget = Effect.gen(function* () { | ||
| const config = yield* MapleConfig | ||
| const target = Option.all({ apiUrl: config.apiUrl, token: config.token }) | ||
| if (Option.isNone(target)) | ||
| return yield* new CliUsageError({ | ||
| message: "not logged in to a Maple workspace", | ||
| hint: "run `maple login`, or set MAPLE_API_URL and MAPLE_API_TOKEN", | ||
| }) | ||
| return { apiUrl: target.value.apiUrl, token: Redacted.value(target.value.token) } | ||
| }) | ||
|
|
||
| const formatBytes = (n: number): string => | ||
| n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MiB` : `${(n / 1024).toFixed(1)} KiB` | ||
|
|
||
| const reportOutcome = (outcome: UploadOutcome): Effect.Effect<void> => { | ||
| switch (outcome._tag) { | ||
| case "uploaded": | ||
| return Console.log( | ||
| `uploaded ${outcome.minifiedPath} (${formatBytes(outcome.sizeBytes)}${Option.match(outcome.debugId, { onNone: () => "", onSome: (id) => `, ${id}` })})`, | ||
| ) | ||
| case "skipped": | ||
| return Console.error(`warning: skipped ${outcome.minifiedPath}: ${outcome.reason}`) | ||
| case "failed": | ||
| return Console.error(`failed ${outcome.minifiedPath}: ${outcome.error.message}`) | ||
| } | ||
| } | ||
|
|
||
| /** Fails the command when nothing was uploaded or an upload failed, so CI stops there. */ | ||
| export const checkUploadOutcomes = ( | ||
| dir: string, | ||
| outcomes: ReadonlyArray<UploadOutcome>, | ||
| ): Effect.Effect<void, CliUsageError | ApiResponseError | ApiTransportError> => | ||
| Effect.gen(function* () { | ||
| const count = (tag: UploadOutcome["_tag"]) => Arr.filter(outcomes, (o) => o._tag === tag).length | ||
| if (outcomes.length === 0) | ||
| return yield* new CliUsageError({ | ||
| message: `no source maps with a matching JS file found under ${dir}`, | ||
| hint: "build with source maps enabled, then run `maple sourcemaps inject` on the output", | ||
| }) | ||
| if (count("skipped") === outcomes.length) | ||
| return yield* new CliUsageError({ | ||
| message: "no source maps were uploaded; every matching map was skipped", | ||
| hint: "check the skip warnings above", | ||
| }) | ||
| const firstFailure = Arr.findFirst(outcomes, (o) => o._tag === "failed") | ||
| if (Option.isSome(firstFailure) && firstFailure.value._tag === "failed") { | ||
| // Reported as the raw API errors so a 4xx reads as the request to fix, not a CLI fault. | ||
| const failed = firstFailure.value.error | ||
| const message = `${count("failed")} source map upload(s) failed; first: ${failed.minifiedPath}: ${failed.message}` | ||
| if (failed.status === undefined) return yield* new ApiTransportError({ message }) | ||
| return yield* failed.status === 401 | ||
| ? new ApiResponseError({ status: 401, message, hint: "run `maple login` again" }) | ||
| : new ApiResponseError({ status: failed.status, message }) | ||
| } | ||
| }) | ||
|
|
||
| const upload = Command.make("upload", { | ||
| dir: dirArg, | ||
| service: Flag.optional( | ||
| Flag.String("service").pipe( | ||
| Flag.withDescription("Service name the maps belong to (OTel service.name)"), | ||
| ), | ||
| ), | ||
| release: Flag.optional( | ||
| Flag.String("release").pipe( | ||
| Flag.withDescription( | ||
| "Release the maps belong to (OTel service.version); defaults to `git rev-parse HEAD` when --service is set", | ||
| ), | ||
| ), | ||
| ), | ||
| urlPrefix: Flag.optional( | ||
| Flag.String("url-prefix").pipe( | ||
| Flag.withDescription( | ||
| "Path the files are served under, prepended to each file path, e.g. assets/", | ||
| ), | ||
| ), | ||
| ), | ||
| }).pipe( | ||
| Command.withDescription( | ||
| "Upload every source map in a build directory to the logged-in workspace so error stack traces show original source", | ||
| ), | ||
| Command.withHandler(({ dir, service, release, urlPrefix }) => | ||
| Effect.gen(function* () { | ||
| const { apiUrl, token } = yield* remoteTarget | ||
| const version = Option.isSome(release) || Option.isNone(service) ? release : yield* gitHead(dir) | ||
| const outcomes = yield* uploadDirectory( | ||
| dir, | ||
| { apiUrl, token, service, version, urlPrefix, concurrency: 4 }, | ||
| reportOutcome, | ||
| ) | ||
| const count = (tag: UploadOutcome["_tag"]) => Arr.filter(outcomes, (o) => o._tag === tag).length | ||
| const bytes = Arr.reduce(outcomes, 0, (sum, o) => | ||
| o._tag === "uploaded" ? sum + o.sizeBytes : sum, | ||
| ) | ||
| yield* Console.log( | ||
| `Uploaded ${count("uploaded")} source map(s) (${formatBytes(bytes)}); ${count("skipped")} skipped, ${count("failed")} failed`, | ||
| ) | ||
| return yield* checkUploadOutcomes(dir, outcomes) | ||
| }), | ||
| ), | ||
| ) | ||
|
|
||
| export const sourcemaps = Command.make("sourcemaps").pipe( | ||
| Command.withDescription("Prepare and upload JavaScript source maps for readable error stack traces"), | ||
| Command.withSubcommands([inject, upload]), | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.