Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cli): adopt bundler-emitted debug ids as chunk ids in event release mode (#85307)

Aleksander Błaszkiewicz7dd3d0f5c27b
diff --git a/cli/.sampo/changesets/cli-event-mode-debug-id-adoption.md b/cli/.sampo/changesets/cli-event-mode-debug-id-adoption.md
new file mode 100644
index 000000000000..328bcfbff943
--- /dev/null
+++ b/cli/.sampo/changesets/cli-event-mode-debug-id-adoption.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: minor
+---
+
+With `--release-mode=event`, `sourcemap inject` now adopts a bundler-emitted ECMA-426 debug id (`//# debugId=` comment or the sourcemap's `debugId` field) as the chunk id instead of deriving its own, so one id identifies the chunk across the toolchain. The sourcemap's `debugId` field is preserved on save instead of being renamed to `chunk_id`, a bundler-stamped debug id no longer makes inject skip the mapping adjustment for the injected snippet, and hermes uploads still accept maps that carry only a `debugId`. Behavior change: `sourcemap upload --hermes` now fails with an error when it finds no maps carrying a chunk id or debug id, instead of exiting successfully having uploaded nothing.
diff --git a/cli/src/sourcemaps/content.rs b/cli/src/sourcemaps/content.rs
index 04b5f729b362..deff57ad35da 100644
--- a/cli/src/sourcemaps/content.rs
+++ b/cli/src/sourcemaps/content.rs
@@ -80,8 +80,13 @@ pub fn get_injected_release_id(source: &str, chunk_id: &str) -> Option<String> {
pub struct SourceMapContent {
#[serde(skip_serializing_if = "Option::is_none")]
pub release_id: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none", alias = "debugId")]
+ #[serde(skip_serializing_if = "Option::is_none")]
pub chunk_id: Option<String>,
+ /// Bundler-emitted ECMA-426 debug id. Kept separate from `chunk_id` so a bundler-stamped
+ /// map isn't mistaken for one we already processed (which would skip the mapping
+ /// adjustment on inject). Preserved on save for interop.
+ #[serde(rename = "debugId", skip_serializing_if = "Option::is_none")]
+ pub debug_id: Option<String>,
#[serde(flatten)]
pub fields: BTreeMap<String, Value>,
}
@@ -151,6 +156,16 @@ impl SourceMapFile {
self.inner.content.chunk_id.clone()
}
+ pub fn get_debug_id(&self) -> Option<String> {
+ self.inner.content.debug_id.clone()
+ }
+
+ /// The id this map's symbol set uploads under: our stamped chunk id when present, else a
+ /// bundler-emitted debug id. Hermes maps built with Expo's tooling carry only the latter.
+ pub fn get_upload_chunk_id(&self) -> Option<String> {
+ self.get_chunk_id().or_else(|| self.get_debug_id())
+ }
+
pub fn get_release_id(&self) -> Option<String> {
self.inner.content.release_id.clone()
}
@@ -200,6 +215,7 @@ impl SourceMapFile {
let mut old_content = std::mem::replace(&mut self.inner.content, new_content);
self.inner.content.chunk_id = old_content.chunk_id.take();
self.inner.content.release_id = old_content.release_id.take();
+ self.inner.content.debug_id = old_content.debug_id.take();
// Preserve extension fields (e.g. x_org_dartlang_dart2js for Flutter/Dart minified name mapping)
// Skip "sections" since that's specific to index sourcemaps which we flatten above
for (key, value) in old_content.fields {
@@ -240,6 +256,11 @@ impl MinifiedSourceFile {
self.get_comment_value(&patterns)
}
+ pub fn get_debug_id(&self) -> Option<String> {
+ let patterns = ["//# debugId="];
+ self.get_comment_value(&patterns)
+ }
+
pub fn set_chunk_id(&mut self, chunk_id: &str, release_id: Option<&str>) -> Result<SourceMap> {
let (new_source_content, source_adjustment) = {
// Update source content with chunk ID
@@ -510,7 +531,10 @@ fn trailing_sourcemap_reference_range(content: &str) -> Option<std::ops::Range<u
for (line_start, line_end, line) in lines.into_iter().rev() {
let trimmed_line = line.trim();
- if trimmed_line.is_empty() || trimmed_line.starts_with("//# chunkId=") {
+ if trimmed_line.is_empty()
+ || trimmed_line.starts_with("//# chunkId=")
+ || trimmed_line.starts_with("//# debugId=")
+ {
continue;
}
if trimmed_line.starts_with("//# sourceMappingURL=")
@@ -529,7 +553,7 @@ impl TryInto<SymbolSetUpload> for SourceMapFile {
fn try_into(self) -> Result<SymbolSetUpload> {
let chunk_id = self
- .get_chunk_id()
+ .get_upload_chunk_id()
.ok_or_else(|| anyhow!("Chunk ID not found"))?;
let release_id = self.get_release_id();
@@ -727,6 +751,47 @@ mod tests {
assert!(!sm.is_empty());
}
+ #[test]
+ fn debug_id_is_not_conflated_with_chunk_id_and_round_trips() {
+ let sm = content_from(json!({
+ "version": 3,
+ "mappings": "AAAA",
+ "sources": ["a.ts"],
+ "names": [],
+ "debugId": "11111111-2222-4333-8444-555555555555",
+ }));
+
+ assert_eq!(
+ sm.debug_id.as_deref(),
+ Some("11111111-2222-4333-8444-555555555555")
+ );
+ assert!(sm.chunk_id.is_none());
+
+ let out = serde_json::to_value(&sm).expect("Failed to serialize");
+ assert_eq!(out["debugId"], "11111111-2222-4333-8444-555555555555");
+ assert!(out.get("chunk_id").is_none());
+ }
+
+ #[test]
+ fn hermes_upload_accepts_map_with_only_debug_id() {
+ let file = SourceMapFile {
+ inner: SourceFile::new(
+ PathBuf::from("bundle.js.map"),
+ content_from(json!({
+ "version": 3,
+ "mappings": "AAAA",
+ "sources": ["a.ts"],
+ "names": [],
+ "debugId": "11111111-2222-4333-8444-555555555555",
+ "x_hermes_function_offsets": {},
+ })),
+ ),
+ };
+
+ let upload: SymbolSetUpload = file.try_into().expect("Failed to convert to upload");
+ assert_eq!(upload.chunk_id, "11111111-2222-4333-8444-555555555555");
+ }
+
#[test]
fn remove_sourcemap_reference_strips_standard_comment() {
let mut source = minified_source("console.log(1);\n//# sourceMappingURL=chunk.js.map\n");
@@ -851,6 +916,18 @@ mod tests {
assert_eq!(source.inner.content, "console.log(1);\n\n//# chunkId=00000");
}
+ #[test]
+ fn remove_sourcemap_reference_strips_comment_with_trailing_debug_id() {
+ // sentry-cli appends its `//# debugId=` comment after the sourceMappingURL line, and
+ // `--delete-after` must still find and strip the reference behind it.
+ let mut source = minified_source(
+ "console.log(1);\n//# sourceMappingURL=chunk.js.map\n//# debugId=00000",
+ );
+
+ assert!(source.remove_sourcemap_reference());
+ assert_eq!(source.inner.content, "console.log(1);\n//# debugId=00000");
+ }
+
#[test]
fn remove_sourcemap_reference_leaves_non_trailing_comment() {
let original = "console.log(1);\n//# sourceMappingURL=chunk.js.map\nconsole.log(2);\n";
diff --git a/cli/src/sourcemaps/hermes/clone.rs b/cli/src/sourcemaps/hermes/clone.rs
index c717630da9b8..5db648155680 100644
--- a/cli/src/sourcemaps/hermes/clone.rs
+++ b/cli/src/sourcemaps/hermes/clone.rs
@@ -63,14 +63,7 @@ pub fn clone(args: &CloneArgs) -> Result<()> {
minified_map.save()?;
}
- // Copy metadata from source map to composed map
- if let Some(chunk_id) = minified_map.get_chunk_id() {
- composed_map.set_chunk_id(Some(chunk_id));
- }
-
- if let Some(release_id) = minified_map.get_release_id() {
- composed_map.set_release_id(Some(release_id));
- }
+ clone_metadata(&minified_map, &mut composed_map);
composed_map.save()?;
info!(
@@ -81,3 +74,67 @@ pub fn clone(args: &CloneArgs) -> Result<()> {
info!("Finished cloning metadata");
Ok(())
}
+
+/// Carry the chunk identity and release from the packager map into the hermes-composed map.
+/// Expo stamps only a `debugId` on the packager map, so the id must come from the upload
+/// fallback — reading the stamped chunk id alone leaves the composed map id-less and the
+/// upload silently empty.
+pub fn clone_metadata(minified_map: &SourceMapFile, composed_map: &mut SourceMapFile) {
+ if let Some(chunk_id) = minified_map.get_upload_chunk_id() {
+ composed_map.set_chunk_id(Some(chunk_id));
+ }
+
+ if let Some(release_id) = minified_map.get_release_id() {
+ composed_map.set_release_id(Some(release_id));
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::clone_metadata;
+ use crate::sourcemaps::content::SourceMapFile;
+ use crate::utils::files::SourceFile;
+ use std::path::PathBuf;
+
+ fn map_from(json: serde_json::Value) -> SourceMapFile {
+ SourceMapFile {
+ inner: SourceFile::new(
+ PathBuf::from("main.jsbundle.map"),
+ serde_json::from_value(json).unwrap(),
+ ),
+ }
+ }
+
+ #[test]
+ fn clone_carries_a_debug_id_only_packager_map_into_the_composed_map() {
+ // The Expo metro plugin stamps only `debugId` on the packager map. Clone must land
+ // that id on the composed map, or `hermes upload` finds no id and uploads nothing
+ // while the build stays green.
+ let minified = map_from(serde_json::json!({
+ "version": 3,
+ "mappings": "AAAA",
+ "sources": ["App.js"],
+ "names": [],
+ "debugId": "c96bfa94-ca84-4f98-8d5e-f15adba692ca",
+ "release_id": "11111111-2222-4333-8444-555555555555",
+ }));
+ let mut composed = map_from(serde_json::json!({
+ "version": 3,
+ "mappings": "AAAA",
+ "sources": ["App.js"],
+ "names": [],
+ "x_hermes_function_offsets": {},
+ }));
+
+ clone_metadata(&minified, &mut composed);
+
+ assert_eq!(
+ composed.get_chunk_id().as_deref(),
+ Some("c96bfa94-ca84-4f98-8d5e-f15adba692ca")
+ );
+ assert_eq!(
+ composed.get_release_id().as_deref(),
+ Some("11111111-2222-4333-8444-555555555555")
+ );
+ }
+}
diff --git a/cli/src/sourcemaps/hermes/upload.rs b/cli/src/sourcemaps/hermes/upload.rs
index 5f1b0041e0a1..9a194740139a 100644
--- a/cli/src/sourcemaps/hermes/upload.rs
+++ b/cli/src/sourcemaps/hermes/upload.rs
@@ -55,7 +55,7 @@ pub fn upload(args: &Args) -> Result<()> {
let mut uploads: Vec<SymbolSetUpload> = Vec::new();
let mut empty_skipped = 0usize;
for mut map in maps.into_iter() {
- if map.get_chunk_id().is_none() {
+ if map.get_upload_chunk_id().is_none() {
warn!("Skipping map {}, no chunk ID", map.inner.path.display());
continue;
}
@@ -76,6 +76,17 @@ pub fn upload(args: &Args) -> Result<()> {
uploads.push(map.try_into()?);
}
+ // A run that discovers nothing must fail rather than exit green: in build pipelines this
+ // command runs right after bundling, so an empty result means the maps or their ids went
+ // missing, and a silent success ships a build whose exceptions never symbolicate.
+ if uploads.is_empty() {
+ anyhow::bail!(
+ "No hermes sourcemaps with a chunk id found under {} — nothing was uploaded. \
+ Check that bundling produced .map files and that they carry a chunk id or debugId.",
+ directory.display()
+ );
+ }
+
info!("Found {} maps to upload", uploads.len());
let file_count = uploads.len();
diff --git a/cli/src/sourcemaps/inject.rs b/cli/src/sourcemaps/inject.rs
index 40217e77340b..d5435d0980bf 100644
--- a/cli/src/sourcemaps/inject.rs
+++ b/cli/src/sourcemaps/inject.rs
@@ -110,14 +110,16 @@ pub fn inject_impl(
}
/// Event-mode injection (`--release-mode=event`): content-addressed chunk ids plus an optional
-/// `_posthogReleaseId` payload.
+/// `_posthogReleaseId` payload. A bundler-emitted debug id, when present, is adopted as the
+/// chunk id so one id identifies the chunk across the whole toolchain.
pub fn inject_pairs(
mut pairs: Vec<SourcePair>,
release_id: Option<&str>,
) -> Result<Vec<SourcePair>> {
for pair in &mut pairs {
let Some(chunk_id) = pair.get_chunk_id() else {
- let chunk_id = stable_chunk_id(&pair.source.inner.content);
+ let chunk_id = adopted_debug_id(pair)
+ .unwrap_or_else(|| stable_chunk_id(&pair.source.inner.content));
pair.add_chunk_id(chunk_id, release_id)?;
continue;
};
@@ -140,6 +142,22 @@ pub fn inject_pairs(
Ok(pairs)
}
+/// A bundler-emitted ECMA-426 debug id is already content-derived, so adopt it as the chunk id
+/// instead of deriving our own. Non-UUID values are refused: the id flows into upload rows and
+/// SDK events, and a malformed one is worse than a derived one.
+fn adopted_debug_id(pair: &SourcePair) -> Option<String> {
+ let debug_id = pair.get_debug_id()?;
+ if uuid::Uuid::parse_str(&debug_id).is_err() {
+ warn!(
+ "ignoring malformed debug id {:?} on {} — falling back to a content-derived chunk id",
+ debug_id,
+ pair.source.inner.path.display()
+ );
+ return None;
+ }
+ Some(debug_id)
+}
+
/// Symbol-set-mode injection (the default): a random per-build chunk id and the created release
/// id stamped into the sourcemap. Regenerates the chunk id whenever the release id changes or is
/// missing.
diff --git a/cli/src/sourcemaps/source_pairs.rs b/cli/src/sourcemaps/source_pairs.rs
index 390cfcb89728..e66fbeaa5c2b 100644
--- a/cli/src/sourcemaps/source_pairs.rs
+++ b/cli/src/sourcemaps/source_pairs.rs
@@ -29,6 +29,24 @@ impl SourcePair {
self.source.get_chunk_id()
}
+ /// Debug id already present in the pair, if any. The chunk's comment is authoritative
+ /// (sourcemaps can be shared across chunks); the sourcemap's field is only a fallback.
+ pub fn get_debug_id(&self) -> Option<String> {
+ let source_debug_id = self.source.get_debug_id();
+ let sourcemap_debug_id = self.sourcemap.get_debug_id();
+ if let (Some(source_id), Some(map_id)) = (&source_debug_id, &sourcemap_debug_id) {
+ if source_id != map_id {
+ warn!(
+ "debug id mismatch for {}: chunk has {}, sourcemap has {} — using the chunk's",
+ self.source.inner.path.display(),
+ source_id,
+ map_id
+ );
+ }
+ }
+ source_debug_id.or(sourcemap_debug_id)
+ }
+
pub fn has_release_id(&self) -> bool {
self.sourcemap.has_release_id()
}
diff --git a/cli/tests/sourcemap.rs b/cli/tests/sourcemap.rs
index 45b5ffa4fe3b..bbd83582f1f8 100644
--- a/cli/tests/sourcemap.rs
+++ b/cli/tests/sourcemap.rs
@@ -1,15 +1,16 @@
use posthog_cli::{
sourcemaps::{
args::ReleaseMode,
- content::SourceMapContent,
+ content::{MinifiedSourceFile, SourceMapContent, SourceMapFile},
inject::{inject_pairs, inject_pairs_legacy},
plain::inject::{is_javascript_file, is_stylesheet_file},
source_pairs::SourcePair,
},
- utils::files::FileSelection,
+ utils::files::{FileSelection, SourceFile},
};
use anyhow::Result;
+use serde_json::json;
use std::{
fs,
@@ -508,6 +509,152 @@ fn test_event_mode_content_hash_is_stable_across_release_states() {
assert_eq!(releaseless, transitioned);
}
+const BUNDLER_DEBUG_ID: &str = "11111111-2222-4333-8444-555555555555";
+
+fn make_pair(source_content: &str, map_json: serde_json::Value) -> SourcePair {
+ SourcePair {
+ source: MinifiedSourceFile {
+ inner: SourceFile::new(PathBuf::from("chunk.js"), source_content.to_string()),
+ },
+ sourcemap: SourceMapFile {
+ inner: SourceFile::new(
+ PathBuf::from("chunk.js.map"),
+ serde_json::from_value(map_json).expect("Failed to build SourceMapContent"),
+ ),
+ },
+ }
+}
+
+fn source_with_debug_id(debug_id: &str) -> String {
+ format!("console.log(1);\n//# debugId={debug_id}\n//# sourceMappingURL=chunk.js.map\n")
+}
+
+fn map_with_debug_id(debug_id: Option<&str>) -> serde_json::Value {
+ let mut map = json!({
+ "version": 3,
+ "file": "chunk.js",
+ "sources": ["src/index.js"],
+ "sourcesContent": ["console.log(1)\n"],
+ "names": [],
+ "mappings": "AAAA",
+ });
+ if let Some(debug_id) = debug_id {
+ map["debugId"] = json!(debug_id);
+ }
+ map
+}
+
+#[test]
+fn test_inject_adopts_bundler_debug_id() {
+ // The bundler already stamped a debug id into the chunk and its map. Inject must adopt it
+ // as the chunk id and still apply the mapping adjustment for the prepended snippet — the
+ // old `alias = "debugId"` conflation made the map look already-processed and skipped it.
+ let source_before = source_with_debug_id(BUNDLER_DEBUG_ID);
+ let pair = make_pair(&source_before, map_with_debug_id(Some(BUNDLER_DEBUG_ID)));
+
+ let injected = inject_pairs(vec![pair], None).expect("Failed to inject pairs");
+ let pair = injected.first().unwrap();
+
+ assert_eq!(
+ pair.source.get_chunk_id().as_deref(),
+ Some(BUNDLER_DEBUG_ID)
+ );
+ assert!(pair
+ .source
+ .inner
+ .content
+ .contains(&format!("=\"{BUNDLER_DEBUG_ID}\"")));
+ let map = &pair.sourcemap.inner.content;
+ assert_eq!(map.chunk_id.as_deref(), Some(BUNDLER_DEBUG_ID));
+ assert_eq!(map.debug_id.as_deref(), Some(BUNDLER_DEBUG_ID));
+ assert_ne!(
+ map.fields.get("mappings").and_then(|v| v.as_str()),
+ Some("AAAA"),
+ "mapping adjustment for the prepended snippet was not applied"
+ );
+
+ // Undoing the injection must hand the bundler's bytes back exactly, debug id comment
+ // included — event-mode uploads hash that pristine form to dedupe across releases.
+ let mut pair = injected.into_iter().next().unwrap();
+ pair.remove_chunk_id(BUNDLER_DEBUG_ID.to_string())
+ .expect("Failed to remove chunk ID");
+ assert_eq!(pair.source.inner.content, source_before);
+}
+
+#[test]
+fn test_inject_ignores_malformed_debug_id() {
+ // Adopted ids flow into upload rows and SDK events; a bundler emitting a non-UUID debug id
+ // must not poison them — fall back to the content-derived chunk id.
+ let pair = make_pair(
+ "console.log(1);\n//# debugId=not-a-uuid\n//# sourceMappingURL=chunk.js.map\n",
+ map_with_debug_id(None),
+ );
+
+ let injected = inject_pairs(vec![pair], None).expect("Failed to inject pairs");
+ let chunk_id = injected.first().unwrap().source.get_chunk_id().unwrap();
+
+ assert_ne!(chunk_id, "not-a-uuid");
+ assert!(uuid::Uuid::parse_str(&chunk_id).is_ok());
+}
+
+#[test]
+fn test_inject_prefers_chunk_debug_id_over_sourcemap() {
+ // Sourcemaps can be shared across chunks, so the chunk's own debug id must win when the two
+ // disagree — flipping the precedence would stamp one chunk's id onto its siblings.
+ let map_debug_id = "99999999-8888-4777-8666-555555555555";
+ let pair = make_pair(
+ &source_with_debug_id(BUNDLER_DEBUG_ID),
+ map_with_debug_id(Some(map_debug_id)),
+ );
+
+ let injected = inject_pairs(vec![pair], None).expect("Failed to inject pairs");
+ let pair = injected.first().unwrap();
+
+ assert_eq!(
+ pair.source.get_chunk_id().as_deref(),
+ Some(BUNDLER_DEBUG_ID)
+ );
+}
+
+#[test]
+fn test_event_mode_content_hash_is_stable_across_releases_for_adopted_ids() {
+ // An adopted debug id keeps one chunk id across releases, so a fresh build and a re-injected
+ // dist must hash identically per release — the server keys its skip-or-overwrite decision on
+ // that hash, and drift would reject the upload as a content_hash_mismatch.
+ let load = || {
+ make_pair(
+ &source_with_debug_id(BUNDLER_DEBUG_ID),
+ map_with_debug_id(Some(BUNDLER_DEBUG_ID)),
+ )
+ };
+ let upload_of = |pair: SourcePair| {
+ pair.into_upload(ReleaseMode::Event)
+ .expect("Failed to convert to SymbolSetUpload")
+ };
+
+ let fresh = upload_of(
+ inject_pairs(vec![load()], Some("release-a"))
+ .expect("Failed to inject pairs")
+ .into_iter()
+ .next()
+ .unwrap(),
+ );
+ let transitioned = {
+ let injected = inject_pairs(vec![load()], Some("release-a")).expect("Failed to inject");
+ upload_of(
+ inject_pairs(injected, Some("release-b"))
+ .expect("Failed to re-inject pairs")
+ .into_iter()
+ .next()
+ .unwrap(),
+ )
+ };
+
+ assert_eq!(fresh.chunk_id, BUNDLER_DEBUG_ID);
+ assert_eq!(transitioned.chunk_id, BUNDLER_DEBUG_ID);
+ assert_eq!(fresh.content_hash, transitioned.content_hash);
+}
+
#[test]
fn test_file_selection() {
// This does not work with glob patterns