@laburen/delta-sdk 1.3.0 → 1.5.0-canary.10

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.
Files changed (150) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +3 -0
  3. package/dist/core/config.d.ts +12 -12
  4. package/dist/core/config.d.ts.map +1 -1
  5. package/dist/core/config.js +88 -88
  6. package/dist/core/config.js.map +1 -1
  7. package/dist/core/{constantes.d.ts → constants.d.ts} +3 -3
  8. package/dist/core/constants.d.ts.map +1 -0
  9. package/dist/core/{constantes.js → constants.js} +3 -3
  10. package/dist/core/constants.js.map +1 -0
  11. package/dist/core/{contadores.d.ts → counters.d.ts} +12 -11
  12. package/dist/core/counters.d.ts.map +1 -0
  13. package/dist/core/counters.js +53 -0
  14. package/dist/core/counters.js.map +1 -0
  15. package/dist/core/{sobre.d.ts → envelope.d.ts} +17 -17
  16. package/dist/core/envelope.d.ts.map +1 -0
  17. package/dist/core/envelope.js +198 -0
  18. package/dist/core/envelope.js.map +1 -0
  19. package/dist/core/scrubbing.d.ts +4 -4
  20. package/dist/core/scrubbing.d.ts.map +1 -1
  21. package/dist/core/scrubbing.js +38 -38
  22. package/dist/core/scrubbing.js.map +1 -1
  23. package/dist/core/{sesion.d.ts → session.d.ts} +2 -2
  24. package/dist/core/session.d.ts.map +1 -0
  25. package/dist/core/{sesion.js → session.js} +2 -2
  26. package/dist/core/session.js.map +1 -0
  27. package/dist/core/{transporte.d.ts → transport.d.ts} +9 -9
  28. package/dist/core/transport.d.ts.map +1 -0
  29. package/dist/core/{transporte.js → transport.js} +15 -15
  30. package/dist/core/transport.js.map +1 -0
  31. package/dist/core/{tipos.d.ts → types.d.ts} +4 -4
  32. package/dist/core/{tipos.d.ts.map → types.d.ts.map} +1 -1
  33. package/dist/core/{tipos.js → types.js} +1 -1
  34. package/dist/core/{tipos.js.map → types.js.map} +1 -1
  35. package/dist/index.d.ts +1 -1
  36. package/dist/platform/client.d.ts +8 -0
  37. package/dist/platform/client.d.ts.map +1 -0
  38. package/dist/platform/client.js +30 -0
  39. package/dist/platform/client.js.map +1 -0
  40. package/dist/platform/core/errors.d.ts +150 -0
  41. package/dist/platform/core/errors.d.ts.map +1 -0
  42. package/dist/platform/core/errors.js +265 -0
  43. package/dist/platform/core/errors.js.map +1 -0
  44. package/dist/platform/core/oauth.d.ts +37 -0
  45. package/dist/platform/core/oauth.d.ts.map +1 -0
  46. package/dist/platform/core/oauth.js +144 -0
  47. package/dist/platform/core/oauth.js.map +1 -0
  48. package/dist/platform/core/pagination.d.ts +30 -0
  49. package/dist/platform/core/pagination.d.ts.map +1 -0
  50. package/dist/platform/core/pagination.js +44 -0
  51. package/dist/platform/core/pagination.js.map +1 -0
  52. package/dist/platform/core/request.d.ts +6 -0
  53. package/dist/platform/core/request.d.ts.map +1 -0
  54. package/dist/platform/core/request.js +24 -0
  55. package/dist/platform/core/request.js.map +1 -0
  56. package/dist/platform/core/send.d.ts +36 -0
  57. package/dist/platform/core/send.d.ts.map +1 -0
  58. package/dist/platform/core/send.js +171 -0
  59. package/dist/platform/core/send.js.map +1 -0
  60. package/dist/platform/core/sse.d.ts +8 -0
  61. package/dist/platform/core/sse.d.ts.map +1 -0
  62. package/dist/platform/core/sse.js +72 -0
  63. package/dist/platform/core/sse.js.map +1 -0
  64. package/dist/platform/core/stream.d.ts +21 -0
  65. package/dist/platform/core/stream.d.ts.map +1 -0
  66. package/dist/platform/core/stream.js +268 -0
  67. package/dist/platform/core/stream.js.map +1 -0
  68. package/dist/platform/generated/resources.d.ts +120 -0
  69. package/dist/platform/generated/resources.d.ts.map +1 -0
  70. package/dist/platform/generated/resources.js +65 -0
  71. package/dist/platform/generated/resources.js.map +1 -0
  72. package/dist/platform/generated/schemas.d.ts +78 -0
  73. package/dist/platform/generated/schemas.d.ts.map +1 -0
  74. package/dist/platform/generated/schemas.js +2 -0
  75. package/dist/platform/generated/schemas.js.map +1 -0
  76. package/dist/platform/generated/types.d.ts +5167 -0
  77. package/dist/platform/generated/types.d.ts.map +1 -0
  78. package/dist/platform/generated/types.js +6 -0
  79. package/dist/platform/generated/types.js.map +1 -0
  80. package/dist/platform/index.d.ts +9 -0
  81. package/dist/platform/index.d.ts.map +1 -0
  82. package/dist/platform/index.js +7 -0
  83. package/dist/platform/index.js.map +1 -0
  84. package/dist/telemetry/{captura.d.ts → capture.d.ts} +3 -3
  85. package/dist/telemetry/capture.d.ts.map +1 -0
  86. package/dist/telemetry/{captura.js → capture.js} +54 -54
  87. package/dist/telemetry/capture.js.map +1 -0
  88. package/dist/telemetry/index.d.ts +2 -2
  89. package/dist/telemetry/index.js +1 -1
  90. package/dist/telemetry/{tipos.d.ts → types.d.ts} +2 -2
  91. package/dist/telemetry/types.d.ts.map +1 -0
  92. package/dist/telemetry/types.js +2 -0
  93. package/dist/telemetry/types.js.map +1 -0
  94. package/dist/telemetry/with-telemetry.d.ts +9 -9
  95. package/dist/telemetry/with-telemetry.d.ts.map +1 -1
  96. package/dist/telemetry/with-telemetry.js +31 -31
  97. package/dist/telemetry/with-telemetry.js.map +1 -1
  98. package/dist/telemetry/with-tool.d.ts +2 -2
  99. package/dist/telemetry/with-tool.d.ts.map +1 -1
  100. package/dist/telemetry/with-tool.js +3 -3
  101. package/dist/telemetry/with-tool.js.map +1 -1
  102. package/docs/platform/guide.md +554 -0
  103. package/docs/telemetry/que-se-manda.md +2 -2
  104. package/docs/telemetry/troubleshooting.md +1 -1
  105. package/package.json +15 -5
  106. package/src/core/config.ts +81 -83
  107. package/src/core/{constantes.ts → constants.ts} +2 -2
  108. package/src/core/counters.ts +72 -0
  109. package/src/core/envelope.ts +234 -0
  110. package/src/core/scrubbing.ts +41 -41
  111. package/src/core/{sesion.ts → session.ts} +1 -1
  112. package/src/core/{transporte.ts → transport.ts} +20 -20
  113. package/src/core/{tipos.ts → types.ts} +3 -3
  114. package/src/index.ts +1 -1
  115. package/src/platform/client.ts +32 -0
  116. package/src/platform/core/errors.ts +348 -0
  117. package/src/platform/core/oauth.ts +201 -0
  118. package/src/platform/core/pagination.ts +67 -0
  119. package/src/platform/core/request.ts +27 -0
  120. package/src/platform/core/send.ts +212 -0
  121. package/src/platform/core/sse.ts +68 -0
  122. package/src/platform/core/stream.ts +314 -0
  123. package/src/platform/generated/resources.ts +192 -0
  124. package/src/platform/generated/schemas.ts +79 -0
  125. package/src/platform/generated/types.ts +5167 -0
  126. package/src/platform/index.ts +45 -0
  127. package/src/telemetry/{captura.ts → capture.ts} +57 -57
  128. package/src/telemetry/index.ts +2 -2
  129. package/src/telemetry/{tipos.ts → types.ts} +1 -1
  130. package/src/telemetry/with-telemetry.ts +51 -54
  131. package/src/telemetry/with-tool.ts +5 -5
  132. package/dist/core/constantes.d.ts.map +0 -1
  133. package/dist/core/constantes.js.map +0 -1
  134. package/dist/core/contadores.d.ts.map +0 -1
  135. package/dist/core/contadores.js +0 -53
  136. package/dist/core/contadores.js.map +0 -1
  137. package/dist/core/sesion.d.ts.map +0 -1
  138. package/dist/core/sesion.js.map +0 -1
  139. package/dist/core/sobre.d.ts.map +0 -1
  140. package/dist/core/sobre.js +0 -200
  141. package/dist/core/sobre.js.map +0 -1
  142. package/dist/core/transporte.d.ts.map +0 -1
  143. package/dist/core/transporte.js.map +0 -1
  144. package/dist/telemetry/captura.d.ts.map +0 -1
  145. package/dist/telemetry/captura.js.map +0 -1
  146. package/dist/telemetry/tipos.d.ts.map +0 -1
  147. package/dist/telemetry/tipos.js +0 -2
  148. package/dist/telemetry/tipos.js.map +0 -1
  149. package/src/core/contadores.ts +0 -71
  150. package/src/core/sobre.ts +0 -236
@@ -1,13 +1,13 @@
1
- import { INGEST_URL } from "./constantes.js";
1
+ import { INGEST_URL } from "./constants.js";
2
2
  import {
3
3
  type Notify,
4
4
  SURFACES,
5
5
  type Surface,
6
6
  type TelemetryConfig,
7
7
  type TelemetryEvent,
8
- } from "./tipos.js";
8
+ } from "./types.js";
9
9
 
10
- export interface ConfigValidada {
10
+ export interface ValidatedConfig {
11
11
  service: { name: string; version?: string; environment?: string };
12
12
  surface: Surface;
13
13
  organizationId: string;
@@ -16,28 +16,26 @@ export interface ConfigValidada {
16
16
  notify: Notify;
17
17
  ingestUrl: string;
18
18
  scrub: string[];
19
- beforeSend?: (evento: TelemetryEvent) => TelemetryEvent | null;
19
+ beforeSend?: (event: TelemetryEvent) => TelemetryEvent | null;
20
20
  debug: boolean;
21
21
  queueMaxRetries?: number;
22
22
  }
23
23
 
24
- export type ResultadoConfig =
25
- | { ok: true; config: ConfigValidada }
26
- | { ok: false; faltan: string[] };
24
+ export type ConfigResult = { ok: true; config: ValidatedConfig } | { ok: false; missing: string[] };
27
25
 
28
26
  // Los `?.` no son paranoia: los valores salen del env del worker, y ahí TypeScript no manda.
29
- function vacio(valor: unknown): boolean {
30
- return typeof valor !== "string" || valor.trim() === "";
27
+ function empty(value: unknown): boolean {
28
+ return typeof value !== "string" || value.trim() === "";
31
29
  }
32
30
 
33
- // Mismo criterio que `textoDe` en sobre.ts: un aviso no puede lanzar por describir el valor que
31
+ // Mismo criterio que `textOf` en envelope.ts: un aviso no puede lanzar por describir el valor que
34
32
  // está avisando. `JSON.stringify` no sabe serializar un `BigInt` (un `queueMaxRetries` armado con
35
33
  // uno lo hace lanzar), así que cae a `String()` en vez de romper el aviso.
36
- function describirValor(valor: unknown): string {
34
+ function describeValue(value: unknown): string {
37
35
  try {
38
- return JSON.stringify(valor) ?? String(valor);
36
+ return JSON.stringify(value) ?? String(value);
39
37
  } catch {
40
- return String(valor);
38
+ return String(value);
41
39
  }
42
40
  }
43
41
 
@@ -45,25 +43,25 @@ function describirValor(valor: unknown): string {
45
43
  // copiarlo acá es coherente.
46
44
  const SLACK_CHANNEL_ID = /^[CGD][A-Z0-9]{8,}$/;
47
45
 
48
- type EstadoCanal = "sinDeclarar" | "incompleto" | "completo";
46
+ type ChannelState = "undeclared" | "incomplete" | "complete";
49
47
 
50
48
  // Objetos sueltos porque vienen de un `unknown` en runtime (env, fila de D1): no se puede confiar
51
49
  // en que respeten el tipo `Notify` solo porque TypeScript los tipó así en el archivo del cliente.
52
- // "sinDeclarar" es un canal AUSENTE (la clave `slack`/`email` no está, o `enabled` es `false`); un
50
+ // "undeclared" es un canal AUSENTE (la clave `slack`/`email` no está, o `enabled` es `false`); un
53
51
  // canal PRESENTE cuyo `enabled` es truthy pero no un booleano estricto (un `1` de una columna
54
52
  // INTEGER de D1 usada como boolean, el mismo patrón que ya cita `emailPlausible` más abajo) es
55
- // "incompleto", no "sinDeclarar": la ingesta valida `enabled` con un union discriminado entre los
53
+ // "incomplete", no "undeclared": la ingesta valida `enabled` con un union discriminado entre los
56
54
  // literales `true`/`false`, y cualquier otro valor le rompe el discriminante — `notify` sale crudo
57
55
  // al sobre si el OTRO canal es válido, y la ingesta lo rechaza con "Invalid discriminator value"
58
56
  // mientras el SDK cree que la config está sana.
59
- function estadoSlack(slack: unknown): EstadoCanal {
60
- if (typeof slack !== "object" || slack === null) return "sinDeclarar";
61
- const valor = slack as { enabled?: unknown; channel?: unknown };
62
- if (typeof valor.enabled !== "boolean") return "incompleto";
63
- if (valor.enabled === false) return "sinDeclarar";
64
- return typeof valor.channel === "string" && SLACK_CHANNEL_ID.test(valor.channel)
65
- ? "completo"
66
- : "incompleto";
57
+ function slackState(slack: unknown): ChannelState {
58
+ if (typeof slack !== "object" || slack === null) return "undeclared";
59
+ const value = slack as { enabled?: unknown; channel?: unknown };
60
+ if (typeof value.enabled !== "boolean") return "incomplete";
61
+ if (value.enabled === false) return "undeclared";
62
+ return typeof value.channel === "string" && SLACK_CHANNEL_ID.test(value.channel)
63
+ ? "complete"
64
+ : "incomplete";
67
65
  }
68
66
 
69
67
  /** Deliberadamente MÁS PERMISIVO que el `z.email()` de la ingesta (verificado con un fuzz test en
@@ -71,26 +69,26 @@ function estadoSlack(slack: unknown): EstadoCanal {
71
69
  * espacios o comas, sin un dominio con punto— y nada más. Quedar más estricto que la ingesta es
72
70
  * peor que el 400 mudo que este archivo cierra: una dirección real rechazada acá manda TODO el
73
71
  * worker a inerte, no solo ese evento. */
74
- function emailPlausible(valor: unknown): boolean {
75
- if (typeof valor !== "string" || valor === "" || valor.trim() !== valor) return false;
76
- if (/\s/.test(valor) || valor.includes(",")) return false;
77
- const arroba = valor.indexOf("@");
78
- if (arroba <= 0 || arroba !== valor.lastIndexOf("@")) return false;
79
- const dominio = valor.slice(arroba + 1);
80
- if (dominio === "" || !dominio.includes(".")) return false;
81
- return !dominio.startsWith(".") && !dominio.endsWith(".");
72
+ function emailPlausible(value: unknown): boolean {
73
+ if (typeof value !== "string" || value === "" || value.trim() !== value) return false;
74
+ if (/\s/.test(value) || value.includes(",")) return false;
75
+ const atSign = value.indexOf("@");
76
+ if (atSign <= 0 || atSign !== value.lastIndexOf("@")) return false;
77
+ const domain = value.slice(atSign + 1);
78
+ if (domain === "" || !domain.includes(".")) return false;
79
+ return !domain.startsWith(".") && !domain.endsWith(".");
82
80
  }
83
81
 
84
- function estadoEmail(email: unknown): EstadoCanal {
85
- if (typeof email !== "object" || email === null) return "sinDeclarar";
86
- const valor = email as { enabled?: unknown; to?: unknown };
82
+ function emailState(email: unknown): ChannelState {
83
+ if (typeof email !== "object" || email === null) return "undeclared";
84
+ const value = email as { enabled?: unknown; to?: unknown };
87
85
  // Mismo criterio que `estadoSlack`: un `enabled` truthy pero no booleano estricto es
88
- // "incompleto", no "sinDeclarar".
89
- if (typeof valor.enabled !== "boolean") return "incompleto";
90
- if (valor.enabled === false) return "sinDeclarar";
91
- return Array.isArray(valor.to) && valor.to.length > 0 && valor.to.every(emailPlausible)
92
- ? "completo"
93
- : "incompleto";
86
+ // "incomplete", no "undeclared".
87
+ if (typeof value.enabled !== "boolean") return "incomplete";
88
+ if (value.enabled === false) return "undeclared";
89
+ return Array.isArray(value.to) && value.to.length > 0 && value.to.every(emailPlausible)
90
+ ? "complete"
91
+ : "incomplete";
94
92
  }
95
93
 
96
94
  /** El motivo por el que `notify` no es usable, o `null` si lo es. Dos reglas, no una: (a) un canal
@@ -101,17 +99,17 @@ function estadoEmail(email: unknown): EstadoCanal {
101
99
  * `notify` armado con un getter o un `Proxy` que lanza al leer sus propiedades cuenta como "no
102
100
  * usable", no como una excepción que se escapa de `createTelemetry` — el SDK no lanza nunca, ni
103
101
  * con el notify más raro. */
104
- export function motivoNotifyInvalido(notify: unknown): string | null {
102
+ export function invalidNotifyReason(notify: unknown): string | null {
105
103
  try {
106
104
  if (typeof notify !== "object" || notify === null) {
107
105
  return "notify (revisá slack.channel / email.to)";
108
106
  }
109
- const valor = notify as { slack?: unknown; email?: unknown };
110
- const slack = estadoSlack(valor.slack);
111
- const email = estadoEmail(valor.email);
112
- if (slack === "incompleto") return "notify: slack.channel declarado pero vacío o mal formado";
113
- if (email === "incompleto") return "notify: email.to declarado pero vacío o mal formado";
114
- if (slack !== "completo" && email !== "completo") {
107
+ const value = notify as { slack?: unknown; email?: unknown };
108
+ const slack = slackState(value.slack);
109
+ const email = emailState(value.email);
110
+ if (slack === "incomplete") return "notify: slack.channel declarado pero vacío o mal formado";
111
+ if (email === "incomplete") return "notify: email.to declarado pero vacío o mal formado";
112
+ if (slack !== "complete" && email !== "complete") {
115
113
  return "notify (revisá slack.channel / email.to)";
116
114
  }
117
115
  return null;
@@ -120,56 +118,56 @@ export function motivoNotifyInvalido(notify: unknown): string | null {
120
118
  }
121
119
  }
122
120
 
123
- /** Wrapper booleano de `motivoNotifyInvalido`, para los callers que solo necesitan saber si el
124
- * `notify` sirve (el override por evento de `captura.ts`) sin mostrar el motivo. */
125
- export function notifyUsable(notify: unknown): boolean {
126
- return motivoNotifyInvalido(notify) === null;
121
+ /** Wrapper booleano de `invalidNotifyReason`, para los callers que solo necesitan saber si el
122
+ * `notify` sirve (el override por evento de `capture.ts`) sin mostrar el motivo. */
123
+ export function usableNotify(notify: unknown): boolean {
124
+ return invalidNotifyReason(notify) === null;
127
125
  }
128
126
 
129
127
  /** Un `queueMaxRetries` usable es un entero ≥ 0: sale del `max_retries` del `wrangler.jsonc` vía
130
128
  * una `var` del env, que siempre es `string` — `"2" + 1` da `"21"`, no `3`. */
131
- export function queueMaxRetriesUsable(valor: unknown): valor is number {
132
- return typeof valor === "number" && Number.isInteger(valor) && valor >= 0;
129
+ export function queueMaxRetriesUsable(value: unknown): value is number {
130
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
133
131
  }
134
132
 
135
133
  /** Valida en runtime lo que el tipo no puede: un campo que llega vacío desde el env es un string
136
134
  * válido para TypeScript, y significa que ese worker nunca va a reportar nada. */
137
- export function validar(entrada: TelemetryConfig): ResultadoConfig {
138
- const faltan: string[] = [];
139
- if (vacio(entrada.service?.name)) faltan.push("service.name");
140
- if (vacio(entrada.organizationId)) faltan.push("organizationId");
141
- if (vacio(entrada.agentId)) faltan.push("agentId");
142
- if (vacio(entrada.apiKey)) faltan.push("apiKey");
143
- if (!(SURFACES as readonly string[]).includes(entrada.surface)) faltan.push("surface");
144
- const motivoNotify = motivoNotifyInvalido(entrada.notify);
145
- if (motivoNotify !== null) faltan.push(motivoNotify);
146
- if (faltan.length > 0) return { ok: false, faltan };
147
-
148
- const service: ConfigValidada["service"] = { name: entrada.service.name.trim() };
149
- if (entrada.service.version !== undefined) service.version = entrada.service.version;
150
- if (entrada.service.environment !== undefined) service.environment = entrada.service.environment;
151
-
152
- const config: ConfigValidada = {
135
+ export function validate(input: TelemetryConfig): ConfigResult {
136
+ const missing: string[] = [];
137
+ if (empty(input.service?.name)) missing.push("service.name");
138
+ if (empty(input.organizationId)) missing.push("organizationId");
139
+ if (empty(input.agentId)) missing.push("agentId");
140
+ if (empty(input.apiKey)) missing.push("apiKey");
141
+ if (!(SURFACES as readonly string[]).includes(input.surface)) missing.push("surface");
142
+ const notifyReason = invalidNotifyReason(input.notify);
143
+ if (notifyReason !== null) missing.push(notifyReason);
144
+ if (missing.length > 0) return { ok: false, missing };
145
+
146
+ const service: ValidatedConfig["service"] = { name: input.service.name.trim() };
147
+ if (input.service.version !== undefined) service.version = input.service.version;
148
+ if (input.service.environment !== undefined) service.environment = input.service.environment;
149
+
150
+ const config: ValidatedConfig = {
153
151
  service,
154
- surface: entrada.surface,
155
- organizationId: entrada.organizationId.trim(),
156
- agentId: entrada.agentId.trim(),
157
- apiKey: entrada.apiKey.trim(),
158
- notify: entrada.notify,
152
+ surface: input.surface,
153
+ organizationId: input.organizationId.trim(),
154
+ agentId: input.agentId.trim(),
155
+ apiKey: input.apiKey.trim(),
156
+ notify: input.notify,
159
157
  // La URL es constante del paquete; el override existe solo para desarrollo local.
160
- ingestUrl: entrada.ingestUrl?.trim() || INGEST_URL,
161
- scrub: entrada.scrub ?? [],
162
- debug: entrada.debug ?? false,
158
+ ingestUrl: input.ingestUrl?.trim() || INGEST_URL,
159
+ scrub: input.scrub ?? [],
160
+ debug: input.debug ?? false,
163
161
  };
164
- if (entrada.beforeSend !== undefined) config.beforeSend = entrada.beforeSend;
165
- if (entrada.queueMaxRetries !== undefined) {
166
- if (queueMaxRetriesUsable(entrada.queueMaxRetries)) {
167
- config.queueMaxRetries = entrada.queueMaxRetries;
162
+ if (input.beforeSend !== undefined) config.beforeSend = input.beforeSend;
163
+ if (input.queueMaxRetries !== undefined) {
164
+ if (queueMaxRetriesUsable(input.queueMaxRetries)) {
165
+ config.queueMaxRetries = input.queueMaxRetries;
168
166
  } else {
169
167
  // Se descarta y no se suma a `faltan`: a diferencia de los seis obligatorios, sin este
170
168
  // dato el cliente sigue reportando — solo se omite `retry.limit` en surface "queue".
171
169
  console.error(
172
- `[delta-sdk] queueMaxRetries inválido (se esperaba un entero ≥ 0, llegó ${describirValor(entrada.queueMaxRetries)}): se ignora`,
170
+ `[delta-sdk] queueMaxRetries inválido (se esperaba un entero ≥ 0, llegó ${describeValue(input.queueMaxRetries)}): se ignora`,
173
171
  );
174
172
  }
175
173
  }
@@ -5,11 +5,11 @@ export const INGEST_URL = "https://telemetry.laburen.com/events";
5
5
  export const SDK_NAME = "@laburen/delta-sdk";
6
6
 
7
7
  /** Tiene que coincidir con `version` del package.json; lo verifica `npm run version:check`. */
8
- export const SDK_VERSION = "1.3.0";
8
+ export const SDK_VERSION = "1.5.0-canary.10";
9
9
 
10
10
  /** Los mismos topes que aplica la ingesta. El cliente los aplica para no perder el sobre entero;
11
11
  * la ingesta, para no confiar en el cliente. */
12
- export const LIMITES = {
12
+ export const LIMITS = {
13
13
  stacktraceChars: 8 * 1024,
14
14
  messageChars: 2 * 1024,
15
15
  attributeKeys: 64,
@@ -0,0 +1,72 @@
1
+ /** Lo que viaja en el campo `drops` del sobre. Estas claves SON el contrato de cable con la ingesta
2
+ * (se serializan tal cual) y quedan en español a propósito. La ingesta lo acepta como
3
+ * `z.record(z.string(), z.number())`, así que las claves son libres; `before_send` conserva la
4
+ * grafía canónica de Sentry para las razones de drop. */
5
+ export interface Drops {
6
+ incompletos: number;
7
+ fallados: number;
8
+ before_send: number;
9
+ recortados: number;
10
+ internos: number;
11
+ }
12
+
13
+ const stats = {
14
+ fired: 0,
15
+ completed: 0,
16
+ failed: 0,
17
+ before_send: 0,
18
+ trimmed: 0,
19
+ internal: 0,
20
+ };
21
+
22
+ /** Veces que el código pidió enviar. */
23
+ export function countFired(): void {
24
+ stats.fired += 1;
25
+ }
26
+
27
+ /** Envíos que terminaron, con cualquier status: un 429 y un 503 salieron y los rechazaron. */
28
+ export function countCompleted(): void {
29
+ stats.completed += 1;
30
+ }
31
+
32
+ /** Envíos que lanzaron: red, DNS. */
33
+ export function countFailed(): void {
34
+ stats.failed += 1;
35
+ }
36
+
37
+ export function countBeforeSend(): void {
38
+ stats.before_send += 1;
39
+ }
40
+
41
+ export function countTrimmed(): void {
42
+ stats.trimmed += 1;
43
+ }
44
+
45
+ /** La quinta forma de perder un evento: algo entre `buildEvent` y `serializeCapped` lanzó, y la
46
+ * red del `catch` de `capture` lo atrapó. Sin este contador, ese evento desaparecía sin dejar
47
+ * rastro en ningún `drops` del sobre siguiente. */
48
+ export function countInternal(): void {
49
+ stats.internal += 1;
50
+ }
51
+
52
+ /** `incompletos` es la resta, y es el único contador que prueba pérdida por ciclo de vida: sin
53
+ * esta separación, un 429 por rate limit y "se perdió el evento" se ven idénticos. */
54
+ export function drops(): Drops {
55
+ return {
56
+ incompletos: stats.fired - stats.completed - stats.failed,
57
+ fallados: stats.failed,
58
+ before_send: stats.before_send,
59
+ recortados: stats.trimmed,
60
+ internos: stats.internal,
61
+ };
62
+ }
63
+
64
+ /** Solo para los tests. No sale por ninguna puerta del `exports` map. */
65
+ export function resetCounters(): void {
66
+ stats.fired = 0;
67
+ stats.completed = 0;
68
+ stats.failed = 0;
69
+ stats.before_send = 0;
70
+ stats.trimmed = 0;
71
+ stats.internal = 0;
72
+ }
@@ -0,0 +1,234 @@
1
+ import { LIMITS, SDK_NAME, SDK_VERSION } from "./constants.js";
2
+ import { countTrimmed, drops } from "./counters.js";
3
+ import { nextSeq, session } from "./session.js";
4
+ import type {
5
+ CaptureOptions,
6
+ Envelope,
7
+ Notify,
8
+ RetryInfo,
9
+ Severity,
10
+ Surface,
11
+ TelemetryEvent,
12
+ } from "./types.js";
13
+
14
+ /** El mismo truncado que aplica la ingesta del lado servidor. */
15
+ export function truncate(value: string, max: number): string {
16
+ return value.length <= max ? value : `${value.slice(0, max)}…[truncado]`;
17
+ }
18
+
19
+ function bytesOf(text: string): number {
20
+ // Se mide en bytes y no en caracteres, igual que la ingesta: un `é` ocupa 2 en UTF-8.
21
+ return new TextEncoder().encode(text).byteLength;
22
+ }
23
+
24
+ /** Deja las primeras 64 claves. Los valores ya son escalares por tipo, así que no hay nada que
25
+ * serializar del lado del cliente. */
26
+ export function capAttributes(
27
+ attrs: Record<string, string | number | boolean> | undefined,
28
+ ): Record<string, string | number | boolean> | undefined {
29
+ if (attrs === undefined) return undefined;
30
+ const entries = Object.entries(attrs).slice(0, LIMITS.attributeKeys);
31
+ return Object.fromEntries(entries);
32
+ }
33
+
34
+ function textOf(value: unknown): string {
35
+ try {
36
+ return typeof value === "string" ? value : (JSON.stringify(value) ?? String(value));
37
+ } catch {
38
+ // Un objeto con referencias circulares no puede hacer perder el evento.
39
+ return String(value);
40
+ }
41
+ }
42
+
43
+ /** Semántica de excepciones de OTel: type, message y stacktrace. */
44
+ export function extractException(error: unknown): TelemetryEvent["exception"] {
45
+ if (error instanceof Error) {
46
+ const output: NonNullable<TelemetryEvent["exception"]> = {
47
+ type: error.name,
48
+ message: error.message,
49
+ };
50
+ if (error.stack !== undefined) output.stacktrace = error.stack;
51
+ return output;
52
+ }
53
+ // Varios repos de cliente lanzan cosas que no son Error; igual tienen que llegar legibles.
54
+ return { type: "UnknownError", message: textOf(error) };
55
+ }
56
+
57
+ const NEUTRAL = {
58
+ attempt: 1,
59
+ limit: 1,
60
+ is_final_attempt: true,
61
+ work_unit_id: null,
62
+ } as const;
63
+
64
+ /** Solo devuelve números donde el SDK REALMENTE los sabe. En `alarm` los maneja el repo, en
65
+ * `workflow` viven en el ctx del step y en `queue` en el mensaje: ahí se omite el bloque, porque
66
+ * un valor inventado silencia la alerta terminal. */
67
+ export function retryForSurface(surface: Surface): TelemetryEvent["retry"] | undefined {
68
+ switch (surface) {
69
+ case "worker":
70
+ case "durable_object":
71
+ case "cron":
72
+ return { ...NEUTRAL };
73
+ default:
74
+ return undefined;
75
+ }
76
+ }
77
+
78
+ // La ingesta exige `attempt`/`limit` >= 1: un 0 (o negativo, o no entero) pasado a mano por
79
+ // CaptureOptions se omite en vez de mandar un 400.
80
+ function positiveInteger(value: number | undefined): value is number {
81
+ return value !== undefined && Number.isInteger(value) && value >= 1;
82
+ }
83
+
84
+ /** Mapea los números de camelCase (API pública) a snake_case (contrato). */
85
+ export function retryFromOptions(info: RetryInfo): NonNullable<TelemetryEvent["retry"]> {
86
+ const output: NonNullable<TelemetryEvent["retry"]> = {};
87
+ if (positiveInteger(info.attempt)) output.attempt = info.attempt;
88
+ if (positiveInteger(info.limit)) output.limit = info.limit;
89
+ if (info.isFinalAttempt !== undefined) {
90
+ output.is_final_attempt = info.isFinalAttempt;
91
+ } else if (output.attempt !== undefined && output.limit !== undefined) {
92
+ // `>=` y nunca `>`: `limit` son intentos totales, así que con `>` la alerta terminal no
93
+ // se dispararía jamás.
94
+ output.is_final_attempt = output.attempt >= output.limit;
95
+ }
96
+ if (info.workUnitId !== undefined) output.work_unit_id = info.workUnitId;
97
+ return output;
98
+ }
99
+
100
+ export interface EventArgs {
101
+ kind: "error" | "event";
102
+ message: string | undefined;
103
+ exception: TelemetryEvent["exception"] | undefined;
104
+ agentId: string;
105
+ surface: Surface;
106
+ severityDefault: Severity;
107
+ options: CaptureOptions;
108
+ }
109
+
110
+ export function buildEvent(args: EventArgs): TelemetryEvent {
111
+ const { options } = args;
112
+
113
+ const event: TelemetryEvent = {
114
+ event_id: crypto.randomUUID(),
115
+ seq: nextSeq(),
116
+ timestamp: new Date().toISOString(),
117
+ type: args.kind,
118
+ severity: options.severity ?? args.severityDefault,
119
+ // El agentId de las opciones pisa el de la config: los workers multi-tenant no lo
120
+ // conocen cuando se arma el cliente. `||` y no `??`: el agentId de la config ya se
121
+ // validó no vacío, así que un "" del caller (fila de D1 con NULL) no puede ganarle.
122
+ context: { agent_id: options.agentId || args.agentId },
123
+ };
124
+
125
+ if (args.message !== undefined) {
126
+ event.message = truncate(args.message, LIMITS.messageChars);
127
+ }
128
+ if (options.workUnit !== undefined) event.context.work_unit = options.workUnit;
129
+ if (options.traceId !== undefined) event.context.trace_id = options.traceId;
130
+ if (options.conversationId !== undefined) {
131
+ event.context.conversation_id = options.conversationId;
132
+ }
133
+ if (options.requestId !== undefined) event.context.request_id = options.requestId;
134
+
135
+ if (args.exception !== undefined) {
136
+ const exception = { ...args.exception };
137
+ if (exception.stacktrace !== undefined) {
138
+ exception.stacktrace = truncate(exception.stacktrace, LIMITS.stacktraceChars);
139
+ }
140
+ // La ingesta no trunca este campo, pero es el mismo texto que `message` y dejarlo suelto
141
+ // hace que un mensaje enorme se coma el tope de bytes del sobre.
142
+ if (exception.message !== undefined) {
143
+ exception.message = truncate(exception.message, LIMITS.messageChars);
144
+ }
145
+ event.exception = exception;
146
+ }
147
+
148
+ const retry =
149
+ options.retry !== undefined ? retryFromOptions(options.retry) : retryForSurface(args.surface);
150
+ if (retry !== undefined) event.retry = retry;
151
+
152
+ const attrs = capAttributes(options.attributes);
153
+ if (attrs !== undefined) event.attributes = attrs;
154
+
155
+ // Si va, la ingesta lo usa tal cual en vez de calcular la huella.
156
+ if (options.fingerprint !== undefined) event.fingerprint = options.fingerprint;
157
+
158
+ return event;
159
+ }
160
+
161
+ export interface EnvelopeArgs {
162
+ event: TelemetryEvent;
163
+ service: { name: string; version?: string; environment?: string };
164
+ organizationId: string;
165
+ surface: Surface;
166
+ notify: Notify;
167
+ }
168
+
169
+ /** Un sobre por captura, sin batching: el caso es 1 error por invocación, y batchear exigiría un
170
+ * punto de flush, que es justo donde se pierde data. */
171
+ export function buildEnvelope(args: EnvelopeArgs): Envelope {
172
+ return {
173
+ sdk: { name: SDK_NAME, version: SDK_VERSION },
174
+ sent_at: new Date().toISOString(),
175
+ // El spread arma un objeto fresco: `Drops` es una interfaz sin índice y TypeScript no la
176
+ // deja pasar directo como `Record<string, number>` (el tipo del sobre, más permisivo a propósito).
177
+ drops: { ...drops() },
178
+ // Perezoso: la primera captura es la que genera el id del isolate.
179
+ session: session(),
180
+ resource: {
181
+ service: args.service,
182
+ client: { organization_id: args.organizationId },
183
+ surface: args.surface,
184
+ },
185
+ notify: args.notify,
186
+ events: [args.event],
187
+ };
188
+ }
189
+
190
+ /** Recorta el sobre hasta que entre en el tope de bytes. NUNCA descarta el evento: un error con
191
+ * stacktrace enorme sigue siendo un error que hay que reportar. Muta el sobre, que es
192
+ * recién armado y de este módulo. */
193
+ export function serializeCapped(envelope: Envelope): { body: string; trimmed: boolean } {
194
+ let body = JSON.stringify(envelope);
195
+ if (bytesOf(body) <= LIMITS.bodyBytes) return { body, trimmed: false };
196
+
197
+ const event = envelope.events[0];
198
+ // En orden de "lo más grande y lo menos valioso" primero.
199
+ const steps: Array<() => void> = [
200
+ () => {
201
+ if (event.exception?.stacktrace !== undefined) {
202
+ event.exception.stacktrace = truncate(event.exception.stacktrace, 1024);
203
+ }
204
+ },
205
+ () => {
206
+ if (event.exception !== undefined) delete event.exception.stacktrace;
207
+ },
208
+ () => {
209
+ if (event.attributes !== undefined) event.attributes = {};
210
+ },
211
+ () => {
212
+ if (event.message !== undefined) event.message = truncate(event.message, 256);
213
+ },
214
+ ];
215
+
216
+ for (const step of steps) {
217
+ step();
218
+ body = JSON.stringify(envelope);
219
+ if (bytesOf(body) <= LIMITS.bodyBytes) break;
220
+ }
221
+
222
+ // No cambia la política —no se descarta el evento, no se agregan pasos—, solo deja de ser
223
+ // mudo: el exceso vive en un campo que ningún paso toca (`fingerprint`, un identificador
224
+ // gigantesco), y la ingesta lo va a rechazar con 413 (docs/telemetry/troubleshooting.md).
225
+ const finalBytes = bytesOf(body);
226
+ if (finalBytes > LIMITS.bodyBytes) {
227
+ console.error(
228
+ `[delta-sdk] el sobre sigue arriba del tope de ${LIMITS.bodyBytes} bytes después de recortar (${finalBytes} bytes); la ingesta lo va a rechazar con 413`,
229
+ );
230
+ }
231
+
232
+ countTrimmed();
233
+ return { body, trimmed: true };
234
+ }