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

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 +184 -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 +88 -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 +5181 -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 +661 -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 +225 -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 +84 -0
  125. package/src/platform/generated/types.ts +5181 -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
@@ -0,0 +1,30 @@
1
+ import { LaburenArgumentError } from "./core/errors.js";
2
+ import { PagePromise } from "./core/pagination.js";
3
+ import { createCall } from "./core/request.js";
4
+ import { buildResources } from "./generated/resources.js";
5
+ /** Los cursores que pasó quien llama; el que no se usó se descarta en cada pedido. */
6
+ function initialCursor(params) {
7
+ if (typeof params?.before_id === "string")
8
+ return { before_id: params.before_id };
9
+ if (typeof params?.after_id === "string")
10
+ return { after_id: params.after_id };
11
+ return {};
12
+ }
13
+ /**
14
+ * Crea el cliente de la puerta `/platform`. No hace ningún pedido al crearse: crealo adentro
15
+ * del handler, nunca en el scope global.
16
+ */
17
+ export function createPlatform(config) {
18
+ if (config.token === "")
19
+ throw new LaburenArgumentError("The token must not be empty.");
20
+ const request = createCall(config);
21
+ const call = (spec, pathValues, params, options) => {
22
+ if (!spec.paginated)
23
+ return request(spec, pathValues, params, options);
24
+ // `limit` y el resto de `params` se repiten en cada página; el cursor lo pone la paginación.
25
+ const { after_id: _after, before_id: _before, ...rest } = params ?? {};
26
+ return new PagePromise((cursor) => request(spec, pathValues, { ...rest, ...cursor }, options), initialCursor(params));
27
+ };
28
+ return buildResources(call);
29
+ }
30
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/platform/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAA8B,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAE,cAAc,EAA6B,MAAM,0BAA0B,CAAC;AAErF,sFAAsF;AACtF,SAAS,aAAa,CAAC,MAA2C;IACjE,IAAI,OAAO,MAAM,EAAE,SAAS,KAAK,QAAQ;QAAE,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC;IAClF,IAAI,OAAO,MAAM,EAAE,QAAQ,KAAK,QAAQ;QAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC;IAC/E,OAAO,EAAE,CAAC;AACX,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,MAAsB;IACpD,IAAI,MAAM,CAAC,KAAK,KAAK,EAAE;QAAE,MAAM,IAAI,oBAAoB,CAAC,8BAA8B,CAAC,CAAC;IACxF,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;IACnC,MAAM,IAAI,GAAS,CAAC,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE;QACxD,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,OAAO,OAAO,CAAC,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;QACvE,6FAA6F;QAC7F,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,IAAI,EAAE,CAAC;QACvE,OAAO,IAAI,WAAW,CACrB,CAAC,MAAM,EAAE,EAAE,CACV,OAAO,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,EAAE,EAAE,OAAO,CAA2B,EACrF,aAAa,CAAC,MAAM,CAAC,CACrB,CAAC;IACH,CAAC,CAAC;IACF,OAAO,cAAc,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC"}
@@ -0,0 +1,150 @@
1
+ import type { components } from "../generated/types.js";
2
+ /** Código del catálogo de la API; acepta cualquier string para que un código nuevo no rompa un SDK viejo. */
3
+ export type ErrorCode = components["schemas"]["Error"]["error"]["code"] | (string & {});
4
+ /** Familia del error; mismo criterio que `ErrorCode`. */
5
+ export type ErrorType = components["schemas"]["Error"]["error"]["type"] | (string & {});
6
+ declare const API_ERROR_BRAND: unique symbol;
7
+ declare const CONNECTION_ERROR_BRAND: unique symbol;
8
+ declare const TIMEOUT_ERROR_BRAND: unique symbol;
9
+ declare const ABORT_ERROR_BRAND: unique symbol;
10
+ declare const OAUTH_ERROR_BRAND: unique symbol;
11
+ declare const ARGUMENT_ERROR_BRAND: unique symbol;
12
+ /**
13
+ * Los valores de `details`, como los declara el contrato: una lista de ids (`agent_ids` de `resource_in_use`) llega como
14
+ * `string[]` y una lista de objetos (`agent_versions`) como `Array<Record<...>>`.
15
+ */
16
+ export type ErrorDetails = Record<string, string | number | boolean | null | string[] | Array<Record<string, string | number | boolean | null>>>;
17
+ type ErrorIssues = Array<{
18
+ field: string;
19
+ message: string;
20
+ }>;
21
+ /** Lo que hace falta para armar un error de la API a partir de una respuesta. */
22
+ export interface LaburenApiErrorInit {
23
+ status: number;
24
+ message: string;
25
+ type?: ErrorType | null;
26
+ code?: ErrorCode | null;
27
+ details?: ErrorDetails;
28
+ issues?: ErrorIssues;
29
+ requestId?: string | null;
30
+ shouldRetry?: boolean | null;
31
+ }
32
+ /** Error que devolvió la API (cualquier status no exitoso con cuerpo del catálogo o sin él). */
33
+ export declare class LaburenApiError extends Error {
34
+ readonly status: number;
35
+ readonly type: ErrorType | null;
36
+ readonly code: ErrorCode | null;
37
+ readonly details: ErrorDetails;
38
+ readonly issues: ErrorIssues;
39
+ readonly requestId: string | null;
40
+ readonly shouldRetry: boolean | null;
41
+ readonly [API_ERROR_BRAND]: true;
42
+ constructor(init: LaburenApiErrorInit);
43
+ }
44
+ /** 400: el pedido es inválido. */
45
+ export declare class InvalidRequestError extends LaburenApiError {
46
+ constructor(init: LaburenApiErrorInit);
47
+ }
48
+ /** 401: token faltante o inválido. */
49
+ export declare class AuthenticationError extends LaburenApiError {
50
+ constructor(init: LaburenApiErrorInit);
51
+ }
52
+ /** Sin créditos o problema de facturación. */
53
+ export declare class BillingError extends LaburenApiError {
54
+ constructor(init: LaburenApiErrorInit);
55
+ }
56
+ /** 403: el token no puede hacer esto. */
57
+ export declare class PermissionError extends LaburenApiError {
58
+ constructor(init: LaburenApiErrorInit);
59
+ }
60
+ /** 404: el recurso no existe. */
61
+ export declare class NotFoundError extends LaburenApiError {
62
+ constructor(init: LaburenApiErrorInit);
63
+ }
64
+ /** 409: choca con el estado actual del recurso. */
65
+ export declare class ConflictError extends LaburenApiError {
66
+ constructor(init: LaburenApiErrorInit);
67
+ }
68
+ /** 429: demasiados pedidos. */
69
+ export declare class RateLimitError extends LaburenApiError {
70
+ constructor(init: LaburenApiErrorInit);
71
+ }
72
+ /** 5xx: falló el servidor. */
73
+ export declare class ApiError extends LaburenApiError {
74
+ constructor(init: LaburenApiErrorInit);
75
+ }
76
+ /** Servicio sobrecargado o dependencia caída. */
77
+ export declare class OverloadedError extends LaburenApiError {
78
+ constructor(init: LaburenApiErrorInit);
79
+ }
80
+ /** No se pudo hablar con el servidor (red, DNS, corte). */
81
+ export declare class LaburenConnectionError extends Error {
82
+ readonly [CONNECTION_ERROR_BRAND]: true;
83
+ constructor(message: string, options?: {
84
+ cause?: unknown;
85
+ });
86
+ }
87
+ /** El servidor no contestó a tiempo. */
88
+ export declare class LaburenTimeoutError extends LaburenConnectionError {
89
+ readonly [TIMEOUT_ERROR_BRAND]: true;
90
+ constructor(message: string, options?: {
91
+ cause?: unknown;
92
+ });
93
+ }
94
+ /** El llamador cortó la operación con su `signal`; el motivo de la señal queda en `cause`. No es un problema de red. */
95
+ export declare class LaburenAbortError extends Error {
96
+ readonly [ABORT_ERROR_BRAND]: true;
97
+ constructor(options?: {
98
+ cause?: unknown;
99
+ });
100
+ }
101
+ /** El llamador pasó un argumento que no sirve (un id vacío, un token vacío); se lanza antes de mandar nada. */
102
+ export declare class LaburenArgumentError extends Error {
103
+ readonly [ARGUMENT_ERROR_BRAND]: true;
104
+ constructor(message: string);
105
+ }
106
+ /** Error del flujo OAuth (formato RFC 6749: `error` y `error_description`). */
107
+ export declare class LaburenOAuthError extends Error {
108
+ readonly error: string;
109
+ readonly description: string | null;
110
+ readonly status: number;
111
+ readonly [OAUTH_ERROR_BRAND]: true;
112
+ constructor(init: {
113
+ error: string;
114
+ description?: string | null;
115
+ status: number;
116
+ });
117
+ }
118
+ /** Dice si es un error de la API, también el de otra copia del paquete (por marca, no por `instanceof`). */
119
+ export declare function isLaburenApiError(value: unknown): value is LaburenApiError;
120
+ /** Dice si es un error de conexión (un timeout también lo es). */
121
+ export declare function isLaburenConnectionError(value: unknown): value is LaburenConnectionError;
122
+ /** Dice si es un error de timeout. */
123
+ export declare function isLaburenTimeoutError(value: unknown): value is LaburenTimeoutError;
124
+ /** Dice si es un error por haber abortado con `signal`. */
125
+ export declare function isLaburenAbortError(value: unknown): value is LaburenAbortError;
126
+ /** Dice si es un error por un argumento inválido. */
127
+ export declare function isLaburenArgumentError(value: unknown): value is LaburenArgumentError;
128
+ /** Dice si es un error de OAuth. */
129
+ export declare function isLaburenOAuthError(value: unknown): value is LaburenOAuthError;
130
+ /** Una versión de agente que bloquea el borrado de una skill o una conexión MCP (`details.agent_versions` de `resource_in_use`). */
131
+ export interface ResourceInUseVersion {
132
+ agent_id: string;
133
+ version_id: string;
134
+ is_active: boolean;
135
+ }
136
+ /**
137
+ * Las versiones de agente que bloquean el borrado, si `error` es un `resource_in_use`; en cualquier otro caso, una lista
138
+ * vacía. Descarta las entradas que no tienen la forma `{ agent_id, version_id, is_active }`, así el resultado se usa sin casts.
139
+ */
140
+ export declare function resourceInUseVersions(error: unknown): ResourceInUseVersion[];
141
+ /** Arma el error de la familia que dice `init.type`; un tipo que el SDK no conoce da el `LaburenApiError` base. */
142
+ export declare function apiErrorFromFamily(init: LaburenApiErrorInit): LaburenApiError;
143
+ /** Dice si `type` es una familia que el SDK conoce. */
144
+ export declare function isKnownErrorType(type: string | undefined): boolean;
145
+ /** Status que corresponde a la familia `type`; sin familia conocida, 500. */
146
+ export declare function statusForErrorType(type: string | undefined): number;
147
+ /** Arma el error tipado de una respuesta no exitosa; sin cuerpo del catálogo devuelve el base con `type` y `code` en null. */
148
+ export declare function apiErrorFromResponse(status: number, body: unknown, headers: Headers): LaburenApiError;
149
+ export {};
150
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/platform/core/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAExD,6GAA6G;AAC7G,MAAM,MAAM,SAAS,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wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,sBAAsB,CAExF;AACD,sCAAsC;AACtC,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAElF;AACD,2DAA2D;AAC3D,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB,CAE9E;AACD,qDAAqD;AACrD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,oBAAoB,CAEpF;AACD,oCAAoC;AACpC,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB,CAE9E;AAED,oIAAoI;AACpI,MAAM,WAAW,oBAAoB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;CACnB;AAWD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,oBAAoB,EAAE,CAI5E;AA2BD,mHAAmH;AACnH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,mBAAmB,GAAG,eAAe,CAM7E;AAeD,uDAAuD;AACvD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAElE;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAEnE;AAED,8HAA8H;AAC9H,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,OAAO,GACd,eAAe,CAmCjB"}
@@ -0,0 +1,265 @@
1
+ const API_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/api-error");
2
+ const CONNECTION_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/connection-error");
3
+ const TIMEOUT_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/timeout-error");
4
+ const ABORT_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/abort-error");
5
+ const OAUTH_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/oauth-error");
6
+ const ARGUMENT_ERROR_BRAND = Symbol.for("@laburen/delta-sdk/argument-error");
7
+ /** Error que devolvió la API (cualquier status no exitoso con cuerpo del catálogo o sin él). */
8
+ export class LaburenApiError extends Error {
9
+ status;
10
+ type;
11
+ code;
12
+ details;
13
+ issues;
14
+ requestId;
15
+ shouldRetry;
16
+ constructor(init) {
17
+ super(init.message);
18
+ this.name = "LaburenApiError";
19
+ this.status = init.status;
20
+ this.type = init.type ?? null;
21
+ this.code = init.code ?? null;
22
+ this.details = init.details ?? {};
23
+ this.issues = init.issues ?? [];
24
+ this.requestId = init.requestId ?? null;
25
+ this.shouldRetry = init.shouldRetry ?? null;
26
+ Object.defineProperty(this, API_ERROR_BRAND, { value: true });
27
+ }
28
+ }
29
+ /** 400: el pedido es inválido. */
30
+ export class InvalidRequestError extends LaburenApiError {
31
+ constructor(init) {
32
+ super(init);
33
+ this.name = "InvalidRequestError";
34
+ }
35
+ }
36
+ /** 401: token faltante o inválido. */
37
+ export class AuthenticationError extends LaburenApiError {
38
+ constructor(init) {
39
+ super(init);
40
+ this.name = "AuthenticationError";
41
+ }
42
+ }
43
+ /** Sin créditos o problema de facturación. */
44
+ export class BillingError extends LaburenApiError {
45
+ constructor(init) {
46
+ super(init);
47
+ this.name = "BillingError";
48
+ }
49
+ }
50
+ /** 403: el token no puede hacer esto. */
51
+ export class PermissionError extends LaburenApiError {
52
+ constructor(init) {
53
+ super(init);
54
+ this.name = "PermissionError";
55
+ }
56
+ }
57
+ /** 404: el recurso no existe. */
58
+ export class NotFoundError extends LaburenApiError {
59
+ constructor(init) {
60
+ super(init);
61
+ this.name = "NotFoundError";
62
+ }
63
+ }
64
+ /** 409: choca con el estado actual del recurso. */
65
+ export class ConflictError extends LaburenApiError {
66
+ constructor(init) {
67
+ super(init);
68
+ this.name = "ConflictError";
69
+ }
70
+ }
71
+ /** 429: demasiados pedidos. */
72
+ export class RateLimitError extends LaburenApiError {
73
+ constructor(init) {
74
+ super(init);
75
+ this.name = "RateLimitError";
76
+ }
77
+ }
78
+ /** 5xx: falló el servidor. */
79
+ export class ApiError extends LaburenApiError {
80
+ constructor(init) {
81
+ super(init);
82
+ this.name = "ApiError";
83
+ }
84
+ }
85
+ /** Servicio sobrecargado o dependencia caída. */
86
+ export class OverloadedError extends LaburenApiError {
87
+ constructor(init) {
88
+ super(init);
89
+ this.name = "OverloadedError";
90
+ }
91
+ }
92
+ /** No se pudo hablar con el servidor (red, DNS, corte). */
93
+ export class LaburenConnectionError extends Error {
94
+ constructor(message, options) {
95
+ super(message, options);
96
+ this.name = "LaburenConnectionError";
97
+ Object.defineProperty(this, CONNECTION_ERROR_BRAND, { value: true });
98
+ }
99
+ }
100
+ /** El servidor no contestó a tiempo. */
101
+ export class LaburenTimeoutError extends LaburenConnectionError {
102
+ constructor(message, options) {
103
+ super(message, options);
104
+ this.name = "LaburenTimeoutError";
105
+ Object.defineProperty(this, TIMEOUT_ERROR_BRAND, { value: true });
106
+ }
107
+ }
108
+ /** El llamador cortó la operación con su `signal`; el motivo de la señal queda en `cause`. No es un problema de red. */
109
+ export class LaburenAbortError extends Error {
110
+ constructor(options) {
111
+ super("Request was aborted.", options);
112
+ this.name = "LaburenAbortError";
113
+ Object.defineProperty(this, ABORT_ERROR_BRAND, { value: true });
114
+ }
115
+ }
116
+ /** El llamador pasó un argumento que no sirve (un id vacío, un token vacío); se lanza antes de mandar nada. */
117
+ export class LaburenArgumentError extends Error {
118
+ constructor(message) {
119
+ super(message);
120
+ this.name = "LaburenArgumentError";
121
+ Object.defineProperty(this, ARGUMENT_ERROR_BRAND, { value: true });
122
+ }
123
+ }
124
+ /** Error del flujo OAuth (formato RFC 6749: `error` y `error_description`). */
125
+ export class LaburenOAuthError extends Error {
126
+ error;
127
+ description;
128
+ status;
129
+ constructor(init) {
130
+ super(init.description ? `${init.error}: ${init.description}` : init.error);
131
+ this.name = "LaburenOAuthError";
132
+ this.error = init.error;
133
+ this.description = init.description ?? null;
134
+ this.status = init.status;
135
+ Object.defineProperty(this, OAUTH_ERROR_BRAND, { value: true });
136
+ }
137
+ }
138
+ function hasBrand(value, brand) {
139
+ return (typeof value === "object" &&
140
+ value !== null &&
141
+ value[brand] === true);
142
+ }
143
+ /** Dice si es un error de la API, también el de otra copia del paquete (por marca, no por `instanceof`). */
144
+ export function isLaburenApiError(value) {
145
+ return hasBrand(value, API_ERROR_BRAND);
146
+ }
147
+ /** Dice si es un error de conexión (un timeout también lo es). */
148
+ export function isLaburenConnectionError(value) {
149
+ return hasBrand(value, CONNECTION_ERROR_BRAND);
150
+ }
151
+ /** Dice si es un error de timeout. */
152
+ export function isLaburenTimeoutError(value) {
153
+ return hasBrand(value, TIMEOUT_ERROR_BRAND);
154
+ }
155
+ /** Dice si es un error por haber abortado con `signal`. */
156
+ export function isLaburenAbortError(value) {
157
+ return hasBrand(value, ABORT_ERROR_BRAND);
158
+ }
159
+ /** Dice si es un error por un argumento inválido. */
160
+ export function isLaburenArgumentError(value) {
161
+ return hasBrand(value, ARGUMENT_ERROR_BRAND);
162
+ }
163
+ /** Dice si es un error de OAuth. */
164
+ export function isLaburenOAuthError(value) {
165
+ return hasBrand(value, OAUTH_ERROR_BRAND);
166
+ }
167
+ function isResourceInUseVersion(value) {
168
+ if (!isRecord(value))
169
+ return false;
170
+ return (typeof value.agent_id === "string" &&
171
+ typeof value.version_id === "string" &&
172
+ typeof value.is_active === "boolean");
173
+ }
174
+ /**
175
+ * Las versiones de agente que bloquean el borrado, si `error` es un `resource_in_use`; en cualquier otro caso, una lista
176
+ * vacía. Descarta las entradas que no tienen la forma `{ agent_id, version_id, is_active }`, así el resultado se usa sin casts.
177
+ */
178
+ export function resourceInUseVersions(error) {
179
+ if (!isLaburenApiError(error) || error.code !== "resource_in_use")
180
+ return [];
181
+ const list = error.details.agent_versions;
182
+ return Array.isArray(list) ? list.filter(isResourceInUseVersion) : [];
183
+ }
184
+ const FAMILIES = {
185
+ invalid_request_error: InvalidRequestError,
186
+ authentication_error: AuthenticationError,
187
+ billing_error: BillingError,
188
+ permission_error: PermissionError,
189
+ not_found_error: NotFoundError,
190
+ conflict_error: ConflictError,
191
+ rate_limit_error: RateLimitError,
192
+ api_error: ApiError,
193
+ overloaded_error: OverloadedError,
194
+ };
195
+ function isRecord(value) {
196
+ return typeof value === "object" && value !== null && !Array.isArray(value);
197
+ }
198
+ function parseShouldRetry(headers) {
199
+ const raw = headers.get("x-should-retry");
200
+ if (raw === "true")
201
+ return true;
202
+ if (raw === "false")
203
+ return false;
204
+ return null;
205
+ }
206
+ /** Arma el error de la familia que dice `init.type`; un tipo que el SDK no conoce da el `LaburenApiError` base. */
207
+ export function apiErrorFromFamily(init) {
208
+ const Family = typeof init.type === "string" && Object.hasOwn(FAMILIES, init.type)
209
+ ? FAMILIES[init.type]
210
+ : LaburenApiError;
211
+ return new Family(init);
212
+ }
213
+ /** Status HTTP de cada familia (mismo mapa que usa la API); un type que el SDK no conoce da 500. */
214
+ const STATUS_BY_TYPE = {
215
+ invalid_request_error: 400,
216
+ authentication_error: 401,
217
+ billing_error: 402,
218
+ permission_error: 403,
219
+ not_found_error: 404,
220
+ conflict_error: 409,
221
+ rate_limit_error: 429,
222
+ api_error: 500,
223
+ overloaded_error: 529,
224
+ };
225
+ /** Dice si `type` es una familia que el SDK conoce. */
226
+ export function isKnownErrorType(type) {
227
+ return typeof type === "string" && Object.hasOwn(STATUS_BY_TYPE, type);
228
+ }
229
+ /** Status que corresponde a la familia `type`; sin familia conocida, 500. */
230
+ export function statusForErrorType(type) {
231
+ return isKnownErrorType(type) ? STATUS_BY_TYPE[type] : 500;
232
+ }
233
+ /** Arma el error tipado de una respuesta no exitosa; sin cuerpo del catálogo devuelve el base con `type` y `code` en null. */
234
+ export function apiErrorFromResponse(status, body, headers) {
235
+ const shouldRetry = parseShouldRetry(headers);
236
+ const headerRequestId = headers.get("request-id");
237
+ const inner = isRecord(body) ? body.error : undefined;
238
+ if (!isRecord(inner) ||
239
+ typeof inner.type !== "string" ||
240
+ typeof inner.code !== "string" ||
241
+ typeof inner.message !== "string") {
242
+ return new LaburenApiError({
243
+ status,
244
+ message: `Error response without the expected format (status ${status}).`,
245
+ requestId: headerRequestId,
246
+ shouldRetry,
247
+ });
248
+ }
249
+ const requestId = isRecord(body) && typeof body.request_id === "string" ? body.request_id : headerRequestId;
250
+ const init = {
251
+ status,
252
+ message: inner.message,
253
+ type: inner.type,
254
+ code: inner.code,
255
+ details: isRecord(inner.details) ? inner.details : {},
256
+ issues: Array.isArray(inner.issues) ? inner.issues : [],
257
+ requestId,
258
+ shouldRetry,
259
+ };
260
+ const Family = Object.hasOwn(FAMILIES, inner.type)
261
+ ? FAMILIES[inner.type]
262
+ : LaburenApiError;
263
+ return new Family(init);
264
+ }
265
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/platform/core/errors.ts"],"names":[],"mappings":"AAOA,MAAM,eAAe,GAAG,MAAM,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;AACnE,MAAM,sBAAsB,GAAG,MAAM,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;AACjF,MAAM,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAC3E,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;AACvE,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;AACvE,MAAM,oBAAoB,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AA6B7E,gGAAgG;AAChG,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAChC,MAAM,CAAS;IACf,IAAI,CAAmB;IACvB,IAAI,CAAmB;IACvB,OAAO,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AI,MAAM,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC"}
@@ -0,0 +1,37 @@
1
+ import type { components } from "../generated/types.js";
2
+ type Schemas = components["schemas"];
3
+ /** Opciones comunes de las funciones de login; ninguna lleva token ni reintenta. */
4
+ export interface OAuthCallOptions {
5
+ baseUrl?: string;
6
+ fetch?: typeof fetch;
7
+ signal?: AbortSignal;
8
+ /** Milisegundos por pedido (default 30 000); en `waitForDeviceToken` vale para cada consulta, no para la espera total. */
9
+ timeout?: number;
10
+ }
11
+ export interface StartDeviceLoginOptions extends OAuthCallOptions {
12
+ /** Texto libre (máx. 200) que la pantalla de aprobación le muestra a quien aprueba. */
13
+ clientInfo?: string;
14
+ }
15
+ export interface WaitForDeviceTokenOptions extends OAuthCallOptions {
16
+ deviceCode: string;
17
+ /** Segundos entre intentos, tal cual lo devolvió `startDeviceLogin`. */
18
+ interval: number;
19
+ /** Segundos de vida del código, tal cual lo devolvió `startDeviceLogin`. */
20
+ expiresIn: number;
21
+ }
22
+ export interface RefreshTokenOptions extends OAuthCallOptions {
23
+ refreshToken: string;
24
+ }
25
+ export interface RevokeTokenOptions extends OAuthCallOptions {
26
+ token: string;
27
+ }
28
+ /** Inicia el login por device code (RFC 8628): devuelve el código para que la persona apruebe en el navegador. */
29
+ export declare function startDeviceLogin(opts?: StartDeviceLoginOptions): Promise<Schemas["DeviceAuthorization"]>;
30
+ /** Consulta cada `interval` segundos hasta que la persona aprueba; corta con `LaburenOAuthError` si se deniega o vence. */
31
+ export declare function waitForDeviceToken(opts: WaitForDeviceTokenOptions): Promise<Schemas["OAuthToken"]>;
32
+ /** Cambia un refresh token por un access token nuevo. */
33
+ export declare function refreshToken(opts: RefreshTokenOptions): Promise<Schemas["OAuthToken"]>;
34
+ /** Revoca un access o refresh token (RFC 7009); la API siempre contesta 200. */
35
+ export declare function revokeToken(opts: RevokeTokenOptions): Promise<void>;
36
+ export {};
37
+ //# sourceMappingURL=oauth.d.ts.map
@@ -0,0 +1 @@
1
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AE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEzE"}
@@ -0,0 +1,144 @@
1
+ import { isLaburenConnectionError, isLaburenOAuthError, LaburenAbortError, LaburenConnectionError, LaburenOAuthError, LaburenTimeoutError, } from "./errors.js";
2
+ import { DEFAULT_BASE_URL } from "./send.js";
3
+ const DEFAULT_TIMEOUT_MS = 30_000;
4
+ const DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
5
+ /** RFC 8628: ante `slow_down` el intervalo sube 5 segundos. */
6
+ const SLOW_DOWN_STEP_SECONDS = 5;
7
+ function isRecord(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+ /** Manda un POST JSON sin `authorization`; un error de la API sale como `LaburenOAuthError`. */
11
+ async function postOAuth(path, body, opts) {
12
+ const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
13
+ const doFetch = opts.fetch ?? fetch;
14
+ const timeoutMs = opts.timeout ?? DEFAULT_TIMEOUT_MS;
15
+ const callerSignal = opts.signal;
16
+ // Un controller por pedido: junta el corte del llamador con el timeout propio.
17
+ const controller = new AbortController();
18
+ let timedOut = false;
19
+ const onCallerAbort = () => controller.abort(callerSignal?.reason);
20
+ if (callerSignal?.aborted)
21
+ controller.abort(callerSignal.reason);
22
+ callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
23
+ const timer = setTimeout(() => {
24
+ timedOut = true;
25
+ controller.abort();
26
+ }, timeoutMs);
27
+ let response;
28
+ let parsed;
29
+ try {
30
+ response = await doFetch(`${baseUrl}${path}`, {
31
+ method: "POST",
32
+ headers: { "content-type": "application/json", accept: "application/json" },
33
+ body: JSON.stringify(body),
34
+ signal: controller.signal,
35
+ });
36
+ try {
37
+ parsed = await response.json();
38
+ }
39
+ catch {
40
+ parsed = undefined;
41
+ }
42
+ }
43
+ catch (cause) {
44
+ // Si cortó el llamador, sale `LaburenAbortError` y no un error de red.
45
+ if (callerSignal?.aborted)
46
+ throw new LaburenAbortError({ cause: callerSignal.reason });
47
+ if (timedOut) {
48
+ throw new LaburenTimeoutError(`The login server did not respond within ${timeoutMs} ms.`, {
49
+ cause,
50
+ });
51
+ }
52
+ throw new LaburenConnectionError("Could not connect to the login server.", { cause });
53
+ }
54
+ finally {
55
+ clearTimeout(timer);
56
+ callerSignal?.removeEventListener("abort", onCallerAbort);
57
+ }
58
+ if (!response.ok) {
59
+ // Sin cuerpo RFC (proxy, HTML, corte) se lo trata como falla del servidor.
60
+ const error = isRecord(parsed) && typeof parsed.error === "string" ? parsed.error : "server_error";
61
+ const description = isRecord(parsed) && typeof parsed.error_description === "string"
62
+ ? parsed.error_description
63
+ : null;
64
+ throw new LaburenOAuthError({ error, description, status: response.status });
65
+ }
66
+ if (parsed === undefined) {
67
+ throw new LaburenOAuthError({
68
+ error: "server_error",
69
+ description: "The response is not JSON.",
70
+ status: response.status,
71
+ });
72
+ }
73
+ return parsed;
74
+ }
75
+ /** Inicia el login por device code (RFC 8628): devuelve el código para que la persona apruebe en el navegador. */
76
+ export function startDeviceLogin(opts = {}) {
77
+ const body = opts.clientInfo === undefined ? {} : { client_info: opts.clientInfo };
78
+ return postOAuth("/oauth/device", body, opts);
79
+ }
80
+ /** Espera `ms` milisegundos; si se aborta `signal` rechaza con `LaburenAbortError` y limpia el timer. */
81
+ function sleep(ms, signal) {
82
+ return new Promise((resolve, reject) => {
83
+ if (signal?.aborted) {
84
+ reject(new LaburenAbortError({ cause: signal.reason }));
85
+ return;
86
+ }
87
+ const onAbort = () => {
88
+ clearTimeout(timer);
89
+ reject(new LaburenAbortError({ cause: signal?.reason }));
90
+ };
91
+ const timer = setTimeout(() => {
92
+ signal?.removeEventListener("abort", onAbort);
93
+ resolve();
94
+ }, ms);
95
+ signal?.addEventListener("abort", onAbort, { once: true });
96
+ });
97
+ }
98
+ /** Consulta cada `interval` segundos hasta que la persona aprueba; corta con `LaburenOAuthError` si se deniega o vence. */
99
+ export async function waitForDeviceToken(opts) {
100
+ const deadline = Date.now() + opts.expiresIn * 1000;
101
+ let intervalSeconds = opts.interval;
102
+ for (;;) {
103
+ const waitMs = intervalSeconds * 1000;
104
+ // Si el próximo intento caería pasado el vencimiento, se espera hasta el vencimiento y se corta.
105
+ if (Date.now() + waitMs >= deadline) {
106
+ await sleep(Math.max(0, deadline - Date.now()), opts.signal);
107
+ throw new LaburenOAuthError({
108
+ error: "expired_token",
109
+ description: "The device code expired.",
110
+ status: 400,
111
+ });
112
+ }
113
+ await sleep(waitMs, opts.signal);
114
+ try {
115
+ return await postOAuth("/oauth/token", { grant_type: DEVICE_GRANT_TYPE, device_code: opts.deviceCode }, opts);
116
+ }
117
+ catch (error) {
118
+ // Un corte de red o un timeout en una consulta no tira el login: se espera más y se reintenta.
119
+ // El vencimiento lo corta el chequeo del principio del loop.
120
+ if (isLaburenConnectionError(error)) {
121
+ intervalSeconds += SLOW_DOWN_STEP_SECONDS;
122
+ continue;
123
+ }
124
+ if (!isLaburenOAuthError(error))
125
+ throw error;
126
+ if (error.error === "authorization_pending")
127
+ continue;
128
+ if (error.error === "slow_down") {
129
+ intervalSeconds += SLOW_DOWN_STEP_SECONDS;
130
+ continue;
131
+ }
132
+ throw error;
133
+ }
134
+ }
135
+ }
136
+ /** Cambia un refresh token por un access token nuevo. */
137
+ export function refreshToken(opts) {
138
+ return postOAuth("/oauth/token", { grant_type: "refresh_token", refresh_token: opts.refreshToken }, opts);
139
+ }
140
+ /** Revoca un access o refresh token (RFC 7009); la API siempre contesta 200. */
141
+ export async function revokeToken(opts) {
142
+ await postOAuth("/oauth/revoke", { token: opts.token }, opts);
143
+ }
144
+ //# sourceMappingURL=oauth.js.map