@laburen/delta-sdk 1.0.0

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 (78) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +133 -0
  4. package/dist/core/config.d.ts +44 -0
  5. package/dist/core/config.d.ts.map +1 -0
  6. package/dist/core/config.js +163 -0
  7. package/dist/core/config.js.map +1 -0
  8. package/dist/core/constantes.d.ts +15 -0
  9. package/dist/core/constantes.d.ts.map +1 -0
  10. package/dist/core/constantes.js +15 -0
  11. package/dist/core/constantes.js.map +1 -0
  12. package/dist/core/contadores.d.ts +28 -0
  13. package/dist/core/contadores.d.ts.map +1 -0
  14. package/dist/core/contadores.js +53 -0
  15. package/dist/core/contadores.js.map +1 -0
  16. package/dist/core/scrubbing.d.ts +10 -0
  17. package/dist/core/scrubbing.d.ts.map +1 -0
  18. package/dist/core/scrubbing.js +92 -0
  19. package/dist/core/scrubbing.js.map +1 -0
  20. package/dist/core/sesion.d.ts +9 -0
  21. package/dist/core/sesion.d.ts.map +1 -0
  22. package/dist/core/sesion.js +20 -0
  23. package/dist/core/sesion.js.map +1 -0
  24. package/dist/core/sobre.d.ts +46 -0
  25. package/dist/core/sobre.d.ts.map +1 -0
  26. package/dist/core/sobre.js +200 -0
  27. package/dist/core/sobre.js.map +1 -0
  28. package/dist/core/tipos.d.ts +154 -0
  29. package/dist/core/tipos.d.ts.map +1 -0
  30. package/dist/core/tipos.js +6 -0
  31. package/dist/core/tipos.js.map +1 -0
  32. package/dist/core/transporte.d.ts +24 -0
  33. package/dist/core/transporte.d.ts.map +1 -0
  34. package/dist/core/transporte.js +70 -0
  35. package/dist/core/transporte.js.map +1 -0
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +2 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/telemetry/captura.d.ts +8 -0
  41. package/dist/telemetry/captura.d.ts.map +1 -0
  42. package/dist/telemetry/captura.js +136 -0
  43. package/dist/telemetry/captura.js.map +1 -0
  44. package/dist/telemetry/index.d.ts +5 -0
  45. package/dist/telemetry/index.d.ts.map +1 -0
  46. package/dist/telemetry/index.js +3 -0
  47. package/dist/telemetry/index.js.map +1 -0
  48. package/dist/telemetry/tipos.d.ts +2 -0
  49. package/dist/telemetry/tipos.d.ts.map +1 -0
  50. package/dist/telemetry/tipos.js +2 -0
  51. package/dist/telemetry/tipos.js.map +1 -0
  52. package/dist/telemetry/with-telemetry.d.ts +18 -0
  53. package/dist/telemetry/with-telemetry.d.ts.map +1 -0
  54. package/dist/telemetry/with-telemetry.js +81 -0
  55. package/dist/telemetry/with-telemetry.js.map +1 -0
  56. package/dist/telemetry/with-tool.d.ts +9 -0
  57. package/dist/telemetry/with-tool.d.ts.map +1 -0
  58. package/dist/telemetry/with-tool.js +20 -0
  59. package/dist/telemetry/with-tool.js.map +1 -0
  60. package/docs/que-se-manda.md +133 -0
  61. package/docs/superficies.md +239 -0
  62. package/docs/telemetria.md +258 -0
  63. package/docs/troubleshooting.md +115 -0
  64. package/package.json +61 -0
  65. package/src/core/config.ts +178 -0
  66. package/src/core/constantes.ts +17 -0
  67. package/src/core/contadores.ts +71 -0
  68. package/src/core/scrubbing.ts +104 -0
  69. package/src/core/sesion.ts +22 -0
  70. package/src/core/sobre.ts +236 -0
  71. package/src/core/tipos.ts +131 -0
  72. package/src/core/transporte.ts +93 -0
  73. package/src/index.ts +7 -0
  74. package/src/telemetry/captura.ts +161 -0
  75. package/src/telemetry/index.ts +16 -0
  76. package/src/telemetry/tipos.ts +13 -0
  77. package/src/telemetry/with-telemetry.ts +128 -0
  78. package/src/telemetry/with-tool.ts +23 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Changelog
2
+
3
+ Formato: [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/).
4
+ El paquete es **additive-only**: se agregan funciones y campos opcionales, nunca se renombra ni se
5
+ saca nada. Un worker que se queda en una versión vieja sigue funcionando.
6
+
7
+ ## [1.0.0] — 2026-08-03
8
+
9
+ Primera versión.
10
+
11
+ ### Agregado
12
+
13
+ - Puerta `@laburen/delta-sdk/telemetry` con `createTelemetry`, `withTelemetry` y, en el cliente,
14
+ `captureException`, `captureEvent` y `withTool`.
15
+ - Transporte a `telemetry.laburen.com/events`, sin reintentos, contando lo que se pierde en el
16
+ campo `drops` del sobre.
17
+ - `session` + `seq` para que la ingesta pueda detectar eventos perdidos.
18
+ - Scrubbing por denylist, términos propios vía `scrub`, y `beforeSend` como escape hatch.
19
+ - Tipos que hacen que una config de `notify` inválida no compile.
20
+ - Chequeo en runtime del `ctx`: si tiene `waitUntil` pero no es invocable, avisa una vez y explica
21
+ cómo arreglarlo.
22
+ - Puerta raíz `@laburen/delta-sdk` con los tipos compartidos.
23
+
24
+ ### Hay que hacer algo
25
+
26
+ Nada: es la primera versión. Para adoptarlo en un worker, leé el README y `docs/telemetria.md` —
27
+ en particular la sección de los cuatro estados del código existente, porque **el grueso del
28
+ trabajo suele ser `captureException` a mano dentro de los `catch` que ya existen**, y no envolver
29
+ con los wrappers.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Laburen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # @laburen/delta-sdk
2
+
3
+ *Sirve para cualquier worker, MCP o workflow de Cloudflare.
4
+
5
+ Le manda los errores de tu worker a la ingesta de telemetría (`telemetry.laburen.com`), que los
6
+ guarda en D1 y avisa por Slack al canal del cliente.
7
+
8
+ ```bash
9
+ npm i @laburen/delta-sdk
10
+ ```
11
+
12
+ Necesitás una API key en el env del worker, como **secret** y nunca como `var`:
13
+
14
+ ```bash
15
+ wrangler secret put LABUREN_TELEMETRY_KEY
16
+ ```
17
+
18
+ ## Lo que tenés que saber antes de empezar
19
+
20
+ - **`captureException` nunca lanza y no se puede `await`.** Un cliente de telemetría no puede
21
+ romper la app que observa.
22
+ - **No hay reintentos.** Si la ingesta está caída, el evento se descarta y se cuenta.
23
+ - **Los wrappers solo ven lo que ESCAPA de la función que envuelven.** Si tu `catch` loguea y
24
+ devuelve un valor, el wrapper no se entera. Ver [docs/telemetria.md](docs/telemetria.md).
25
+ - **Pasale el `ctx` original del handler**, no una copia hecha con spread. Ver
26
+ [docs/troubleshooting.md](docs/troubleshooting.md).
27
+
28
+ ## Caso 1 — MCP en un Durable Object (el 80% del uso)
29
+
30
+ ```ts
31
+ import { createTelemetry } from "@laburen/delta-sdk/telemetry";
32
+
33
+ export class MiAgenteMCP extends McpAgent<Env> {
34
+ server = new McpServer({ name: "mi-mcp", version: "1.0.0" });
35
+
36
+ async init() {
37
+ const telemetry = createTelemetry({
38
+ service: { name: "mi-mcp", version: "1.0.0", environment: this.env.ENVIRONMENT },
39
+ surface: "durable_object",
40
+ organizationId: this.env.MI_ORGANIZATION_ID,
41
+ agentId: this.env.MI_AGENT_ID,
42
+ apiKey: this.env.LABUREN_TELEMETRY_KEY,
43
+ notify: { slack: { enabled: true, channel: this.env.MI_SLACK_CHANNEL_ID } },
44
+ ctx: this.ctx,
45
+ });
46
+
47
+ // La tool que NO atrapa su error: la envolvés y listo.
48
+ this.server.registerTool("MiTool", schema,
49
+ telemetry.withTool("MiTool", async (args) => {
50
+ const token = await renovarToken(); // si lanza: se captura Y se re-lanza
51
+ return await hacerAlgo(args, token);
52
+ }),
53
+ );
54
+
55
+ // La tool que SÍ atrapa su error: sumás una línea adentro del catch que ya tenés.
56
+ this.server.registerTool("OtraTool", schema, async (args) => {
57
+ try {
58
+ return await hacerOtraCosa(args);
59
+ } catch (error) {
60
+ telemetry.captureException(error, { workUnit: "OtraTool" }); // ← lo único nuevo
61
+ return { content: [{ type: "text", text: `Ocurrió un error: ${error.message}` }], isError: true };
62
+ }
63
+ });
64
+ }
65
+ }
66
+ ```
67
+
68
+ > **`createTelemetry` va DENTRO de `init()`, nunca a nivel de módulo.** Un valor aleatorio generado
69
+ > en el scope global hace fallar el deploy con *"Disallowed operation called within global scope"*,
70
+ > y `wrangler dev` local **no lo detecta**.
71
+
72
+ ## Caso 2 — Worker plano, cola y cron
73
+
74
+ ```ts
75
+ import { withTelemetry } from "@laburen/delta-sdk/telemetry";
76
+
77
+ export default withTelemetry(
78
+ (env: Env) => ({
79
+ service: { name: "mi-worker", version: "1.0.0" },
80
+ organizationId: env.MI_ORGANIZATION_ID,
81
+ agentId: env.MI_AGENT_ID,
82
+ apiKey: env.LABUREN_TELEMETRY_KEY,
83
+ notify: { slack: { enabled: true, channel: env.MI_SLACK_CHANNEL_ID } },
84
+ queueMaxRetries: 3, // el MISMO número del wrangler.jsonc, sin sumarle 1
85
+ }),
86
+ {
87
+ async fetch(req, env, ctx) { /* ... */ }, // → surface "worker"
88
+ async queue(batch, env, ctx) { /* ... */ }, // → surface "queue"
89
+ async scheduled(ctrl, env, ctx) { /* ... */ }, // → surface "cron"
90
+ },
91
+ );
92
+ ```
93
+
94
+ La config **no lleva `surface`**: se deduce del nombre del handler, y pasarla no compila.
95
+
96
+ > **Los nombres de las env var no están estandarizados entre proyectos.** Abrí tu `env.d.ts` antes
97
+ > de copiar los nombres: no asumas que son los mismos que en otro worker.
98
+
99
+ ## Caso 3 — Un error que nunca fue una excepción
100
+
101
+ Es el caso más común en los repos que ya existen: `if (!res.ok) { log; return null }`. No hay nada
102
+ que pasarle a `captureException`, así que va `captureEvent`.
103
+
104
+ ```ts
105
+ if (!res.ok) {
106
+ telemetry.captureEvent("mi-integracion: crearTicket devolvió no-2xx", {
107
+ workUnit: "crear-ticket",
108
+ attributes: { status: res.status, ticket_id: ticketId }, // ← los ids van ACÁ
109
+ });
110
+ return null;
111
+ }
112
+ ```
113
+
114
+ **El `message` va sin interpolar ids.** Si el mensaje lleva `ticket:157249`, cada ocurrencia genera
115
+ un grupo nuevo y el dedup de la ingesta no sirve.
116
+
117
+ ## Documentación
118
+
119
+ | Archivo | Para qué |
120
+ |---|---|
121
+ | [docs/telemetria.md](docs/telemetria.md) | la guía larga: config campo por campo, `CaptureOptions`, scrubbing, `beforeSend` |
122
+ | [docs/superficies.md](docs/superficies.md) | qué cambia entre worker, durable object, workflow, queue, alarm y cron |
123
+ | [docs/que-se-manda.md](docs/que-se-manda.md) | el contrato en prosa, con un payload de ejemplo |
124
+ | [docs/troubleshooting.md](docs/troubleshooting.md) | "no llega nada", error 1042, 401, 413, "el worker no deploya" |
125
+
126
+ El TypeScript real está en `node_modules/@laburen/delta-sdk/src/`: si algo no cierra, se lee.
127
+
128
+ ## Versionado
129
+
130
+ El paquete es **additive-only**: se agregan funciones y campos opcionales, nunca se renombra ni se
131
+ saca nada. Un worker que se queda en `1.2.0` tres años **sigue funcionando**. En la práctica el
132
+ paquete vive en `1.x` y los bumps son `minor` y `patch`. El [CHANGELOG](CHANGELOG.md) dice, en cada
133
+ entrada, **qué cambió y si hay que hacer algo**.
@@ -0,0 +1,44 @@
1
+ import { type Notify, type Surface, type TelemetryConfig, type TelemetryEvent } from "./tipos.js";
2
+ export interface ConfigValidada {
3
+ service: {
4
+ name: string;
5
+ version?: string;
6
+ environment?: string;
7
+ };
8
+ surface: Surface;
9
+ organizationId: string;
10
+ agentId: string;
11
+ apiKey: string;
12
+ notify: Notify;
13
+ ingestUrl: string;
14
+ scrub: string[];
15
+ beforeSend?: (evento: TelemetryEvent) => TelemetryEvent | null;
16
+ debug: boolean;
17
+ queueMaxRetries?: number;
18
+ }
19
+ export type ResultadoConfig = {
20
+ ok: true;
21
+ config: ConfigValidada;
22
+ } | {
23
+ ok: false;
24
+ faltan: string[];
25
+ };
26
+ /** El motivo por el que `notify` no es usable, o `null` si lo es. Dos reglas, no una: (a) un canal
27
+ * DECLARADO (`enabled: true`) pero incompleto invalida TODA la config, aunque el otro canal esté
28
+ * bien — antes esto era un `||`, y un slack roto con un email bueno pasaba la validación porque el
29
+ * email "salvaba" el OR; la ingesta igual rechazaba el sobre por `slack.channel`, un 400 mudo que
30
+ * el SDK nunca llegaba a ver; (b) al menos un canal tiene que estar completo. Nunca lanza: un
31
+ * `notify` armado con un getter o un `Proxy` que lanza al leer sus propiedades cuenta como "no
32
+ * usable", no como una excepción que se escapa de `createTelemetry` — el SDK no lanza nunca, ni
33
+ * con el notify más raro. */
34
+ export declare function motivoNotifyInvalido(notify: unknown): string | null;
35
+ /** Wrapper booleano de `motivoNotifyInvalido`, para los callers que solo necesitan saber si el
36
+ * `notify` sirve (el override por evento de `captura.ts`) sin mostrar el motivo. */
37
+ export declare function notifyUsable(notify: unknown): boolean;
38
+ /** Un `queueMaxRetries` usable es un entero ≥ 0: sale del `max_retries` del `wrangler.jsonc` vía
39
+ * una `var` del env, que siempre es `string` — `"2" + 1` da `"21"`, no `3`. */
40
+ export declare function queueMaxRetriesUsable(valor: unknown): valor is number;
41
+ /** Valida en runtime lo que el tipo no puede: un campo que llega vacío desde el env es un string
42
+ * válido para TypeScript, y significa que ese worker nunca va a reportar nada. */
43
+ export declare function validar(entrada: TelemetryConfig): ResultadoConfig;
44
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/core/config.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,MAAM,EAEX,KAAK,OAAO,EACZ,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAClE,OAAO,EAAE,OAAO,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,MAAM,EAAE,cAAc,KAAK,cAAc,GAAG,IAAI,CAAC;IAC/D,KAAK,EAAE,OAAO,CAAC;IACf,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,eAAe,GACxB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,cAAc,CAAA;CAAE,GACpC;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAsEnC;;;;;;;8BAO8B;AAC9B,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAiBnE;AAED;qFACqF;AACrF,wBAAgB,YAAY,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAErD;AAED;gFACgF;AAChF,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAErE;AAED;mFACmF;AACnF,wBAAgB,OAAO,CAAC,OAAO,EAAE,eAAe,GAAG,eAAe,CAyCjE"}
@@ -0,0 +1,163 @@
1
+ import { INGEST_URL } from "./constantes.js";
2
+ import { SURFACES, } from "./tipos.js";
3
+ // Los `?.` no son paranoia: los valores salen del env del worker, y ahí TypeScript no manda.
4
+ function vacio(valor) {
5
+ return typeof valor !== "string" || valor.trim() === "";
6
+ }
7
+ // Mismo criterio que `textoDe` en sobre.ts: un aviso no puede lanzar por describir el valor que
8
+ // está avisando. `JSON.stringify` no sabe serializar un `BigInt` (un `queueMaxRetries` armado con
9
+ // uno lo hace lanzar), así que cae a `String()` en vez de romper el aviso.
10
+ function describirValor(valor) {
11
+ try {
12
+ return JSON.stringify(valor) ?? String(valor);
13
+ }
14
+ catch {
15
+ return String(valor);
16
+ }
17
+ }
18
+ // El mismo regex que aplica la ingesta: el contrato ya está duplicado a propósito, así que
19
+ // copiarlo acá es coherente.
20
+ const SLACK_CHANNEL_ID = /^[CGD][A-Z0-9]{8,}$/;
21
+ // Objetos sueltos porque vienen de un `unknown` en runtime (env, fila de D1): no se puede confiar
22
+ // en que respeten el tipo `Notify` solo porque TypeScript los tipó así en el archivo del cliente.
23
+ // "sinDeclarar" es un canal AUSENTE (la clave `slack`/`email` no está, o `enabled` es `false`); un
24
+ // canal PRESENTE cuyo `enabled` es truthy pero no un booleano estricto (un `1` de una columna
25
+ // INTEGER de D1 usada como boolean, el mismo patrón que ya cita `emailPlausible` más abajo) es
26
+ // "incompleto", no "sinDeclarar": la ingesta valida `enabled` con un union discriminado entre los
27
+ // literales `true`/`false`, y cualquier otro valor le rompe el discriminante — `notify` sale crudo
28
+ // al sobre si el OTRO canal es válido, y la ingesta lo rechaza con "Invalid discriminator value"
29
+ // mientras el SDK cree que la config está sana.
30
+ function estadoSlack(slack) {
31
+ if (typeof slack !== "object" || slack === null)
32
+ return "sinDeclarar";
33
+ const valor = slack;
34
+ if (typeof valor.enabled !== "boolean")
35
+ return "incompleto";
36
+ if (valor.enabled === false)
37
+ return "sinDeclarar";
38
+ return typeof valor.channel === "string" && SLACK_CHANNEL_ID.test(valor.channel)
39
+ ? "completo"
40
+ : "incompleto";
41
+ }
42
+ /** Deliberadamente MÁS PERMISIVO que el `z.email()` de la ingesta (verificado con un fuzz test en
43
+ * `test/config.test.ts` que compara contra el Zod real): atrapa la basura obvia —sin `@`, con
44
+ * espacios o comas, sin un dominio con punto— y nada más. Quedar más estricto que la ingesta es
45
+ * peor que el 400 mudo que este archivo cierra: una dirección real rechazada acá manda TODO el
46
+ * worker a inerte, no solo ese evento. */
47
+ function emailPlausible(valor) {
48
+ if (typeof valor !== "string" || valor === "" || valor.trim() !== valor)
49
+ return false;
50
+ if (/\s/.test(valor) || valor.includes(","))
51
+ return false;
52
+ const arroba = valor.indexOf("@");
53
+ if (arroba <= 0 || arroba !== valor.lastIndexOf("@"))
54
+ return false;
55
+ const dominio = valor.slice(arroba + 1);
56
+ if (dominio === "" || !dominio.includes("."))
57
+ return false;
58
+ return !dominio.startsWith(".") && !dominio.endsWith(".");
59
+ }
60
+ function estadoEmail(email) {
61
+ if (typeof email !== "object" || email === null)
62
+ return "sinDeclarar";
63
+ const valor = email;
64
+ // Mismo criterio que `estadoSlack`: un `enabled` truthy pero no booleano estricto es
65
+ // "incompleto", no "sinDeclarar".
66
+ if (typeof valor.enabled !== "boolean")
67
+ return "incompleto";
68
+ if (valor.enabled === false)
69
+ return "sinDeclarar";
70
+ return Array.isArray(valor.to) && valor.to.length > 0 && valor.to.every(emailPlausible)
71
+ ? "completo"
72
+ : "incompleto";
73
+ }
74
+ /** El motivo por el que `notify` no es usable, o `null` si lo es. Dos reglas, no una: (a) un canal
75
+ * DECLARADO (`enabled: true`) pero incompleto invalida TODA la config, aunque el otro canal esté
76
+ * bien — antes esto era un `||`, y un slack roto con un email bueno pasaba la validación porque el
77
+ * email "salvaba" el OR; la ingesta igual rechazaba el sobre por `slack.channel`, un 400 mudo que
78
+ * el SDK nunca llegaba a ver; (b) al menos un canal tiene que estar completo. Nunca lanza: un
79
+ * `notify` armado con un getter o un `Proxy` que lanza al leer sus propiedades cuenta como "no
80
+ * usable", no como una excepción que se escapa de `createTelemetry` — el SDK no lanza nunca, ni
81
+ * con el notify más raro. */
82
+ export function motivoNotifyInvalido(notify) {
83
+ try {
84
+ if (typeof notify !== "object" || notify === null) {
85
+ return "notify (revisá slack.channel / email.to)";
86
+ }
87
+ const valor = notify;
88
+ const slack = estadoSlack(valor.slack);
89
+ const email = estadoEmail(valor.email);
90
+ if (slack === "incompleto")
91
+ return "notify: slack.channel declarado pero vacío o mal formado";
92
+ if (email === "incompleto")
93
+ return "notify: email.to declarado pero vacío o mal formado";
94
+ if (slack !== "completo" && email !== "completo") {
95
+ return "notify (revisá slack.channel / email.to)";
96
+ }
97
+ return null;
98
+ }
99
+ catch {
100
+ return "notify (no se pudo leer: revisá slack.channel / email.to)";
101
+ }
102
+ }
103
+ /** Wrapper booleano de `motivoNotifyInvalido`, para los callers que solo necesitan saber si el
104
+ * `notify` sirve (el override por evento de `captura.ts`) sin mostrar el motivo. */
105
+ export function notifyUsable(notify) {
106
+ return motivoNotifyInvalido(notify) === null;
107
+ }
108
+ /** Un `queueMaxRetries` usable es un entero ≥ 0: sale del `max_retries` del `wrangler.jsonc` vía
109
+ * una `var` del env, que siempre es `string` — `"2" + 1` da `"21"`, no `3`. */
110
+ export function queueMaxRetriesUsable(valor) {
111
+ return typeof valor === "number" && Number.isInteger(valor) && valor >= 0;
112
+ }
113
+ /** Valida en runtime lo que el tipo no puede: un campo que llega vacío desde el env es un string
114
+ * válido para TypeScript, y significa que ese worker nunca va a reportar nada. */
115
+ export function validar(entrada) {
116
+ const faltan = [];
117
+ if (vacio(entrada.service?.name))
118
+ faltan.push("service.name");
119
+ if (vacio(entrada.organizationId))
120
+ faltan.push("organizationId");
121
+ if (vacio(entrada.agentId))
122
+ faltan.push("agentId");
123
+ if (vacio(entrada.apiKey))
124
+ faltan.push("apiKey");
125
+ if (!SURFACES.includes(entrada.surface))
126
+ faltan.push("surface");
127
+ const motivoNotify = motivoNotifyInvalido(entrada.notify);
128
+ if (motivoNotify !== null)
129
+ faltan.push(motivoNotify);
130
+ if (faltan.length > 0)
131
+ return { ok: false, faltan };
132
+ const service = { name: entrada.service.name.trim() };
133
+ if (entrada.service.version !== undefined)
134
+ service.version = entrada.service.version;
135
+ if (entrada.service.environment !== undefined)
136
+ service.environment = entrada.service.environment;
137
+ const config = {
138
+ service,
139
+ surface: entrada.surface,
140
+ organizationId: entrada.organizationId.trim(),
141
+ agentId: entrada.agentId.trim(),
142
+ apiKey: entrada.apiKey.trim(),
143
+ notify: entrada.notify,
144
+ // La URL es constante del paquete; el override existe solo para desarrollo local.
145
+ ingestUrl: entrada.ingestUrl?.trim() || INGEST_URL,
146
+ scrub: entrada.scrub ?? [],
147
+ debug: entrada.debug ?? false,
148
+ };
149
+ if (entrada.beforeSend !== undefined)
150
+ config.beforeSend = entrada.beforeSend;
151
+ if (entrada.queueMaxRetries !== undefined) {
152
+ if (queueMaxRetriesUsable(entrada.queueMaxRetries)) {
153
+ config.queueMaxRetries = entrada.queueMaxRetries;
154
+ }
155
+ else {
156
+ // Se descarta y no se suma a `faltan`: a diferencia de los seis obligatorios, sin este
157
+ // dato el cliente sigue reportando — solo se omite `retry.limit` en surface "queue".
158
+ console.error(`[delta-sdk] queueMaxRetries inválido (se esperaba un entero ≥ 0, llegó ${describirValor(entrada.queueMaxRetries)}): se ignora`);
159
+ }
160
+ }
161
+ return { ok: true, config };
162
+ }
163
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/core/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAEN,QAAQ,GAIR,MAAM,YAAY,CAAC;AAoBpB,6FAA6F;AAC7F,SAAS,KAAK,CAAC,KAAc;IAC5B,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AAE;QAC1B,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,KAAK;KAC7B,CAAC;IACF,IAAI,OAAO,CAAC,UAAU,KAAK,SAAS;QAAE,MAAM,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IAC7E,IAAI,OAAO,CAAC,eAAe,KAAK,SAAS,EAAE,CAAC;QAC3C,IAAI,qBAAqB,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC;YACpD,MAAM,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAClD,CAAC;aAAM,CAAC;YACP,uFAAuF;YACvF,qFAAqF;YACrF,OAAO,CAAC,KAAK,CACZ,0EAA0E,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,cAAc,CAC/H,CAAC;QACH,CAAC;IACF,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC7B,CAAC"}
@@ -0,0 +1,15 @@
1
+ /** La ingesta es infraestructura, no config del cliente: si viviera en cada worker, cambiarla
2
+ * obligaría a editar y redeployar cada worker que la use. */
3
+ export declare const INGEST_URL = "https://telemetry.laburen.com/events";
4
+ export declare const SDK_NAME = "@laburen/delta-sdk";
5
+ /** Tiene que coincidir con `version` del package.json; lo verifica `npm run version:check`. */
6
+ export declare const SDK_VERSION = "1.0.0";
7
+ /** Los mismos topes que aplica la ingesta. El cliente los aplica para no perder el sobre entero;
8
+ * la ingesta, para no confiar en el cliente. */
9
+ export declare const LIMITES: {
10
+ readonly stacktraceChars: number;
11
+ readonly messageChars: number;
12
+ readonly attributeKeys: 64;
13
+ readonly bodyBytes: number;
14
+ };
15
+ //# sourceMappingURL=constantes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constantes.d.ts","sourceRoot":"","sources":["../../src/core/constantes.ts"],"names":[],"mappings":"AAAA;8DAC8D;AAC9D,eAAO,MAAM,UAAU,yCAAyC,CAAC;AAEjE,eAAO,MAAM,QAAQ,uBAAuB,CAAC;AAE7C,+FAA+F;AAC/F,eAAO,MAAM,WAAW,UAAU,CAAC;AAEnC;iDACiD;AACjD,eAAO,MAAM,OAAO;;;;;CAKV,CAAC"}
@@ -0,0 +1,15 @@
1
+ /** La ingesta es infraestructura, no config del cliente: si viviera en cada worker, cambiarla
2
+ * obligaría a editar y redeployar cada worker que la use. */
3
+ export const INGEST_URL = "https://telemetry.laburen.com/events";
4
+ export const SDK_NAME = "@laburen/delta-sdk";
5
+ /** Tiene que coincidir con `version` del package.json; lo verifica `npm run version:check`. */
6
+ export const SDK_VERSION = "1.0.0";
7
+ /** Los mismos topes que aplica la ingesta. El cliente los aplica para no perder el sobre entero;
8
+ * la ingesta, para no confiar en el cliente. */
9
+ export const LIMITES = {
10
+ stacktraceChars: 8 * 1024,
11
+ messageChars: 2 * 1024,
12
+ attributeKeys: 64,
13
+ bodyBytes: 512 * 1024,
14
+ };
15
+ //# sourceMappingURL=constantes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constantes.js","sourceRoot":"","sources":["../../src/core/constantes.ts"],"names":[],"mappings":"AAAA;8DAC8D;AAC9D,MAAM,CAAC,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAEjE,MAAM,CAAC,MAAM,QAAQ,GAAG,oBAAoB,CAAC;AAE7C,+FAA+F;AAC/F,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AAEnC;iDACiD;AACjD,MAAM,CAAC,MAAM,OAAO,GAAG;IACtB,eAAe,EAAE,CAAC,GAAG,IAAI;IACzB,YAAY,EAAE,CAAC,GAAG,IAAI;IACtB,aAAa,EAAE,EAAE;IACjB,SAAS,EAAE,GAAG,GAAG,IAAI;CACZ,CAAC"}
@@ -0,0 +1,28 @@
1
+ /** Lo que viaja en el campo `drops` del sobre. La ingesta lo acepta como
2
+ * `z.record(z.string(), z.number())`, así que las claves son libres; `before_send` conserva la
3
+ * grafía canónica de Sentry para las razones de drop. */
4
+ export interface Drops {
5
+ incompletos: number;
6
+ fallados: number;
7
+ before_send: number;
8
+ recortados: number;
9
+ internos: number;
10
+ }
11
+ /** Veces que el código pidió enviar. */
12
+ export declare function contarDisparado(): void;
13
+ /** Envíos que terminaron, con cualquier status: un 429 y un 503 salieron y los rechazaron. */
14
+ export declare function contarCompletado(): void;
15
+ /** Envíos que lanzaron: red, DNS. */
16
+ export declare function contarFallado(): void;
17
+ export declare function contarBeforeSend(): void;
18
+ export declare function contarRecortado(): void;
19
+ /** La quinta forma de perder un evento: algo entre `armarEvento` y `serializarAcotado` lanzó, y la
20
+ * red del `catch` de `capturar` lo atrapó. Sin este contador, ese evento desaparecía sin dejar
21
+ * rastro en ningún `drops` del sobre siguiente. */
22
+ export declare function contarInterno(): void;
23
+ /** `incompletos` es la resta, y es el único contador que prueba pérdida por ciclo de vida: sin
24
+ * esta separación, un 429 por rate limit y "se perdió el evento" se ven idénticos. */
25
+ export declare function drops(): Drops;
26
+ /** Solo para los tests. No sale por ninguna puerta del `exports` map. */
27
+ export declare function reiniciarContadores(): void;
28
+ //# sourceMappingURL=contadores.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contadores.d.ts","sourceRoot":"","sources":["../../src/core/contadores.ts"],"names":[],"mappings":"AAAA;;0DAE0D;AAC1D,MAAM,WAAW,KAAK;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;CACjB;AAWD,wCAAwC;AACxC,wBAAgB,eAAe,IAAI,IAAI,CAEtC;AAED,8FAA8F;AAC9F,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC;AAED,qCAAqC;AACrC,wBAAgB,aAAa,IAAI,IAAI,CAEpC;AAED,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC;AAED,wBAAgB,eAAe,IAAI,IAAI,CAEtC;AAED;;oDAEoD;AACpD,wBAAgB,aAAa,IAAI,IAAI,CAEpC;AAED;uFACuF;AACvF,wBAAgB,KAAK,IAAI,KAAK,CAQ7B;AAED,yEAAyE;AACzE,wBAAgB,mBAAmB,IAAI,IAAI,CAO1C"}
@@ -0,0 +1,53 @@
1
+ const stats = {
2
+ disparados: 0,
3
+ completados: 0,
4
+ fallados: 0,
5
+ before_send: 0,
6
+ recortados: 0,
7
+ internos: 0,
8
+ };
9
+ /** Veces que el código pidió enviar. */
10
+ export function contarDisparado() {
11
+ stats.disparados += 1;
12
+ }
13
+ /** Envíos que terminaron, con cualquier status: un 429 y un 503 salieron y los rechazaron. */
14
+ export function contarCompletado() {
15
+ stats.completados += 1;
16
+ }
17
+ /** Envíos que lanzaron: red, DNS. */
18
+ export function contarFallado() {
19
+ stats.fallados += 1;
20
+ }
21
+ export function contarBeforeSend() {
22
+ stats.before_send += 1;
23
+ }
24
+ export function contarRecortado() {
25
+ stats.recortados += 1;
26
+ }
27
+ /** La quinta forma de perder un evento: algo entre `armarEvento` y `serializarAcotado` lanzó, y la
28
+ * red del `catch` de `capturar` lo atrapó. Sin este contador, ese evento desaparecía sin dejar
29
+ * rastro en ningún `drops` del sobre siguiente. */
30
+ export function contarInterno() {
31
+ stats.internos += 1;
32
+ }
33
+ /** `incompletos` es la resta, y es el único contador que prueba pérdida por ciclo de vida: sin
34
+ * esta separación, un 429 por rate limit y "se perdió el evento" se ven idénticos. */
35
+ export function drops() {
36
+ return {
37
+ incompletos: stats.disparados - stats.completados - stats.fallados,
38
+ fallados: stats.fallados,
39
+ before_send: stats.before_send,
40
+ recortados: stats.recortados,
41
+ internos: stats.internos,
42
+ };
43
+ }
44
+ /** Solo para los tests. No sale por ninguna puerta del `exports` map. */
45
+ export function reiniciarContadores() {
46
+ stats.disparados = 0;
47
+ stats.completados = 0;
48
+ stats.fallados = 0;
49
+ stats.before_send = 0;
50
+ stats.recortados = 0;
51
+ stats.internos = 0;
52
+ }
53
+ //# sourceMappingURL=contadores.js.map
@@ -0,0 +1 @@
1
+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,GAAG,CAAC,CAAC;IACnB,KAAK,CAAC,WAAW,GAAG,CAAC,CAAC;IACtB,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC;IACrB,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC;AACpB,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { TelemetryEvent } from "./tipos.js";
2
+ export declare const REDACTADO = "[redactado]";
3
+ /** Los términos habituales en credenciales: claves, tokens y headers de autorización. */
4
+ export declare const DENYLIST: readonly ["secret", "token", "apikey", "api_key", "password", "authorization", "bearer", "cookie", "credential", "private_key"];
5
+ /** Devuelve una copia con la denylist y los términos del cliente aplicados. No muta la entrada:
6
+ * el evento original es el que ve el implementador si algo falla después. */
7
+ export declare function scrubEvento(evento: TelemetryEvent, extra?: string[]): TelemetryEvent;
8
+ /** El escape hatch. Un `null` descarta el evento; una excepción no puede hacerlo perder. */
9
+ export declare function aplicarBeforeSend(evento: TelemetryEvent, beforeSend: ((evento: TelemetryEvent) => TelemetryEvent | null) | undefined): TelemetryEvent | null;
10
+ //# sourceMappingURL=scrubbing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scrubbing.d.ts","sourceRoot":"","sources":["../../src/core/scrubbing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,eAAO,MAAM,SAAS,gBAAgB,CAAC;AAEvC,yFAAyF;AACzF,eAAO,MAAM,QAAQ,iIAWX,CAAC;AAwCX;8EAC8E;AAC9E,wBAAgB,WAAW,CAAC,MAAM,EAAE,cAAc,EAAE,KAAK,GAAE,MAAM,EAAO,GAAG,cAAc,CA+BxF;AAED,4FAA4F;AAC5F,wBAAgB,iBAAiB,CAChC,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,cAAc,KAAK,cAAc,GAAG,IAAI,CAAC,GAAG,SAAS,GACzE,cAAc,GAAG,IAAI,CAQvB"}
@@ -0,0 +1,92 @@
1
+ export const REDACTADO = "[redactado]";
2
+ /** Los términos habituales en credenciales: claves, tokens y headers de autorización. */
3
+ export const DENYLIST = [
4
+ "secret",
5
+ "token",
6
+ "apikey",
7
+ "api_key",
8
+ "password",
9
+ "authorization",
10
+ "bearer",
11
+ "cookie",
12
+ "credential",
13
+ "private_key",
14
+ ];
15
+ function escaparRegex(termino) {
16
+ return termino.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17
+ }
18
+ function claveSospechosa(clave, terminos) {
19
+ const bajo = clave.toLowerCase();
20
+ return terminos.some((termino) => bajo.includes(termino.toLowerCase()));
21
+ }
22
+ /** Es una red para descuidos, no una garantía: un secreto en un campo llamado `config` no lo
23
+ * agarra. La defensa real es no meter secretos en el mensaje de error.
24
+ *
25
+ * Dos reglas con alcance distinto a propósito. `clave: valor` / `clave=valor` es inequívoca —el
26
+ * separador ya dice "lo que sigue es un valor"— y por eso corre para la denylist completa. La
27
+ * regla sin separador, `clave valor`, es una apuesta: no hay forma de distinguir un valor real de
28
+ * la palabra siguiente de una frase, y la denylist completa aparece todo el tiempo en prosa
29
+ * común ("Token no disponible", "Password reset required"); aplicarla ahí mutila mensajes que no
30
+ * tenían ningún secreto. Con `bearer` la apuesta vale la pena porque el 100% de sus apariciones
31
+ * reales son un header sin dos puntos (`Bearer eyJ…`); con los términos que el propio cliente
32
+ * pasa por `scrub` también, porque ahí la agresividad es la que pidió explícitamente. */
33
+ function redactarTexto(texto, completa, agresivos) {
34
+ let salida = texto;
35
+ for (const termino of completa) {
36
+ const t = escaparRegex(termino);
37
+ // `clave: valor` y `clave=valor`: se borra el resto de la línea, porque el valor puede
38
+ // tener espacios (`Authorization: Bearer eyJ…`).
39
+ salida = salida.replace(new RegExp(`(${t})\\s*[:=]\\s*[^\\n]*`, "gi"), `$1: ${REDACTADO}`);
40
+ }
41
+ for (const termino of agresivos) {
42
+ const t = escaparRegex(termino);
43
+ // `clave valor`: solo el token que sigue, y solo para `bearer` y los términos del cliente
44
+ // (ver el comentario de arriba). No matchea una mención suelta al final de la frase, que
45
+ // no tiene nada detrás.
46
+ salida = salida.replace(new RegExp(`(${t})\\s+(\\S+)`, "gi"), `$1 ${REDACTADO}`);
47
+ }
48
+ return salida;
49
+ }
50
+ /** Devuelve una copia con la denylist y los términos del cliente aplicados. No muta la entrada:
51
+ * el evento original es el que ve el implementador si algo falla después. */
52
+ export function scrubEvento(evento, extra = []) {
53
+ const terminos = [...DENYLIST, ...extra];
54
+ // La regla sin separador solo corre para `bearer` (headers reales sin dos puntos) y lo que el
55
+ // cliente mismo eligió redactar así: el resto de la denylist es prosa común, no un valor.
56
+ const agresivos = ["bearer", ...extra];
57
+ const salida = { ...evento };
58
+ if (salida.message !== undefined) {
59
+ salida.message = redactarTexto(salida.message, terminos, agresivos);
60
+ }
61
+ if (salida.exception !== undefined) {
62
+ const excepcion = { ...salida.exception };
63
+ if (excepcion.message !== undefined) {
64
+ excepcion.message = redactarTexto(excepcion.message, terminos, agresivos);
65
+ }
66
+ if (excepcion.stacktrace !== undefined) {
67
+ excepcion.stacktrace = redactarTexto(excepcion.stacktrace, terminos, agresivos);
68
+ }
69
+ salida.exception = excepcion;
70
+ }
71
+ if (salida.attributes !== undefined) {
72
+ const atributos = {};
73
+ for (const [clave, valor] of Object.entries(salida.attributes)) {
74
+ atributos[clave] = claveSospechosa(clave, terminos) ? REDACTADO : valor;
75
+ }
76
+ salida.attributes = atributos;
77
+ }
78
+ return salida;
79
+ }
80
+ /** El escape hatch. Un `null` descarta el evento; una excepción no puede hacerlo perder. */
81
+ export function aplicarBeforeSend(evento, beforeSend) {
82
+ if (beforeSend === undefined)
83
+ return evento;
84
+ try {
85
+ return beforeSend(evento);
86
+ }
87
+ catch (error) {
88
+ console.error("[delta-sdk] beforeSend lanzó; el evento se manda sin aplicarlo", error);
89
+ return evento;
90
+ }
91
+ }
92
+ //# sourceMappingURL=scrubbing.js.map